Ejemplo n.º 1
0
        public void CanConstructWithSemanticVersion()
        {
            var firstVersion = new UpdateVersion("1.0-a");

            Assert.AreEqual("1.0.0.0a", firstVersion.ToString());

            var secondVersion = new UpdateVersion("1.0-a.2");

            Assert.AreEqual("1.0.0.0a2", secondVersion.ToString());

            var thirdVersion = new UpdateVersion("1.0a.2");

            Assert.AreEqual("1.0.0.0a2", thirdVersion.ToString());
        }
Ejemplo n.º 2
0
        private void addVersionButton_Click(object sender, EventArgs e)
        {
            if (
                unsupportedMajorNumericUpDown.Value == 0 && unsupportedMinorNumericUpDown.Value == 0 &&
                unsupportedBuildNumericUpDown.Value == 0 && unsupportedRevisionNumericUpDown.Value == 0)
            {
                Popup.ShowPopup(this, SystemIcons.Warning, "Invalid version.",
                    "You can't add version \"0.0.0.0\" to the unsupported versions. Please specify a minimum version of \"0.1.0.0\"",
                    PopupButtons.Ok);
                return;
            }

            var version = new UpdateVersion((int) unsupportedMajorNumericUpDown.Value,
                (int) unsupportedMinorNumericUpDown.Value, (int) unsupportedBuildNumericUpDown.Value,
                (int) unsupportedRevisionNumericUpDown.Value);
            _unsupportedVersionLiteralsBindingList.Add(version.ToString());
        }
Ejemplo n.º 3
0
        private void saveButton_Click(object sender, EventArgs e)
        {
            _newVersion = new UpdateVersion((int) majorNumericUpDown.Value, (int) minorNumericUpDown.Value,
                (int) buildNumericUpDown.Value, (int) revisionNumericUpDown.Value, (DevelopmentalStage)
                    Enum.Parse(typeof (DevelopmentalStage),
                        developmentalStageComboBox.GetItemText(developmentalStageComboBox.SelectedItem)),
                (int) developmentBuildNumericUpDown.Value);
            if (_newVersion.BasicVersion == "0.0.0.0")
            {
                Popup.ShowPopup(this, SystemIcons.Error, "Invalid version set.",
                    "Version \"0.0.0.0\" is not a valid version.", PopupButtons.Ok);
                generalPanel.BringToFront();
                categoryTreeView.SelectedNode = categoryTreeView.Nodes[0];
                return;
            }

            if (Project.Packages != null && Project.Packages.Count != 0)
            {
                if (PackageVersion != _newVersion && Project.Packages.Any(item => new UpdateVersion(item.Version) == _newVersion))
                {
                    Popup.ShowPopup(this, SystemIcons.Error, "Invalid version set.",
                        String.Format(
                            "Version \"{0}\" is already existing.",
                            _newVersion.FullText), PopupButtons.Ok);
                    generalPanel.BringToFront();
                    categoryTreeView.SelectedNode = categoryTreeView.Nodes[0];
                    return;
                }
            }

            if (String.IsNullOrEmpty(englishChangelogTextBox.Text))
            {
                Popup.ShowPopup(this, SystemIcons.Error, "No changelog set.",
                    "Please specify a changelog for the package. If you have already set a changelog in another language, you still need to specify one for \"English - en\" to support client's that don't use your specified culture on their computer.",
                    PopupButtons.Ok);
                changelogPanel.BringToFront();
                categoryTreeView.SelectedNode = categoryTreeView.Nodes[1];
                return;
            }

            foreach (
                var tabPage in
                    from tabPage in categoryTabControl.TabPages.Cast<TabPage>().Where(item => item.TabIndex > 3)
                    let operationPanel = tabPage.Controls[0] as IOperationPanel
                    where operationPanel != null && !operationPanel.IsValid
                    select tabPage)
            {
                Popup.ShowPopup(this, SystemIcons.Error, "An added operation isn't valid.",
                    "Please make sure to fill out all required fields correctly.",
                    PopupButtons.Ok);
                categoryTreeView.SelectedNode =
                    categoryTreeView.Nodes[3].Nodes.Cast<TreeNode>()
                        .First(item => item.Index == tabPage.TabIndex - 4);
                return;
            }

            var changelog = new Dictionary<CultureInfo, string>
            {
                {new CultureInfo("en"), englishChangelogTextBox.Text}
            };
            foreach (
                var tabPage in
                    changelogContentTabControl.TabPages.Cast<TabPage>().Where(tabPage => tabPage.Text != "English"))
            {
                var panel = (ChangelogPanel) tabPage.Controls[0];
                if (String.IsNullOrEmpty(panel.Changelog)) continue;
                changelog.Add((CultureInfo) tabPage.Tag, panel.Changelog);
            }

            _packageConfiguration.NecessaryUpdate = necessaryUpdateCheckBox.Checked;
            _packageConfiguration.Architecture = (Architecture) architectureComboBox.SelectedIndex;
            _packageConfiguration.Changelog = changelog;

            if (unsupportedVersionsListBox.Items.Count == 0)
                allVersionsRadioButton.Checked = true;
            else if (unsupportedVersionsListBox.Items.Count > 0 && someVersionsRadioButton.Checked)
            {
                _packageConfiguration.UnsupportedVersions =
                    unsupportedVersionsListBox.Items.Cast<string>().ToArray();
            }

            _packageConfiguration.Operations.Clear();
            foreach (var operationPanel in from TreeNode node in categoryTreeView.Nodes[3].Nodes
                select (IOperationPanel) categoryTabControl.TabPages[4 + node.Index].Controls[0])
            {
                _packageConfiguration.Operations.Add(operationPanel.Operation);
            }

            _packageConfiguration.UseStatistics = includeIntoStatisticsCheckBox.Checked;

            string[] unsupportedVersionLiterals = null;

            if (unsupportedVersionsListBox.Items.Count == 0)
                allVersionsRadioButton.Checked = true;
            else if (unsupportedVersionsListBox.Items.Count > 0 && someVersionsRadioButton.Checked)
            {
                unsupportedVersionLiterals = _unsupportedVersionLiteralsBindingList.ToArray();
            }

            _packageConfiguration.UnsupportedVersions = unsupportedVersionLiterals;
            _packageConfiguration.LiteralVersion = _newVersion.ToString();
            _packageConfiguration.UpdatePackageUri = new Uri(String.Format("{0}/{1}.zip",
                UriConnector.ConnectUri(Project.UpdateUrl, _packageConfiguration.LiteralVersion), Project.Guid));

            _newPackageDirectory = Path.Combine(Program.Path, "Projects", Project.Name,
                _newVersion.ToString());

            if (_existingVersionString != _newVersion.ToString())
            {
                _oldPackageDirectoryPath = Path.Combine(Program.Path, "Projects", Project.Name,
                    _existingVersionString);
                try
                {
                    Directory.Move(_oldPackageDirectoryPath, _newPackageDirectory);
                }
                catch (Exception ex)
                {
                    Popup.ShowPopup(this, SystemIcons.Error,
                        "Error while changing the version of the package directory.", ex,
                        PopupButtons.Ok);
                    return;
                }
            }

            UpdateConfiguration[
                UpdateConfiguration.IndexOf(
                    UpdateConfiguration.First(item => item.LiteralVersion == PackageVersion.ToString()))] =
                _packageConfiguration;
            var configurationFilePath = Path.Combine(_newPackageDirectory, "updates.json");
            try
            {
                File.WriteAllText(configurationFilePath, Serializer.Serialize(UpdateConfiguration));
            }
            catch (Exception ex)
            {
                Popup.ShowPopup(this, SystemIcons.Error, "Error while saving the new configuration.", ex,
                    PopupButtons.Ok);
                return;
            }

            loadingPanel.Location = new Point(180, 91);
            loadingPanel.BringToFront();

            if (IsReleased)
                InitializePackage();
            else
                DialogResult = DialogResult.OK;
        }
Ejemplo n.º 4
0
        public void CanConstructWithSemanticVersion()
        {
            var firstVersion = new UpdateVersion("1.0-a");
            Assert.AreEqual("1.0.0.0a", firstVersion.ToString());

            var secondVersion = new UpdateVersion("1.0-a.2");
            Assert.AreEqual("1.0.0.0a2", secondVersion.ToString());

            var thirdVersion = new UpdateVersion("1.0a.2");
            Assert.AreEqual("1.0.0.0a2", thirdVersion.ToString());
        }
Ejemplo n.º 5
0
 public void CanConstructTwoDigitVersion()
 {
     var version = new UpdateVersion("1.0");
     Assert.AreEqual("1.0.0.0", version.ToString());
 }
Ejemplo n.º 6
0
 public void CanConstructOneDigitAlphaVersionWithoutDevelopmentalStage()
 {
     var version = new UpdateVersion("1a");
     Assert.AreEqual("1.0.0.0a", version.ToString());
 }
Ejemplo n.º 7
0
 public void CanConstructOneDigitAlphaVersion()
 {
     var version = new UpdateVersion("1a1");
     Assert.AreEqual("1.0.0.0a1", version.ToString());
 }
Ejemplo n.º 8
0
 public void CanGetCorrectReleaseCandidateVersionString()
 {
     var version = new UpdateVersion("1.2rc2");
     Assert.AreEqual("1.2.0.0rc2", version.ToString());
 }
Ejemplo n.º 9
0
        private async void InitializeEditing()
        {
            if (packagesList.SelectedItems.Count == 0)
                return;

            var packageVersion = new UpdateVersion((string)packagesList.SelectedItems[0].Tag);
            UpdatePackage correspondingPackage;

            try
            {
                correspondingPackage = Project.Packages.First(item => new UpdateVersion(item.Version) == packageVersion);
            }
            catch (Exception ex)
            {
                Popup.ShowPopup(this, SystemIcons.Error, "Error while selecting the corresponding package.", ex,
                    PopupButtons.Ok);
                return;
            }

            if (!ConnectionChecker.IsConnectionAvailable() && correspondingPackage.IsReleased)
            {
                Popup.ShowPopup(this, SystemIcons.Error, "No network connection available.",
                    "No active network connection was found. In order to edit a package, which is already existing on the server, a network connection is required because the update configuration must be downloaded from the server.",
                    PopupButtons.Ok);
                return;
            }

            var packageEditDialog = new PackageEditDialog
            {
                Project = Project,
                PackageVersion = packageVersion,
                FtpPassword = FtpPassword.Copy(),
                SqlPassword = SqlPassword.Copy(),
                ProxyPassword = ProxyPassword.Copy()
            };

            if (correspondingPackage.IsReleased)
            {
                bool loadingSuccessful = await LoadConfiguration();
                if (loadingSuccessful)
                {
                    packageEditDialog.IsReleased = true;
                    packageEditDialog.UpdateConfiguration = _editingUpdateConfiguration == null
                        ? null
                        : _editingUpdateConfiguration.ToList();
                }
                else
                    return;
            }
            else
            {
                if (!File.Exists(
                        Project.Packages.First(item => item.Version == packageVersion.ToString()).LocalPackagePath))
                {
                    Invoke(
                        new Action(
                            () => Popup.ShowPopup(this, SystemIcons.Error,
                                "Edit operation cancelled", "The package file doesn't exist locally and can't be edited locally.", PopupButtons.Ok)));
                    return;
                }
                packageEditDialog.IsReleased = false;

                try
                {
                    packageEditDialog.UpdateConfiguration =
                        UpdateConfiguration.FromFile(Path.Combine(Directory.GetParent(
                            Project.Packages.First(item => new UpdateVersion(item.Version) == packageVersion).LocalPackagePath).FullName,
                            "updates.json")).ToList();
                }
                catch (Exception ex)
                {
                    Popup.ShowPopup(this, SystemIcons.Error, "Error while loading the configuration.", ex,
                        PopupButtons.Ok);
                    return;
                }
            }

            packageEditDialog.ConfigurationFileUrl = _configurationFileUrl;
            if (packageEditDialog.ShowDialog() != DialogResult.OK)
                return;
            InitializeProjectData();
            InitializePackageItems();
            if (Project.UseStatistics)
                await InitializeStatisticsData();
        }
Ejemplo n.º 10
0
        private async void UploadPackage(UpdateVersion packageVersion)
        {
            await TaskEx.Run(() =>
            {
                if (!File.Exists(
                        Project.Packages.First(item => item.Version == packageVersion.ToString()).LocalPackagePath))
                {
                    Invoke(
                        new Action(
                            () => Popup.ShowPopup(this, SystemIcons.Error,
                                "Upload operation cancelled", "The package file doesn't exist locally and can't be uploaded to the server.", PopupButtons.Ok)));
                    return;
                }

                var updateConfigurationFilePath = Path.Combine(Program.Path, "Projects", Project.Name,
                    packageVersion.ToString(), "updates.json");

                SetUiState(false);
                Invoke(new Action(() => loadingLabel.Text = "Getting old configuration..."));
                try
                {
                    var updateConfiguration = UpdateConfiguration.Download(_configurationFileUrl, Project.Proxy) ?? Enumerable.Empty<UpdateConfiguration>();
                    _backupConfiguration = updateConfiguration.ToList();
                }
                catch (Exception ex)
                {
                    Invoke(
                        new Action(
                            () => Popup.ShowPopup(this, SystemIcons.Error,
                                "Error while downloading the old configuration.", ex, PopupButtons.Ok)));
                    SetUiState(true);
                    return;
                }

                if (Project.UseStatistics)
                {
                    int versionId;
                    try
                    {
                        versionId =
                            UpdateConfiguration.FromFile(updateConfigurationFilePath)
                                .First(item => new UpdateVersion(item.LiteralVersion) == packageVersion)
                                .VersionId;
                    }
                    catch (InvalidOperationException)
                    {
                        Invoke(
                            new Action(
                                () =>
                                    Popup.ShowPopup(this, SystemIcons.Error, "Error while preparing the SQL-connection.",
                                        "The update configuration of package \"{0}\" doesn't contain any entries for that version.",
                                        PopupButtons.Ok)));
                        Reset();
                        return;
                    }

                    Invoke(new Action(() => loadingLabel.Text = "Connecting to SQL-server..."));

                    var connectionString = String.Format("SERVER={0};" +
                                                         "DATABASE={1};" +
                                                         "UID={2};" +
                                                         "PASSWORD={3};",
                        Project.SqlWebUrl, Project.SqlDatabaseName,
                        Project.SqlUsername,
                        SqlPassword.ConvertToUnsecureString());

                    var insertConnection = new MySqlConnection(connectionString);
                    try
                    {
                        insertConnection.Open();
                    }
                    catch (MySqlException ex)
                    {
                        Invoke(
                            new Action(
                                () =>
                                    Popup.ShowPopup(this, SystemIcons.Error, "An MySQL-exception occured.",
                                        ex, PopupButtons.Ok)));
                        insertConnection.Close();
                        SetUiState(true);
                        return;
                    }
                    catch (Exception ex)
                    {
                        Invoke(
                            new Action(
                                () =>
                                    Popup.ShowPopup(this, SystemIcons.Error, "Error while connecting to the database.",
                                        ex, PopupButtons.Ok)));
                        insertConnection.Close();
                        SetUiState(true);
                        return;
                    }

                    Invoke(new Action(() => loadingLabel.Text = "Executing SQL-commands..."));

                    var command = insertConnection.CreateCommand();
                    command.CommandText =
                        String.Format(
                            "INSERT INTO `Version` (`ID`, `Version`, `Application_ID`) VALUES ({0}, \"{1}\", {2});",
                            versionId, packageVersion, Project.ApplicationId);

                    try
                    {
                        command.ExecuteNonQuery();
                        _commandsExecuted = true;
                    }
                    catch (Exception ex)
                    {
                        Invoke(
                            new Action(
                                () =>
                                    Popup.ShowPopup(this, SystemIcons.Error, "Error while executing the commands.",
                                        ex, PopupButtons.Ok)));
                        SetUiState(true);
                        return;
                    }
                    finally
                    {
                        insertConnection.Close();
                        command.Dispose();
                    }
                }

                Invoke(new Action(() =>
                {
                    loadingLabel.Text = String.Format("Uploading... {0}", "0%");
                    cancelLabel.Visible = true;
                }));

                try
                {
                    var packagePath = Project.Packages.First(x => new UpdateVersion(x.Version) == packageVersion).LocalPackagePath;
                    _ftp.UploadPackage(packagePath, packageVersion.ToString());
                }
                catch (InvalidOperationException)
                {
                    Invoke(
                        new Action(
                            () =>
                                Popup.ShowPopup(this, SystemIcons.Error, "Error while uploading the package.",
                                    "The project's package data doesn't contain any entries for version \"{0}\".",
                                    PopupButtons.Ok)));
                    Reset();
                    return;
                }
                catch (Exception ex) // Errors that were thrown directly relate to the directory
                {
                    Invoke(
                        new Action(
                            () =>
                                Popup.ShowPopup(this, SystemIcons.Error, "Error while creating the package directory.",
                                    ex, PopupButtons.Ok)));
                    Reset();
                    return;
                }

                if (_uploadCancelled)
                    return;

                if (_ftp.PackageUploadException != null)
                {
                    var ex = _ftp.PackageUploadException.InnerException ?? _ftp.PackageUploadException;
                    Invoke(
                        new Action(
                            () => Popup.ShowPopup(this, SystemIcons.Error, "Error while uploading the package.", ex,
                                PopupButtons.Ok)));

                    Reset();
                    return;
                }

                Invoke(new Action(() =>
                {
                    loadingLabel.Text = "Uploading new configuration...";
                    cancelLabel.Visible = false;
                }));

                try
                {
                    _ftp.UploadFile(updateConfigurationFilePath);
                    _configurationUploaded = true;
                }
                catch (Exception ex)
                {
                    Invoke(
                        new Action(
                            () =>
                                Popup.ShowPopup(this, SystemIcons.Error, "Error while uploading the configuration.", ex,
                                    PopupButtons.Ok)));
                    Reset();
                    return;
                }

                _updateLog.Write(LogEntry.Upload, packageVersion.FullText);

                try
                {
                    Project.Packages.First(x => new UpdateVersion(x.Version) == packageVersion).IsReleased = true;
                    UpdateProject.SaveProject(Project.Path, Project);
                }
                catch (Exception ex)
                {
                    Invoke(
                        new Action(
                            () =>
                                Popup.ShowPopup(this, SystemIcons.Error, "Error while saving the new project data.", ex,
                                    PopupButtons.Ok)));
                    Reset();
                    return;
                }

                SetUiState(true);
                InitializeProjectData();
                InitializePackageItems();
            });
        }
Ejemplo n.º 11
0
        /// <summary>
        ///     Runs the updating process. This method does not block the calling thread.
        /// </summary>
        private void RunUpdateAsync()
        {
            string parentPath = Directory.GetParent(Program.PackageFilePaths.First()).FullName;
            /* Extract and count for the progress */
            foreach (var packageFilePath in Program.PackageFilePaths)
            {
                var version = new UpdateVersion(Path.GetFileNameWithoutExtension(packageFilePath));
                string extractedDirectoryPath =
                    Path.Combine(parentPath, version.ToString());
                Directory.CreateDirectory(extractedDirectoryPath);
                using (var zf = ZipFile.Read(packageFilePath))
                {
                    zf.ParallelDeflateThreshold = -1;
                    try
                    {
                        foreach (var entry in zf)
                        {
                            entry.Extract(extractedDirectoryPath);
                        }
                    }
                    catch (Exception ex)
                    {
                        _progressReporter.Fail(ex);
                        CleanUp();
                        _progressReporter.Terminate();
                        if (!Program.IsHostApplicationClosed)
                            return;

                        var process = new Process
                        {
                            StartInfo =
                            {
                                UseShellExecute = true,
                                FileName = Program.ApplicationExecutablePath,
                                Arguments =
                                    String.Join("|",
                                        Program.Arguments.Where(
                                            item =>
                                                item.ExecutionOptions ==
                                                UpdateArgumentExecutionOptions.OnlyOnFaulted).Select(item => item.Argument))
                            }
                        };
                        process.Start();
                        return;
                    }

                    _totalTaskCount += new DirectoryInfo(extractedDirectoryPath).GetDirectories().Sum(
                        directory => Directory.GetFiles(directory.FullName, "*.*", SearchOption.AllDirectories).Length);
                }
            }

            foreach (var operationEnumerable in Program.Operations.Select(item => item.Value))
                    _totalTaskCount +=
                        operationEnumerable.Count(
                            item => item.Area != OperationArea.Registry && item.Method != OperationMethod.Delete);

                foreach (
                    var array in
                        Program.Operations.Select(entry => entry.Value)
                            .Select(operationEnumerable => operationEnumerable.Where(
                                item =>
                                    item.Area == OperationArea.Registry && item.Method != OperationMethod.SetValue)
                                .Select(registryOperation => registryOperation.Value2)
                                .OfType<JArray>()).SelectMany(entries =>
                                {
                                    var entryEnumerable = entries as JArray[] ?? entries.ToArray();
                                    return entryEnumerable;
                                }))
                {
                    _totalTaskCount += array.ToObject<IEnumerable<string>>().Count();
                }

                foreach (
                    var array in
                        Program.Operations.Select(entry => entry.Value)
                            .Select(operationEnumerable => operationEnumerable.Where(
                                item => item.Area == OperationArea.Files && item.Method == OperationMethod.Delete)
                                .Select(registryOperation => registryOperation.Value2)
                                .OfType<JArray>()).SelectMany(entries =>
                                {
                                    var entryEnumerable = entries as JArray[] ?? entries.ToArray();
                                    return entryEnumerable;
                                }))
                {
                    _totalTaskCount += array.ToObject<IEnumerable<string>>().Count();
                }

                foreach (
                    var array in
                        Program.Operations.Select(entry => entry.Value)
                            .Select(operationEnumerable => operationEnumerable.Where(
                                item =>
                                    item.Area == OperationArea.Registry && item.Method == OperationMethod.SetValue)
                                .Select(registryOperation => registryOperation.Value2)
                                .OfType<JArray>()).SelectMany(entries =>
                                {
                                    var entryEnumerable = entries as JArray[] ?? entries.ToArray();
                                    return entryEnumerable;
                                }))
                {
                    _totalTaskCount += array.ToObject<IEnumerable<string>>().Count();
                }

            foreach (
                var packageFilePath in
                    Program.PackageFilePaths.OrderBy(item => new UpdateVersion(Path.GetFileNameWithoutExtension(item))))
            {
                var version = new UpdateVersion(Path.GetFileNameWithoutExtension(packageFilePath));
                string extractedDirectoryPath =
                    Path.Combine(parentPath, version.ToString());
                foreach (var directory in new DirectoryInfo(extractedDirectoryPath).GetDirectories())
                {
                    switch (directory.Name)
                    {
                        case "Program":
                            CopyDirectoryRecursively(directory.FullName, Program.AimFolder);
                            break;
                        case "AppData":
                            CopyDirectoryRecursively(directory.FullName,
                                Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
                            break;
                        case "Temp":
                            CopyDirectoryRecursively(directory.FullName, Path.GetTempPath());
                            break;
                        case "Desktop":
                            CopyDirectoryRecursively(directory.FullName,
                                Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
                            break;
                    }
                }

                try
                {
                    IEnumerable<Operation> currentVersionOperations =
                        Program.Operations.Any(item => new UpdateVersion(item.Key) == version)
                            ? Program.Operations.First(item => new UpdateVersion(item.Key) == version).Value
                            : Enumerable.Empty<Operation>();
                    foreach (var operation in currentVersionOperations)
                    {
                        float percentage;
                        JArray secondValueAsArray;
                        switch (operation.Area)
                        {
                            case OperationArea.Files:
                                switch (operation.Method)
                                {
                                    case OperationMethod.Delete:
                                        var deleteFilePathParts = operation.Value.Split('\\');
                                        var deleteFileFullPath = Path.Combine(
                                            Operation.GetDirectory(deleteFilePathParts[0]),
                                            String.Join("\\",
                                                deleteFilePathParts.Where(item => item != deleteFilePathParts[0])));
                                        secondValueAsArray = operation.Value2 as JArray;
                                        if (secondValueAsArray != null)
                                            foreach (
                                                var fileToDelete in secondValueAsArray.ToObject<IEnumerable<string>>())
                                            {
                                                string path = Path.Combine(deleteFileFullPath, fileToDelete);
                                                if (File.Exists(path))
                                                    File.Delete(path);

                                                _doneTaskAmount += 1;
                                                percentage = ((float) _doneTaskAmount/_totalTaskCount)*100f;
                                                _progressReporter.ReportOperationProgress(percentage,
                                                    String.Format(Program.FileDeletingOperationText, fileToDelete));
                                            }
                                        break;

                                    case OperationMethod.Rename:
                                        var renameFilePathParts = operation.Value.Split('\\');
                                        var renameFileFullPath = Path.Combine(
                                            Operation.GetDirectory(renameFilePathParts[0]),
                                            String.Join("\\",
                                                renameFilePathParts.Where(item => item != renameFilePathParts[0])));
                                        if (File.Exists(renameFileFullPath))
                                            File.Move(renameFileFullPath,
                                                Path.Combine(Directory.GetParent(renameFileFullPath).FullName,
                                                    operation.Value2.ToString()));

                                        _doneTaskAmount += 1;
                                        percentage = ((float) _doneTaskAmount/_totalTaskCount)*100f;
                                        _progressReporter.ReportOperationProgress(percentage,
                                            String.Format(Program.FileRenamingOperationText,
                                                Path.GetFileName(operation.Value),
                                                operation.Value2));
                                        break;
                                }
                                break;
                            case OperationArea.Registry:
                                switch (operation.Method)
                                {
                                    case OperationMethod.Create:
                                        secondValueAsArray = operation.Value2 as JArray;
                                        if (secondValueAsArray != null)
                                            foreach (
                                                var registryKey in secondValueAsArray.ToObject<IEnumerable<string>>())
                                            {
                                                RegistryManager.CreateSubKey(operation.Value, registryKey);

                                                _doneTaskAmount += 1;
                                                percentage = ((float) _doneTaskAmount/_totalTaskCount)*100f;
                                                _progressReporter.ReportOperationProgress(percentage,
                                                    String.Format(Program.RegistrySubKeyCreateOperationText, registryKey));
                                            }
                                        break;

                                    case OperationMethod.Delete:
                                        secondValueAsArray = operation.Value2 as JArray;
                                        if (secondValueAsArray != null)
                                            foreach (
                                                var registryKey in secondValueAsArray.ToObject<IEnumerable<string>>())
                                            {
                                                RegistryManager.DeleteSubKey(operation.Value, registryKey);

                                                _doneTaskAmount += 1;
                                                percentage = ((float) _doneTaskAmount/_totalTaskCount)*100f;
                                                _progressReporter.ReportOperationProgress(percentage,
                                                    String.Format(Program.RegistrySubKeyDeleteOperationText, registryKey));
                                            }
                                        break;

                                    case OperationMethod.SetValue:
                                        secondValueAsArray = operation.Value2 as JArray;
                                        if (secondValueAsArray != null)
                                            foreach (
                                                var nameValuePair in
                                                    secondValueAsArray
                                                        .ToObject<IEnumerable<Tuple<string, object, RegistryValueKind>>>
                                                        ())
                                            {
                                                RegistryManager.SetValue(operation.Value, nameValuePair.Item1,
                                                    nameValuePair.Item2, nameValuePair.Item3);

                                                _doneTaskAmount += 1;
                                                percentage = ((float) _doneTaskAmount/_totalTaskCount)*100f;
                                                _progressReporter.ReportOperationProgress(percentage,
                                                    String.Format(Program.RegistryNameValuePairSetValueOperationText,
                                                        nameValuePair.Item1, nameValuePair.Item2));
                                            }
                                        break;

                                    case OperationMethod.DeleteValue:
                                        secondValueAsArray = operation.Value2 as JArray;
                                        if (secondValueAsArray != null)
                                            foreach (var valueName in secondValueAsArray.ToObject<IEnumerable<string>>()
                                                )
                                            {
                                                RegistryManager.DeleteValue(operation.Value, valueName);

                                                _doneTaskAmount += 1;
                                                percentage = ((float) _doneTaskAmount/_totalTaskCount)*100f;
                                                _progressReporter.ReportOperationProgress(percentage,
                                                    String.Format(Program.RegistryNameValuePairSetValueOperationText,
                                                        valueName));
                                            }
                                        break;
                                }
                                break;

                            case OperationArea.Processes:
                                switch (operation.Method)
                                {
                                    case OperationMethod.Start:
                                        var processFilePathParts = operation.Value.Split('\\');
                                        var processFileFullPath =
                                            Path.Combine(Operation.GetDirectory(processFilePathParts[0]),
                                                String.Join("\\",
                                                    processFilePathParts.Where(item => item != processFilePathParts[0])));

                                        var process = new Process
                                        {
                                            StartInfo =
                                            {
                                                FileName = processFileFullPath,
                                                Arguments = operation.Value2.ToString()
                                            }
                                        };
                                        try
                                        {
                                            process.Start();
                                        }
                                        catch (Win32Exception ex)
                                        {
                                            if (ex.NativeErrorCode != 1223)
                                                throw;
                                        }

                                        _doneTaskAmount += 1;
                                        percentage = ((float) _doneTaskAmount/_totalTaskCount)*100f;
                                        _progressReporter.ReportOperationProgress(percentage,
                                            String.Format(Program.ProcessStartOperationText, operation.Value));
                                        break;

                                    case OperationMethod.Stop:
                                        var processes = Process.GetProcessesByName(operation.Value);
                                        foreach (var foundProcess in processes)
                                            foundProcess.Kill();

                                        _doneTaskAmount += 1;
                                        percentage = ((float) _doneTaskAmount/_totalTaskCount)*100f;
                                        _progressReporter.ReportOperationProgress(percentage,
                                            String.Format(Program.ProcessStopOperationText, operation.Value));
                                        break;
                                }
                                break;

                            case OperationArea.Services:
                                switch (operation.Method)
                                {
                                    case OperationMethod.Start:
                                        ServiceManager.StartService(operation.Value, (string[]) operation.Value2);

                                        _doneTaskAmount += 1;
                                        percentage = ((float) _doneTaskAmount/_totalTaskCount)*100f;
                                        _progressReporter.ReportOperationProgress(percentage,
                                            String.Format(Program.ServiceStartOperationText, operation.Value));
                                        break;

                                    case OperationMethod.Stop:
                                        ServiceManager.StopService(operation.Value);

                                        _doneTaskAmount += 1;
                                        percentage = ((float) _doneTaskAmount/_totalTaskCount)*100f;
                                        _progressReporter.ReportOperationProgress(percentage,
                                            String.Format(Program.ServiceStopOperationText, operation.Value));
                                        break;
                                }
                                break;
                            case OperationArea.Scripts:
                                switch (operation.Method)
                                {
                                    case OperationMethod.Execute:
                                        var helper = new CodeDomHelper();
                                        helper.ExecuteScript(operation.Value);
                                        break;
                                }
                                break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    _progressReporter.Fail(ex);
                    CleanUp();
                    _progressReporter.Terminate();
                    if (!Program.IsHostApplicationClosed)
                        return;

                    var process = new Process
                    {
                        StartInfo =
                        {
                            UseShellExecute = true,
                            FileName = Program.ApplicationExecutablePath,
                            Arguments =
                                String.Join("|",
                                    Program.Arguments.Where(
                                        item =>
                                            item.ExecutionOptions ==
                                            UpdateArgumentExecutionOptions.OnlyOnFaulted).Select(item => item.Argument))
                        }
                    };
                    process.Start();
                    return;
                }
            }

            CleanUp();
            if (Program.IsHostApplicationClosed)
            {
                var p = new Process
                {
                    StartInfo =
                    {
                        UseShellExecute = true,
                        FileName = Program.ApplicationExecutablePath,
                        Arguments =
                            String.Join("|",
                                Program.Arguments.Where(
                                    item =>
                                        item.ExecutionOptions == UpdateArgumentExecutionOptions.OnlyOnSucceeded)
                                    .Select(item => item.Argument))
                    }
                };
                p.Start();
            }
            _progressReporter.Terminate();
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            foreach (var arg in args)
            {
                if (String.IsNullOrWhiteSpace(arg))
                {
                    continue;
                }

                if (arg.Equals("-silent"))
                {
                    isSilent = true;
                }
                else if (arg.Equals("-silent_minor"))
                {
                    isSilentMinor = true;
                }
                else if (arg.Equals("-update_major"))
                {
                    installType = UpdateType.Major;
                }
                else if (arg.Equals("-update_minor"))
                {
                    installType = UpdateType.Minor;
                }

                passedArgs += arg + " ";
            }

            passedArgs.TrimEnd(' ');

            exePath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);

            //Check privilege
            WindowsIdentity  identity  = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);

            isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);

            //Initialize UpdateManager
            StaticStorage.Manager = new UpdateManager();

            //Check if update retrieval was successful.
            if (StaticStorage.Manager.updateState == UpdateStatus.Error)
            {
                return;
            }

            if (installType != UpdateType.Undefined)
            {
                if (isElevated)
                {
                    updateForm = new MainForm(installType);
                    updateForm.ShowDialog();
                }
                else
                {
                    MessageBox.Show(
                        "Updater was not granted Admin rights.",
                        "Aurora Updater - Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                }
            }
            else
            {
                string _maj = "";

                string auroraPath;
                if (File.Exists(auroraPath = Path.Combine(exePath, "Aurora.exe")))
                {
                    _maj = FileVersionInfo.GetVersionInfo(auroraPath).FileVersion;
                }

                if (!String.IsNullOrWhiteSpace(_maj))
                {
                    UpdateVersion latestV = new UpdateVersion(StaticStorage.Manager.LatestRelease.TagName.TrimStart('v'));
                    versionMajor = new UpdateVersion(_maj);

                    if (!(latestV <= versionMajor))
                    {
                        UpdateInfoForm userResult = new UpdateInfoForm()
                        {
                            changelog         = StaticStorage.Manager.LatestRelease.Body,
                            updateDescription = StaticStorage.Manager.LatestRelease.Name,
                            updateVersion     = latestV.ToString(),
                            currentVersion    = versionMajor.ToString(),
                            updateSize        = StaticStorage.Manager.LatestRelease.Assets.First(s => s.Name.StartsWith("release") || s.Name.StartsWith("Aurora-v")).Size,
                            preRelease        = StaticStorage.Manager.LatestRelease.Prerelease
                        };

                        userResult.ShowDialog();

                        if (userResult.DialogResult == DialogResult.OK)
                        {
                            if (isElevated)
                            {
                                updateForm = new MainForm(UpdateType.Major);
                                updateForm.ShowDialog();
                            }
                            else
                            {
                                //Request user to grant admin rights
                                try
                                {
                                    ProcessStartInfo updaterProc = new ProcessStartInfo();
                                    updaterProc.FileName  = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
                                    updaterProc.Arguments = passedArgs + " -update_major";
                                    updaterProc.Verb      = "runas";
                                    Process.Start(updaterProc);

                                    return; //Exit, no further action required
                                }
                                catch (Exception exc)
                                {
                                    MessageBox.Show(
                                        $"Could not start Aurora Updater. Error:\r\n{exc}",
                                        "Aurora Updater - Error",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (!isSilent)
                        {
                            MessageBox.Show(
                                "You have latest version of Aurora installed.",
                                "Aurora Updater",
                                MessageBoxButtons.OK);
                        }
                    }
                }
                else
                {
                    if (!isSilent)
                    {
                        MessageBox.Show(
                            "Application launched incorrectly, no version was specified.\r\nPlease use Aurora if you want to check for updates.\r\nOptions -> \"Updates\" \"Check for Updates\"",
                            "Aurora Updater",
                            MessageBoxButtons.OK);
                    }
                }

                /*string _min = "";
                 *
                 * if (File.Exists(Path.Combine(exePath, "ver_minor.txt")))
                 *  _min = File.ReadAllText(Path.Combine(exePath, "ver_minor.txt"));
                 *
                 * if (!String.IsNullOrWhiteSpace(_min))
                 * {
                 *  versionMinor = new UpdateVersion(_min);
                 *
                 *  if (!(StaticStorage.Manager.response.Minor.Version <= versionMinor))
                 *  {
                 *      if (isSilentMinor)
                 *          StaticStorage.Manager.RetrieveUpdate(UpdateType.Minor);
                 *      else
                 *      {
                 *          UpdateInfoForm userResult = new UpdateInfoForm()
                 *          {
                 *              changelog = StaticStorage.Manager.response.Minor.Changelog,
                 *              updateDescription = StaticStorage.Manager.response.Minor.Description,
                 *              updateVersion = StaticStorage.Manager.response.Minor.Version.ToString(),
                 *              currentVersion = versionMinor.ToString(),
                 *              updateSize = StaticStorage.Manager.response.Minor.FileSize,
                 *              preRelease = StaticStorage.Manager.response.Minor.PreRelease
                 *          };
                 *
                 *          userResult.ShowDialog();
                 *
                 *          if (userResult.DialogResult == DialogResult.Yes)
                 *          {
                 *              if (isElevated)
                 *              {
                 *                  updateForm = new MainForm(UpdateType.Minor);
                 *                  updateForm.ShowDialog();
                 *              }
                 *              else
                 *              {
                 *                  //Request user to grant admin rights
                 *                  try
                 *                  {
                 *                      ProcessStartInfo updaterProc = new ProcessStartInfo();
                 *                      updaterProc.FileName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
                 *                      updaterProc.Arguments = passedArgs + " -update_minor";
                 *                      updaterProc.Verb = "runas";
                 *                      Process.Start(updaterProc);
                 *
                 *                      return; //Exit, no further action required
                 *                  }
                 *                  catch (Exception exc)
                 *                  {
                 *                      MessageBox.Show(
                 *                          $"Could not start Aurora Updater. Error:\r\n{exc}",
                 *                          "Aurora Updater - Error",
                 *                          MessageBoxButtons.OK,
                 *                          MessageBoxIcon.Error);
                 *                  }
                 *              }
                 *          }
                 *      }
                 *
                 *  }
                 *  else
                 *  {
                 *      if (!isSilent && !isSilentMinor)
                 *          MessageBox.Show(
                 *              "You have latest Minor version of Aurora installed.",
                 *              "Aurora Updater",
                 *              MessageBoxButtons.OK);
                 *  }
                 * }
                 * else
                 * {
                 *  if (!isSilent)
                 *      MessageBox.Show(
                 *          "Application launched incorrectly, no version was specified.\r\nPlease use Aurora if you want to check for updates.\r\nOptions -> \"Updates\" \"Check for Updates\"",
                 *          "Aurora Updater",
                 *          MessageBoxButtons.OK);
                 * }*/
            }
        }
Ejemplo n.º 13
0
        public void CanGetCorrectReleaseCandidateVersionString()
        {
            var version = new UpdateVersion("1.2rc2");

            Assert.AreEqual("1.2.0.0rc2", version.ToString());
        }
Ejemplo n.º 14
0
        public void CanConstructOneDigitAlphaVersionWithoutDevelopmentalStage()
        {
            var version = new UpdateVersion("1a");

            Assert.AreEqual("1.0.0.0a", version.ToString());
        }
Ejemplo n.º 15
0
        public void CanConstructOneDigitAlphaVersion()
        {
            var version = new UpdateVersion("1a1");

            Assert.AreEqual("1.0.0.0a1", version.ToString());
        }
Ejemplo n.º 16
0
        public void CanConstructFourDigitVersion()
        {
            var version = new UpdateVersion("1.0.0.0");

            Assert.AreEqual("1.0.0.0", version.ToString());
        }