/// <summary> /// Check if an update is available /// </summary> private bool UpdateCheck() { Result = new CheckUpdateResult(); try { // Read file WebClient client = new WebClient(); Stream stream = client.OpenRead(FileUrl); StreamReader reader = new StreamReader(stream); string content = reader.ReadToEnd(); // Create xml XmlDocument doc = new XmlDocument(); doc.LoadXml(content); // Get tag version XmlNodeList versionNode = doc.GetElementsByTagName("version"); if (versionNode.Count != 0) { Result.lastVersion = new Version(versionNode[0].InnerText); Result.currentVersion = new Version(ProductVersion); // Check versions if (Result.lastVersion > Result.currentVersion) { // Update available Result.needUpdate = true; // Get the download path XmlNodeList urlNode = doc.GetElementsByTagName("url"); if (urlNode.Count != 0) { Result.updateURL = urlNode[0].InnerText; } // Get the silent update path urlNode = doc.GetElementsByTagName("silent"); if (urlNode.Count != 0) { Result.silentUpdateURL = urlNode[0].InnerText; } // Get the filename urlNode = doc.GetElementsByTagName("name"); if (urlNode.Count != 0) { Result.filename = urlNode[0].InnerText; } } } } catch (Exception ex) { Result.errorOccured = true; Result.error = ex; return(false); } return(Result.NeedUpdate); }
public async Task <IReadOnlyList <CheckUpdateResult> > GetLatestVersionAsync(IEnumerable <IManagedTemplatePackage> packages, IManagedTemplatePackageProvider provider, CancellationToken cancellationToken) { _ = packages ?? throw new ArgumentNullException(nameof(packages)); return(await Task.WhenAll(packages.Select(async package => { if (package is NuGetManagedTemplatePackage nugetPackage) { try { (string latestVersion, bool isLatestVersion) = await _updateChecker.GetLatestVersionAsync(nugetPackage.Identifier, nugetPackage.Version, nugetPackage.NuGetSource, cancellationToken).ConfigureAwait(false); return CheckUpdateResult.CreateSuccess(package, latestVersion, isLatestVersion); } catch (PackageNotFoundException e) { return CheckUpdateResult.CreateFailure( package, InstallerErrorCode.PackageNotFound, string.Format(LocalizableStrings.NuGetInstaller_Error_FailedToReadPackage, e.PackageIdentifier, string.Join(", ", e.SourcesList))); } catch (InvalidNuGetSourceException e) { string message = e.SourcesList == null || !e.SourcesList.Any() ? LocalizableStrings.NuGetInstaller_InstallResut_Error_InvalidSources_None : string.Format(LocalizableStrings.NuGetInstaller_InstallResut_Error_InvalidSources, string.Join(", ", e.SourcesList)); return CheckUpdateResult.CreateFailure( package, InstallerErrorCode.InvalidSource, message); } catch (OperationCanceledException) { return CheckUpdateResult.CreateFailure( package, InstallerErrorCode.GenericError, LocalizableStrings.NuGetInstaller_InstallResut_Error_OperationCancelled); } catch (Exception e) { _logger.LogDebug($"Retrieving latest version for package {package.DisplayName} failed. Details: {e}."); return CheckUpdateResult.CreateFailure( package, InstallerErrorCode.GenericError, string.Format(LocalizableStrings.NuGetInstaller_InstallResut_Error_UpdateCheckGeneric, package.DisplayName, e.Message)); } } else { return CheckUpdateResult.CreateFailure( package, InstallerErrorCode.UnsupportedRequest, string.Format(LocalizableStrings.NuGetInstaller_InstallResut_Error_PackageNotSupported, package.DisplayName, Factory.Name)); } })).ConfigureAwait(false)); }
public async Task GetLatestVersion_Success() { MockInstallerFactory factory = new MockInstallerFactory(); MockManagedTemplatePackageProvider provider = new MockManagedTemplatePackageProvider(); IEngineEnvironmentSettings engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); FolderInstaller folderInstaller = new FolderInstaller(engineEnvironmentSettings, factory); FolderManagedTemplatePackage source = new FolderManagedTemplatePackage(engineEnvironmentSettings, folderInstaller, provider, Path.GetRandomFileName()); IReadOnlyList <CheckUpdateResult> results = await folderInstaller.GetLatestVersionAsync(new[] { source }, provider, CancellationToken.None).ConfigureAwait(false); Assert.Single(results); CheckUpdateResult result = results.Single(); Assert.True(result.Success); Assert.Equal(source, result.TemplatePackage); Assert.Equal(InstallerErrorCode.Success, result.Error); result.ErrorMessage.Should().BeNullOrEmpty(); result.LatestVersion.Should().BeNullOrEmpty(); Assert.True(result.IsLatestVersion); }
internal void DisplayUpdateCheckResult(CheckUpdateResult versionCheckResult, INewCommandInput commandInput) { _ = versionCheckResult ?? throw new ArgumentNullException(nameof(versionCheckResult)); _ = commandInput ?? throw new ArgumentNullException(nameof(commandInput)); if (versionCheckResult.Success) { if (!versionCheckResult.IsLatestVersion) { string displayString = $"{versionCheckResult.TemplatePackage.Identifier}::{versionCheckResult.TemplatePackage.Version}"; // the package::version currently installed Reporter.Output.WriteLine(string.Format(LocalizableStrings.TemplatePackageCoordinator_Update_Info_UpdateAvailable, displayString)); Reporter.Output.WriteLine(LocalizableStrings.TemplatePackageCoordinator_Update_Info_UpdateSingleCommandHeader); Reporter.Output.WriteCommand(commandInput.InstallCommandExample( packageID: versionCheckResult.TemplatePackage.Identifier, version: versionCheckResult.LatestVersion)); } } else { HandleUpdateCheckErrors(versionCheckResult); } }
public async Task <IReadOnlyList <CheckUpdateResult> > GetLatestVersionAsync(IEnumerable <IManagedTemplatePackage> packages, IManagedTemplatePackageProvider provider, CancellationToken cancellationToken) { _ = packages ?? throw new ArgumentNullException(nameof(packages)); return(await Task.WhenAll(packages.Select(async package => { if (package is NuGetManagedTemplatePackage nugetPackage) { try { (string latestVersion, bool isLatestVersion) = await _updateChecker.GetLatestVersionAsync(nugetPackage.Identifier, nugetPackage.Version, nugetPackage.NuGetSource, cancellationToken).ConfigureAwait(false); return CheckUpdateResult.CreateSuccess(package, latestVersion, isLatestVersion); } catch (PackageNotFoundException e) { return CheckUpdateResult.CreateFailure(package, InstallerErrorCode.PackageNotFound, e.Message); } catch (InvalidNuGetSourceException e) { return CheckUpdateResult.CreateFailure(package, InstallerErrorCode.InvalidSource, e.Message); } catch (OperationCanceledException) { return CheckUpdateResult.CreateFailure(package, InstallerErrorCode.GenericError, "Operation canceled"); } catch (Exception e) { _environmentSettings.Host.LogDiagnosticMessage($"Retrieving latest version for package {package.DisplayName} failed.", DebugLogCategory); _environmentSettings.Host.LogDiagnosticMessage($"Details:{e}", DebugLogCategory); return CheckUpdateResult.CreateFailure(package, InstallerErrorCode.GenericError, $"Failed to check the update for the package {package.Identifier}, reason: {e.Message}"); } } else { return CheckUpdateResult.CreateFailure(package, InstallerErrorCode.UnsupportedRequest, $"package {package.Identifier} is not supported by installer {Factory.Name}"); } })).ConfigureAwait(false)); }
private async Task <CheckUpdateResult> CheckUpdateAsync(bool enforce = false, bool forSuppress = false) { var curVersion = SmartStoreVersion.CurrentFullVersion; var lang = _services.WorkContext.WorkingLanguage.UniqueSeoCode; var cacheKeyPattern = "Common.CheckUpdateResult"; var cacheKey = "{0}.{1}".FormatInvariant(cacheKeyPattern, lang); if (enforce) { _services.Cache.RemoveByPattern(cacheKeyPattern); } var result = await _services.Cache.Get(cacheKey, async() => { var noUpdateResult = new CheckUpdateResult { UpdateAvailable = false, LanguageCode = lang, CurrentVersion = curVersion }; try { string url = "http://dlm.smartstore.com/api/v1/apprelease/CheckUpdate?app=SMNET&version={0}&language={1}".FormatInvariant(curVersion, lang); using (var client = new HttpClient()) { client.Timeout = TimeSpan.FromMilliseconds(3000); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.UserAgent.ParseAdd("SmartStore.NET {0}".FormatInvariant(curVersion)); client.DefaultRequestHeaders.Add("Authorization-Key", _services.StoreContext.CurrentStore.Url.TrimEnd('/')); HttpResponseMessage response = await client.GetAsync(url); if (response.StatusCode != HttpStatusCode.OK) { return(noUpdateResult); } var jsonStr = await response.Content.ReadAsStringAsync(); var model = JsonConvert.DeserializeObject <CheckUpdateResult>(jsonStr); model.UpdateAvailable = true; model.CurrentVersion = curVersion; model.LanguageCode = lang; if (CommonHelper.IsDevEnvironment || !_commonSettings.Value.AutoUpdateEnabled || !_services.Permissions.Authorize(StandardPermissionProvider.ManageMaintenance)) { model.AutoUpdatePossible = false; } // don't show message if user decided to suppress it var suppressKey = "SuppressUpdateMessage.{0}.{1}".FormatInvariant(curVersion, model.Version); if (enforce) { // but ignore user's decision if 'enforce' _genericAttributeService.SaveAttribute <bool?>(_services.WorkContext.CurrentCustomer, suppressKey, null); } var showMessage = enforce || _services.WorkContext.CurrentCustomer.GetAttribute <bool?>(suppressKey, _genericAttributeService).GetValueOrDefault() == false; if (!showMessage) { return(noUpdateResult); } return(model); } } catch (Exception ex) { Logger.Error("An error occurred while checking for update", ex); return(noUpdateResult); } }, 1440 /* 24h * 60min. */); return(result); }
private async void FrmMain_Load(object sender, EventArgs e) { await SafeExecutionContext.ExecuteAsync( this, async () => { this.lblTitle.Text = string.Empty; this.lblDatePublished.Text = string.Empty; this.htmlEditor.Html = EmptyContent; this.htmlEditor.Enabled = false; if (this.mnuSaveAs != null) { this.mnuSaveAs.Enabled = false; } var desktopClientService = new DesktopClientService(this.settings); this.checkUpdateResult = await desktopClientService.CheckUpdateAsync(); this.slblUpdateAvailable.Visible = this.checkUpdateResult.HasUpdate; await this.LoadNotesAsync(); }, () => { this.slblStatus.Text = Resources.Loading; this.sp.Visible = true; }, () => this.sp.Visible = false); }
public Task <IReadOnlyList <CheckUpdateResult> > GetLatestVersionAsync(IEnumerable <IManagedTemplatePackage> packages, IManagedTemplatePackageProvider provider, CancellationToken cancellationToken) { _ = packages ?? throw new ArgumentNullException(nameof(packages)); return(Task.FromResult <IReadOnlyList <CheckUpdateResult> >(packages.Select(s => CheckUpdateResult.CreateSuccess(s, null, true)).ToList())); }