private async Task Reconnect(PhotonServerDefinition server, string latestVersion, TimeSpan timeout) { using (var tokenSource = new CancellationTokenSource(timeout)) using (var client = new WebClient()) { var token = tokenSource.Token; while (true) { token.ThrowIfCancellationRequested(); try { var url = NetPath.Combine(server.Url, "api/version"); var version = await client.DownloadStringTaskAsync(url); if (!VersionTools.HasUpdates(version, latestVersion)) { break; } } catch (Exception error) when(error is SocketException || error is WebException) { await Task.Delay(1000, tokenSource.Token); } } } }
public async Task PublishAsync(CancellationToken token) { client.Output? .Append("Checking Package ", ConsoleColor.DarkCyan) .Append(PackageId, ConsoleColor.Cyan) .AppendLine(" for updates...", ConsoleColor.DarkCyan); var versionList = await client.GetAllPackageVersions(PackageId, token); var packageVersion = versionList.Any() ? versionList.Max() : null; if (!VersionTools.HasUpdates(packageVersion, Version)) { client.Output? .Append($"Package '{PackageId}' is up-to-date. Version ", ConsoleColor.DarkBlue) .AppendLine(packageVersion, ConsoleColor.Blue); return; } var cl = new NuGetCommandLine { ExeFilename = ExeFilename, ApiKey = client.ApiKey, Output = client.Output, }; cl.Pack(PackageDefinition, PackageDirectory); var packageFilename = Directory .GetFiles(PackageDirectory, $"{PackageId}.*.nupkg") .FirstOrDefault(); await client.PushAsync(packageFilename, token); }
private async Task PublishPackage(string packageId, string packageDefinitionFilename, string assemblyVersion, CancellationToken token) { var versionList = await nugetCore.GetAllPackageVersions(packageId, token); var packageVersion = versionList.Any() ? versionList.Max() : null; if (!VersionTools.HasUpdates(packageVersion, assemblyVersion)) { Context.Output.WriteLine($"Package '{packageId}' is up-to-date. Version {packageVersion}", ConsoleColor.DarkCyan); return; } await nugetCmd.RunAsync(new NuGetPackArguments { Filename = packageDefinitionFilename, Version = assemblyVersion, OutputDirectory = nugetPackageDir, Properties = { ["Configuration"] = "Release", ["Platform"] = "AnyCPU", ["frameworkVersion"] = frameworkVersion, }, }, token); var packageFilename = Directory .GetFiles(nugetPackageDir, $"{packageId}.*.nupkg") .FirstOrDefault(); if (string.IsNullOrEmpty(packageFilename)) { throw new ApplicationException($"No package found matching package ID '{packageId}'!"); } await nugetCore.PushAsync(packageFilename, token); }
public static void ChangeVersion() { //先更新版本号文件 if (SFTPHelper.DownLoad( new SFTPHelper(sftpIp, sftpUserName, sftpPassword), GetVersionPath(), sftpPath + GameConfig.remoteFolder + "/" + versionName)) { Debug.Log("下载版本文件成功"); //最后一位+1 VersionInfo versionInfo = JsonMapper.ToObject <VersionInfo>(File.ReadAllText(GetVersionPath())); versionInfo.version = VersionTools.AddAbVersion(versionInfo.version); //上传最新版本号文件 if (SFTPHelper.UpLoad( new SFTPHelper(sftpIp, sftpUserName, sftpPassword), GetVersionPath(), sftpPath + GameConfig.remoteFolder + "/" + versionName)) { Debug.Log("上传版本文件成功"); } else { Debug.LogError("上传版本文件失败"); } } else { Debug.LogError("下载版本文件失败"); } }
public async Task Run(CommandContext context) { ConsoleEx.Out .WriteLine($"Photon CLI {Configuration.Version}", ConsoleColor.DarkBlue) .WriteLine("Checking for updates...", ConsoleColor.DarkCyan); var index = await DownloadTools.GetLatestCliIndex(); var latestVersion = index.Version; if (!VersionTools.HasUpdates(Configuration.Version, latestVersion)) { ConsoleEx.Out.WriteLine("CLI is up-to-date.", ConsoleColor.DarkBlue); return; } ConsoleEx.Out.Write("Downloading CLI update ", ConsoleColor.DarkCyan) .Write(latestVersion, ConsoleColor.Cyan) .WriteLine("...", ConsoleColor.DarkCyan); updateDirectory = Path.Combine(Configuration.Directory, "Updates"); updateFilename = Path.Combine(updateDirectory, "Photon.Server.msi"); await DownloadUpdate(index); ConsoleEx.Out .WriteLine("Download Complete.", ConsoleColor.DarkGreen) .WriteLine("Launching installer...", ConsoleColor.DarkCyan); StartInstaller(); }
public static void UpLoadHotfixZip() { //先更新版本号文件 if (SFTPHelper.DownLoad( new SFTPHelper(sftpIp, sftpUserName, sftpPassword), GetVersionPath(), sftpPath + GameConfig.remoteFolder + "/" + versionName)) { Debug.Log("下载版本文件成功"); VersionInfo versionInfo = JsonMapper.ToObject <VersionInfo>(File.ReadAllText(GetVersionPath())); //重命名压缩包,命名规则为当前版本号最后一位+1 if (SFTPHelper.UpLoad( new SFTPHelper(sftpIp, sftpUserName, sftpPassword), GetHotfixZipPath(), sftpPath + GameConfig.remoteFolder + "/" + VersionTools.AddAbVersion(versionInfo.version) + ".zip")) { Debug.Log("上传热更包成功"); } else { Debug.LogError("上传热更包失败"); } } else { Debug.LogError("下载版本文件失败"); } }
private async Task <MessageClient> Reconnect(ServerAgent agent, TimeSpan timeout) { var client = new MessageClient(PhotonServer.Instance.MessageRegistry); client.ThreadException += (o, e) => { var error = (Exception)e.ExceptionObject; Output.AppendLine("An error occurred while messaging the client!", ConsoleColor.DarkRed) .AppendLine(error.UnfoldMessages()); Log.Error("Message Client error after update!", error); }; var tokenSource = new CancellationTokenSource(timeout); var token = tokenSource.Token; while (true) { token.ThrowIfCancellationRequested(); try { await client.ConnectAsync(agent.TcpHost, agent.TcpPort, tokenSource.Token); var handshakeRequest = new HandshakeRequest { Key = Guid.NewGuid().ToString(), ServerVersion = Configuration.Version, }; var handshakeTimeout = TimeSpan.FromSeconds(HandshakeTimeoutSec); var handshakeResponse = await client.Handshake <HandshakeResponse>(handshakeRequest, handshakeTimeout, TokenSource.Token); if (!string.Equals(handshakeRequest.Key, handshakeResponse.Key, StringComparison.Ordinal)) { throw new ApplicationException("Handshake Failed! An invalid key was returned."); } if (!handshakeResponse.PasswordMatch) { throw new ApplicationException("Handshake Failed! Unauthorized."); } var versionRequest = new AgentGetVersionRequest(); var versionResponse = await client.Send(versionRequest) .GetResponseAsync <AgentGetVersionResponse>(token); if (!VersionTools.HasUpdates(versionResponse.Version, UpdateVersion)) { break; } } catch (SocketException) { await Task.Delay(1000, tokenSource.Token); } } return(client); }
public formMain() { InitializeComponent(); _podcastService = new PodcastService(); _podcasts = new List <PodcastModel>(); lblVersion.Text = VersionTools.GetVersion(); }
void LoadClientServerFile() { // load the self server file if it doesn't already exist if (SelfServerFile == null) { SelfServerFile = ServerFile.Load(clientSFLoc, updatePathVar, customUrlArgs); } updateFrom = SelfServerFile.GetVersionChoice(VersionTools.FromExecutingAssembly()); }
public StartUpModeControl() { this.VersionString = VersionTools.GetAppVersion(); InitializeComponent(); // If possible, point to build-specific release notes Uri releaseNotesUri = MsiUtilities.GetReleaseNotesUri(new SetupExceptionReporter()); if (releaseNotesUri != null) { hlLink.NavigateUri = releaseNotesUri; } }
/// <summary> /// Compute version text, per https://github.com/microsoft/accessibility-insights-windows/issues/347 /// </summary> private string ComputeVersionBarString() { ReleaseChannel?channel = ConfigurationManager.GetDefaultInstance()?.AppConfig?.ReleaseChannel; if ((channel.HasValue && channel.Value != ReleaseChannel.Production) || _updateOption != AutoUpdateOption.NewerThanCurrent) { return(string.Format(CultureInfo.InvariantCulture, Properties.Resources.VersionBarPreReleaseVersion, VersionTools.GetAppVersion())); } return(string.Empty); }
public void CompareTest() { string[] versionA = { "1.0", "1.0 beta 1", "1 a", "1.0 Beta .5", ".9", "1.1.0", "1.0rc2", "1.0beta1", "1.2.03", "1.2rc" }; string[] versionB = { "1.0.0.0", "1.0.0.0 beta 1", "1.0 beta", "1.0 Beta 4", "1.0", "2.1.0", "1.0rc3", "1.0rc2", "1 2 3", "1.2 release candidate" }; int[] expected = { 0, 0, 1, -1, -1, -1, -1, -1, 0, 0 }; //TODO: update this test to use the actual proper return codes from version compare for (int i = 0; i < versionA.Length; i++) { int actual = VersionTools.Compare(versionA[i], versionB[i]); Assert.AreEqual(expected[i], actual); } }
private async Task <MessageClient> Reconnect(ServerAgent agent, TimeSpan timeout, CancellationToken token) { using (var timeoutTokenSource = new CancellationTokenSource(timeout)) using (var mergedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutTokenSource.Token, token)) { while (true) { mergedTokenSource.Token.ThrowIfCancellationRequested(); var client = new MessageClient(PhotonServer.Instance.MessageRegistry); try { using (var connectionTimeoutTokenSource = new CancellationTokenSource(20_000)) using (var connectTokenSource = CancellationTokenSource.CreateLinkedTokenSource(mergedTokenSource.Token, connectionTimeoutTokenSource.Token)) { await client.ConnectAsync(agent.TcpHost, agent.TcpPort, connectTokenSource.Token); await ClientHandshake.Verify(client, connectTokenSource.Token); var versionRequest = new AgentGetVersionRequest(); var versionResponse = await client.Send(versionRequest) .GetResponseAsync <AgentGetVersionResponse>(connectTokenSource.Token); if (string.IsNullOrEmpty(versionResponse.Version)) { Log.Warn("An empty version response was received!"); continue; } if (!VersionTools.HasUpdates(versionResponse.Version, UpdateVersion)) { return(client); } } } catch (SocketException) {} catch (OperationCanceledException) {} catch (Exception error) { Log.Warn("An unhandled exception occurred while attempting to reconnect to an updating agent.", error); } client.Dispose(); await Task.Delay(3_000, mergedTokenSource.Token); } } }
public async Task Run(CommandContext context) { var server = context.Servers.Get(ServerName); ConsoleEx.Out.WriteLine("Checking server version...", ConsoleColor.DarkCyan); string currentVersion = null; await AuthRetryAsync(async() => { currentVersion = await WebClient(server, async client => { return((await client.DownloadStringTaskAsync("api/version")).Trim()); }); }); ConsoleEx.Out .WriteLine($"Photon Server {currentVersion}", ConsoleColor.DarkBlue) .WriteLine("Checking for updates...", ConsoleColor.DarkCyan); var serverIndex = await DownloadTools.GetLatestServerIndex(); if (!VersionTools.HasUpdates(currentVersion, serverIndex.Version)) { ConsoleEx.Out.WriteLine("Server is up-to-date.", ConsoleColor.DarkBlue); return; } await BeginServerUpdate(server, serverIndex); ConsoleEx.Out.WriteLine("Server update started. Waiting for restart...", ConsoleColor.Cyan); await Task.Delay(3000); var timeout = TimeSpan.FromMinutes(2); try { await Reconnect(server, serverIndex.Version, timeout); ConsoleEx.Out.WriteLine("Update completed successfully.", ConsoleColor.DarkGreen); } catch (TaskCanceledException) { throw new ApplicationException($"Server failed to restart within timeout '{timeout}'."); } }
public ModInfo ToInfo(Analyzer analyzer) { ModInfo info = new ModInfo() { ID = this.ID, Name = this.Name, Description = this.Description, Version = this.Version, URL = this.URL, Credits = this.Credits, Authors = this.Authors, }; if (this.MinecraftVersion != null) { info.MinecraftVersion = VersionTools.ToVersion(this.MinecraftVersion); } string[] dependencies = null; if (this.Dependencies1 != null && this.Dependencies1.Length > 0) { dependencies = this.Dependencies1; } else if (this.Dependencies2 != null && this.Dependencies2.Length > 0) { dependencies = this.Dependencies2; } if (dependencies != null) { info.Dependencies = VersionTools.AllToVersion(dependencies); } if (this.LogoFile != null) { info.Logo = analyzer.ReadFile(this.LogoFile); } return(info); }
/// <summary> /// Called when the self-update server files has downloaded successfully. /// </summary> void DownloadClientSFSuccess() { // load the wyUpdate server file, and see if a new version is availiable ServerFile clientSF = ServerFile.Load(clientSFLoc, updatePathVar, customUrlArgs); // check if the wyUpdate is new enough. if (VersionTools.Compare(VersionTools.FromExecutingAssembly(), clientSF.NewVersion) < 0) { SelfUpdateState = SelfUpdateState.WillUpdate; // autoupdate will need this SF if (isAutoUpdateMode) { SelfServerFile = clientSF; LoadClientServerFile(); } } // Show update info page (or just start downloading & installing) if (SkipUpdateInfo) { // check if elevation is needed needElevation = NeedElevationToUpdate(); if (needElevation || SelfUpdateState == SelfUpdateState.WillUpdate) { StartSelfElevated(); } else { ShowFrame(Frame.InstallUpdates); } } else { ShowFrame(Frame.UpdateInfo); } }
private async Task <bool> PreCheckUsingCore(CancellationToken token) { context.Output.WriteBlock() .Write("Checking Package ", ConsoleColor.DarkCyan) .Write(PackageId, ConsoleColor.Cyan) .WriteLine(" for updates...", ConsoleColor.DarkCyan) .Post(); var versionList = await Client.GetAllPackageVersions(PackageId, token); var packageVersion = versionList.Any() ? versionList.Max() : null; if (VersionTools.HasUpdates(packageVersion, Version)) { return(true); } context.Output.WriteBlock() .Write($"Package '{PackageId}' is up-to-date. Version ", ConsoleColor.DarkBlue) .WriteLine(packageVersion, ConsoleColor.Blue) .Post(); return(false); }
private async Task Reconnect(PhotonServerDefinition server, string latestVersion, TimeSpan timeout) { using (var tokenSource = new CancellationTokenSource(timeout)) using (var webClient = WebClientFactory.Create(server, Username, Password)) { var token = tokenSource.Token; while (true) { token.ThrowIfCancellationRequested(); try { var version = await webClient.DownloadStringTaskAsync("api/version"); if (!VersionTools.HasUpdates(version, latestVersion)) { break; } } catch (Exception error) when(error is SocketException || error is WebException) { await Task.Delay(1000, tokenSource.Token); } } } }
/// <summary> /// Constructor /// </summary> public AboutTabControl() { InitializeComponent(); lbVersion.Content = VersionTools.GetAppVersion(); }
public StartUpModeControl() { this.VersionString = VersionTools.GetAppVersion(); InitializeComponent(); WaitHandle.Reset(); }
//returns True if an update is necessary, otherwise false void LoadServerFile(bool setChangesText) { //load the server file ServerFile = ServerFile.Load(serverFileLoc, updatePathVar, customUrlArgs); clientLang.NewVersion = ServerFile.NewVersion; // if no update is needed... if (VersionTools.Compare(update.InstalledVersion, ServerFile.NewVersion) >= 0) { if (isAutoUpdateMode) { // send reponse that there's no update available updateHelper.SendSuccess(null, null, true); // close this client isCancelled = true; // let wyUpdate cleanup the files isAutoUpdateMode = false; // let ServerDownloadedSuccessfully() exit early frameOn = Frame.AlreadyUpToDate; Close(); return; } // Show "All Finished" page ShowFrame(Frame.AlreadyUpToDate); return; } // get the correct update file to download updateFrom = ServerFile.GetVersionChoice(update.InstalledVersion); // if the update install the x64 system32 folder on an x86 machine we need to throw an error if ((updateFrom.InstallingTo & InstallingTo.SysDirx64) == InstallingTo.SysDirx64 && !SystemFolders.Is64Bit()) { error = "Update available, but can't install 64-bit files on a 32-bit machine."; errorDetails = "There's an update available (version " + ServerFile.NewVersion + "). However, this update will install files to the x64 (64-bit) system32 folder. And because this machine is an x86 (32-bit), there isn't an x64 system32 folder."; ShowFrame(Frame.Error); return; } // if the update install the x64 system32 folder on an x86 machine we need to throw an error if ((updateFrom.InstallingTo & InstallingTo.CommonFilesx64) == InstallingTo.CommonFilesx64 && !SystemFolders.Is64Bit()) { error = "Update available, but can't install 64-bit files on a 32-bit machine."; errorDetails = "There's an update available (version " + ServerFile.NewVersion + "). However, this update will install files to the x64 (64-bit) \"Program File\\Common Files\" folder. And because this machine is an x86 (32-bit), there isn't an x64 \"Program File\\Common Files\" folder."; ShowFrame(Frame.Error); return; } // set the changes text if (setChangesText || isAutoUpdateMode) { int i = ServerFile.VersionChoices.IndexOf(updateFrom); //if there's a catch-all update start with one less than "update.VersionChoices.Count - 1" //build the changes from all previous versions for (int j = ServerFile.VersionChoices.Count - 1; j >= i; j--) { //show the version number for previous updates we may have missed if (j != ServerFile.VersionChoices.Count - 1 && (!ServerFile.CatchAllUpdateExists || ServerFile.CatchAllUpdateExists && j != ServerFile.VersionChoices.Count - 2)) { panelDisplaying.AppendAndBoldText("\r\n\r\n" + ServerFile.VersionChoices[j + 1].Version + ":\r\n\r\n"); } // append the changes to the total changes list if (!ServerFile.CatchAllUpdateExists || ServerFile.CatchAllUpdateExists && j != ServerFile.VersionChoices.Count - 2) { if (ServerFile.VersionChoices[j].RTFChanges) { panelDisplaying.AppendRichText(ServerFile.VersionChoices[j].Changes); } else { panelDisplaying.AppendText(ServerFile.VersionChoices[j].Changes); } } } } }
public async Task Run(CommandContext context) { var server = context.Servers.Get(ServerName); ConsoleEx.Out.WriteLine("Retrieving latest agent version...", ConsoleColor.DarkCyan); var agentIndex = await DownloadTools.GetLatestAgentIndex(); var latestVersion = agentIndex.Version; ConsoleEx.Out .Write("Found Latest Version ", ConsoleColor.DarkCyan) .WriteLine(latestVersion, ConsoleColor.Cyan) .WriteLine("Checking agent versions...", ConsoleColor.DarkCyan); HttpAgentVersionListResponse agentVersionResponse = null; await AuthRetryAsync(async() => { agentVersionResponse = await WebClient(server, async client => { var json = (await client.DownloadStringTaskAsync("api/agent/versions")).Trim(); return(JsonConvert.DeserializeObject <HttpAgentVersionListResponse>(json)); }); }); var updateAgents = new List <string>(); foreach (var agentVersion in agentVersionResponse.VersionList.OrderBy(x => x.AgentName)) { if (!string.IsNullOrEmpty(agentVersion.Exception)) { ConsoleEx.Out.Write("Failed to get version of agent ", ConsoleColor.DarkYellow) .Write(agentVersion.AgentName, ConsoleColor.Yellow) .WriteLine($"! {agentVersion.Exception}", ConsoleColor.DarkYellow); continue; } if (!VersionTools.HasUpdates(agentVersion.AgentVersion, latestVersion)) { ConsoleEx.Out.Write("Agent ", ConsoleColor.DarkBlue) .Write(agentVersion.AgentName, ConsoleColor.Blue) .WriteLine(" is up-to-date.", ConsoleColor.DarkBlue); continue; } ConsoleEx.Out.Write("Updating ", ConsoleColor.DarkCyan) .Write(agentVersion.AgentName, ConsoleColor.Cyan) .Write(" from version ", ConsoleColor.DarkCyan) .Write(agentVersion.AgentVersion, ConsoleColor.Cyan) .WriteLine(".", ConsoleColor.DarkCyan); updateAgents.Add(agentVersion.AgentId); } if (!updateAgents.Any()) { ConsoleEx.Out.WriteLine("All agents are up-to-date.", ConsoleColor.DarkGreen); return; } // Download update msi ConsoleEx.Out.Write("Downloading Agent update ", ConsoleColor.DarkCyan) .Write(agentIndex.Version, ConsoleColor.Cyan) .WriteLine("...", ConsoleColor.DarkCyan); var url = NetPath.Combine(Configuration.DownloadUrl, "agent", agentIndex.Version, agentIndex.MsiFilename); var updateDirectory = Path.Combine(Configuration.Directory, "Updates"); var updateFilename = Path.Combine(updateDirectory, "Photon.Agent.msi"); PathEx.CreatePath(updateDirectory); using (var client = new WebClient()) { await client.DownloadFileTaskAsync(url, updateFilename); } ConsoleEx.Out.WriteLine("Download Complete.", ConsoleColor.DarkBlue); // Perform updates var agentIdList = updateAgents.ToArray(); var startResult = await StartSession(server, agentIdList, updateFilename); var sessionId = startResult?.SessionId; if (string.IsNullOrEmpty(sessionId)) { throw new ApplicationException($"An invalid session-id was returned! [{sessionId}]"); } var position = 0; while (true) { var data = await UpdateOutput(server, sessionId, position); if (data == null) { throw new ApplicationException("An empty session-output response was returned!"); } if (data.IsComplete) { break; } if (!data.IsModified) { await Task.Delay(PollIntervalMs); continue; } position = data.NewLength; ConsoleEx.Out.WriteLine(data.NewText, ConsoleColor.Gray); } Result = await GetResult(server, sessionId); ConsoleEx.Out.WriteLine("Update completed successfully.", ConsoleColor.DarkGreen); }
/// <summary> /// Set version text /// [(ReleaseChannel) - ]Version - UIAccess state /// </summary> private void UpdateVersionString() { StringBuilder sb = new StringBuilder(); ReleaseChannel?channel = ConfigurationManager.GetDefaultInstance()?.AppConfig?.ReleaseChannel; if (channel.HasValue && channel.Value != ReleaseChannel.Production) { sb.AppendFormat(CultureInfo.InvariantCulture, "({0}) - ", channel.Value); } sb.AppendFormat(CultureInfo.InvariantCulture, Properties.Resources.UpdateVersionStringVer, VersionTools.GetAppVersion()); if (NativeMethods.IsRunningWithUIAccess()) { sb.Append(Properties.Resources.UpdateVersionStringUIAccess); } this.lblVersion.Content = sb.ToString(); }
public async Task PublishAsync(string packageName, string packageId, CancellationToken token = default(CancellationToken)) { context.Output.WriteBlock() .Write("Updating Application ", ConsoleColor.DarkCyan) .Write(packageName, ConsoleColor.Cyan) .WriteLine("...", ConsoleColor.DarkCyan) .Post(); var photonVars = context.ServerVariables["photon"]; if (photonVars == null) { throw new ApplicationException("Photon Variables were not found!"); } var assemblyVersion = AssemblyTools.GetVersion(AssemblyFilename); var webVersion = await GetWebVersion(); if (!VersionTools.HasUpdates(webVersion, assemblyVersion)) { context.Output.WriteBlock() .Write("Application ", ConsoleColor.DarkBlue) .Write(packageName, ConsoleColor.Blue) .Write(" is up-to-date. Version ", ConsoleColor.DarkBlue) .WriteLine(assemblyVersion, ConsoleColor.Blue) .Post(); return; } // Publish // Create ZIP PathEx.CreatePath(PackagePath); var zipFilename = Path.Combine(PackagePath, $"{packageId}.zip"); await CreateZip(BinPath, zipFilename); // Create Version Directory try { await CreateWebPath(assemblyVersion, token); } catch (WebException) { //... } var webMsiName = $"{packageId}.{assemblyVersion}.msi"; var webZipName = $"{packageId}.{assemblyVersion}.zip"; var msiWebUrl = NetPath.Combine(UploadPath, assemblyVersion, webMsiName); var zipWebUrl = NetPath.Combine(UploadPath, assemblyVersion, webZipName); await UploadFile(MsiFilename, msiWebUrl, token); await UploadFile(zipFilename, zipWebUrl, token); var index = new { version = assemblyVersion, msiFilename = webMsiName, zipFilename = webZipName, notes = "...", }; await UploadIndex(index, assemblyVersion, token); await UpdateLatest(assemblyVersion, token); context.Output.WriteBlock() .Write("Application ", ConsoleColor.DarkGreen) .Write(packageName, ConsoleColor.Green) .Write(" updated successfully. ", ConsoleColor.DarkGreen) .Write("Version ", ConsoleColor.DarkCyan) .WriteLine(assemblyVersion, ConsoleColor.Cyan) .Post(); }
void SelfUpdateProgress(int percentDone, int unweightedPercent, string extraStatus, ProgressStatus status, Object payload) { if (IsDisposed) { return; } //update progress bar if (percentDone > -1 && percentDone < 101) { panelDisplaying.Progress = percentDone; } //update bottom status if (!string.IsNullOrEmpty(extraStatus) && extraStatus != panelDisplaying.ProgressStatus) { panelDisplaying.ProgressStatus = extraStatus; } if (installUpdate != null && (status == ProgressStatus.Success || status == ProgressStatus.Failure)) { installUpdate.ProgressChanged -= SelfUpdateProgress; } if (status == ProgressStatus.Success) { if (frameOn == Frame.Checking) { clientSFLoc = downloader.DownloadingTo; try { // client server file downloaded sucessfully DownloadClientSFSuccess(); } catch (Exception e) { //error occured, show error screen status = ProgressStatus.Failure; payload = e; } } else { switch (update.CurrentlyUpdating) { case UpdateOn.DownloadingSelfUpdate: //set the filename of the downloaded client update file updateFilename = downloader.DownloadingTo; if (isAutoUpdateMode) { SelfUpdateState = SelfUpdateState.Downloaded; // save autoupdate file (new selfupdate state is saved) SaveAutoUpdateData(wyDay.Controls.UpdateStepOn.UpdateAvailable); // begin extracting self update.CurrentlyUpdating = UpdateOn.ExtractSelfUpdate; InstallUpdates(update.CurrentlyUpdating); } else // regular self update mode { panelDisplaying.UpdateItems[0].Status = UpdateItemStatus.Success; //begin extracting and installing the update update.CurrentlyUpdating = UpdateOn.FullSelfUpdate; InstallUpdates(update.CurrentlyUpdating); } break; case UpdateOn.FullSelfUpdate: panelDisplaying.UpdateItems[1].Status = UpdateItemStatus.Success; //start the newly installed client and resume "normal" downloading & updating StartSelfElevated(); break; case UpdateOn.ExtractSelfUpdate: SelfUpdateState = SelfUpdateState.Extracted; // oldSelfLocation already set in the InstallUpdates(ExtractSelfUpdate) newSelfLocation = installUpdate.NewSelfLoc; // save autoupdate file (new selfupdate state is saved) SaveAutoUpdateData(wyDay.Controls.UpdateStepOn.UpdateAvailable); // start the new client StartNewSelfAndClose(); return; case UpdateOn.InstallSelfUpdate: SelfUpdateState = SelfUpdateState.None; // save autoupdate file (new selfupdate state is saved) SaveAutoUpdateData(wyDay.Controls.UpdateStepOn.UpdateReadyToInstall); // we must set new self to false because it's used in StartSelfElevated() // to set the /ns argument for the newly launched wyUpdate IsNewSelf = false; // relaunch newly installed self to do regular update StartSelfElevated(); return; } } } if (status == ProgressStatus.Failure) { bool selfUpdateRequired = VersionTools.Compare(VersionTools.FromExecutingAssembly(), ServerFile.MinClientVersion) < 0; bool canTryCatchAllUpdate = frameOn != Frame.Checking // patch failed && payload.GetType() == typeof(PatchApplicationException) // if the catch-all update isn't the one that failed && updateFrom != SelfServerFile.VersionChoices[SelfServerFile.VersionChoices.Count - 1] // and there is a catch-all update && SelfServerFile.VersionChoices[SelfServerFile.VersionChoices.Count - 1].Version == SelfServerFile.NewVersion; // if a new client is *required* to install the update... if (selfUpdateRequired && !canTryCatchAllUpdate) { //show an error and bail out error = clientLang.SelfUpdateInstallError; errorDetails = ((Exception)payload).Message; ShowFrame(Frame.Error); } else if (frameOn == Frame.Checking) { // client server file failed to download, continue as usual: SelfUpdateState = SelfUpdateState.None; // Show update info page (or just start downloading & installing) if (SkipUpdateInfo) { // check if elevation is needed needElevation = NeedElevationToUpdate(); if (needElevation) { StartSelfElevated(); } else { ShowFrame(Frame.InstallUpdates); } } else { ShowFrame(Frame.UpdateInfo); } } else { if (canTryCatchAllUpdate) { // select the catch all update updateFrom = SelfServerFile.VersionChoices[SelfServerFile.VersionChoices.Count - 1]; // clear errors error = null; errorDetails = null; panelDisplaying.UpdateItems[1].Status = UpdateItemStatus.Nothing; if (isAutoUpdateMode) { // change update state from Downloaded to WillUpdate (just autoupdate) SelfUpdateState = SelfUpdateState.WillUpdate; // save the fact that there's no longer an update file SaveAutoUpdateData(wyDay.Controls.UpdateStepOn.UpdateAvailable); } // download the catch-all update DownloadUpdate(); return; } if (isAutoUpdateMode) { SelfUpdateState = SelfUpdateState.None; if (update.CurrentlyUpdating == UpdateOn.InstallSelfUpdate) { // update has already been downloaded & extracted SaveAutoUpdateData(wyDay.Controls.UpdateStepOn.UpdateReadyToInstall); UpdateHelper_RequestReceived(this, UpdateAction.UpdateStep, UpdateStep.Install); } else { // update hasn't been downloaded yet SaveAutoUpdateData(wyDay.Controls.UpdateStepOn.UpdateAvailable); UpdateHelper_RequestReceived(this, UpdateAction.UpdateStep, UpdateStep.DownloadUpdate); } } else { //self-update failed to download or install //just relaunch old client and continue with update StartSelfElevated(); } } } }
private ModInfo ReadFromClassFile(ZipFileInfo file) { if (file.IsVolumeLabel || file.IsFolder || !file.Name.ToLower().EndsWith(".class")) { return(null); } ClassAnalyzer analyzer = null; using (Stream stream = file.OpenStream()) analyzer = ClassAnalyzer.Read(stream); if (analyzer == null) { return(null); } ModInfo info = new ModInfo(); foreach (JavaAttribute attribute in analyzer.Attributes) { if (attribute == null) { continue; } if (attribute is JavaRuntimeAnnotations) { foreach (JavaAnnotation annotation in ((JavaRuntimeAnnotations)attribute).Annotations) { if (annotation.Name.EndsWith("/fml/common/Mod;")) { if (annotation.Elements.ContainsKey("modid")) { info.ID = (string)annotation.Elements["modid"]; } if (annotation.Elements.ContainsKey("name")) { info.Name = (string)annotation.Elements["name"]; } if (annotation.Elements.ContainsKey("version")) { info.Version = (string)annotation.Elements["version"]; } if (annotation.Elements.ContainsKey("acceptedMinecraftVersions")) { info.MinecraftVersion = VersionTools.ToVersion((string)annotation.Elements["acceptedMinecraftVersions"]); } if (annotation.Elements.ContainsKey("dependencies")) { info.Dependencies = VersionTools.ToVersion((string)annotation.Elements["dependencies"]); } } else if (annotation.Name.EndsWith("/fml/relauncher/IFMLLoadingPlugin$Name;")) { info.Name = (string)annotation.Elements["value"]; if (info.ID == null) { info.ID = info.Name; } } else if (annotation.Name.EndsWith("/fml/relauncher/IFMLLoadingPlugin$MCVersion;")) { info.MinecraftVersion = VersionTools.ToVersion((string)annotation.Elements["value"]); } } } } return(info); }
//returns True if an update is necessary, otherwise false void LoadServerFile(bool setChangesText) { //load the server file ServerFile = ServerFile.Load(serverFileLoc); updateFilename = serverFileLoc; clientLang.NewVersion = ServerFile.NewVersion; // if no update is needed... if (VersionTools.Compare(update.InstalledVersion, ServerFile.NewVersion) >= 0) { if (isAutoUpdateMode) { // send reponse that there's no update available updateHelper.SendSuccess(null, null, true); // close this client isCancelled = true; // let wyUpdate cleanup the files isAutoUpdateMode = false; // let ServerDownloadedSuccessfully() exit early frameOn = Frame.AlreadyUpToDate; Close(); return; } // Show "All Finished" page ShowFrame(Frame.AlreadyUpToDate); return; } // get the correct update file to download updateFrom = ServerFile.GetVersionChoice(update.InstalledVersion); // if the update install the x64 system32 folder on an x86 machine we need to throw an error if ((updateFrom.InstallingTo & InstallingTo.SysDirx64) == InstallingTo.SysDirx64 && !SystemFolders.Is64Bit()) { error = "Update available, but can't install 64-bit files on a 32-bit machine."; errorDetails = "There's an update available (version " + ServerFile.NewVersion + "). However, this update will install files to the x64 (64-bit) system32 folder. And because this machine is an x86 (32-bit), there isn't an x64 system32 folder."; ShowFrame(Frame.Error); return; } // if the update install the x64 system32 folder on an x86 machine we need to throw an error if ((updateFrom.InstallingTo & InstallingTo.CommonFilesx64) == InstallingTo.CommonFilesx64 && !SystemFolders.Is64Bit()) { error = "Update available, but can't install 64-bit files on a 32-bit machine."; errorDetails = "There's an update available (version " + ServerFile.NewVersion + "). However, this update will install files to the x64 (64-bit) \"Program File\\Common Files\" folder. And because this machine is an x86 (32-bit), there isn't an x64 \"Program File\\Common Files\" folder."; ShowFrame(Frame.Error); return; } // Update the client language variables if (VersionTools.Compare(update.InstalledVersion, "1.0.0.0") < 0) { clientLang.UpdateInfo.Content = String.Format("Version {0} of Animatum is ready to be installed. Listed below is its current changelog:", ServerFile.NewVersion); clientLang.UpdateBottom = "Click Install to begin."; clientLang.DownInstall.Content = "Animatum Updater is installing Animatum. This process could take a few minutes."; clientLang.Download = "Downloading Animatum and its dependecies"; clientLang.SuccessUpdate.Content = String.Format("Animatum has been successfully updated to version {0}", ServerFile.NewVersion); clientLang.FinishBottom = "Click Finish to exit and start Animatum."; installing = true; } else { clientLang.UpdateInfo.Content = String.Format("The version of Animatum installed on this computer is {0}. The latest version is {1}. Listed below are the changes and improvements:", update.InstalledVersion, ServerFile.NewVersion); } // set the changes text if (setChangesText || isAutoUpdateMode) { int i = ServerFile.VersionChoices.IndexOf(updateFrom); //if there's a catch-all update start with one less than "update.VersionChoices.Count - 1" //build the changes from all previous versions for (int j = ServerFile.VersionChoices.Count - 1; j >= i; j--) { //show the version number for previous updates we may have missed if (j != ServerFile.VersionChoices.Count - 1 && (!ServerFile.CatchAllUpdateExists || ServerFile.CatchAllUpdateExists && j != ServerFile.VersionChoices.Count - 2)) { panelDisplaying.AppendAndBoldText("\r\n\r\n" + ServerFile.VersionChoices[j + 1].Version + ":\r\n\r\n"); } // append the changes to the total changes list if (!ServerFile.CatchAllUpdateExists || ServerFile.CatchAllUpdateExists && j != ServerFile.VersionChoices.Count - 2) { if (ServerFile.VersionChoices[j].RTFChanges) { panelDisplaying.AppendRichText(ServerFile.VersionChoices[j].Changes); } else { panelDisplaying.AppendText(ServerFile.VersionChoices[j].Changes); } } } } }