public void CanCheckVersionValidity() { var alphaVersion = new UpdateVersion("1.0.0.0a1"); var betaVersion = new UpdateVersion("1.0.0.0b1"); var releaseCandidateVersion = new UpdateVersion("1.0.0.0rc1"); var normalVersion = new UpdateVersion("1.0.0.0"); //var firstInvalidVersion = new UpdateVersion("1.0.0."); // Invalid //var secondInvalidVersion = new UpdateVersion("1.0.0.0c1"); // Invalid }
/// <summary> /// Initializes a new instance of the <see cref="UpdateResult" /> class. /// </summary> public UpdateResult(IEnumerable<UpdateConfiguration> packageConfigurations, UpdateVersion currentVersion, bool isAlphaWished, bool isBetaWished) { if (packageConfigurations != null) { var is64Bit = Environment.Is64BitOperatingSystem; foreach ( var config in packageConfigurations.Where( item => new UpdateVersion(item.LiteralVersion) > currentVersion || item.NecessaryUpdate) .Where( config => new UpdateVersion(config.LiteralVersion).DevelopmentalStage == DevelopmentalStage.Release || new UpdateVersion(config.LiteralVersion).DevelopmentalStage == DevelopmentalStage.ReleaseCandidate || ((isAlphaWished && new UpdateVersion(config.LiteralVersion).DevelopmentalStage == DevelopmentalStage.Alpha) || (isBetaWished && new UpdateVersion(config.LiteralVersion).DevelopmentalStage == DevelopmentalStage.Beta))) ) { if (config.UnsupportedVersions != null) { if ( config.UnsupportedVersions.Any( unsupportedVersion => new UpdateVersion(unsupportedVersion).BasicVersion == currentVersion.BasicVersion)) continue; } if (config.Architecture == Architecture.X86 && is64Bit || config.Architecture == Architecture.X64 && !is64Bit) continue; if (new UpdateVersion(config.LiteralVersion) <= currentVersion) continue; _newUpdateConfigurations.Add(config); } var highestVersion = UpdateVersion.GetHighestUpdateVersion( _newUpdateConfigurations.Select(item => new UpdateVersion(item.LiteralVersion))); _newUpdateConfigurations.RemoveAll( item => new UpdateVersion(item.LiteralVersion) < highestVersion && !item.NecessaryUpdate); } _updatesFound = _newUpdateConfigurations.Count != 0; }
public void CanCompareVersionsCorrectly() { var firstVersion = new UpdateVersion("1.2"); var secondVersion = new UpdateVersion("1.3.0.0"); Assert.AreEqual(firstVersion < secondVersion, true); var thirdVersion = new UpdateVersion("1.3a1"); var fourthVersion = new UpdateVersion("1.3.0.0a"); Assert.AreEqual(thirdVersion > fourthVersion, true); var fifthVersion = new UpdateVersion("1.4.0.0-b1"); var sixthVersion = new UpdateVersion("1.4.0.0rc"); var seventhVersion = new UpdateVersion("1.4.0.0-rc.1"); var eighthVersion = new UpdateVersion("1.4.0.0"); Assert.AreEqual(fifthVersion < sixthVersion && sixthVersion < seventhVersion && seventhVersion < eighthVersion, true); }
public void when_database_already_exists_and_configuration_does_not_allow_override_then_fails() { var configuration = new AnmatConfiguration { DocumentsPath = "GeneratedDb", TargetDatabaseName = this.GetDatabaseName("TestDb"), ReplaceExistingTargetDatabase = false }; var updateVersion = new UpdateVersion { Number = 2, Date = DateTime.UtcNow }; var job = new DataGenerationJob { Version = updateVersion.Number, Status = DataGenerationJobStatus.InProgress }; var jobService = new Mock <IDataGenerationJobService> (); jobService .Setup(s => s.GetLatestJob()) .Returns(job); var versionService = new Mock <IVersionService> (); versionService .Setup(r => r.IncrementVersion()) .Returns(updateVersion); var sqlGenerator = new SQLiteGenerator(jobService.Object, versionService.Object, configuration); var documentGenerator = new Mock <IDocumentGenerator> (); var databaseFileName = this.GetDatabaseFileName(configuration, sqlGenerator); using (File.Create(databaseFileName)) {}; Assert.Throws <SQLGenerationException>( () => sqlGenerator.GenerateDatabase(documentGenerator.Object)); }
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; }
public void CanGetCorrectSemanticVersion() { var firstVersion = new UpdateVersion("1.2a2"); Assert.AreEqual("1.2-a.2", firstVersion.SemanticVersion); var secondVersion = new UpdateVersion("1.2a"); Assert.AreEqual("1.2-a", secondVersion.SemanticVersion); var thirdVersion = new UpdateVersion("1.2"); Assert.AreEqual("1.2.0.0", thirdVersion.SemanticVersion); }
public void CanConstructOneDigitAlphaVersion() { var version = new UpdateVersion("1a1"); Assert.AreEqual("1.0.0.0a1", version.ToString()); }
public bool IsUpdateAvailable(string CurrentVersion) { if (!EnableUpdates) { return(false); } string ReleasePageAddress = "https://github.com/dlebansais/PgMessenger/releases"; try { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; HttpWebRequest Request = WebRequest.Create(ReleasePageAddress) as HttpWebRequest; using (WebResponse Response = Request.GetResponse()) { using (Stream ResponseStream = Response.GetResponseStream()) { using (StreamReader Reader = new StreamReader(ResponseStream, Encoding.ASCII)) { string Content = Reader.ReadToEnd(); string Pattern = @"<a href=""/dlebansais/PgMessenger/releases/tag/"; int Index = Content.IndexOf(Pattern); if (Index >= 0) { string UpdateTagVersion = Content.Substring(Index + Pattern.Length, 20); int EndIndex = UpdateTagVersion.IndexOf('"'); if (EndIndex > 0) { UpdateTagVersion = UpdateTagVersion.Substring(0, EndIndex); string UpdateVersion; if (UpdateTagVersion.ToLower().StartsWith("v")) { UpdateVersion = UpdateTagVersion.Substring(1); } else { UpdateVersion = UpdateTagVersion; } string[] UpdateSplit = UpdateVersion.Split('.'); string[] CurrentSplit = CurrentVersion.Split('.'); for (int i = 0; i < UpdateSplit.Length && i < CurrentSplit.Length; i++) { int UpdateValue, CurrentValue; if (!int.TryParse(UpdateSplit[i], out UpdateValue) || !int.TryParse(CurrentSplit[i], out CurrentValue)) { break; } else if (UpdateValue < CurrentValue) { break; } else if (UpdateValue > CurrentValue) { UpdateLink = "https://github.com/dlebansais/PgMessenger/releases/download/" + UpdateTagVersion + "/PgMessenger.exe"; break; } } } } } } } } catch (Exception e) { Debug.Print(e.Message); } return(UpdateLink != null); }
private void continueButton_Click(object sender, EventArgs e) { backButton.Enabled = true; if (_sender == optionTabPage) { if (importProjectRadioButton.Checked) { wizardTabControl.SelectedTab = importTabPage; _sender = importTabPage; } else if (shareProjectRadioButton.Checked) { wizardTabControl.SelectedTab = shareTabPage; _sender = shareTabPage; } } else if (_sender == importTabPage) { if (!ValidationManager.Validate(importTabPage)) { Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.", "All fields need to have a value.", PopupButtons.Ok); return; } if (!Path.IsPathRooted(projectToImportTextBox.Text) || !File.Exists(projectToImportTextBox.Text)) { Popup.ShowPopup(this, SystemIcons.Error, "Invalid path.", "The given local path for the project is invalid.", PopupButtons.Ok); return; } wizardTabControl.SelectedTab = importTabPage1; _sender = importTabPage1; } else if (_sender == importTabPage1) { if (!ValidationManager.Validate(importTabPage1)) { Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.", "All fields need to have a value.", PopupButtons.Ok); return; } if (_projectConfigurations.Any(item => item.Name == projectNameTextBox.Text)) { Popup.ShowPopup(this, SystemIcons.Error, "Project already existing.", String.Format("A project with the name \"{0}\" does already exist.", projectNameTextBox.Text), PopupButtons.Ok); return; } try { string folderPath = Path.Combine(Program.Path, "ImpProj"); string statisticsFilePath = Path.Combine(folderPath, "statistics.php"); string projectFilePath = Path.Combine(folderPath, String.Format("{0}.nupdproj", projectNameTextBox.Text)); Directory.CreateDirectory(folderPath); var updateProject = UpdateProject.LoadProject(projectFilePath); if (updateProject.UseStatistics) { Popup.ShowPopup(this, SystemIcons.Warning, "Incompatible project.", "This project cannot be imported because the support for projects using statistics is currently missing. It will be available in the next version(s) of nUpdate Administration.", PopupButtons.Ok); Directory.Delete(folderPath); return; } //if (updateProject.ConfigVersion != "3b2") //{ // Popup.ShowPopup(this, SystemIcons.Warning, "Incompatible project.", "This project is not compatible to this version of nUpdate Administration. Please download the newest version of nUpdate Administration and then export the project again.", PopupButtons.Ok); // Directory.Delete(folderPath); // return; //} updateProject.Path = projectFilePathTextBox.Text; //if (updateProject.UseStatistics) //{ // var statisticsServers = Serializer.Deserialize<List<StatisticsServer>>(Path.Combine(Program.Path, "statservers.json")); // if (!statisticsServers.Any(item => item.WebUrl == updateProject.SqlWebUrl && item.DatabaseName == updateProject.SqlDatabaseName && item.Username == updateProject.SqlUsername)) // { // if (Popup.ShowPopup(this, SystemIcons.Information, "New statistics server found.", "This project uses a statistics server that isn't currently available on this computer. Should nUpdate Administration add this server to your list?", PopupButtons.YesNo) == DialogResult.Yes) // { // statisticsServers.Add(new StatisticsServer(updateProject.SqlWebUrl, updateProject.SqlDatabaseName, updateProject.SqlUsername)); // File.WriteAllText(Path.Combine(Program.Path, "statservers.json"), Serializer.Serialize(statisticsServers)); // } // } //} UpdateProject.SaveProject(updateProject.Path, updateProject); string projectPath = Path.Combine(Program.Path, "Projects", projectNameTextBox.Text); if (!Directory.Exists(projectPath)) { Directory.CreateDirectory(projectPath); } using (var zip = new ZipFile(projectToImportTextBox.Text)) { zip.ExtractAll(folderPath); } if (File.Exists(statisticsFilePath)) { File.Move(statisticsFilePath, Path.Combine(projectPath, "statistics.php")); } File.Move(projectFilePath, projectFilePathTextBox.Text); foreach (var versionDirectory in new DirectoryInfo(folderPath).GetDirectories()) { Directory.Move(versionDirectory.FullName, Path.Combine(projectPath, versionDirectory.Name)); } Directory.Delete(folderPath); _projectConfigurations.Add(new ProjectConfiguration(projectNameTextBox.Text, projectFilePathTextBox.Text)); File.WriteAllText(Program.ProjectsConfigFilePath, Serializer.Serialize(_projectConfigurations)); } catch (Exception ex) { Popup.ShowPopup(this, SystemIcons.Error, "Error while importing the project.", ex, PopupButtons.Ok); return; } Close(); } else if (_sender == shareTabPage) { wizardTabControl.SelectedTab = shareTabPage1; _sender = shareTabPage1; } else if (_sender == shareTabPage1) { if (!ValidationManager.Validate(shareTabPage1)) { Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.", "All fields need to have a value.", PopupButtons.Ok); return; } if (!Path.IsPathRooted(projectOutputPathTextBox.Text)) { Popup.ShowPopup(this, SystemIcons.Error, "Invalid path.", "The given local path for the project is invalid.", PopupButtons.Ok); return; } try { string projectPath = Path.Combine(Program.Path, "Projects", projectsListBox.SelectedItem.ToString()); using (var zip = new ZipFile()) { string statisticsFilePath = Path.Combine(projectPath, "statistics.php"); if (File.Exists(statisticsFilePath)) { zip.AddFile(statisticsFilePath, "/"); } zip.AddFile( _projectConfigurations.First(item => item.Name == projectsListBox.SelectedItem.ToString()) .Path, "/"); foreach ( var versionDirectory in new DirectoryInfo(projectPath).GetDirectories() .Where(item => UpdateVersion.IsValid(item.Name))) { zip.AddDirectoryByName(versionDirectory.Name); zip.AddDirectory(versionDirectory.FullName, versionDirectory.Name); } zip.Save(projectOutputPathTextBox.Text); } } catch (Exception ex) { Popup.ShowPopup(this, SystemIcons.Error, "Error while sharing the project.", ex, PopupButtons.Ok); return; } Close(); } }
private void NewUpdateDialog_Load(object sender, EventArgs e) { if (!String.IsNullOrEmpty(LanguageFilePath)) { try { _lp = Serializer.Deserialize <LocalizationProperties>(File.ReadAllText(LanguageFilePath)); } catch (Exception) { _lp = new LocalizationProperties(); } } else if (String.IsNullOrEmpty(LanguageFilePath) && LanguageName != "en") { string resourceName = String.Format("nUpdate.Core.Localization.{0}.json", LanguageName); using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) { _lp = Serializer.Deserialize <LocalizationProperties>(stream); } } else if (String.IsNullOrEmpty(LanguageFilePath) && LanguageName == "en") { _lp = new LocalizationProperties(); } headerLabel.Text = String.Format(PackageConfigurations.Count() > 1 ? _lp.NewUpdateDialogMultipleUpdatesHeader : _lp.NewUpdateDialogSingleUpdateHeader, PackageConfigurations.Count()); infoLabel.Text = String.Format(_lp.NewUpdateDialogInfoText, Application.ProductName); var availableVersions = PackageConfigurations.Select(item => new UpdateVersion(item.LiteralVersion)).ToArray(); newestVersionLabel.Text = String.Format(_lp.NewUpdateDialogAvailableVersionsText, PackageConfigurations.Count() <= 2 ? String.Join(", ", availableVersions.Select(item => item.FullText)) : String.Format("{0} - {1}", UpdateVersion.GetLowestUpdateVersion(availableVersions).FullText, UpdateVersion.GetHighestUpdateVersion(availableVersions).FullText)); currentVersionLabel.Text = String.Format(_lp.NewUpdateDialogCurrentVersionText, CurrentVersion.FullText); changelogLabel.Text = _lp.NewUpdateDialogChangelogText; cancelButton.Text = _lp.CancelButtonText; installButton.Text = _lp.InstallButtonText; var size = SizeHelper.ConvertSize(PackageSize); updateSizeLabel.Text = String.Format("{0} {1}", String.Format(_lp.NewUpdateDialogSizeText, size.Item1), size.Item2); Icon = _appIcon; Text = Application.ProductName; iconPictureBox.Image = _appIcon.ToBitmap(); iconPictureBox.BackgroundImageLayout = ImageLayout.Center; foreach (var updateConfiguration in PackageConfigurations) { var versionText = new UpdateVersion(updateConfiguration.LiteralVersion).FullText; var changelogText = updateConfiguration.Changelog.ContainsKey(new CultureInfo(LanguageName)) ? updateConfiguration.Changelog.First(item => item.Key.Name == LanguageName).Value : updateConfiguration.Changelog.First(item => item.Key.Name == "en").Value; if (PackageSize > GB) { changelogTextBox.Text += _lp.NewUpdateDialogBigPackageWarning; } changelogTextBox.Text += String.Format(String.IsNullOrEmpty(changelogTextBox.Text) ? "{0}:\n{1}" : "\n\n{0}:\n{1}", versionText, changelogText); } AddShieldToButton(installButton); if (OperationAreas == null || OperationAreas.Count == 0) { accessLabel.Text = String.Format("{0} -", _lp.NewUpdateDialogAccessText); _allowCancel = true; return; } accessLabel.Text = String.Format("{0} {1}", _lp.NewUpdateDialogAccessText, String.Join(", ", LocalizationHelper.GetLocalizedEnumerationValues(_lp, OperationAreas.Cast <object>().GroupBy(item => item).Select(item => item.First()).ToArray()))); _allowCancel = true; }
/* The Reset-method is only used for the upload */ public void Reset() { UpdateVersion packageVersion = null; Invoke( new Action(() => packageVersion = new UpdateVersion(packagesList.SelectedItems[0].Tag.ToString()))); if (_commandsExecuted) { Invoke(new Action(() => loadingLabel.Text = "Connecting to MySQL-server...")); var connectionString = String.Format("SERVER={0};" + "DATABASE={1};" + "UID={2};" + "PASSWORD={3};", Project.SqlWebUrl, Project.SqlDatabaseName, Project.SqlUsername, SqlPassword.ConvertToUnsecureString()); var deleteConnection = new MySqlConnection(connectionString); try { deleteConnection.Open(); } catch (MySqlException ex) { Invoke( new Action( () => Popup.ShowPopup(this, SystemIcons.Error, "An MySQL-exception occured when trying to undo the SQL-insertions...", ex, PopupButtons.Ok))); deleteConnection.Close(); return; } catch (Exception ex) { Invoke( new Action( () => Popup.ShowPopup(this, SystemIcons.Error, "Error while connecting to the database when trying to undo the SQL-insertions...", ex, PopupButtons.Ok))); deleteConnection.Close(); SetUiState(true); return; } var command = deleteConnection.CreateCommand(); command.CommandText = String.Format("DELETE FROM `Version` WHERE `Version` = \"{0}\"", packageVersion); try { command.ExecuteNonQuery(); _commandsExecuted = false; } catch (Exception ex) { Invoke( new Action( () => Popup.ShowPopup(this, SystemIcons.Error, "Error while executing the commands when trying to undo the SQL-insertions...", ex, PopupButtons.Ok))); deleteConnection.Close(); } } if (_packageExisting) { Invoke( new Action( () => loadingLabel.Text = "Undoing package upload...")); try { _ftp.DeleteDirectory(String.Format("{0}/{1}", _ftp.Directory, packageVersion)); _packageExisting = false; } catch (Exception ex) { if (!ex.Message.Contains("No such file or directory")) { Invoke( new Action( () => Popup.ShowPopup(this, SystemIcons.Error, "Error while undoing the package upload.", ex, PopupButtons.Ok))); SetUiState(true); return; } _packageExisting = false; } } if (_configurationUploaded) { Invoke( new Action( () => loadingLabel.Text = "Uploading old configuration...")); string updateConfigurationFilePath = Path.Combine(Program.Path, "updates.json"); try { File.WriteAllText(updateConfigurationFilePath, Serializer.Serialize(_backupConfiguration)); } catch (Exception ex) { Invoke( new Action( () => Popup.ShowPopup(this, SystemIcons.Error, "Error while saving the old configuration.", ex, PopupButtons.Ok))); SetUiState(true); return; } 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))); SetUiState(true); return; } try { File.WriteAllText(updateConfigurationFilePath, String.Empty); } catch (Exception ex) { Invoke( new Action( () => Popup.ShowPopup(this, SystemIcons.Error, "Error while saving the local configuration.", ex, PopupButtons.Ok))); } } SetUiState(true); }
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); * }*/ } }
/// <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(); }
/// <summary> /// 一个版本升级完成后执行事件 /// </summary> /// <param name="result"></param> private void UpdateCallBack(IAsyncResult result) { UpdateVersion update = result.AsyncState as UpdateVersion; if (update != null) { if (update.UpdateServiceError != null) // 升级失败处理 { // 将继续升级按钮置为可用 this.btnResetState.Invoke(new MethodInvoker(delegate() { btnResetState.Enabled = true; })); string errorMessage = string.Format("【{0}】版本【{1}】升级失败,\r\n请修改升级文件,修改完后,请点击继续升级", update.Version, update.UpdateServiceError.Title); MessageBox.Show(errorMessage, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { lblTotalState.Invoke(new MethodInvoker(delegate() { lblTotalState.Text = string.Format("{0}{1}", _currentVersion, "升级完成"); })); if (_updateVersionsQueue.Count > 0) // 执行下一版本升级 { UpdateVersion nextUpdate = _updateVersionsQueue.Dequeue(); this._currentVersion = nextUpdate; if (MessageBox.Show(string.Format("{0}升级完成,请查看详细日志,是否继续升级?", update.Version), "提示", MessageBoxButtons.YesNo) == DialogResult.Yes) { // 继续升级下个 StartUpdate(nextUpdate); } else { // 暂停跟新下个版本 将继续升级按钮置为可用 this.btnResetState.Invoke(new MethodInvoker(delegate() { btnResetState.Enabled = true; })); } } else // 全部版本升级完成 { MessageBox.Show(string.Format("{0}升级完成,请查看详细日志", update.Version)); } } } }
private void NewUpdateDialog_Load(object sender, EventArgs e) { if (!String.IsNullOrEmpty(LanguageFilePath)) { try { _lp = Serializer.Deserialize<LocalizationProperties>(File.ReadAllText(LanguageFilePath)); } catch (Exception) { _lp = new LocalizationProperties(); } } else if (String.IsNullOrEmpty(LanguageFilePath) && LanguageName != "en") { string resourceName = String.Format("nUpdate.Core.Localization.{0}.json", LanguageName); using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) { _lp = Serializer.Deserialize<LocalizationProperties>(stream); } } else if (String.IsNullOrEmpty(LanguageFilePath) && LanguageName == "en") { _lp = new LocalizationProperties(); } headerLabel.Text = String.Format(PackageConfigurations.Count() > 1 ? _lp.NewUpdateDialogMultipleUpdatesHeader : _lp.NewUpdateDialogSingleUpdateHeader, PackageConfigurations.Count()); infoLabel.Text = String.Format(_lp.NewUpdateDialogInfoText, Application.ProductName); var availableVersions = PackageConfigurations.Select(item => new UpdateVersion(item.LiteralVersion)).ToArray(); newestVersionLabel.Text = String.Format(_lp.NewUpdateDialogAvailableVersionsText, PackageConfigurations.Count() <= 2 ? String.Join(", ", availableVersions.Select(item => item.FullText)) : String.Format("{0} - {1}", UpdateVersion.GetLowestUpdateVersion(availableVersions).FullText, UpdateVersion.GetHighestUpdateVersion(availableVersions).FullText)); currentVersionLabel.Text = String.Format(_lp.NewUpdateDialogCurrentVersionText, CurrentVersion.FullText); changelogLabel.Text = _lp.NewUpdateDialogChangelogText; cancelButton.Text = _lp.CancelButtonText; installButton.Text = _lp.InstallButtonText; var size = SizeHelper.ConvertSize(PackageSize); updateSizeLabel.Text = String.Format("{0} {1}", String.Format(_lp.NewUpdateDialogSizeText, size.Item1), size.Item2); Icon = _appIcon; Text = Application.ProductName; iconPictureBox.Image = _appIcon.ToBitmap(); iconPictureBox.BackgroundImageLayout = ImageLayout.Center; foreach (var updateConfiguration in PackageConfigurations) { var versionText = new UpdateVersion(updateConfiguration.LiteralVersion).FullText; var changelogText = updateConfiguration.Changelog.ContainsKey(new CultureInfo(LanguageName)) ? updateConfiguration.Changelog.First(item => item.Key.Name == LanguageName).Value : updateConfiguration.Changelog.First(item => item.Key.Name == "en").Value; if (PackageSize > GB) changelogTextBox.Text += _lp.NewUpdateDialogBigPackageWarning; changelogTextBox.Text += String.Format(String.IsNullOrEmpty(changelogTextBox.Text) ? "{0}:\n{1}" : "\n\n{0}:\n{1}", versionText, changelogText); } AddShieldToButton(installButton); if (OperationAreas == null || OperationAreas.Count == 0) { accessLabel.Text = String.Format("{0} -", _lp.NewUpdateDialogAccessText); _allowCancel = true; return; } accessLabel.Text = String.Format("{0} {1}", _lp.NewUpdateDialogAccessText, String.Join(", ", LocalizationHelper.GetLocalizedEnumerationValues(_lp, OperationAreas.Cast<object>().GroupBy(item => item).Select(item => item.First()).ToArray()))); _allowCancel = true; }
/// <summary> /// 开始升级 /// </summary> /// <param name="updateVersion"></param> private void StartUpdate(UpdateVersion updateVersion) { this._currentVersion = updateVersion; // 重新绑定升级时升级状态的变化事件 foreach (UCUpdateState ucUpdateState in _ucUpdateStates) { IUpdateService updateServiceService = ((List<IUpdateService>)updateVersion.CurrentService).Find(delegate(IUpdateService update) { return update.Title == ucUpdateState.Title; }); if (updateServiceService.State != UpdateState.Success && updateServiceService.State != UpdateState.AfterUpdate) { ucUpdateState.ResetPanelColor(); // 重置Panel 的色彩 } // 注册升级状态发生变化事件 控件颜色变化 updateServiceService.StateChange -= ucUpdateState.UpdateState; updateServiceService.StateChange += ucUpdateState.UpdateState; // 进度条信息变化 updateServiceService.StateChange -= UpdateServiceServiceStateChange; updateServiceService.StateChange += UpdateServiceServiceStateChange; } updateVersion.RegisterMessage(ShowMessage); // 注册消息事件 this.ShowMessage(string.Format("本次升级版本为:{0}", updateVersion.Version)); // 异步升级开始 new MethodInvoker(delegate() { updateVersion.BeginUpdate(); }).BeginInvoke(UpdateCallBack, updateVersion); }
public void CanGetCorrectReleaseCandidateVersionString() { var version = new UpdateVersion("1.2rc2"); Assert.AreEqual("1.2.0.0rc2", version.ToString()); }
public void CanConstructOneDigitAlphaVersionWithoutDevelopmentalStage() { var version = new UpdateVersion("1a"); Assert.AreEqual("1.0.0.0a", version.ToString()); }
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()); }
public void setLatestVersion(XmlElement element) { UpdateVersion test = UpdateVersion.getVersionFromXml(element); if(latest_version.CompareTo(test)>0) return; string latest_version_url; if(element.HasAttribute("url")) { latest_version_url = element.GetAttribute("url"); } else { throw new MException("Update XML Error","url attribute missing in " + name,true); } if (latest_version.CompareTo(test) < 0) { latest_version_urls = new List<string>(); latest_version_urls.Add(latest_version_url); latest_version = test; } NotifyPropertyChanged("latest_version_string"); }
private void createPackageButton_Click(object sender, EventArgs e) { if (_developmentalStage == DevelopmentalStage.Release) { _packageVersion = new UpdateVersion((int) majorNumericUpDown.Value, (int) minorNumericUpDown.Value, (int) buildNumericUpDown.Value, (int) revisionNumericUpDown.Value); } else { _packageVersion = new UpdateVersion((int) majorNumericUpDown.Value, (int) minorNumericUpDown.Value, (int) buildNumericUpDown.Value, (int) revisionNumericUpDown.Value, _developmentalStage, (int) developmentBuildNumericUpDown.Value); } if (_packageVersion.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 (ExistingVersions.Any(item => item == _packageVersion)) { Popup.ShowPopup(this, SystemIcons.Error, "Invalid version set.", String.Format( "Version \"{0}\" is already existing.", _packageVersion.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; } if (!filesDataTreeView.Nodes.Cast<TreeNode>().Any(node => node.Nodes.Count > 0) && categoryTreeView.Nodes[3].Nodes.Count <= 1) { Popup.ShowPopup(this, SystemIcons.Error, "No files and/or folders or operations set.", "Please specify some files and/or folders that should be included or operations into the package.", PopupButtons.Ok); filesPanel.BringToFront(); categoryTreeView.SelectedNode = categoryTreeView.Nodes[3].Nodes[0]; return; } foreach (var tabPage in from tabPage in categoryTabControl.TabPages.Cast<TabPage>().Where(item => item.TabIndex > 4) 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; } SetUiState(false); loadingPanel.Location = new Point(180, 91); loadingPanel.BringToFront(); loadingPanel.Visible = true; InitializePackage(); }
public void update() { string tmp_name = current_version_path.Substring(0,current_version_path.Length-3) + "TMP"; WebClient Client; Stream new_file; FileStream writer; Client = new WebClient(); updating = true; foreach(string latest_version_url in latest_version_urls) { try { new_file = Client.OpenRead(latest_version_url); writer = new FileStream(tmp_name,FileMode.Create,FileAccess.Write); int Length = 256; Byte [] buffer = new Byte[Length]; int bytesRead = new_file.Read(buffer,0,Length); while( bytesRead > 0 ) { writer.Write(buffer,0,bytesRead); bytesRead = new_file.Read(buffer,0,Length); } writer.Close(); new_file.Close(); XmlDocument game_config; try { game_config = Core.readXmlFile(tmp_name); } catch (InvalidOperationException ex) { MessageHandler.SendError("Error Downloading",latest_version_url + " is producing bad data.\nYou really should click Send Report so I can fix it.",ex); File.Delete(tmp_name); continue; } catch (XmlException ex) { MessageHandler.SendError("Error Downloading",latest_version_url + " is producing bad data.\nYou really should click Send Report so I can fix it.",ex); File.Delete(tmp_name); continue; } if(File.Exists(current_version_path)) File.Delete(current_version_path); File.Move(tmp_name,current_version_path); NotifyPropertyChanged("needs_update"); current_version = latest_version; break; } catch(WebException exception) { File.Delete(tmp_name); MessageHandler.SendError("Getting Old",name + " failed to download. Here's why:" + Environment.NewLine + latest_version_url,exception); } } updating = false; NotifyPropertyChanged("updating"); NotifyPropertyChanged("needs_updating"); NotifyPropertyChanged("current_version_string"); }
public static UpdateVersion CheckForUpdates() { const string GITHUB_RELEASES_API_URL = "https://api.github.com/repos/TV-Rename/tvrename/releases"; UpdateVersion currentVersion; System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; try { string currentVersionString = Helpers.DisplayVersion; bool inDebug = currentVersionString.EndsWith(" ** Debug Build **"); //remove debug stuff if (inDebug) { currentVersionString = currentVersionString.Substring(0, currentVersionString.LastIndexOf(" ** Debug Build **", StringComparison.Ordinal)); } currentVersion = new UpdateVersion(currentVersionString, UpdateVersion.VersionType.Friendly); } catch (ArgumentException e) { logger.Error("Failed to establish if there are any new releases as could not parse internal version: " + Helpers.DisplayVersion, e); return(null); } UpdateVersion latestVersion = null; UpdateVersion latestBetaVersion = null; try { WebClient client = new WebClient(); client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"); string response = client.DownloadString(GITHUB_RELEASES_API_URL); JArray gitHubInfo = JArray.Parse(response); foreach (JObject gitHubReleaseJSON in gitHubInfo.Children <JObject>()) { try { DateTime.TryParse(gitHubReleaseJSON["published_at"].ToString(), out DateTime releaseDate); UpdateVersion testVersion = new UpdateVersion(gitHubReleaseJSON["tag_name"].ToString(), UpdateVersion.VersionType.Semantic) { DownloadUrl = gitHubReleaseJSON["assets"][0]["browser_download_url"].ToString(), ReleaseNotesText = gitHubReleaseJSON["body"].ToString(), ReleaseNotesUrl = gitHubReleaseJSON["html_url"].ToString(), ReleaseDate = releaseDate, IsBeta = (gitHubReleaseJSON["prerelease"].ToString() == "True") }; //all versions want to be considered if you are in the beta stream if (testVersion.NewerThan(latestBetaVersion)) { latestBetaVersion = testVersion; } //If the latest version is a production one then update the latest production version if (!testVersion.IsBeta) { if (testVersion.NewerThan(latestVersion)) { latestVersion = testVersion; } } } catch (NullReferenceException ex) { logger.Warn("Looks like the JSON payload from GitHub has changed"); logger.Debug(ex, gitHubReleaseJSON.ToString()); continue; } catch (ArgumentOutOfRangeException ex) { logger.Debug("Generally happens because the release did not have an exe attached"); logger.Debug(ex, gitHubReleaseJSON.ToString()); continue; } } if (latestVersion == null) { logger.Error("Could not find latest version information from GitHub: {0}", response); return(null); } if (latestBetaVersion == null) { logger.Error("Could not find latest beta version information from GitHub: {0}", response); return(null); } } catch (Exception e) { logger.Error(e, "Failed to contact GitHub to identify new releases"); return(null); } if ((TVSettings.Instance.mode == TVSettings.BetaMode.ProductionOnly) && (latestVersion.NewerThan(currentVersion))) { return(latestVersion); } if ((TVSettings.Instance.mode == TVSettings.BetaMode.BetaToo) && (latestBetaVersion.NewerThan(currentVersion))) { return(latestBetaVersion); } return(null); }
public UpdateHandler(UpdateVersion current_version, string name, string path) : this(name,path) { this.current_version = current_version; }
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(); }
/// <summary> /// Initializes a new instance of the <see cref="UpdateManager" /> class. /// </summary> /// <param name="updateConfigurationFileUri">The URI of the update configuration file.</param> /// <param name="publicKey">The public key for the validity check of the update packages.</param> /// <param name="languageCulture">The language culture to use for the localization of the integrated UpdaterUI.</param> /// <remarks> /// The public key can be found in the overview of your project when you're opening it in nUpdate Administration. /// If you have problems inserting the data (or if you want to save time) you can scroll down there and follow the /// steps of the category "Copy data" which will automatically generate the necessray code for you. /// </remarks> public UpdateManager(Uri updateConfigurationFileUri, string publicKey, CultureInfo languageCulture) { if (updateConfigurationFileUri == null) throw new ArgumentNullException("updateConfigurationFileUri"); _updateConfigurationFileUri = updateConfigurationFileUri; if (String.IsNullOrEmpty(publicKey)) throw new ArgumentNullException("publicKey"); _publicKey = publicKey; if (languageCulture == null) throw new ArgumentNullException("languageCulture"); _languageCulture = languageCulture; CultureFilePaths = new Dictionary<CultureInfo, string>(); Arguments = new List<UpdateArgument>(); var projectAssembly = Assembly.GetCallingAssembly(); var nUpateVersionAttribute = projectAssembly.GetCustomAttributes(false).OfType<nUpdateVersionAttribute>().SingleOrDefault(); if (nUpateVersionAttribute == null) throw new ArgumentException( "The version string couldn't be loaded because the nUpdateVersionAttribute isn't implemented in the executing assembly."); CurrentVersion = new UpdateVersion(nUpateVersionAttribute.VersionString); var existingCultureInfos = new[] { new CultureInfo("en"), new CultureInfo("de-DE"), new CultureInfo("de-AT"), new CultureInfo("de-CH") }; if (!existingCultureInfos.Any(item => item.Equals(_languageCulture)) && !CultureFilePaths.ContainsKey(_languageCulture)) throw new ArgumentException( "The given culture info does neither exist in nUpdate's resources, nor in property \"CultureFilePaths\"."); if (UseCustomInstallerUserInterface && String.IsNullOrEmpty(CustomInstallerUiAssemblyPath)) throw new ArgumentException( "The property \"CustomInstallerUiAssemblyPath\" is not initialized although \"UseCustomInstallerUserInterface\" is set to \"true\""); Initialize(); }
private void MainForm_Load(object sender, EventArgs e) { addItems = new AddItems(addItemsMethod); updateVersion = new UpdateVersion(updateVersionMethod); }
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()); }
// This is the constructor for when reading the current data files public UpdateHandler(XmlElement element, string name, string path) : this(name,path) { current_version = UpdateVersion.getVersionFromXml(element); }
public void CanConstructFourDigitVersion() { var version = new UpdateVersion("1.0.0.0"); Assert.AreEqual("1.0.0.0", version.ToString()); }
protected UpdateHandler(String name) : base(name) { this.name = name; latest_version = new UpdateVersion(0, 0, 0); }
public void CanConstructTwoDigitVersion() { var version = new UpdateVersion("1.0"); Assert.AreEqual("1.0.0.0", version.ToString()); }
public bool NewerThan(UpdateVersion compare) => (CompareTo(compare) > 0);
private void PackageEditDialog_Load(object sender, EventArgs e) { Text = String.Format(Text, PackageVersion.FullText, Program.VersionString); try { _ftp = new FtpManager(Project.FtpHost, Project.FtpPort, Project.FtpDirectory, Project.FtpUsername, FtpPassword, Project.Proxy, Project.FtpUsePassiveMode, Project.FtpTransferAssemblyFilePath, Project.FtpProtocol); if (!String.IsNullOrWhiteSpace(Project.FtpTransferAssemblyFilePath)) _ftp.TransferAssemblyPath = Project.FtpTransferAssemblyFilePath; else _ftp.Protocol = (FtpSecurityProtocol)Project.FtpProtocol; } catch (Exception ex) { Popup.ShowPopup(this, SystemIcons.Error, "Error while loading the FTP-data.", ex, PopupButtons.Ok); Close(); return; } if (UpdateConfiguration == null) { Popup.ShowPopup(this, SystemIcons.Error, "Error while loading the configuration.", "There are no entries available in the configuration.", PopupButtons.Ok); Close(); return; } try { _packageConfiguration = UpdateConfiguration.First(item => item.LiteralVersion == PackageVersion.ToString()).DeepCopy(); } catch (InvalidOperationException) { Popup.ShowPopup(this, SystemIcons.Error, "Error while loading the configuration.", "There are no entries available for the current package in the configuration.", PopupButtons.Ok); Close(); return; } var packageVersion = new UpdateVersion(_packageConfiguration.LiteralVersion); majorNumericUpDown.Maximum = Decimal.MaxValue; minorNumericUpDown.Maximum = Decimal.MaxValue; buildNumericUpDown.Maximum = Decimal.MaxValue; revisionNumericUpDown.Maximum = Decimal.MaxValue; majorNumericUpDown.Value = packageVersion.Major; minorNumericUpDown.Value = packageVersion.Minor; buildNumericUpDown.Value = packageVersion.Build; revisionNumericUpDown.Value = packageVersion.Revision; _existingVersionString = _packageConfiguration.LiteralVersion; var devStages = Enum.GetValues(typeof (DevelopmentalStage)); Array.Reverse(devStages); developmentalStageComboBox.DataSource = devStages; developmentalStageComboBox.SelectedIndex = developmentalStageComboBox.FindStringExact(packageVersion.DevelopmentalStage.ToString()); developmentBuildNumericUpDown.Value = packageVersion.DevelopmentBuild; developmentBuildNumericUpDown.Enabled = (packageVersion.DevelopmentalStage != DevelopmentalStage.Release); architectureComboBox.SelectedIndex = (int) _packageConfiguration.Architecture; necessaryUpdateCheckBox.Checked = _packageConfiguration.NecessaryUpdate; includeIntoStatisticsCheckBox.Enabled = Project.UseStatistics; includeIntoStatisticsCheckBox.Checked = _packageConfiguration.UseStatistics; foreach (var package in Project.Packages.Where(package => new UpdateVersion(package.Version) == packageVersion)) { descriptionTextBox.Text = package.Description; } unsupportedVersionsListBox.DataSource = _unsupportedVersionLiteralsBindingList; var cultureInfos = CultureInfo.GetCultures(CultureTypes.AllCultures).ToList(); foreach (var info in cultureInfos) { changelogLanguageComboBox.Items.Add(String.Format("{0} - {1}", info.EnglishName, info.Name)); _cultures.Add(info); } changelogContentTabControl.TabPages[0].Tag = _cultures.Where(x => x.Name == "en"); changelogLanguageComboBox.SelectedIndex = changelogLanguageComboBox.FindStringExact("English - en"); foreach (var changelogDictionaryEntry in _packageConfiguration.Changelog) { var culture = changelogDictionaryEntry.Key; if (culture.Name != "en") { var page = new TabPage("Changelog") { BackColor = SystemColors.Window, Tag = culture }; page.Controls.Add(new ChangelogPanel {Changelog = changelogDictionaryEntry.Value}); changelogContentTabControl.TabPages.Add(page); } else { englishChangelogTextBox.Text = changelogDictionaryEntry.Value; } } categoryTreeView.SelectedNode = categoryTreeView.Nodes[0]; if (_packageConfiguration.UnsupportedVersions != null && _packageConfiguration.UnsupportedVersions.Count() != 0) { someVersionsRadioButton.Checked = true; unsupportedVersionsPanel.Enabled = true; foreach (var unsupportedVersionLiteral in _packageConfiguration.UnsupportedVersions) { _unsupportedVersionLiteralsBindingList.Add(unsupportedVersionLiteral); } } else { unsupportedVersionsPanel.Enabled = false; } foreach (var operation in _packageConfiguration.Operations) { switch (Operation.GetOperationTag(operation)) { case "DeleteFile": categoryTreeView.Nodes[3].Nodes.Add((TreeNode) _deleteNode.Clone()); var deletePage = new TabPage("Delete file") {BackColor = SystemColors.Window}; deletePage.Controls.Add(new FileDeleteOperationPanel { Path = operation.Value, ItemList = new BindingList<string>(((JArray) operation.Value2).ToObject<BindingList<string>>()) }); categoryTabControl.TabPages.Add(deletePage); break; case "RenameFile": categoryTreeView.Nodes[3].Nodes.Add((TreeNode) _renameNode.Clone()); var renamePage = new TabPage("Rename file") {BackColor = SystemColors.Window}; renamePage.Controls.Add(new FileRenameOperationPanel { Path = operation.Value, NewName = operation.Value2.ToString() }); categoryTabControl.TabPages.Add(renamePage); break; case "CreateRegistrySubKey": categoryTreeView.Nodes[3].Nodes.Add((TreeNode) _createRegistrySubKeyNode.Clone()); var createRegistrySubKeyPage = new TabPage("Create registry subkey") { BackColor = SystemColors.Window }; createRegistrySubKeyPage.Controls.Add(new RegistrySubKeyCreateOperationPanel { KeyPath = operation.Value, ItemList = new BindingList<string>(((JArray) operation.Value2).ToObject<BindingList<string>>()) }); categoryTabControl.TabPages.Add(createRegistrySubKeyPage); break; case "DeleteRegistrySubKey": categoryTreeView.Nodes[3].Nodes.Add((TreeNode) _deleteRegistrySubKeyNode.Clone()); var deleteRegistrySubKeyPage = new TabPage("Delete registry subkey") { BackColor = SystemColors.Window }; deleteRegistrySubKeyPage.Controls.Add(new RegistrySubKeyDeleteOperationPanel { KeyPath = operation.Value, ItemList = new BindingList<string>(((JArray) operation.Value2).ToObject<BindingList<string>>()) }); categoryTabControl.TabPages.Add(deleteRegistrySubKeyPage); break; case "SetRegistryValue": categoryTreeView.Nodes[3].Nodes.Add((TreeNode) _setRegistryValueNode.Clone()); var setRegistryValuePage = new TabPage("Set registry value") { BackColor = SystemColors.Window }; setRegistryValuePage.Controls.Add(new RegistrySetValueOperationPanel { KeyPath = operation.Value, NameValuePairs = ((JArray) operation.Value2).ToObject<List<Tuple<string, object, RegistryValueKind>>>() }); categoryTabControl.TabPages.Add(setRegistryValuePage); break; case "DeleteRegistryValue": categoryTreeView.Nodes[3].Nodes.Add((TreeNode) _deleteRegistryValueNode.Clone()); var deleteRegistryValuePage = new TabPage("Delete registry value") { BackColor = SystemColors.Window }; deleteRegistryValuePage.Controls.Add(new RegistryDeleteValueOperationPanel { KeyPath = operation.Value, ItemList = ((JObject) operation.Value2).ToObject<BindingList<string>>() }); categoryTabControl.TabPages.Add(deleteRegistryValuePage); break; case "StartProcess": categoryTreeView.Nodes[3].Nodes.Add((TreeNode) _startProcessNode.Clone()); var startProcessPage = new TabPage("Start process") {BackColor = SystemColors.Window}; startProcessPage.Controls.Add(new ProcessStartOperationPanel { Path = operation.Value, Arguments = ((JArray) operation.Value2).ToObject<BindingList<string>>() }); categoryTabControl.TabPages.Add(startProcessPage); break; case "TerminateProcess": categoryTreeView.Nodes[3].Nodes.Add((TreeNode) _terminateProcessNode.Clone()); var terminateProcessPage = new TabPage("Terminate process") {BackColor = SystemColors.Window}; terminateProcessPage.Controls.Add(new ProcessStopOperationPanel { ProcessName = operation.Value }); categoryTabControl.TabPages.Add(terminateProcessPage); break; case "StartService": categoryTreeView.Nodes[3].Nodes.Add((TreeNode) _startServiceNode.Clone()); var startServicePage = new TabPage("Start service") {BackColor = SystemColors.Window}; startServicePage.Controls.Add(new ServiceStartOperationPanel { ServiceName = operation.Value }); categoryTabControl.TabPages.Add(startServicePage); break; case "StopService": categoryTreeView.Nodes[3].Nodes.Add((TreeNode) _stopServiceNode.Clone()); var stopServicePage = new TabPage("Stop service") {BackColor = SystemColors.Window}; stopServicePage.Controls.Add(new ServiceStopOperationPanel { ServiceName = operation.Value }); categoryTabControl.TabPages.Add(stopServicePage); break; case "ExecuteScript": categoryTreeView.Nodes[3].Nodes.Add((TreeNode)_executeScriptNode.Clone()); var executeScriptPage = new TabPage("Execute script") { BackColor = SystemColors.Window }; executeScriptPage.Controls.Add(new ScriptExecuteOperationPanel { Code = operation.Value }); categoryTabControl.TabPages.Add(executeScriptPage); break; } } }
public static async Task <UpdateVersion> CheckForUpdatesAsync() { // ReSharper disable once InconsistentNaming const string GITHUB_RELEASES_API_URL = "https://api.github.com/repos/TV-Rename/tvrename/releases"; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; UpdateVersion currentVersion; try { currentVersion = ObtainCurrentVersion(); } catch (ArgumentException e) { Logger.Error("Failed to establish if there are any new releases as could not parse internal version: " + Helpers.DisplayVersion, e); return(null); } UpdateVersion latestVersion = null; UpdateVersion latestBetaVersion = null; try { WebClient client = new WebClient(); client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"); Task <string> response = client.DownloadStringTaskAsync(GITHUB_RELEASES_API_URL); JArray gitHubInfo = JArray.Parse(await response.ConfigureAwait(false)); foreach (JObject gitHubReleaseJson in gitHubInfo.Children <JObject>()) { try { if (!gitHubReleaseJson["assets"].HasValues) { continue; //we have no files for this release, so ignore } DateTime.TryParse(gitHubReleaseJson["published_at"].ToString(), out DateTime releaseDate); UpdateVersion testVersion = new UpdateVersion(gitHubReleaseJson["tag_name"].ToString(), UpdateVersion.VersionType.semantic) { DownloadUrl = gitHubReleaseJson["assets"][0]["browser_download_url"].ToString(), ReleaseNotesText = gitHubReleaseJson["body"].ToString(), ReleaseNotesUrl = gitHubReleaseJson["html_url"].ToString(), ReleaseDate = releaseDate, IsBeta = (gitHubReleaseJson["prerelease"].ToString() == "True") }; //all versions want to be considered if you are in the beta stream if (testVersion.NewerThan(latestBetaVersion)) { latestBetaVersion = testVersion; } //If the latest version is a production one then update the latest production version if (!testVersion.IsBeta) { if (testVersion.NewerThan(latestVersion)) { latestVersion = testVersion; } } } catch (NullReferenceException ex) { Logger.Warn("Looks like the JSON payload from GitHub has changed"); Logger.Debug(ex, gitHubReleaseJson.ToString()); } catch (ArgumentOutOfRangeException ex) { Logger.Debug("Generally happens because the release did not have an exe attached"); Logger.Debug(ex, gitHubReleaseJson.ToString()); } } if (latestVersion == null) { Logger.Error("Could not find latest version information from GitHub: {0}", response); return(null); } if (latestBetaVersion == null) { Logger.Error("Could not find latest beta version information from GitHub: {0}", response); return(null); } } catch (Exception e) { Logger.Error(e, "Failed to contact GitHub to identify new releases"); return(null); } if ((TVSettings.Instance.mode == TVSettings.BetaMode.ProductionOnly) && (latestVersion.NewerThan(currentVersion))) { return(latestVersion); } if ((TVSettings.Instance.mode == TVSettings.BetaMode.BetaToo) && (latestBetaVersion.NewerThan(currentVersion))) { return(latestBetaVersion); } return(null); }
private void NewUpdateDialog_Load(object sender, EventArgs e) { _lp = LocalizationHelper.GetLocalizationProperties(UpdateManager.LanguageCulture, UpdateManager.CultureFilePaths); headerLabel.Text = string.Format( UpdateManager.PackageConfigurations.Count() > 1 ? _lp.NewUpdateDialogMultipleUpdatesHeader : _lp.NewUpdateDialogSingleUpdateHeader, UpdateManager.PackageConfigurations.Count()); infoLabel.Text = string.Format(_lp.NewUpdateDialogInfoText, Application.ProductName); var availableVersions = UpdateManager.PackageConfigurations.Select(item => new UpdateVersion(item.LiteralVersion)).ToArray(); newestVersionLabel.Text = string.Format(_lp.NewUpdateDialogAvailableVersionsText, UpdateManager.PackageConfigurations.Count() <= 2 ? string.Join(", ", availableVersions.Select(item => item.FullText)) : $"{UpdateVersion.GetLowestUpdateVersion(availableVersions).FullText} - {UpdateVersion.GetHighestUpdateVersion(availableVersions).FullText}"); currentVersionLabel.Text = string.Format(_lp.NewUpdateDialogCurrentVersionText, UpdateManager.CurrentVersion.FullText); changelogLabel.Text = _lp.NewUpdateDialogChangelogText; cancelButton.Text = _lp.CancelButtonText; installButton.Text = _lp.InstallButtonText; var size = SizeHelper.ConvertSize((long)UpdateManager.TotalSize); updateSizeLabel.Text = $"{string.Format(_lp.NewUpdateDialogSizeText, size)}"; Icon = _appIcon; Text = Application.ProductName; iconPictureBox.Image = _appIcon.ToBitmap(); iconPictureBox.BackgroundImageLayout = ImageLayout.Center; foreach (var updateConfiguration in UpdateManager.PackageConfigurations) { var versionText = new UpdateVersion(updateConfiguration.LiteralVersion).FullText; var changelogText = updateConfiguration.Changelog.ContainsKey(UpdateManager.LanguageCulture) ? updateConfiguration.Changelog.First(item => Equals(item.Key, UpdateManager.LanguageCulture)).Value : updateConfiguration.Changelog.First(item => item.Key.Name == "en").Value; changelogTextBox.Text += string.Format(string.IsNullOrEmpty(changelogTextBox.Text) ? "{0}:\n{1}" : "\n\n{0}:\n{1}", versionText, changelogText); } AddShieldToButton(installButton); if (OperationAreas == null || OperationAreas.Count == 0) { accessLabel.Text = $"{_lp.NewUpdateDialogAccessText} -"; _allowCancel = true; return; } accessLabel.Text = $"{_lp.NewUpdateDialogAccessText} {string.Join(", ", LocalizationHelper.GetLocalizedEnumerationValues(_lp, OperationAreas.Cast<object>().GroupBy(item => item).Select(item => item.First()).ToArray()))}"; _allowCancel = true; }
private void uploadButton_Click(object sender, EventArgs e) { if (packagesList.SelectedItems.Count == 0) return; var version = new UpdateVersion((string) packagesList.SelectedItems[0].Tag); #pragma warning disable 4014 UploadPackage(version); #pragma warning restore 4014 }
private void PackageAddDialog_Load(object sender, EventArgs e) { Text = String.Format(Text, Project.Name, Program.VersionString); try { _ftp = new FtpManager(Project.FtpHost, Project.FtpPort, Project.FtpDirectory, Project.FtpUsername, FtpPassword, Project.Proxy, Project.FtpUsePassiveMode, Project.FtpTransferAssemblyFilePath, Project.FtpProtocol); _ftp.ProgressChanged += ProgressChanged; _ftp.CancellationFinished += CancellationFinished; if (!String.IsNullOrWhiteSpace(Project.FtpTransferAssemblyFilePath)) _ftp.TransferAssemblyPath = Project.FtpTransferAssemblyFilePath; else _ftp.Protocol = (FtpSecurityProtocol)Project.FtpProtocol; } catch (Exception ex) { Popup.ShowPopup(this, SystemIcons.Error, "Error while loading the FTP-data.", ex, PopupButtons.Ok); Close(); return; } _zip.ParallelDeflateThreshold = -1; _zip.UseZip64WhenSaving = Zip64Option.AsNecessary; _updateLog.Project = Project; categoryTreeView.Nodes[3].Nodes.Add(_replaceNode); categoryTreeView.Nodes[3].Toggle(); unsupportedVersionsListBox.DataSource = _unsupportedVersionLiteralsBindingList; var devStages = Enum.GetValues(typeof (DevelopmentalStage)); Array.Reverse(devStages); developmentalStageComboBox.DataSource = devStages; var cultureInfos = CultureInfo.GetCultures(CultureTypes.AllCultures).ToList(); foreach (var info in cultureInfos) { changelogLanguageComboBox.Items.Add(String.Format("{0} - {1}", info.EnglishName, info.Name)); _cultures.Add(info); } changelogContentTabControl.TabPages[0].Tag = _cultures.Where(x => x.Name == "en"); changelogLanguageComboBox.SelectedIndex = changelogLanguageComboBox.FindStringExact("English - en"); architectureComboBox.SelectedIndex = 2; categoryTreeView.SelectedNode = categoryTreeView.Nodes[0]; developmentalStageComboBox.SelectedIndex = 3; unsupportedVersionsPanel.Enabled = false; _publishUpdate = publishCheckBox.Checked; _necessaryUpdate = necessaryUpdateCheckBox.Checked; includeIntoStatisticsCheckBox.Enabled = Project.UseStatistics; majorNumericUpDown.Maximum = Decimal.MaxValue; minorNumericUpDown.Maximum = Decimal.MaxValue; buildNumericUpDown.Maximum = Decimal.MaxValue; revisionNumericUpDown.Maximum = Decimal.MaxValue; if (!String.IsNullOrEmpty(Project.AssemblyVersionPath)) { var projectAssembly = Assembly.GetCallingAssembly(); var nUpateVersionAttribute = projectAssembly.GetCustomAttributes(false).OfType<nUpdateVersionAttribute>().SingleOrDefault(); if (nUpateVersionAttribute == null) return; var assemblyVersion = new UpdateVersion(nUpateVersionAttribute.VersionString); majorNumericUpDown.Value = assemblyVersion.Major; minorNumericUpDown.Value = assemblyVersion.Minor; buildNumericUpDown.Value = assemblyVersion.Build; revisionNumericUpDown.Value = assemblyVersion.Revision; } generalTabPage.DoubleBuffer(); changelogTabPage.DoubleBuffer(); cancelToolTip.SetToolTip(cancelLabel, "Click here to cancel the package upload."); }
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(); }); }
public ChangelogViewModel(UpdateManager manager) { UpdateManager = manager; DoInstall = new RelayCommand(o => DoInstall_Execute(), o => true); Abort = new RelayCommand(o => Abort_Execute(), o => true); LocProperties = LocalizationHelper.GetLocalizationProperties(UpdateManager.LanguageCulture, UpdateManager.CultureFilePaths); Header = string.Format( UpdateManager.PackageConfigurations.Count() > 1 ? LocProperties.NewUpdateDialogMultipleUpdatesHeader : LocProperties.NewUpdateDialogSingleUpdateHeader, UpdateManager.PackageConfigurations.Count()); WindowIcon = GetIcon(_appIcon); WindowTitle = string.Format(LocProperties.NewUpdateDialogSingleUpdateHeader, UpdateManager.PackageConfigurations.Count()); InfoText = string.Format(LocProperties.NewUpdateDialogInfoText, Application.ProductName); var availableVersions = UpdateManager.PackageConfigurations.Select(item => new UpdateVersion(item.LiteralVersion)).ToArray(); AviableVersionText = string.Format(LocProperties.NewUpdateDialogAvailableVersionsText, UpdateManager.PackageConfigurations.Count() <= 2 ? string.Join(", ", availableVersions.Select(item => item.FullText)) : $"{UpdateVersion.GetLowestUpdateVersion(availableVersions).FullText} - {UpdateVersion.GetHighestUpdateVersion(availableVersions).FullText}"); CurrentVersionText = string.Format(LocProperties.NewUpdateDialogCurrentVersionText, UpdateManager.CurrentVersion.FullText); var size = SizeHelper.ConvertSize((long)UpdateManager.TotalSize); UpdateSizeText = $"{string.Format(LocProperties.NewUpdateDialogSizeText, size)}"; foreach (var updateConfiguration in UpdateManager.PackageConfigurations) { var versionText = new UpdateVersion(updateConfiguration.LiteralVersion).FullText; var changelogText = updateConfiguration.Changelog.ContainsKey(UpdateManager.LanguageCulture) ? updateConfiguration.Changelog.First(item => Equals(item.Key, UpdateManager.LanguageCulture)).Value : updateConfiguration.Changelog.First(item => item.Key.Name == "en").Value; ChangelogText += string.Format(string.IsNullOrEmpty(ChangelogText) ? "{0}:\n{1}" : "\n\n{0}:\n{1}", versionText, changelogText); } if (OperationAreas == null || OperationAreas.Count == 0) { AccessesText = $"{LocProperties.NewUpdateDialogAccessText} -"; return; } AccessesText = $"{LocProperties.NewUpdateDialogAccessText} {string.Join(", ", LocalizationHelper.GetLocalizedEnumerationValues(LocProperties, OperationAreas.Cast<object>().GroupBy(item => item).Select(item => item.First()).ToArray()))}"; }
private void CancellationFinished(object sender, EventArgs e) { UpdateVersion packageVersion = null; try { Invoke( new Action( () => packageVersion = new UpdateVersion((string)packagesList.SelectedItems[0].Tag))); _ftp.DeleteDirectory(String.Format("{0}/{1}", _ftp.Directory, packageVersion)); } catch (Exception deletingEx) { Invoke( new Action( () => Popup.ShowPopup(this, SystemIcons.Error, "Error while undoing the package upload.", deletingEx, PopupButtons.Ok))); } Reset(); _uploadCancelled = false; }
//кнопка редактирования и сохранения файлов private void button3_Click(object sender, EventArgs e) { UpdateVersion updateVersionForm = new UpdateVersion(); updateVersionForm.Show(); }
private async Task InitializeStatisticsData() { await Task.Factory.StartNew(() => { if (_dataGridViewRowTags.Count > 0) _dataGridViewRowTags.Clear(); Invoke( new Action( () => { statisticsDataGridView.Visible = false; gatheringStatisticsPictureBox.Visible = true; statisticsStatusLabel.Visible = true; statisticsStatusLabel.Text = "Gathering statistics..."; })); var connectionString = String.Format("SERVER={0};" + "DATABASE={1};" + "UID={2};" + "PASSWORD={3};", Project.SqlWebUrl, Project.SqlDatabaseName, Project.SqlUsername, SqlPassword.ConvertToUnsecureString()); _queryConnection = new MySqlConnection(connectionString); try { _queryConnection.Open(); } catch (MySqlException ex) { Invoke(new Action(() => { Popup.ShowPopup(this, SystemIcons.Error, "An MySQL-exception occured.", ex, PopupButtons.Ok); statisticsStatusLabel.Visible = true; statisticsStatusLabel.Text = "No downloads."; gatheringStatisticsPictureBox.Visible = false; })); _queryConnection.Close(); return; } catch (Exception ex) { Invoke(new Action(() => { Popup.ShowPopup(this, SystemIcons.Error, "Error while connecting to the database.", ex, PopupButtons.Ok); statisticsStatusLabel.Visible = true; statisticsStatusLabel.Text = "No downloads."; gatheringStatisticsPictureBox.Visible = false; })); _queryConnection.Close(); return; } var dataSet = new DataSet(); using (var dataAdapter = new MySqlDataAdapter( String.Format( "SELECT v.Version, COUNT(*) AS 'Downloads' FROM Download LEFT JOIN Version v ON (v.ID = Version_ID) WHERE `Application_ID` = {0} GROUP BY Version_ID;", Project.ApplicationId), _queryConnection)) { try { dataAdapter.Fill(dataSet); foreach (DataRow row in dataSet.Tables[0].Rows) { row[0] = new UpdateVersion(row.ItemArray[0].ToString()).FullText; } } catch (Exception ex) { Invoke(new Action(() => { Popup.ShowPopup(this, SystemIcons.Error, "Error while gathering the table entries of the database.", ex, PopupButtons.Ok); statisticsStatusLabel.Visible = true; statisticsStatusLabel.Text = "No downloads."; gatheringStatisticsPictureBox.Visible = false; })); _queryConnection.Close(); return; } } IEnumerable<UpdateConfiguration> updateConfiguration; try { updateConfiguration = UpdateConfiguration.Download(_configurationFileUrl, Project.Proxy) ?? Enumerable.Empty<UpdateConfiguration>(); } catch (Exception ex) { Invoke(new Action(() => { Popup.ShowPopup(this, SystemIcons.Error, "Error while downloading the configuration.", ex, PopupButtons.Ok); statisticsStatusLabel.Visible = true; statisticsStatusLabel.Text = "No downloads."; gatheringStatisticsPictureBox.Visible = false; })); _queryConnection.Close(); return; } string[] operatingSystemStrings = { "Windows Vista", "Windows 7", "Windows 8", "Windows 8.1", "Windows 10" }; const string commandString = "SELECT ((SELECT COUNT(OperatingSystem) FROM Download WHERE `Version_ID` = {0} AND `OperatingSystem` = \"{1}\") / (SELECT COUNT(OperatingSystem) FROM Download WHERE `Version_ID` = {0})*100)"; var updateConfigurationArray = updateConfiguration as UpdateConfiguration[] ?? updateConfiguration.ToArray(); foreach (var configuration in updateConfigurationArray) { var version = configuration.LiteralVersion; var statisticsChart = new StatisticsChart { Version = new UpdateVersion(configuration.LiteralVersion) }; foreach (var operatingSystemString in operatingSystemStrings) { string adjustedCommandString = String.Format(commandString, updateConfigurationArray.First(item => item.LiteralVersion == version.ToString()) .VersionId, operatingSystemString); var command = _queryConnection.CreateCommand(); command.CommandText = adjustedCommandString; MySqlDataReader reader = null; try { reader = command.ExecuteReader(); if (!reader.Read()) continue; var value = reader.GetValue(0); if (Convert.IsDBNull(value)) continue; var percentage = Convert.ToInt32(value, CultureInfo.InvariantCulture); switch (operatingSystemString) { case "Windows Vista": statisticsChart.WindowsVistaPercentage = percentage; break; case "Windows 7": statisticsChart.WindowsSevenPercentage = percentage; break; case "Windows 8": statisticsChart.WindowsEightPercentage = percentage; break; case "Windows 8.1": statisticsChart.WindowsEightPointOnePercentage = percentage; break; case "Windows 10": statisticsChart.WindowsTenPercentage = percentage; break; } } catch (MySqlException ex) { Invoke( new Action( () => Popup.ShowPopup(this, SystemIcons.Error, "An MySQL-exception occured.", ex, PopupButtons.Ok))); _queryConnection.Close(); return; } catch (Exception ex) { Invoke( new Action( () => Popup.ShowPopup(this, SystemIcons.Error, "Error while reading the SQL-data.", ex, PopupButtons.Ok))); _queryConnection.Close(); return; } finally { if (reader != null) reader.Close(); } } try { _dataGridViewRowTags.Add(new UpdateVersion(version), statisticsChart); } catch (InvalidOperationException) { // "continue"-statement would be unnecessary } } Invoke(new Action(() => { statisticsDataGridView.DataSource = dataSet.Tables[0]; statisticsDataGridView.Columns[0].Width = 278; statisticsDataGridView.Columns[1].Width = 278; lastUpdatedLabel.Text = String.Format("Last updated: {0}", DateTime.Now); gatheringStatisticsPictureBox.Visible = false; statisticsDataGridView.Visible = true; if (statisticsDataGridView.Rows.Count == 0) { statisticsStatusLabel.Visible = true; statisticsStatusLabel.Text = "No downloads."; } else statisticsStatusLabel.Visible = false; })); _queryConnection.Close(); _isSetByUser = true; }); }