public static void CheckUpdateStatus(string url,string xmlFileName,string zipFileName) { Ezhu.AutoUpdater.Lib.Constants.RemoteUrl = url; Ezhu.AutoUpdater.Lib.Constants.XmlFileName = xmlFileName; Ezhu.AutoUpdater.Lib.Constants.ZipFileName = zipFileName; System.Threading.ThreadPool.QueueUserWorkItem((s) => { var client = new System.Net.WebClient(); client.DownloadDataCompleted += (x, y) => { try { MemoryStream stream = new MemoryStream(y.Result); XDocument xDoc = XDocument.Load(stream); UpdateInfo updateInfo = new UpdateInfo(); XElement root = xDoc.Element("UpdateInfo"); updateInfo.AppName = root.Element("AppName").Value; updateInfo.AppVersion = root.Element("AppVersion").Value; updateInfo.RequiredMinVersion = root.Element("RequiredMinVersion").Value; updateInfo.Desc = root.Element("Desc").Value; updateInfo.MD5 = Guid.NewGuid().ToString(); updateInfo.UrlZip = Ezhu.AutoUpdater.Lib.Constants.RemoteUrl + Ezhu.AutoUpdater.Lib.Constants.ZipFileName; stream.Close(); Updater.Instance.StartUpdate(updateInfo); } catch { } }; client.DownloadDataAsync(new Uri(Ezhu.AutoUpdater.Lib.Constants.RemoteUrl + Ezhu.AutoUpdater.Lib.Constants.XmlFileName)); }); }
protected override void BuilderFailed(AuProject project, Exception exception, UpdateInfo resultUpdateInfo) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("更新项目构建失败:" + exception.Message); Console.ResetColor(); base.BuilderFailed(project, exception, resultUpdateInfo); }
public MainWindow() { m_UpdateInfo += new UpdateInfo(InitOnLoad); InitializeComponent(); Loaded += InitOnLoad; m_Manager = new GroceryManager(); this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen; }
static void GetResults(UpdateInfo[] updates) { int debug = 0; if(updates == null) debug= 0; foreach (ArchVision.Beacon.UpdateInfo update in updates) { Console.WriteLine(update.ToString()); } }
public void DoUpdate_ChangesTheCurrentVersion() { string newVersion = "2.6.8"; UpdateInfo updateInfo = new UpdateInfo(true, newVersion); updateServer.Stub(x => x.GetManifest(newVersion)).Return(new VersionManifest(newVersion, new VersionManifestFile[0])); localStructureManager.Stub(x => x.LoadManifest(initialVersion)).Return(new VersionManifest(initialVersion, new VersionManifestFile[0])); updateManager.DoUpdate(updateInfo); Assert.That(updateManager.CurrentVersion, Is.EqualTo(newVersion)); }
public static void Download(UpdateInfo updateInfo, out string fileName) { string folder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\"; Directory.CreateDirectory(folder); fileName = folder + updateInfo.Name; using (WebClient webClient = new WebClient()) { webClient.DownloadFile(updateInfo.Url, fileName); } }
/// <summary> /// Checks if there are any updates available for the application. /// </summary> /// <returns>A UpdateHelper.UpdateInfo representing the received update data.</returns> public static UpdateInfo CheckUpdates() { try { updateData = null; WebClient downloader = new WebClient(); string[] update = downloader.DownloadString(updateCheckUrl).Split(';'); if (update.Length >= 2) { updateData = new UpdateInfo(); updateData.UpdateVersion = update[0]; updateData.UpdateUrl = update[1]; string[] current = AssemblyHelper.Version.Split('.'); string[] latest = update[0].Split('.'); if (latest.Length == current.Length) { bool validNumber = true; int[] latestVersion = new int[latest.Length]; for (int i = 0; i < latest.Length; i++) validNumber &= Int32.TryParse(latest[i], out latestVersion[i]); if (validNumber) { int[] currentVersion = new int[current.Length]; for (int i = 0; i < current.Length; i++) Int32.TryParse(current[i], out currentVersion[i]); for (int i = 0; i < currentVersion.Length; i++) { if (latestVersion[i] > currentVersion[i]) { updateData.IsUpdateAvailable = true; break; } } } } } return updateData; } catch (Exception ex) { ExceptionHandler.LogException(ex); return updateData; } }
public static string LatestInstallationPath(this UpdateManager updateManager, UpdateInfo updateInfo) { var installationFolder = new DirectoryInfo(Path.Combine(updateManager.PackageDirectory, @"..\")); const string ApplicationPrefix = "app-"; var version = updateInfo.FutureReleaseEntry != null ? updateInfo.FutureReleaseEntry.Version : updateInfo.CurrentlyInstalledVersion.Version; var latestInstallationPath = Path.Combine(installationFolder.FullName, string.Concat(ApplicationPrefix, version.ToString())); return latestInstallationPath; }
public ShimmerInstaller(ShimmerConfiguration configuration) { var urlOrPath = configuration.UrlOrPath; var applicationName = configuration.ApplicationName; var frameworkVersion = configuration.FrameworkVersion; updateManager = new UpdateManager(urlOrPath, applicationName, frameworkVersion); updateInfo = updateManager.CheckForUpdate().Wait(); UpdatesAvailable = updateInfo.ReleasesToApply.Any(); InstallationPath = updateManager.LatestInstallationPath(updateInfo); }
private void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { try { Stream data = e.Result; StreamReader httpReader = new StreamReader(data); string xml = httpReader.ReadToEnd(); data.Close(); httpReader.Close(); XmlSerializer xmlReader = new XmlSerializer(typeof(VersionInfo)); StringReader stringReader = new StringReader(xml); VersionInfo versionInfo = (VersionInfo)xmlReader.Deserialize(stringReader); MainModule = (UpdateInfo)Xml.CheckIfNull(typeof(UpdateInfo), versionInfo.MainModule, MainModule); stringReader.Close(); } catch (Exception ex) { if (showMsg) System.Windows.Forms.MessageBox.Show("Unable to connect to server:\n\n" + ex.Message, "Update", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { ((WebClient)sender).Dispose(); } // Check modules for new versions List<Modules> newUpdates = new List<Modules>(); // Check MainModule version if (new Version(MainModule.LatestVersion).CompareTo(MainModule.CurrentVersion) > 0 && MainModule.Urls.Count > 0) newUpdates.Add(Modules.MainModule); // If any module has an update if (newUpdates.Count > 0) { if (showMsg) { UpdateForm form = new UpdateForm(this); DialogResult result = form.ShowDialog(); if (result == DialogResult.Yes) Update(); } if (UpdateAvailableEvent != null) UpdateAvailableEvent(this, new UpdateEventArgs(newUpdates)); } else { if (showMsg) MessageBox.Show("No update available. You already have the latest version (" + MainModule.CurrentVersion.ToString() + ").", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public static bool IsAvailable(out UpdateInfo updateInfo) { System.Net.ServicePointManager.Expect100Continue = false; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(HttpUpdateUrl); request.Method = "GET"; string responseString; using (WebResponse response = request.GetResponse()) { using (StreamReader responseReader = new StreamReader(response.GetResponseStream())) { responseString = responseReader.ReadToEnd(); } } updateInfo = Helper.XmlDeserialize<UpdateInfo>(responseString); return CompareVersion(updateInfo.Version, CurrentVersion) > 0; }
protected override void BuildSuccess(AuProject project, Dictionary<string, string> packages, UpdateInfo resultUpdateInfo) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("更新项目构建成功"); Console.WriteLine("==============================="); Console.ForegroundColor = ConsoleColor.Yellow; var index = 0; foreach (var package in packages) { Console.WriteLine("[{0:#0000}] {1} {2}", ++index, package.Key, package.Value); } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("==============================="); Console.WriteLine("已构建 {0} 个包。", packages.Count); Console.ResetColor(); base.BuildSuccess(project, packages, resultUpdateInfo); }
public static UpdateInfo.Update_InfoRow ReadUpdateInfoFile(string path) { //read saved settings file if (File.Exists(path)) { using (UpdateInfo ui = new UpdateInfo()) { ui.ReadXml(path); if (ui.Update_Info.Rows.Count > 0) return ui.Update_Info.First(); else return null; } } else { return null; } }
private void btnSave_Click(object sender, RoutedEventArgs e) { try { var files = System.IO.Directory.GetFiles(txtDir.Text, "随身袋.exe"); if (files.Length == 1) { System.Diagnostics.FileVersionInfo fv = System.Diagnostics.FileVersionInfo.GetVersionInfo(System.IO.Path.GetFullPath(files[0])); var asmTitle = fv.ProductName; var asmVer = fv.ProductVersion; txtAppName.Text = asmTitle; txtCVer.Text = asmVer; System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.GetFullPath(files[0])); txtUpdateTime.Text = file.LastWriteTime.ToShortDateString(); } txtDes.Text = System.IO.File.ReadAllText((@"..\..\..\随身袋\bin\Release\CarryBag\使用说明.txt")); System.IO.File.Delete("update.zip"); ICCEmbedded.SharpZipLib.Zip.FastZipEvents evt = new ICCEmbedded.SharpZipLib.Zip.FastZipEvents(); ICCEmbedded.SharpZipLib.Zip.FastZip fz = new ICCEmbedded.SharpZipLib.Zip.FastZip(evt); fz.CreateZip("update.zip", txtDir.Text, true, ""); System.IO.FileInfo file2 = new System.IO.FileInfo(System.IO.Path.GetFullPath("update.zip")); txtPackageSize.Text = file2.Length.ToString(); UpdateInfo uinfo = new UpdateInfo(); uinfo.AppName = txtAppName.Text; uinfo.AppVersion = txtCVer.Text; uinfo.Desc = txtDes.Text; uinfo.RequiredMinVersion = txtMinVer.Text; uinfo.PackageName = txtPackageName.Text; uinfo.PackageSize = txtPackageSize.Text; uinfo.UpdateTime = txtUpdateTime.Text; EasyFramework.Serialize.XMLHelper.Serialize("update.xml", uinfo); } catch { } }
public static void DownloadAsync(UpdateInfo updateInfo, object state, DownloadComplete complete) { new Thread(new ThreadStart(() => { try { string fileName; Download(updateInfo, out fileName); if (complete != null) { complete(fileName, state, null); } } catch (Exception e) { if (complete != null) { complete(null, state, e); } } })).Start(); }
public static UpdateInfo CheckFromUpdates() { UpdateInfo info = new UpdateInfo(); info.ThisInternalVersion = ConfigurationHelper.GetInternalVersionString(); info.ThisVersion = ConfigurationHelper.GetVersionString(); info.UpdateAvailable = false; Configuration config; config = ConfigurationHelper.GetConfiguration(ConfigurationKey.CheckForUpdates); if (Convert.ToInt32(config.Value) == 0) { return info; } else if (Convert.ToInt32(config.Value) == 1) { if (!IsConnectedToInternet()) return info; XmlDocument doc = new XmlDocument(); try { doc.Load(@"http://ptm.sourceforge.net/info.xml"); info.CurrentVersion = doc.SelectSingleNode(@"/root/CurrentVersion").InnerText; info.CurrentInternalVersion = doc.SelectSingleNode(@"/root/CurrentInternalVersion").InnerText; if (string.CompareOrdinal(info.CurrentInternalVersion, info.ThisInternalVersion) > 0) { info.UpdateAvailable = true; } } catch (Exception ex) { //do nothing Logger.WriteException(ex); } } return info; }
public void DoUpdate_SavesTheLastValidVersionAsTheExecutingBeingExecuted() { string versionBeingExecuted = initialVersion; string newVersion = "2.6.8"; UpdateInfo updateInfo = new UpdateInfo(true, newVersion); updateServer.Stub(x => x.GetManifest(newVersion)).Return(new VersionManifest(newVersion, new VersionManifestFile[0])); localStructureManager.Stub(x => x.GetCurrentVersion()).Return("2.0.0"); localStructureManager.Stub(x => x.LoadManifest(initialVersion)).Return(new VersionManifest(initialVersion, new VersionManifestFile[0])); updateManager.DoUpdate(updateInfo); localStructureManager.AssertWasCalled(x => x.SetLastValidVersion(versionBeingExecuted)); }
private void OnDownloadSuccess(object sender, DownloadSuccessEventArgs e) { UpdateInfo updateInfo = e.UserData as UpdateInfo; if (updateInfo == null) { return; } using (FileStream fileStream = new FileStream(e.DownloadPath, FileMode.Open, FileAccess.ReadWrite)) { bool zip = (updateInfo.Length != updateInfo.ZipLength || updateInfo.HashCode != updateInfo.ZipHashCode); int length = (int)fileStream.Length; if (length != updateInfo.ZipLength) { fileStream.Close(); string errorMessage = Utility.Text.Format("Resource zip length error, need '{0}', downloaded '{1}'.", updateInfo.ZipLength.ToString(), length.ToString()); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } if (zip) { fileStream.Position = 0L; int hashCode = Utility.Verifier.GetCrc32(fileStream); if (hashCode != updateInfo.ZipHashCode) { fileStream.Close(); string errorMessage = Utility.Text.Format("Resource zip hash code error, need '{0}', downloaded '{1}'.", updateInfo.ZipHashCode.ToString(), hashCode.ToString()); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } if (m_ResourceManager.m_DecompressCachedStream == null) { m_ResourceManager.m_DecompressCachedStream = new MemoryStream(); } try { fileStream.Position = 0L; m_ResourceManager.m_DecompressCachedStream.Position = 0L; m_ResourceManager.m_DecompressCachedStream.SetLength(0L); if (!Utility.Zip.Decompress(fileStream, m_ResourceManager.m_DecompressCachedStream)) { fileStream.Close(); string errorMessage = Utility.Text.Format("Unable to decompress resource '{0}'.", e.DownloadPath); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } if (m_ResourceManager.m_DecompressCachedStream.Length != updateInfo.Length) { fileStream.Close(); string errorMessage = Utility.Text.Format("Resource length error, need '{0}', downloaded '{1}'.", updateInfo.Length.ToString(), m_ResourceManager.m_DecompressCachedStream.Length.ToString()); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } fileStream.Position = 0L; fileStream.SetLength(0L); fileStream.Write(m_ResourceManager.m_DecompressCachedStream.GetBuffer(), 0, (int)m_ResourceManager.m_DecompressCachedStream.Length); } catch (Exception exception) { fileStream.Close(); string errorMessage = Utility.Text.Format("Unable to decompress resource '{0}' with error message '{1}'.", e.DownloadPath, exception.ToString()); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } finally { m_ResourceManager.m_DecompressCachedStream.Position = 0L; m_ResourceManager.m_DecompressCachedStream.SetLength(0L); } } else { int hashCode = 0; fileStream.Position = 0L; if (updateInfo.LoadType == LoadType.LoadFromMemoryAndQuickDecrypt || updateInfo.LoadType == LoadType.LoadFromMemoryAndDecrypt) { Utility.Converter.GetBytes(updateInfo.HashCode, m_CachedHashBytes); if (updateInfo.LoadType == LoadType.LoadFromMemoryAndQuickDecrypt) { hashCode = Utility.Verifier.GetCrc32(fileStream, m_CachedHashBytes, Utility.Encryption.QuickEncryptLength); } else if (updateInfo.LoadType == LoadType.LoadFromMemoryAndDecrypt) { hashCode = Utility.Verifier.GetCrc32(fileStream, m_CachedHashBytes, length); } Array.Clear(m_CachedHashBytes, 0, CachedHashBytesLength); } else { hashCode = Utility.Verifier.GetCrc32(fileStream); } if (hashCode != updateInfo.HashCode) { fileStream.Close(); string errorMessage = Utility.Text.Format("Zip hash code error, need '{0}', downloaded '{1}'.", updateInfo.ZipHashCode.ToString(), hashCode.ToString()); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } } } m_UpdatingCount--; if (m_ResourceManager.m_ResourceInfos.ContainsKey(updateInfo.ResourceName)) { throw new GameFrameworkException(Utility.Text.Format("Resource info '{0}' is already exist.", updateInfo.ResourceName.FullName)); } m_ResourceManager.m_ResourceInfos.Add(updateInfo.ResourceName, new ResourceInfo(updateInfo.ResourceName, updateInfo.LoadType, updateInfo.Length, updateInfo.HashCode, false)); if (m_ResourceManager.m_ReadWriteResourceInfos.ContainsKey(updateInfo.ResourceName)) { throw new GameFrameworkException(Utility.Text.Format("Read-write resource info '{0}' is already exist.", updateInfo.ResourceName.FullName)); } m_ResourceManager.m_ReadWriteResourceInfos.Add(updateInfo.ResourceName, new ReadWriteResourceInfo(updateInfo.LoadType, updateInfo.Length, updateInfo.HashCode)); m_CurrentGenerateReadWriteListLength += updateInfo.ZipLength; if (m_UpdatingCount <= 0 || m_CurrentGenerateReadWriteListLength >= m_GenerateReadWriteListLength) { m_CurrentGenerateReadWriteListLength = 0; GenerateReadWriteList(); } if (ResourceUpdateSuccess != null) { ResourceUpdateSuccess(updateInfo.ResourceName, e.DownloadPath, e.DownloadUri, updateInfo.Length, updateInfo.ZipLength); } }
public void DoUpdate_ExecutesTheUpdate() { string newVersion = "2.6.8"; UpdateInfo updateInfo = new UpdateInfo(true, newVersion); updateServer.Stub(x => x.GetManifest(newVersion)).Return(new VersionManifest(newVersion, new VersionManifestFile[0])); localStructureManager.Stub(x => x.LoadManifest(initialVersion)).Return(new VersionManifest(initialVersion, new VersionManifestFile[0])); updateManager.DoUpdate(updateInfo); updaterChef.AssertWasCalled(x => x.Cook(Arg<UpdateRecipe>.Is.Anything)); }
private async void StartBackgroundUpdate() { if (this.State != UpdateState.NotStarted && this.State != UpdateState.Failed && this.State != UpdateState.UpToDate) { // Can only start updates from certain states. return; } this.State = UpdateState.DownloadingInfo; this.updateDownloadCancellationTokenSource = new CancellationTokenSource(); await Task.Run(async() => { try { UpdateInfo updateInfo = await GetUpdateInfoAsync(CommonUtilities.Beta).ConfigureAwait(false); if (updateInfo == null) { this.State = UpdateState.Failed; this.logger.Log("Update download failed. Unable to get update info."); return; } Version updateVersion = updateInfo.LatestVersion; this.LatestVersion = updateVersion; if (updateVersion > Utilities.CurrentVersion) { // If an update is reported to be ready but the installer doesn't exist, clear out all the // installer info and redownload. string updateInstallerLocation = Config.UpdateInstallerLocation; if (updateInstallerLocation != string.Empty && !File.Exists(updateInstallerLocation)) { using (SQLiteTransaction transaction = Database.ThreadLocalConnection.BeginTransaction()) { ClearUpdateMetadata(); transaction.Commit(); } this.logger.Log("Downloaded update (" + updateInstallerLocation + ") could not be found. Re-downloading it."); } // If we have an installer downloaded, but there's a newer one out, clear out the downloaded update metadata if (Config.UpdateInstallerLocation != string.Empty && Version.TryParse(Config.UpdateVersion, out Version downloadedUpdateVersion) && downloadedUpdateVersion.FillInWithZeroes() < updateVersion.FillInWithZeroes()) { using (SQLiteTransaction transaction = Database.ThreadLocalConnection.BeginTransaction()) { ClearUpdateMetadata(); transaction.Commit(); } } // If we have not finished the download update yet, start/resume the download. if (Config.UpdateInstallerLocation == string.Empty) { string updateVersionText = updateVersion.ToShortString(); if (CommonUtilities.Beta) { updateVersionText += " Beta"; } string newVersionStartedMessage = string.Format(MainRes.NewVersionDownloadStartedStatus, updateVersionText); this.logger.Log(newVersionStartedMessage); DispatchUtilities.BeginInvoke(() => { this.logger.ShowStatus(newVersionStartedMessage); }); this.State = UpdateState.DownloadingInstaller; this.UpdateDownloadProgressFraction = 0; string downloadLocation = updateInfo.DownloadUrl; string changelogLink = updateInfo.ChangelogUrl; string installerFileName = Path.GetFileName(downloadLocation); string installerFilePath = Path.Combine(Utilities.UpdatesFolder, installerFileName); Stream responseStream = null; FileStream fileStream = null; try { ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, downloadLocation); long bytesProgressTotal = 0; if (File.Exists(installerFilePath)) { var fileInfo = new FileInfo(installerFilePath); request.Headers.Range = new RangeHeaderValue(fileInfo.Length, null); bytesProgressTotal = fileInfo.Length; fileStream = new FileStream(installerFilePath, FileMode.Append, FileAccess.Write, FileShare.None); } else { fileStream = new FileStream(installerFilePath, FileMode.Create, FileAccess.Write, FileShare.None); } var response = await client.SendAsync(request).ConfigureAwait(false); responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); byte[] downloadBuffer = new byte[2048]; int bytesRead; while ((bytesRead = await responseStream.ReadAsync(downloadBuffer, 0, downloadBuffer.Length).ConfigureAwait(false)) > 0 && !this.updateDownloadCancellationTokenSource.Token.IsCancellationRequested) { fileStream.Write(downloadBuffer, 0, bytesRead); bytesProgressTotal += bytesRead; this.UpdateDownloadProgressFraction = (double)bytesProgressTotal / response.Content.Headers.ContentLength.Value; } if (bytesRead == 0) { using (SQLiteTransaction transaction = Database.ThreadLocalConnection.BeginTransaction()) { Config.UpdateVersion = updateVersion.ToString(); Config.UpdateInstallerLocation = installerFilePath; Config.UpdateChangelogLocation = changelogLink; transaction.Commit(); } this.State = UpdateState.InstallerReady; this.UpdateDownloadProgressFraction = 1; string downloadFinishedFormat = CustomConfig.UpdatePromptTiming == UpdatePromptTiming.OnExit ? MainRes.NewVersionDownloadFinishedStatus : MainRes.NewVersionDownloadFinishedOnLaunchStatus; string message = string.Format(downloadFinishedFormat, updateVersionText); this.logger.Log(message); this.logger.ShowStatus(message); } else { // In this case the download must have been cancelled. this.State = UpdateState.NotStarted; } } finally { responseStream?.Close(); fileStream?.Close(); } } else { this.State = UpdateState.InstallerReady; } } else { this.State = UpdateState.UpToDate; } } catch (Exception exception) { this.State = UpdateState.Failed; this.logger.Log("Update download failed." + Environment.NewLine + exception); } finally { this.updateDownloadCancellationTokenSource?.Dispose(); this.updateDownloadCancellationTokenSource = null; } if (this.State == UpdateState.InstallerReady && CustomConfig.UpdatePromptTiming == UpdatePromptTiming.OnLaunch) { DispatchUtilities.BeginInvoke(() => { if (this.PromptToApplyUpdate(relaunchWhenComplete: true)) { StaticResolver.Resolve <MainViewModel>().Exit.Execute(null); } }); } }); }
private void Update(IThreatEventsContainer container, IThreatEvent mitigation) { UpdateInfo?.Invoke(this.GetExtensionId(), CurrentStatus); }
public void NotifyUpdate(UpdateInfo updateInfo) { _toolWindowAccessor.CodeSearch.NotifyPackageUpdate(updateInfo); }
public FabrikamUpdater( string machine, PSCredential cred, CancellationToken cancelToken, Guid runId, string command ) { if( String.IsNullOrEmpty( machine ) ) throw new ArgumentException( "You must supply a machine name.", "machine" ); // If cred is null, that means just use the security context of the user // running this process. if( String.IsNullOrEmpty( command ) ) throw new ArgumentException( "You must supply a command to run.", "command" ); m_machine = machine; m_cred = cred; m_cancelToken = cancelToken; m_runId = runId; m_command = command; m_update = new UpdateInfo( m_machine, m_command, "Fabrikam CAU Command Update", "This update will run the command specified by the administrator on each cluster node. The command is: " + m_command ); _TestWmiConnection(); } // end constructor
public static async Task <DiscordEmbedBuilder> AsEmbedAsync(this UpdateInfo info, DiscordClient client, bool includePrBody = false, DiscordEmbedBuilder builder = null) { if ((info?.LatestBuild?.Windows?.Download ?? info?.LatestBuild?.Linux?.Download) == null) { return builder ?? new DiscordEmbedBuilder { Title = "Error", Description = "Error communicating with the update API. Try again later.", Color = Config.Colors.Maintenance } } ; var justAppend = builder != null; var latestBuild = info.LatestBuild; var latestPr = latestBuild?.Pr; var currentPr = info.CurrentBuild?.Pr; string url = null; PrInfo latestPrInfo = null; PrInfo currentPrInfo = null; string prDesc = ""; if (!justAppend) { if (latestPr > 0) { latestPrInfo = await githubClient.GetPrInfoAsync(latestPr.Value, Config.Cts.Token).ConfigureAwait(false); url = latestPrInfo?.HtmlUrl ?? "https://github.com/RPCS3/rpcs3/pull/" + latestPr; var userName = latestPrInfo?.User?.Login ?? "???"; var emoji = GetUserNameEmoji(client, userName); if (emoji != null) { userName += " " + emoji; } prDesc = $"PR #{latestPr} by {userName}"; } else { prDesc = "PR #???"; } if (currentPr > 0 && currentPr != latestPr) { currentPrInfo = await githubClient.GetPrInfoAsync(currentPr.Value, Config.Cts.Token).ConfigureAwait(false); } } var desc = latestPrInfo?.Title; if (includePrBody && latestPrInfo?.Body is string prInfoBody && !string.IsNullOrEmpty(prInfoBody)) { desc = $"**{desc.TrimEnd()}**\n\n{prInfoBody}"; } desc = desc?.Trim(); if (!string.IsNullOrEmpty(desc) && GithubLinksHandler.IssueMention.Matches(desc) is MatchCollection matches && matches.Any()) { foreach (Match m in matches) { if (m.Groups["issue_mention"]?.Value is string str && !string.IsNullOrEmpty(str)) { var name = str; var num = m.Groups["number"].Value; if (string.IsNullOrEmpty(num)) { num = m.Groups["also_number"].Value; } if (string.IsNullOrEmpty(num)) { num = m.Groups["another_number"].Value; name = "#" + num; } if (string.IsNullOrEmpty(num)) { continue; } desc = desc.Replace(str, $"[{name}](https://github.com/RPCS3/rpcs3/issues/{num})"); } } } desc = desc.Trim(EmbedPager.MaxDescriptionLength); builder ??= new DiscordEmbedBuilder { Title = prDesc, Url = url, Description = desc, Color = Config.Colors.DownloadLinks }; var currentCommit = currentPrInfo?.MergeCommitSha; var latestCommit = latestPrInfo?.MergeCommitSha; var currentAppveyorBuild = await appveyorClient.GetMasterBuildAsync(currentCommit, currentPrInfo?.MergedAt, Config.Cts.Token).ConfigureAwait(false); var latestAppveyorBuild = await appveyorClient.GetMasterBuildAsync(latestCommit, latestPrInfo?.MergedAt, Config.Cts.Token).ConfigureAwait(false); var buildTimestampKind = "Build"; var latestBuildTimestamp = latestAppveyorBuild?.Finished?.ToUniversalTime(); var currentBuildTimestamp = currentAppveyorBuild?.Finished?.ToUniversalTime(); if (!latestBuildTimestamp.HasValue) { buildTimestampKind = "Merge"; latestBuildTimestamp = latestPrInfo?.MergedAt; currentBuildTimestamp = currentPrInfo?.MergedAt; } if (!string.IsNullOrEmpty(latestBuild?.Datetime)) { var timestampInfo = latestBuildTimestamp?.ToString("u") ?? latestBuild.Datetime; if (currentPr > 0 && currentPr != latestPr && GetUpdateDelta(latestBuildTimestamp, currentBuildTimestamp) is TimeSpan timeDelta) { timestampInfo += $" ({timeDelta.AsTimeDeltaDescription()} newer)"; } else if (!justAppend && latestBuildTimestamp.HasValue && DateTime.UtcNow.Ticks > latestBuildTimestamp.Value.Ticks) { timestampInfo += $" ({(DateTime.UtcNow - latestBuildTimestamp.Value).AsTimeDeltaDescription()} ago)"; } if (justAppend) { builder.AddField($"Latest master build ({timestampInfo})", "This pull request has been merged, and is a part of `master` now"); } else { builder.AddField($"{buildTimestampKind} timestamp", timestampInfo); } } return(builder .AddField("Windows download", GetLinkMessage(latestBuild?.Windows?.Download, true), true) .AddField("Linux download", GetLinkMessage(latestBuild?.Linux?.Download, true), true)); }
/// <returns>True if the user has upgraded</returns> private async Task <Boolean> githubCheck() { log.Debug("Checking for Squirrel update..."); UpdateManager updateManager = null; isBusy = true; try { String installRootDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); if (string.IsNullOrEmpty(nonGitHubReleaseUri)) { updateManager = await Squirrel.UpdateManager.GitHubUpdateManager("https://github.com/phw198/OutlookGoogleCalendarSync", "OutlookGoogleCalendarSync", installRootDir); } else { updateManager = new Squirrel.UpdateManager(nonGitHubReleaseUri, "OutlookGoogleCalendarSync", installRootDir); } UpdateInfo updates = await updateManager.CheckForUpdate(); if (updates.ReleasesToApply.Any()) { if (updates.CurrentlyInstalledVersion != null) { log.Info("Currently installed version: " + updates.CurrentlyInstalledVersion.Version.ToString()); } log.Info("Found " + updates.ReleasesToApply.Count() + " new releases available."); foreach (ReleaseEntry update in updates.ReleasesToApply.OrderBy(x => x.Version).Reverse()) { log.Info("Found a new " + update.Version.SpecialVersion + " version: " + update.Version.Version.ToString()); if (update.Version.SpecialVersion == "alpha" && !Settings.Instance.AlphaReleases) { log.Debug("User doesn't want alpha releases."); continue; } DialogResult dr = MessageBox.Show("A " + update.Version.SpecialVersion + " update for OGCS is available.\nWould you like to update the application to v" + update.Version.Version.ToString() + " now?", "OGCS Update Available", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (dr == DialogResult.Yes) { log.Debug("Download started..."); updateManager.DownloadReleases(updates.ReleasesToApply).Wait(); log.Debug("Download complete."); //System.Collections.Generic.Dictionary<ReleaseEntry, String> notes = updates.FetchReleaseNotes(); //String notes = update.GetReleaseNotes(updateManager.RootAppDirectory +"\\packages"); log.Info("Applying the updated release..."); updateManager.ApplyReleases(updates).Wait(); /* * new System.Net.WebClient().DownloadFile("https://github.com/phw198/OutlookGoogleCalendarSync/releases/download/v2.6-beta/OutlookGoogleCalendarSync-2.5.0-beta-full.nupkg", "OutlookGoogleCalendarSync-2.5.0-beta-full.nupkg"); * String notes = update.GetReleaseNotes(""); * //if (!string.IsNullOrEmpty(notes)) log.Debug(notes); */ log.Info("The application has been successfully updated."); MessageBox.Show("The application has been updated and will now restart.", "OGCS successfully updated!", MessageBoxButtons.OK, MessageBoxIcon.Information); log.Info("Restarting OGCS."); restartUpdateExe = updateManager.RootAppDirectory + "\\Update.exe"; return(true); } else { log.Info("User chose not to upgrade."); } break; } } else { log.Info("Already running the latest version of OGCS."); if (this.isManualCheck) //Was a manual check, so give feedback { MessageBox.Show("You are already running the latest version of OGCS.", "Latest Version", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (System.Exception ex) { OGCSexception.Analyse(ex, true); if (ex.InnerException != null) { log.Error(ex.InnerException.Message); } throw ex; } finally { isBusy = false; updateManager.Dispose(); } return(false); }
public async Task CheckForUpdates() { _lastUpdate = await GetLatestUpdateInfo(); }
private void updateBridge_UpdateDismissed(object sender, UpdateInfo update) { Config.DismissedUpdate = update.VersionTag; Config.Save(); }
protected abstract void CallEvent(UpdateInfo updateInfo);
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) { global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); UpdateInfo ds = new UpdateInfo(); global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny(); any1.Namespace = "http://www.w3.org/2001/XMLSchema"; any1.MinOccurs = new decimal(0); any1.MaxOccurs = decimal.MaxValue; any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; sequence.Items.Add(any1); global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny(); any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"; any2.MinOccurs = new decimal(1); any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; sequence.Items.Add(any2); global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute(); attribute1.Name = "namespace"; attribute1.FixedValue = ds.Namespace; type.Attributes.Add(attribute1); global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute(); attribute2.Name = "tableTypeName"; attribute2.FixedValue = "Update_InfoDataTable"; type.Attributes.Add(attribute2); type.Particle = sequence; global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); try { global::System.Xml.Schema.XmlSchema schema = null; dsSchema.Write(s1); for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext();) { schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); s2.SetLength(0); schema.Write(s2); if ((s1.Length == s2.Length)) { s1.Position = 0; s2.Position = 0; for (; ((s1.Position != s1.Length) && (s1.ReadByte() == s2.ReadByte()));) { ; } if ((s1.Position == s1.Length)) { return(type); } } } } finally { if ((s1 != null)) { s1.Close(); } if ((s2 != null)) { s2.Close(); } } } xs.Add(dsSchema); return(type); }
static bool NotEqualVersions(UpdateInfo updateInfo) => updateInfo.FutureReleaseEntry != updateInfo.CurrentlyInstalledVersion;
private void OnDownloadSuccess(object sender, DownloadSuccessEventArgs e) { UpdateInfo updateInfo = e.UserData as UpdateInfo; if (updateInfo == null) { return; } using (FileStream fileStream = new FileStream(e.DownloadPath, FileMode.Open, FileAccess.ReadWrite)) { bool compressed = updateInfo.Length != updateInfo.CompressedLength || updateInfo.HashCode != updateInfo.CompressedHashCode; int length = (int)fileStream.Length; if (length != updateInfo.CompressedLength) { fileStream.Close(); string errorMessage = Utility.Text.Format("Resource compressed length error, need '{0}', downloaded '{1}'.", updateInfo.CompressedLength.ToString(), length.ToString()); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } if (compressed) { fileStream.Position = 0L; int hashCode = Utility.Verifier.GetCrc32(fileStream); if (hashCode != updateInfo.CompressedHashCode) { fileStream.Close(); string errorMessage = Utility.Text.Format("Resource compressed hash code error, need '{0}', downloaded '{1}'.", updateInfo.CompressedHashCode.ToString(), hashCode.ToString()); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } if (m_ResourceManager.m_DecompressCachedStream == null) { m_ResourceManager.m_DecompressCachedStream = new MemoryStream(); } try { fileStream.Position = 0L; m_ResourceManager.m_DecompressCachedStream.Position = 0L; m_ResourceManager.m_DecompressCachedStream.SetLength(0L); if (!Utility.Compression.Decompress(fileStream, m_ResourceManager.m_DecompressCachedStream)) { fileStream.Close(); string errorMessage = Utility.Text.Format("Unable to decompress resource '{0}'.", e.DownloadPath); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } if (m_ResourceManager.m_DecompressCachedStream.Length != updateInfo.Length) { fileStream.Close(); string errorMessage = Utility.Text.Format("Resource length error, need '{0}', downloaded '{1}'.", updateInfo.Length.ToString(), m_ResourceManager.m_DecompressCachedStream.Length.ToString()); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } fileStream.Position = 0L; fileStream.SetLength(0L); fileStream.Write(m_ResourceManager.m_DecompressCachedStream.GetBuffer(), 0, (int)m_ResourceManager.m_DecompressCachedStream.Length); } catch (Exception exception) { fileStream.Close(); string errorMessage = Utility.Text.Format("Unable to decompress resource '{0}' with error message '{1}'.", e.DownloadPath, exception.ToString()); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } finally { m_ResourceManager.m_DecompressCachedStream.Position = 0L; m_ResourceManager.m_DecompressCachedStream.SetLength(0L); } } else { int hashCode = 0; fileStream.Position = 0L; if (updateInfo.LoadType == LoadType.LoadFromMemoryAndQuickDecrypt || updateInfo.LoadType == LoadType.LoadFromMemoryAndDecrypt || updateInfo.LoadType == LoadType.LoadFromBinaryAndQuickDecrypt || updateInfo.LoadType == LoadType.LoadFromBinaryAndDecrypt) { Utility.Converter.GetBytes(updateInfo.HashCode, m_CachedHashBytes); if (updateInfo.LoadType == LoadType.LoadFromMemoryAndQuickDecrypt || updateInfo.LoadType == LoadType.LoadFromBinaryAndQuickDecrypt) { hashCode = Utility.Verifier.GetCrc32(fileStream, m_CachedHashBytes, Utility.Encryption.QuickEncryptLength); } else if (updateInfo.LoadType == LoadType.LoadFromMemoryAndDecrypt || updateInfo.LoadType == LoadType.LoadFromBinaryAndDecrypt) { hashCode = Utility.Verifier.GetCrc32(fileStream, m_CachedHashBytes, length); } Array.Clear(m_CachedHashBytes, 0, CachedHashBytesLength); } else { hashCode = Utility.Verifier.GetCrc32(fileStream); } if (hashCode != updateInfo.HashCode) { fileStream.Close(); string errorMessage = Utility.Text.Format("Resource hash code error, need '{0}', downloaded '{1}'.", updateInfo.HashCode.ToString(), hashCode.ToString()); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } } } if (updateInfo.UseFileSystem) { IFileSystem fileSystem = m_ResourceManager.GetFileSystem(updateInfo.FileSystemName, false); bool retVal = fileSystem.WriteFile(updateInfo.ResourceName.FullName, updateInfo.ResourcePath); if (File.Exists(updateInfo.ResourcePath)) { File.Delete(updateInfo.ResourcePath); } if (!retVal) { string errorMessage = Utility.Text.Format("Write resource to file system '{0}' error.", fileSystem.FullPath); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); return; } } m_UpdatingCount--; m_ResourceManager.m_ResourceInfos[updateInfo.ResourceName].MarkReady(); m_ResourceManager.m_ReadWriteResourceInfos.Add(updateInfo.ResourceName, new ReadWriteResourceInfo(updateInfo.FileSystemName, updateInfo.LoadType, updateInfo.Length, updateInfo.HashCode)); m_CurrentGenerateReadWriteVersionListLength += updateInfo.CompressedLength; if (m_UpdatingCount <= 0 || m_CurrentGenerateReadWriteVersionListLength >= m_GenerateReadWriteVersionListLength) { m_CurrentGenerateReadWriteVersionListLength = 0; GenerateReadWriteVersionList(); } if (ResourceUpdateSuccess != null) { ResourceUpdateSuccess(updateInfo.ResourceName, e.DownloadPath, e.DownloadUri, updateInfo.Length, updateInfo.CompressedLength); } }
/// <returns>True if the user has upgraded</returns> private async Task <Boolean> githubCheck() { log.Debug("Checking for Squirrel update..."); UpdateManager updateManager = null; isBusy = true; try { String installRootDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); if (string.IsNullOrEmpty(nonGitHubReleaseUri)) { updateManager = await Squirrel.UpdateManager.GitHubUpdateManager("https://github.com/phw198/OutlookGoogleCalendarSync", "OutlookGoogleCalendarSync", installRootDir, prerelease : Settings.Instance.AlphaReleases); } else { updateManager = new Squirrel.UpdateManager(nonGitHubReleaseUri, "OutlookGoogleCalendarSync", installRootDir); } UpdateInfo updates = await updateManager.CheckForUpdate(); if (updates.ReleasesToApply.Any()) { if (updates.CurrentlyInstalledVersion != null) { log.Info("Currently installed version: " + updates.CurrentlyInstalledVersion.Version.ToString()); } log.Info("Found " + updates.ReleasesToApply.Count() + " newer releases available."); foreach (ReleaseEntry update in updates.ReleasesToApply.OrderBy(x => x.Version).Reverse()) { log.Info("Found a new " + update.Version.SpecialVersion + " version: " + update.Version.Version.ToString()); if (!this.isManualCheck && update.Version.Version.ToString() == Settings.Instance.SkipVersion) { log.Info("The user has previously requested to skip this version."); break; } String releaseNotes = ""; if (nonGitHubReleaseUri != null) { releaseNotes = update.GetReleaseNotes(nonGitHubReleaseUri); } else { //Somewhat annoyingly we have to download the release in order to get the release notes, as they are embedded in the .nupkg upgrade file(s) try { updateManager.DownloadReleases(new[] { update }).Wait(30 * 1000); System.Collections.Generic.Dictionary <ReleaseEntry, String> allReleaseNotes = updates.FetchReleaseNotes(); releaseNotes = allReleaseNotes[update]; } catch (System.Exception ex) { OGCSexception.Analyse(ex); log.Error("Failed pre-fetching release notes. " + ex.Message); releaseNotes = null; } } DialogResult dr = DialogResult.Cancel; if (!string.IsNullOrEmpty(releaseNotes)) { log.Debug("Release notes retrieved."); } var t = new System.Threading.Thread(() => new Forms.UpdateInfo(update.Version.Version.ToString(), update.Version.SpecialVersion, releaseNotes, out dr)); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); String squirrelAnalyticsLabel = "from=" + Application.ProductVersion + ";to=" + update.Version.Version.ToString(); if (dr == DialogResult.No) { log.Info("User chose not to upgrade right now."); Analytics.Send(Analytics.Category.squirrel, Analytics.Action.upgrade, squirrelAnalyticsLabel + ";later"); } else if (dr == DialogResult.Ignore) { Analytics.Send(Analytics.Category.squirrel, Analytics.Action.upgrade, squirrelAnalyticsLabel + ";skipped"); } else if (dr == DialogResult.Yes) { log.Debug("Download started..."); if (!updateManager.DownloadReleases(new[] { update }).Wait(60 * 1000)) { log.Warn("The download failed to completed within 60 seconds."); Analytics.Send(Analytics.Category.squirrel, Analytics.Action.download, squirrelAnalyticsLabel + ";timedout"); if (MessageBox.Show("The update failed to download.", "Download timed out", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Retry) { if (!updateManager.DownloadReleases(new[] { update }).Wait(60 * 1000)) { Analytics.Send(Analytics.Category.squirrel, Analytics.Action.download, squirrelAnalyticsLabel + ";retry-timedout"); if (MessageBox.Show("The update failed to download again.\nTo download from the project website, click Yes.", "Download timed out", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) { Analytics.Send(Analytics.Category.squirrel, Analytics.Action.download, squirrelAnalyticsLabel + ";from-website"); System.Diagnostics.Process.Start("https://phw198.github.io/OutlookGoogleCalendarSync/"); } else { Analytics.Send(Analytics.Category.squirrel, Analytics.Action.download, squirrelAnalyticsLabel + ";gave-up"); } break; } } else { if (MessageBox.Show("Would you like to download directly from the project website?", "Go to OGCS website", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) { Analytics.Send(Analytics.Category.squirrel, Analytics.Action.download, squirrelAnalyticsLabel + ";from-website"); System.Diagnostics.Process.Start("https://phw198.github.io/OutlookGoogleCalendarSync/"); } else { Analytics.Send(Analytics.Category.squirrel, Analytics.Action.download, squirrelAnalyticsLabel + ";gave-up"); } break; } } try { log.Debug("Download complete."); Analytics.Send(Analytics.Category.squirrel, Analytics.Action.download, squirrelAnalyticsLabel + ";successful"); log.Info("Applying the updated release..."); updateManager.ApplyReleases(updates).Wait(); log.Info("The application has been successfully updated."); MessageBox.Show("The application has been updated and will now restart.", "OGCS successfully updated!", MessageBoxButtons.OK, MessageBoxIcon.Information); restartUpdateExe = updateManager.RootAppDirectory + "\\Update.exe"; return(true); } catch (System.AggregateException ae) { foreach (System.Exception ex in ae.InnerExceptions) { OGCSexception.Analyse(ex, true); ex.Data.Add("analyticsLabel", squirrelAnalyticsLabel); throw new ApplicationException("Failed upgrading OGCS.", ex); } } catch (System.Exception ex) { OGCSexception.Analyse(ex, true); ex.Data.Add("analyticsLabel", squirrelAnalyticsLabel); throw new ApplicationException("Failed upgrading OGCS.", ex); } } break; } } else { log.Info("Already running the latest version of OGCS."); if (this.isManualCheck) //Was a manual check, so give feedback { MessageBox.Show("You are already running the latest version of OGCS.", "Latest Version", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (ApplicationException ex) { Analytics.Send(Analytics.Category.squirrel, Analytics.Action.download, ex.Data["analyticsLabel"] + ";failed"); throw ex; } catch (System.AggregateException ae) { log.Error("Failed checking for update."); foreach (System.Exception ex in ae.InnerExceptions) { OGCSexception.Analyse(ex, true); throw ex; } } catch (System.Exception ex) { log.Error("Failed checking for update."); OGCSexception.Analyse(ex, true); throw ex; } finally { isBusy = false; updateManager.Dispose(); } return(false); }
protected override void BuilderFailed(AuProject project, Exception exception, UpdateInfo resultUpdateInfo) { _form.SetFailed(); System.Windows.Forms.MessageBox.Show("更新项目构建失败:" + exception.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); base.BuilderFailed(project, exception, resultUpdateInfo); }
public void Check(UpdateInfo updateInfo) { updateUtils.Update(AutoUpdate.Context, updateInfo); }
private static bool TryParseUpdateInfo(string response, out UpdateInfo updateInfo) { try { JSONNode node = JSON.Parse(response); JSONClass root = node.AsObject; if (root != null) { return TryParseUpdateInfo(root, out updateInfo); } } catch (Exception e) { Log.e(e, "Unable to parse plugin update info"); } updateInfo = default(UpdateInfo); return false; }
private void UpdateCheckStart() { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(kUpdatesAvailableUrl); request.Credentials = CredentialCache.DefaultCredentials; request.Proxy.Credentials = CredentialCache.DefaultCredentials; try { request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache); } catch { // not supported for all platforms } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); XmlDocument document = new XmlDocument(); document.Load(response.GetResponseStream()); XmlNamespaceManager nsManager = new XmlNamespaceManager(document.NameTable); nsManager.AddNamespace("linn", kLinnNamespace); // get update info foreach (XmlNode n in document.SelectNodes("/rss/channel/" + kReleasedDeviceTag, nsManager)) { string model = n["linn:model"].InnerText; string type = n["linn:type"].InnerText; string version = n["linn:version"].InnerText; //string family = n["linn:family"].InnerText; string url = n["linn:url"].InnerText; UpdateInfo updateInfo = null; if (type == "Main") { updateInfo = new UpdateInfo(model, version, url); if (iUpdateInfo.ContainsKey(model)) { iUpdateInfo[model] = updateInfo; } else { iUpdateInfo.Add(model, updateInfo); } } else if (type == "Proxy") { updateInfo = new UpdateInfo(model, version); if (iUpdateInfoProxy.ContainsKey(model)) { iUpdateInfoProxy[model] = updateInfo; } else { iUpdateInfoProxy.Add(model, updateInfo); } } } // get variant info foreach (XmlNode n in document.SelectNodes("/rss/channel/linn:variantList/linn:variant", nsManager)) { string pcas = n["linn:pcas"].InnerText; string basepcas = null; if (n["linn:basepcas"] != null) { basepcas = n["linn:basepcas"].InnerText; } string name = n["linn:name"].InnerText; VariantInfo variantInfo = new VariantInfo(pcas, basepcas, name); iVariantInfo.Add(variantInfo); } // get release notes request = (HttpWebRequest)WebRequest.Create(kReleaseNotesUrl); request.Credentials = CredentialCache.DefaultCredentials; request.Proxy.Credentials = CredentialCache.DefaultCredentials; try { request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache); } catch { // not supported for all platforms } response = (HttpWebResponse)request.GetResponse(); document = new XmlDocument(); document.Load(response.GetResponseStream()); iReleaseNotesXml = document.OuterXml; Lock(); iUpdateCheckThread = null; Unlock(); iUpdateCheckComplete = true; iUpdateCheckFailed = false; if (EventUpdateCheckComplete != null) { EventUpdateCheckComplete(this, EventArgs.Empty); } } catch (Exception e) { Lock(); iUpdateCheckThread = null; Unlock(); iUpdateCheckFailed = true; if (EventUpdateCheckError != null) { EventUpdateCheckError(this, new EventArgsUpdateError(e.Message)); } } }
static bool HasFutureReleaseEntry(UpdateInfo updateInfo) => updateInfo.FutureReleaseEntry != null;
//private int m_downloadRetryTimes = 0; //private int m_downloadRetryMaxCount = 1; private IEnumerator GetVersionInfoFile(System.Action <UpdateCheckResult> callback) { var result = new UpdateCheckResult(); UpdateInfo cfg = null; var url = GetUpdateConfigUrl(); bool isDownloadSuc = false; //先判断网络 if (Application.internetReachability != NetworkReachability.NotReachable) { Debug.Log("fetch config url:" + url); WWW w = new WWW(url); float beginTime = Time.realtimeSinceStartup; bool timeOut = false; while (!w.isDone && !timeOut) { timeOut = (Time.realtimeSinceStartup - beginTime) >= 3; yield return(null); } if (w.error != null) { Debug.LogError(w.error); w.Dispose(); } else if (timeOut) { Debug.LogError("fetch config timeout"); w.Dispose(); } else { isDownloadSuc = true; Debug.Log("w.text:" + w.text); //parse config cfg = JsonMapper.ToObject <UpdateInfo>(w.text); w.Dispose(); } //m_downloadRetryTimes++; } //开关窗口 有0.4S动画 这里统一加一下 yield return(new WaitForSeconds(0.5f)); if (isDownloadSuc) { Debug.Log("拉取更新配置成功"); result = CheckIfNeedsUpdate(cfg); callback(result); } else { Debug.LogError("拉取更新失败!"); result.Success = isDownloadSuc; result.ErrorCode = GameUpdateSys.ErrorCode.FetchConfigFailed; callback(result); } }
public override void Setup() { plugin = new HeightStructuresPlugin(); updateInfo = plugin.GetUpdateInfos().First(i => i.DataType == typeof(HeightStructuresContext)); }
public void NotifyPackageUpdate(UpdateInfo updateInfo) { WpfUtilities.Post(ExplorerControl, () => { ExplorerControl.UpdateInfo = updateInfo; }); }
//here is public for Unit Test public UpdateCheckResult CheckIfNeedsUpdate(UpdateInfo cfg) { UpdateCheckResult result = new UpdateCheckResult(); if (cfg == null) { Debug.LogError("invalid cfg, cfg == null"); result.Success = false; result.ErrorCode = GameUpdateSys.ErrorCode.InvalidConfig; return(result); } var currPlatform = (int)m_context.Platform; string publishedVersion = null; for (int i = 0; i < cfg.serverInfo.Count; i++) { var info = cfg.serverInfo[i]; //版本发布根据小平台走,如果有配相应平台去相应平台,如果没有取通用平台 "0" if (info.platform == currPlatform) { publishedVersion = info.version; break; } else if (info.platform == (int)ENUM_SDK_PLATFORM.ESP_General) { publishedVersion = info.version; } } result.Success = true; result.PublishedVersion = publishedVersion; //当本地版本号比预发布版本号大时,表明正在提审阶段,不需要更新内容 var packageVerNum = GetVersionCode(m_context.PackageVersion); var publishedVerNum = GetVersionCode(publishedVersion); if (publishedVerNum < packageVerNum) { Debug.Log("本地版本号比预发布版本号大, packageVer = " + packageVerNum + ", publishedVer = " + publishedVerNum); result.IsPackageUpdateAvailable = false; result.IsResourceUpdateAvailable = false; return(result); } if (cfg.packageUpdateInfo != null) { for (int i = 0; i < cfg.packageUpdateInfo.Count; i++) { var pinfo = cfg.packageUpdateInfo[i]; if (pinfo.platform == currPlatform || pinfo.platform == (int)ENUM_SDK_PLATFORM.ESP_General) { //当自己版本好号比最小版本号小时,需要强制更新 if (packageVerNum < GetVersionCode(pinfo.version)) { result.IsPackageUpdateAvailable = true; result.IsPackageForceUpdate = true; } //当自己版本号比最小版本号大,但比最大版本号小时,建议更新 else if (GetVersionCode(pinfo.maxVersion) > packageVerNum) { result.IsPackageUpdateAvailable = true; result.IsPackageForceUpdate = false; } else { //自己版本号大于或等于最大版本号,无需更新 } if (result.IsPackageUpdateAvailable) { result.PackageUpdateUrl = pinfo.updateUrl; result.PackageUpdateDesc = pinfo.updateDesc; } if (pinfo.platform == currPlatform) { break; } } } } //如果是强制更新,直接告诉用户需要更新才能进行游戏,后续检测不再需要。 if (result.IsPackageForceUpdate) { return(result); } //collect dynamic update info if (cfg.dynamicUpdateInfo == null) { return(result); } Queue <string> appQueue = new Queue <string>(); var versionInfoList = new List <UpdateInfo.ResVersionInfo>(); appQueue.Enqueue(m_context.BaseVersion); while (appQueue.Count > 0) { var curVersion = appQueue.Dequeue(); for (int i = 0; i < cfg.dynamicUpdateInfo.Count; i++) { var info = cfg.dynamicUpdateInfo[i]; if (info.baseVersion.Equals(curVersion)) { for (int j = 0; j < info.resVersionInfo.Count; j++) { var versionInfo = info.resVersionInfo[j]; bool _added = false; if (versionInfo.basePlatform == (int)m_context.BasePlatform) { _added = AddResVersionInfo(versionInfoList, versionInfo); } if (versionInfo.basePlatform == (int)EnumAppName.general) { _added = AddResVersionInfo(versionInfoList, versionInfo); } // 这个appVersion 是用来更新DLL //比如当前版本是0.7.2 0.7.3版本更新了DLL 并把版本提升到了0.7.3 //那么按原来的逻辑它就不会去拉新的更新了,而这里的逻辑上再把0.7.3的更细也拉下来 //这里是和刀锋逻辑不一样的地方 if (!string.IsNullOrEmpty(versionInfo.appVersion)) { appQueue.Enqueue(versionInfo.appVersion); versionInfo.forceUpdate = true; } versionInfo.downloadVersion = curVersion; if (_added) { result.IsResourceForceUpdate = result.IsResourceForceUpdate || versionInfo.forceUpdate; } } } } } //collect res update info for all this baseVersion List <UpdateInfo.ResInfo> tmpResInfoList = new List <UpdateInfo.ResInfo>(); for (int i = 0; i < versionInfoList.Count; i++) { var info = versionInfoList[i]; var list = info.resInfo; for (int j = 0; j < list.Count; j++) { var resInfo = list[j]; resInfo.versionInfo = info; AddResInfo(tmpResInfoList, resInfo); } } tmpResInfoList.Sort((a, b) => { return(GetVersionCode(a.versionInfo.resVersion) - GetVersionCode(b.versionInfo.resVersion)); }); //check existing resource files, and filter them for (int i = 0; i < tmpResInfoList.Count; i++) { var info = tmpResInfoList[i]; if (!m_context.ResMd5Mgr.IsResourceExisted(info)) { result.AddResInfo(info); } } if (result.ResInfoList != null && result.ResInfoList.Count > 0) { result.IsResourceUpdateAvailable = true; } return(result); }
public UpdateChecker(GameUpdateSys.UpdateContext context, IUpdateFilter filter) { m_context = context; m_filter = filter; UpdateInfo info = new UpdateInfo(); }
public override void Setup() { plugin = new PipingPlugin(); updateInfo = plugin.GetUpdateInfos().First(i => i.DataType == typeof(PipingSurfaceLinesContext)); }
private void btn_update_Click(object sender, EventArgs e2) { if (isdown) { return; } if (SystemSettings.UpdateInfo != null && btn_update.IsActive) { UpdateInfo updateInfo = SystemSettings.UpdateInfo; if (updateInfo.files.Count > 0) { isdown = true; //btn_update.Enabled = false; label_updateInfo.Visible = false; metroLoading.Visible = metroLoading.State = true; btn_update.Width = 160; bool isok = false; string updatebasePath = Program.UpdatePath + updateInfo.verson + "\\"; string updatePath = updatebasePath + updateInfo.files[0].name; Action _action = () => { if (File.Exists(updatePath)) { isok = true; } else { btn_update.Invoke(new Action(() => { btn_update.Enabled = false; btn_update.Text = "正在下载"; })); Helper.DownCore core = new Helper.DownCore(); core.MaxValueChange += (s, e) => { metroLoading.MaxValue = e; }; core.ValueChange += (s, e) => { metroLoading.Value = e; }; core.SpeedChange += (s, e) => { btn_update.Invoke(new Action(() => { btn_update.Text = "正在下载 " + e.CountSize(); })); }; string InitErr; if (core.DownInit(updateInfo.files[0].url, updateInfo.files[0].name, out InitErr)) { string Err; if (core.DownUrl(updatePath, updatebasePath + "temp\\", out Err)) { isok = true; //btn_update.Invoke(new Action(() => //{ // btn_update.MaxValue = btn_update.Value = 0; // btn_update.Text = "点击安装"; // //label1.Text = verson; //})); } else { //下载失败 btn_update.Invoke(new Action(() => { btn_update.IsActive = false; btn_update.State = false; btn_update.ForeColor = Color.Red; btn_update.Text = Err; })); System.Threading.Thread.Sleep(2000); btn_update.Invoke(new Action(() => { btn_update.ForeColor = this.ForeColor; btn_update.Text = "检查更新"; btn_update.Enabled = true; })); } } else { btn_update.Invoke(new Action(() => { btn_update.IsActive = false; btn_update.State = false; btn_update.ForeColor = Color.Red; btn_update.Text = InitErr; })); System.Threading.Thread.Sleep(2000); btn_update.Invoke(new Action(() => { btn_update.ForeColor = this.ForeColor; btn_update.Text = "检查更新"; btn_update.Enabled = true; })); } } }; _task.ContinueWhenAll(new Task[] { _task.StartNew(_action) }, (action => { if (isok) { if (updatePath.EndsWith(".exe")) { AdminAppMainUpdate adminAppMainUpdate = new AdminAppMainUpdate(updatebasePath, new List <string> { "TPlayer.exe" }); btn_update.Invoke(new Action(() => { btn_update.BackColorActive = btn_update.BackColorActive2 = Color.DodgerBlue; btn_update.Text = "等待升级"; })); if (adminAppMainUpdate.OpenAssistExe("Update")) { btn_update.Invoke(new Action(() => { Environment.Exit(0); })); return; } else { btn_update.Invoke(new Action(() => { btn_update.IsActive = false; btn_update.ForeColor = Color.Red; btn_update.Text = "启动更新程序失败"; })); System.Threading.Thread.Sleep(2000); btn_update.Invoke(new Action(() => { btn_update.ForeColor = this.ForeColor; btn_update.Text = "检查更新"; })); } Directory.Delete(updatebasePath, true); } else { string err; List <string> files = Compression.DecompressionList(updatePath, updatebasePath, out err); if (files != null && files.Count > 0) { AdminAppMainUpdate adminAppMainUpdate = new AdminAppMainUpdate(updatebasePath, files); btn_update.Invoke(new Action(() => { btn_update.ForeColor = Color.DodgerBlue; btn_update.Text = "等待升级"; })); if (adminAppMainUpdate.OpenAssistExe("Update")) { btn_update.Invoke(new Action(() => { Environment.Exit(0); })); return; } else { btn_update.Invoke(new Action(() => { btn_update.State = false; btn_update.ForeColor = Color.Red; btn_update.Text = "启动更新程序失败"; })); System.Threading.Thread.Sleep(2000); btn_update.Invoke(new Action(() => { btn_update.ForeColor = this.ForeColor; btn_update.Text = "检查更新"; })); } Directory.Delete(updatebasePath, true); } else { File.Delete(updatePath); btn_update.Invoke(new Action(() => { btn_update.State = false; btn_update.ForeColor = Color.Red; btn_update.Text = "文件已损坏"; })); System.Threading.Thread.Sleep(2000); btn_update.Invoke(new Action(() => { btn_update.ForeColor = this.ForeColor; btn_update.Text = "检查更新"; })); } } } this.Invoke(new Action(() => { btn_update.Width = 114; metroLoading.Visible = metroLoading.State = false; btn_update.Enabled = true; })); isdown = false; })); } else { SystemSettings.UpdateInfo = null; metroLoading.State = false; metroLoading.Visible = false; label_updateInfo.Visible = btn_update.Visible = true; UpdateInfo(); btn_update_Click(sender, e2); } } else { label_NewVersion.Text = "正在检查更新"; label_updateInfo.Visible = btn_info.Visible = btn_update.Visible = false; metroLoading.Visible = true; metroLoading.State = true; SystemSettings.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm"); bool htmlErr = false; Action _action = () => { Version verson = new Version(Application.ProductVersion); UpdateInfo updateInfo; if (UpdateCore.Update(verson, out updateInfo, out htmlErr, SystemSettings.UpdatePie)) { SystemSettings.UpdateInfo = updateInfo; //this.BeginInvoke(new Action(() => //{ // Frm.Update update = new Frm.Update(this, verson.ToString(), updateInfo); // update.Show(); //})); //Debug.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(updateInfo)); } else { SystemSettings.UpdateInfo = null; } }; _task.ContinueWhenAll(new Task[] { _task.StartNew(_action) }, (action => { this.Invoke(new Action(() => { metroLoading.State = false; metroLoading.Visible = false; label_updateInfo.Visible = btn_update.Visible = true; UpdateInfo(htmlErr); })); })); } }
public void DoUpdate_SavesTheCurrentVersion() { string newVersion = "2.6.8"; UpdateInfo updateInfo = new UpdateInfo(true, newVersion); updateServer.Stub(x => x.GetManifest(newVersion)).Return(new VersionManifest(newVersion, new VersionManifestFile[0])); localStructureManager.Stub(x => x.LoadManifest(initialVersion)).Return(new VersionManifest(initialVersion, new VersionManifestFile[0])); updateManager.DoUpdate(updateInfo); localStructureManager.AssertWasCalled(x => x.SetCurrentVersion(newVersion)); }
private void OnDownloadSuccess(object sender, DownloadSuccessEventArgs e) { UpdateInfo updateInfo = e.UserData as UpdateInfo; if (updateInfo == null) { return; } bool zip = (updateInfo.Length != updateInfo.ZipLength || updateInfo.HashCode != updateInfo.ZipHashCode); byte[] bytes = File.ReadAllBytes(e.DownloadPath); if (updateInfo.ZipLength != bytes.Length) { string errorMessage = string.Format("Zip length error, need '{0}', downloaded '{1}'.", updateInfo.ZipLength.ToString(), bytes.Length.ToString()); OnDownloadFailure(this, new DownloadFailureEventArgs(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData)); return; } if (!zip) { byte[] hashBytes = Utility.Converter.GetBytesFromInt(updateInfo.HashCode); if (updateInfo.LoadType == LoadType.LoadFromMemoryAndQuickDecrypt) { bytes = Utility.Encryption.GetQuickXorBytes(bytes, hashBytes); } else if (updateInfo.LoadType == LoadType.LoadFromMemoryAndDecrypt) { bytes = Utility.Encryption.GetXorBytes(bytes, hashBytes); } } int hashCode = Utility.Converter.GetIntFromBytes(Utility.Verifier.GetCrc32(bytes)); if (updateInfo.ZipHashCode != hashCode) { string errorMessage = string.Format("Zip hash code error, need '{0}', downloaded '{1}'.", updateInfo.ZipHashCode.ToString("X8"), hashCode.ToString("X8")); OnDownloadFailure(this, new DownloadFailureEventArgs(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData)); return; } if (zip) { try { bytes = Utility.Zip.Decompress(bytes); } catch (Exception exception) { string errorMessage = string.Format("Unable to decompress from file '{0}' with error message '{1}'.", e.DownloadPath, exception.Message); OnDownloadFailure(this, new DownloadFailureEventArgs(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData)); return; } if (updateInfo.Length != bytes.Length) { string errorMessage = string.Format("Resource length error, need '{0}', downloaded '{1}'.", updateInfo.Length.ToString(), bytes.Length.ToString()); OnDownloadFailure(this, new DownloadFailureEventArgs(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData)); return; } File.WriteAllBytes(e.DownloadPath, bytes); } m_UpdatingCount--; if (m_ResourceManager.m_ResourceInfos.ContainsKey(updateInfo.ResourceName)) { throw new GameFrameworkException(string.Format("Resource info '{0}' is already exist.", updateInfo.ResourceName.FullName)); } m_ResourceManager.m_ResourceInfos.Add(updateInfo.ResourceName, new ResourceInfo(updateInfo.ResourceName, updateInfo.LoadType, updateInfo.Length, updateInfo.HashCode, false)); if (m_ResourceManager.m_ReadWriteResourceInfos.ContainsKey(updateInfo.ResourceName)) { throw new GameFrameworkException(string.Format("Read-write resource info '{0}' is already exist.", updateInfo.ResourceName.FullName)); } m_ResourceManager.m_ReadWriteResourceInfos.Add(updateInfo.ResourceName, new ReadWriteResourceInfo(updateInfo.LoadType, updateInfo.Length, updateInfo.HashCode)); GenerateReadWriteList(); if (ResourceUpdateSuccess != null) { ResourceUpdateSuccess(updateInfo.ResourceName, e.DownloadPath, e.DownloadUri, updateInfo.Length, updateInfo.ZipLength); } }
private UpdateInfo SetupUpdateToVersion(string newVersion) { UpdateInfo updateInfo = new UpdateInfo(true, newVersion); updateServer.Stub(x => x.GetManifest(newVersion)).Return(new VersionManifest(newVersion, new VersionManifestFile[0])); localStructureManager.Stub(x => x.LoadManifest(initialVersion)).Return(new VersionManifest(initialVersion, new VersionManifestFile[0])); return updateInfo; }
private void Update() { UpdateInfo?.Invoke(this.GetExtensionId(), CurrentStatus); }
protected override void BuildSuccess(AuProject project, Dictionary<string, string> packages, UpdateInfo resultUpdateInfo) { _form.SetSuccess(); System.Windows.Forms.MessageBox.Show("更新项目构建成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); base.BuildSuccess(project, packages, resultUpdateInfo); }
public List <Employee> Update(UpdateInfo Modal) { return(epObj.Update(Modal)); }
private void NotifyUpdate(UpdateInfo updateInfo) { Logger.LogInfo("New version {0} available online at {1}", updateInfo.Version, updateInfo.Url); _updateNotificationListeners.ForAll(x => x.NotifyUpdate(updateInfo)); }
private void ThreatEventRemoved([NotNull] IThreatEventsContainer container, [NotNull] IThreatEvent threatEvent) { threatEvent.ThreatEventMitigationAdded -= Update; threatEvent.ThreatEventMitigationRemoved -= Update; UpdateInfo?.Invoke(this.GetExtensionId(), CurrentStatus); }
public bool CheckUpdate() { UpdateInfo = new UpdateInfo(ReleaseChannel); UpdateInfo.CurrentVersion = ApplicationVersion; try { RequestCachePolicy cachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); using (WebClient wc = new WebClient { Proxy = Proxy, CachePolicy = cachePolicy }) using (MemoryStream ms = new MemoryStream(wc.DownloadData(URL))) using (XmlTextReader xml = new XmlTextReader(ms)) { XDocument xd = XDocument.Load(xml); if (xd != null) { string node; switch (ReleaseChannel) { default: case ReleaseChannelType.Stable: node = "Stable"; break; case ReleaseChannelType.Beta: node = "Beta|Stable"; break; case ReleaseChannelType.Dev: node = "Dev|Beta|Stable"; break; } string path = string.Format("Update/{0}/{1}", ApplicationName, node); XElement xe = xd.GetNode(path); if (xe != null) { UpdateInfo.LatestVersion = new Version(xe.GetValue("Version")); UpdateInfo.URL = xe.GetValue("URL"); string date = xe.GetValue("Date"); if (!string.IsNullOrEmpty(date)) { DateTime dateTime; if (DateTime.TryParse(date, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime)) { UpdateInfo.Date = dateTime; } } UpdateInfo.Summary = xe.GetValue("Summary"); if (UpdateInfo.IsUpdateRequired) { UpdateInfo.Status = UpdateStatus.UpdateRequired; if (!string.IsNullOrEmpty(UpdateInfo.Summary) && UpdateInfo.Summary.IsValidUrl()) { try { wc.Encoding = Encoding.UTF8; UpdateInfo.Summary = wc.DownloadString(UpdateInfo.Summary.Trim()); } catch (Exception ex) { DebugHelper.WriteException(ex); } } } else { UpdateInfo.Status = UpdateStatus.UpToDate; } return true; } } } } catch (Exception ex) { DebugHelper.WriteException(ex); } UpdateInfo.Status = UpdateStatus.UpdateCheckFailed; return false; }
protected override async Task <HandleResult> HandleCoreAsync(RegisterDeviceRequest reqObj) { if (string.IsNullOrWhiteSpace(reqObj.UniqueId)) { await Task.Delay(0); return(new HandleResult { State = HandleStates.InvalidData, Msg = "请求数据有误" }); } var devSig = Utils.GenId(); var info = new Data.Entities.DeviceReg { Brand = reqObj.Brand, CurrentVersion = reqObj.Version, DevIdenNo = reqObj.UniqueId, DeviceSig = devSig, DeviceType = reqObj.Type ?? string.Empty, Model = reqObj.Model, OprSystem = reqObj.OS, ResolutionRatio = reqObj.Resolution, ScreenDesity = reqObj.Midu, ScreenSize = reqObj.Screen, SystemID = reqObj.OSId, SystemVer = reqObj.OSVersion, TerminalVersion = reqObj.TVersion, UserId = "", Note = "" }; try { UpdateInfo uinfo = null; var rowAffected = _commonRepo.RegisterDevice(info, out uinfo); _eventPublisher.Publish(new DeviceRegEvent { Signature = info.DeviceSig }); var result = new RegisterDeviceResult { State = HandleStates.Success, Msg = string.Empty, Sign = info.DeviceSig }; if (uinfo != null) { result.UpdateFlag = uinfo.ForceUpdate ? 2 : 1; result.UpdateSummary = uinfo.PubDesc; result.NewVersion = uinfo.DisplayVersion; result.DownloadUrl = uinfo.Url; } else { result.UpdateFlag = 0; result.UpdateSummary = string.Empty; result.NewVersion = string.Empty; result.DownloadUrl = string.Empty; } var today = DateTime.Today; if (today.Day <= 20) { int theMonth = today.Year * 100 + today.Month; var displayNotice = _cacheManager.GetCache <IDeviceSignatureCache>().ShouldDisplayNotice(result.Sign, theMonth); switch (displayNotice) { case DisplayNotice.Award: if (awardSpotlight != null && awardSpotlight.TheMonth == theMonth) { result.Extra = awardSpotlight; } else { SpotLight award = await _giftRepo.GetAwardSpotlightAsync(theMonth); awardSpotlight = award; result.Extra = award; } break; case DisplayNotice.Awardee: if (awardeeSpotlight != null && awardeeSpotlight.TheMonth == theMonth) { result.Extra = awardeeSpotlight; } else { SpotLight awardee = await _giftRepo.GetAwardeeSpotligthAsync(theMonth); awardeeSpotlight = awardee; result.Extra = awardee; } break; } if (result.Extra != null) { #if !DEV _eventPublisher.Publish(new DisplayNoticeEvent { Sign = result.Sign, DisplayNotice = displayNotice, TheMonth = theMonth }); #endif } } return(result); } catch (Exception ex) { _logger.LogError("Register device error:{0}", ex); return(new RegisterDeviceResult { State = HandleStates.UnkownError, Msg = ex.Message, Sign = info.DeviceSig }); } }
private static bool TryParseUpdateInfo(JSONClass response, out UpdateInfo updateInfo) { string status = response["status"]; if (status != "OK") { Log.e("Unexpected response 'status': {0}", status); updateInfo = default(UpdateInfo); return false; } string version = response["version"]; if (version == null) { Log.e("Missing response 'version' string"); updateInfo = default(UpdateInfo); return false; } string url = response["url"]; if (url == null) { Log.e("Missing response 'url' string"); updateInfo = default(UpdateInfo); return false; } string message = response["message"]; if (message == null) { Log.e("Missing response 'message'"); updateInfo = default(UpdateInfo); return false; } updateInfo = new UpdateInfo(version, url, message); return true; }
private void Update([NotNull] IThreatEventsContainer container, [NotNull] IThreatEvent threatEvent) { // ReSharper disable once SuspiciousTypeConversion.Global ((INotifyPropertyChanged)threatEvent).PropertyChanged += OnPropertyChanged; UpdateInfo?.Invoke(this.GetExtensionId(), CurrentStatus); }
private void OnDownloadSuccess(object sender, DownloadSuccessEventArgs e) { UpdateInfo updateInfo = e.UserData as UpdateInfo; if (updateInfo == null) { return; } using (FileStream fileStream = new FileStream(e.DownloadPath, FileMode.Open, FileAccess.ReadWrite)) { bool zip = (updateInfo.Length != updateInfo.ZipLength || updateInfo.HashCode != updateInfo.ZipHashCode); int length = (int)fileStream.Length; if (length != updateInfo.ZipLength) { fileStream.Close(); string errorMessage = Utility.Text.Format("Zip length error, need '{0}', downloaded '{1}'.", updateInfo.ZipLength.ToString(), length.ToString()); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } if (m_ResourceManager.UpdateFileCacheLength < length) { m_ResourceManager.UpdateFileCacheLength = (length / OneMegaBytes + 1) * OneMegaBytes; } int offset = 0; int count = length; while (count > 0) { int bytesRead = fileStream.Read(m_ResourceManager.m_UpdateFileCache, offset, count); if (bytesRead <= 0) { throw new GameFrameworkException(Utility.Text.Format("Unknown error when load file '{0}'.", e.DownloadPath)); } offset += bytesRead; count -= bytesRead; } if (!zip) { Utility.Converter.GetBytes(updateInfo.HashCode, m_CachedHashBytes); if (updateInfo.LoadType == LoadType.LoadFromMemoryAndQuickDecrypt) { Utility.Encryption.GetQuickSelfXorBytes(m_ResourceManager.m_UpdateFileCache, m_CachedHashBytes); } else if (updateInfo.LoadType == LoadType.LoadFromMemoryAndDecrypt) { Utility.Encryption.GetSelfXorBytes(m_ResourceManager.m_UpdateFileCache, m_CachedHashBytes, length); } Array.Clear(m_CachedHashBytes, 0, CachedHashBytesLength); } int hashCode = Utility.Verifier.GetCrc32(m_ResourceManager.m_UpdateFileCache, 0, length); if (hashCode != updateInfo.ZipHashCode) { fileStream.Close(); string errorMessage = Utility.Text.Format("Zip hash code error, need '{0}', downloaded '{1}'.", updateInfo.ZipHashCode.ToString(), hashCode.ToString()); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } if (zip) { try { if (m_ResourceManager.m_DecompressCache == null) { m_ResourceManager.m_DecompressCache = new MemoryStream(); } m_ResourceManager.m_DecompressCache.Position = 0L; m_ResourceManager.m_DecompressCache.SetLength(0L); if (!Utility.Zip.Decompress(m_ResourceManager.m_UpdateFileCache, 0, length, m_ResourceManager.m_DecompressCache)) { fileStream.Close(); string errorMessage = Utility.Text.Format("Unable to decompress from file '{0}'.", e.DownloadPath); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } if (m_ResourceManager.m_DecompressCache.Length != updateInfo.Length) { fileStream.Close(); string errorMessage = Utility.Text.Format("Resource length error, need '{0}', downloaded '{1}'.", updateInfo.Length.ToString(), m_ResourceManager.m_DecompressCache.Length.ToString()); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } fileStream.Position = 0L; fileStream.SetLength(0L); m_ResourceManager.m_DecompressCache.Position = 0L; int bytesRead = 0; while ((bytesRead = m_ResourceManager.m_DecompressCache.Read(m_ResourceManager.m_UpdateFileCache, 0, m_ResourceManager.m_UpdateFileCache.Length)) > 0) { fileStream.Write(m_ResourceManager.m_UpdateFileCache, 0, bytesRead); } } catch (Exception exception) { fileStream.Close(); string errorMessage = Utility.Text.Format("Unable to decompress from file '{0}' with error message '{1}'.", e.DownloadPath, exception.Message); DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData); OnDownloadFailure(this, downloadFailureEventArgs); ReferencePool.Release(downloadFailureEventArgs); return; } } } m_UpdatingCount--; if (m_ResourceManager.m_ResourceInfos.ContainsKey(updateInfo.ResourceName)) { throw new GameFrameworkException(Utility.Text.Format("Resource info '{0}' is already exist.", updateInfo.ResourceName.FullName)); } m_ResourceManager.m_ResourceInfos.Add(updateInfo.ResourceName, new ResourceInfo(updateInfo.ResourceName, updateInfo.LoadType, updateInfo.Length, updateInfo.HashCode, false)); if (m_ResourceManager.m_ReadWriteResourceInfos.ContainsKey(updateInfo.ResourceName)) { throw new GameFrameworkException(Utility.Text.Format("Read-write resource info '{0}' is already exist.", updateInfo.ResourceName.FullName)); } m_ResourceManager.m_ReadWriteResourceInfos.Add(updateInfo.ResourceName, new ReadWriteResourceInfo(updateInfo.LoadType, updateInfo.Length, updateInfo.HashCode)); m_CurrentGenerateReadWriteListLength += updateInfo.ZipLength; if (m_UpdatingCount <= 0 || m_CurrentGenerateReadWriteListLength >= m_GenerateReadWriteListLength) { m_CurrentGenerateReadWriteListLength = 0; GenerateReadWriteList(); } if (ResourceUpdateSuccess != null) { ResourceUpdateSuccess(updateInfo.ResourceName, e.DownloadPath, e.DownloadUri, updateInfo.Length, updateInfo.ZipLength); } }
public static async Task <DiscordEmbedBuilder> AsEmbedAsync(this UpdateInfo info, DiscordClient client, bool includePrBody = false, DiscordEmbedBuilder builder = null) { if ((info?.LatestBuild?.Windows?.Download ?? info?.LatestBuild?.Linux?.Download) == null) { return builder ?? new DiscordEmbedBuilder { Title = "Error", Description = "Error communicating with the update API. Try again later.", Color = Config.Colors.Maintenance } } ; var justAppend = builder != null; var latestBuild = info.LatestBuild; var latestPr = latestBuild?.Pr; var currentPr = info.CurrentBuild?.Pr; string url = null; PrInfo latestPrInfo = null; PrInfo currentPrInfo = null; string prDesc = ""; if (!justAppend) { if (latestPr > 0) { latestPrInfo = await githubClient.GetPrInfoAsync(latestPr.Value, Config.Cts.Token).ConfigureAwait(false); url = latestPrInfo?.HtmlUrl ?? "https://github.com/RPCS3/rpcs3/pull/" + latestPr; var userName = latestPrInfo?.User?.Login ?? "???"; var emoji = GetUserNameEmoji(client, userName); if (emoji != null) { userName += " " + emoji; } prDesc = $"PR #{latestPr} by {userName}"; } else { prDesc = "PR #???"; } if (currentPr > 0 && currentPr != latestPr) { currentPrInfo = await githubClient.GetPrInfoAsync(currentPr.Value, Config.Cts.Token).ConfigureAwait(false); } } var desc = latestPrInfo?.Title; if (includePrBody && latestPrInfo?.Body is string prInfoBody && !string.IsNullOrEmpty(prInfoBody)) { desc = $"**{desc.TrimEnd()}**\n\n{prInfoBody}"; } desc = desc?.Trim(); if (!string.IsNullOrEmpty(desc)) { if (GithubLinksHandler.IssueMention.Matches(desc) is MatchCollection issueMatches && issueMatches.Any()) { var uniqueLinks = new HashSet <string>(10); foreach (Match m in issueMatches) { if (m.Groups["issue_mention"]?.Value is string str && !string.IsNullOrEmpty(str) && uniqueLinks.Add(str)) { var name = str; var num = m.Groups["number"].Value; if (string.IsNullOrEmpty(num)) { num = m.Groups["also_number"].Value; } if (string.IsNullOrEmpty(num)) { num = m.Groups["another_number"].Value; name = "#" + num; } if (string.IsNullOrEmpty(num)) { continue; } desc = desc.Replace(str, $"[{name}](https://github.com/RPCS3/rpcs3/issues/{num})"); } } } if (GithubLinksHandler.CommitMention.Matches(desc) is MatchCollection commitMatches && commitMatches.Any()) { var uniqueLinks = new HashSet <string>(2); foreach (Match m in commitMatches) { if (m.Groups["commit_mention"]?.Value is string lnk && !string.IsNullOrEmpty(lnk) && uniqueLinks.Add(lnk)) { var num = m.Groups["commit_hash"].Value; if (string.IsNullOrEmpty(num)) { continue; } if (num.Length > 7) { num = num[..7];
private void Process(UpdateInfo update) { if (update.IsCommand()) { ProcessCommand(update.Message); } else { ProcessParameter(update.Message); } }
/// <summary> /// 更新用户 /// </summary> /// <param name="menu"></param> /// <returns></returns> public bool UpdateSysUser(UpdateInfo updateInfo) { return(_sysUserBizService.UpdateSysUser(updateInfo)); }