CheckForUpdate() public method

public CheckForUpdate ( bool ignoreDeltaUpdates = false, Action progress = null ) : Task
ignoreDeltaUpdates bool
progress Action
return Task
Exemplo n.º 1
0
        /// <summary>
        /// Squirrel check and update.
        /// </summary>
        private async Task CheckAndUpdate(bool checkOnly = false)
        {
            // 6/27/15 - Task.Wait always times out. Seems to be an issue with the return of Squirrel's async methods.
            try
            {
                AddMessage("Start of CheckAndUpdate");
                using (var updateManager = new UpdateManager(Program.PackageUrl, Program.PackageId))
                {
                    // Check
                    AddMessage(String.Format("UpdateManager: {0}", JsonConvert.SerializeObject(updateManager, Formatting.Indented)));
                    AddMessage("Calling UpdateManager.CheckForUpdate");
                    var updateInfo = await updateManager.CheckForUpdate();
                    AddMessage(String.Format(
                                        "UpdateManager.CheckForUpdate returned UpdateInfo: {0}", 
                                        JsonConvert.SerializeObject(updateInfo, Formatting.Indented)));
                    if (checkOnly) { return; }

                    // Update
                    if (updateInfo.ReleasesToApply.Count > 0)
                    {
                        AddMessage("Calling UpdateManager.UpdateApp");
                        var releaseEntry = await updateManager.UpdateApp();
                        AddMessage(String.Format(
                                            "UpdateManager.UpdateApp returned ReleaseEntry: {0}",
                                            JsonConvert.SerializeObject(releaseEntry, Formatting.Indented)));
                    }
                    else { AddMessage("No updates to apply"); }
                }
            }
            catch (Exception exception) 
            { 
                Log.Error("Exception in CheckAndUpdate", exception);
                throw;
            }
        }
Exemplo n.º 2
0
        private static async void Update(Task<string> result)
        {
            if (result.Result == null || result.Result != "1")
                return;

            try
            {
                using (var mgr = new UpdateManager(@"https://releases.noelpush.com/", "NoelPush"))
                {
                    var updates = await mgr.CheckForUpdate();

                    if (updates.ReleasesToApply.Any())
                    {
                        var lastVersion = updates.ReleasesToApply.OrderBy(x => x.Version).Last();

                        await mgr.DownloadReleases(updates.ReleasesToApply);
                        await mgr.ApplyReleases(updates);

                        var latestExe = Path.Combine(mgr.RootAppDirectory, string.Concat("app-", lastVersion.Version), "NoelPush.exe");
                        mgr.Dispose();

                        RestartAppEvent();
                        UpdateManager.RestartApp(latestExe);
                    }
                    mgr.Dispose();
                }
            }
            catch (Exception e)
            {
                LogManager.GetCurrentClassLogger().Error(e.Message);
            }
        }
Exemplo n.º 3
0
        private static async Task Update()
        {
            try
            {
                using (var mgr = new UpdateManager("http://lunyx.net/CasualMeter"))
                {
                    Logger.Info("Checking for updates.");
                    if (mgr.IsInstalledApp)
                    {
                        Logger.Info($"Current Version: v{mgr.CurrentlyInstalledVersion()}");
                        var updates = await mgr.CheckForUpdate();
                        if (updates.ReleasesToApply.Any())
                        {
                            Logger.Info("Updates found. Applying updates.");
                            var release = await mgr.UpdateApp();

                            MessageBox.Show(CleanReleaseNotes(release.GetReleaseNotes(Path.Combine(mgr.RootAppDirectory, "packages"))),
                                $"Casual Meter Update - v{release.Version}");

                            Logger.Info("Updates applied. Restarting app.");
                            UpdateManager.RestartApp();
                        }
                    }
                }
            }
            catch (Exception e)
            {   //log exception and move on
                HandleException(e);
            }
        }
Exemplo n.º 4
0
        private async void ScheduleApplicationUpdates(Object o)
        {
            var location = UpdateHelper.AppUpdateCheckLocation;
            var appName = Assembly.GetExecutingAssembly().GetName().Name;
            using (var mgr = new UpdateManager(location, appName, FrameworkVersion.Net45))
            {
                try
                {
                    UpdateInfo updateInfo = await mgr.CheckForUpdate();
                    if (updateInfo.FutureReleaseEntry != null)
                    {
                        if (updateInfo.CurrentlyInstalledVersion.Version == updateInfo.FutureReleaseEntry.Version) return;
                        await mgr.UpdateApp();

                        // This will show a button that will let the user restart the app
                        Dispatcher.Invoke(ShowUpdateIsAvailable);

                        // This will restart the app automatically
                        //Dispatcher.InvokeAsync<Task>(ShutdownApp);
                    }
                }
                catch (Exception ex)
                {
                    var a = ex;
                }
            }
        }
Exemplo n.º 5
0
        private static ThreadStart UpdateOpenLiveWriter(string downloadUrl, bool checkNow)
        {
            return(async() =>
            {
                if (checkNow)
                {
                    try
                    {
                        using (var manager = new Squirrel.UpdateManager(downloadUrl))
                        {
                            var update = await manager.CheckForUpdate();

                            if (update != null &&
                                update.ReleasesToApply.Count > 0 &&
                                update.FutureReleaseEntry.Version < update.CurrentlyInstalledVersion.Version)
                            {
                                Trace.WriteLine("Update is older than currently running version, not installing.");
                                Trace.WriteLine($"Current: {update.CurrentlyInstalledVersion.Version} Update: {update.FutureReleaseEntry.Version}");
                                return;
                            }

                            await manager.UpdateApp();
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine("Unexpected error while updating Open Live Writer. " + ex);
                    }
                }
            });
        }
Exemplo n.º 6
0
 private async void ButtonUpdateQuestion_OnClick(object sender, RoutedEventArgs e)
  {
      try
      {
          using (var mgr = new UpdateManager(ConfigurationManager.AppSettings["UpdatePath"]))
          {
              var release = await mgr.CheckForUpdate();
              this.UpdateQuestionResult.Text = "Possible Update: " + release.FutureReleaseEntry.Version.ToString();
          }
      }
      catch (Exception test)
      {
          this.UpdateQuestionResult.Text = test.Message;
      }
  }
Exemplo n.º 7
0
        private static void Main()
        {
            Task.Run(async () =>
            {
                var upgraded = false;
                while (!upgraded)
                {
                    await Task.Delay(TimeSpan.FromSeconds(5));

                    using (
                        var mgr = new UpdateManager(@"http://distribute.klonmaschine.de/metrothing/", "metrothing",
                            FrameworkVersion.Net45))
                    {
                        SquirrelAwareApp.HandleEvents(
                            v => mgr.CreateShortcutForThisExe(),
                            v => mgr.CreateShortcutForThisExe(),
                            onAppUninstall: v => mgr.RemoveShortcutForThisExe());

                        // Try the update
                        try
                        {
                            var updateInfo = await mgr.CheckForUpdate();

                            if (updateInfo != null && updateInfo.ReleasesToApply.Count > 0)
                            {
            #if !DEBUG
                                await mgr.UpdateApp();
            #endif

                                upgraded = true;
                                Singleton<InstallationManager>.Instance.Updated(
                                    updateInfo.FutureReleaseEntry.Version.ToString(),
                                    String.Join("", updateInfo.FetchReleaseNotes().Values));
                            }
                        }
                        catch (Exception e)
                        {
                            Trace.WriteLine("Squirrel update failed: " + e.Message);
                        }
                    }

                    if (!upgraded)
                        await Task.Delay(TimeSpan.FromHours(12));
                }
            });

            MetroThing.Program.Main();
        }
 async void bw_DoWork(object sender, DoWorkEventArgs e) {
     do {
         try {
             using (var mgr = new UpdateManager(@"C:\dev\helloworld\HelloWorld\Releases", "HelloWorldSquirrel")) {
                 var updateInfo = await mgr.CheckForUpdate(false, progress => { });
                 if (updateInfo != null && updateInfo.ReleasesToApply.Count != 0) {
                     await mgr.UpdateApp();
                     Restart = true;                            
                 }
             }
         } catch (Exception ex) {
             Console.WriteLine(ex.StackTrace);
         }
         Console.WriteLine("I am running");
         Thread.Sleep(2000);
     } while (true);
 }
Exemplo n.º 9
0
        public async Task UpdateApp()
        {
            var updatePath = ConfigurationManager.AppSettings["UpdatePathFolder"];
            var packageId = ConfigurationManager.AppSettings["PackageID"];

            using (var mgr = new UpdateManager(updatePath, packageId, FrameworkVersion.Net45))
            {
                var updates = await mgr.CheckForUpdate();
                if (updates.ReleasesToApply.Any())
                {
                    var lastVersion = updates.ReleasesToApply.OrderBy(x => x.Version).Last();
                    await mgr.DownloadReleases(new[] { lastVersion });
                    await mgr.ApplyReleases(updates);
                    await mgr.UpdateApp();

                    MessageBox.Show("The application has been updated - please close and restart.");
                }
                else
                {
                    MessageBox.Show("No Updates are available at this time.");
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Check for updates using Squirrel UpdateManager and return the UpdateInfo result.
        /// </summary>
        /// <returns></returns>
        public static async Task <UpdateInfo> CheckForUpdateAsync()
        {
            var    appName        = GetAppName();
            var    updateLocation = GetUpdateLocation();
            object ret            = null;

            _log.Debug("Checking for update. Called " + Utilities.GetCallerName() + " with UpdateLocation = \"" + updateLocation + "\" and AppName = " + appName + "\".");

            using (var mgr = new Squirrel.UpdateManager(updateLocation, appName, Squirrel.FrameworkVersion.Net45))
            {
                try
                {
                    var updateInfo = await mgr.CheckForUpdate().ConfigureAwait(false);

                    ret = updateInfo;
                }
                catch (Exception)
                {
                    throw;
                }

                return((UpdateInfo)ret);
            }
        }
Exemplo n.º 11
0
        private async Task<string> SquirrelUpdate(bool showInfo)
        {
            try
            {
                using (UpdateManager _manager = new UpdateManager(ConfigurationManager.AppSettings["CurrentReleaseURL"]))
                {
                    UpdateInfo _update = await _manager.CheckForUpdate();

                    if (_update.ReleasesToApply.Any())
                    {
                        Version _newVersion = _update.ReleasesToApply.OrderByDescending(r => r.Version).First().Version.Version;

                        Update _updateWindow = new Update();
                        _updateWindow.Show();

                        await _manager.UpdateApp((p) => _updateWindow.SetProgress(p));

                        _updateWindow.Close();

                        return Utilities.Paths.Exe(_newVersion);
                    }
                    else if (showInfo)
                    {
                        MessageBox.Show(Framework.Resources.UpdateSuccessText, Framework.Resources.AppName, MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly);
                    }
                }
            }
            catch (WebException)
            {
                if (showInfo)
                {
                    MessageBox.Show(Framework.Resources.UpdateErrorText, Framework.Resources.UpdateErrorTitle, MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly);
                }
            }
            catch (Exception e)
            {
                Framework.Settings.Instance.AutoUpdate = false;
                Framework.Settings.Instance.Save();

                using (EventLog _log = new EventLog("Application"))
                {
                    _log.Source = Framework.Resources.AppName;
                    _log.WriteEntry(e.ToString(), EventLogEntryType.Error, 100, 1);
                }

                MessageBox.Show(Framework.Resources.UpdateErrorFatalText, Framework.Resources.UpdateErrorTitle, MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly);
            }

            return null;
        }
Exemplo n.º 12
0
 /// <summary>
 /// Update the program
 /// </summary>
 /// <returns></returns>
 private async Task Squirrel_UpdateAppAsync(bool showMessages = false)
 {
     Debug.WriteLine("Checking for updates...");
     try
     {
         using (var mgr = new UpdateManager("https://s3.amazonaws.com/steamdesktopauthenticator/releases"))
         {
             UpdateInfo update = await mgr.CheckForUpdate();
             if(update.ReleasesToApply.Count > 0)
             {
                 await mgr.UpdateApp();
                 MessageBox.Show("A new version has been installed. Restart to apply.", "Updater", MessageBoxButtons.OK, MessageBoxIcon.Information);
             }
             else
             {
                 if (showMessages)
                 {
                     MessageBox.Show("You are using the latest version.", "Updater", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 }
             }
         }
     }
     catch (Exception err)
     {
         Debug.WriteLine("Failed");
         if (showMessages)
         {
             MessageBox.Show(err.ToString(), "Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// Check for updates using Squirrel UpdateManager and return the UpdateInfo result.
        /// </summary>
        /// <returns></returns>
        public static async Task<UpdateInfo> CheckForUpdateAsync()
        {
            var appName = GetAppName();
            var updateLocation = GetUpdateLocation();
            object ret = null;

            _log.Debug("Checking for update. Called " + Utilities.GetCallerName() + " with UpdateLocation = \"" + updateLocation + "\" and AppName = " + appName + "\".");

            using (var mgr = new Squirrel.UpdateManager(updateLocation, appName, Squirrel.FrameworkVersion.Net45))
            {
                try
                {
                    var updateInfo = await mgr.CheckForUpdate().ConfigureAwait(false);
                    ret = updateInfo;
                }
                catch (Exception)
                {
                    throw;
                }

                return (UpdateInfo)ret;
            }
        }
Exemplo n.º 14
0
        public async Task<string> Download(string updateUrl, string appName = null)
        {
            appName = appName ?? getAppNameFromDirectory();

            // NB: Always basing the rootAppDirectory relative to ours allows us to create Portable
            // Applications
            var ourDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..");

            this.Log().Info("Fetching update information, downloading from " + updateUrl);
            using (var mgr = new UpdateManager(updateUrl, appName, FrameworkVersion.Net45, ourDir)) {
                var updateInfo = await mgr.CheckForUpdate(progress: x => Console.WriteLine(x / 3));
                await mgr.DownloadReleases(updateInfo.ReleasesToApply, x => Console.WriteLine(33 + x / 3));

                var releaseNotes = updateInfo.FetchReleaseNotes();

                var sanitizedUpdateInfo = new {
                    currentVersion = updateInfo.CurrentlyInstalledVersion.Version.ToString(),
                    futureVersion = updateInfo.FutureReleaseEntry.Version.ToString(),
                    releasesToApply = updateInfo.ReleasesToApply.Select(x => new {
                        version = x.Version.ToString(),
                        releaseNotes = releaseNotes.ContainsKey(x) ? releaseNotes[x] : "",
                    }).ToArray(),
                };

                return SimpleJson.SerializeObject(sanitizedUpdateInfo);
            }
        }
 public async Task WhenUrlResultsInWebExceptionReturnNull()
 {
     // This should result in a WebException (which gets caught) unless you can actually access http://lol
     using (var fixture = new UpdateManager("http://lol", "theApp", FrameworkVersion.Net45)) {
         var updateInfo = await fixture.CheckForUpdate();
         Assert.Null(updateInfo);
     }
 }
            public async Task WhenReleasesFileIsBlankReturnNull()
            {
                string tempDir;
                using (Utility.WithTempDirectory(out tempDir)) {
                    var fixture = new UpdateManager(tempDir, "MyAppName", FrameworkVersion.Net40);
                    File.WriteAllText(Path.Combine(tempDir, "RELEASES"), "");

                    using (fixture) {
                        Assert.Null(await fixture.CheckForUpdate());
                    }
                }
            }
Exemplo n.º 17
0
        private async Task SquirrelUpdate(bool showInfo)
        {
            try
            {
                using (UpdateManager _manager = new UpdateManager(ConfigurationManager.AppSettings["CurrentReleaseURL"]))
                {
                    UpdateInfo _update = await _manager.CheckForUpdate();

                    if (_update.ReleasesToApply.Any())
                    {
                        Version _newVersion = _update.ReleasesToApply.OrderByDescending(r => r.Version).First().Version.Version;

                        Update _updateWindow = new Update();
                        _updateWindow.Show();

                        await _manager.UpdateApp((p) => _updateWindow.SetProgress(p));

                        _updateWindow.Close();

                        string _newExePath = Utilities.Paths.Exe(_newVersion);

                        if (Framework.Settings.Instance.RunAtStartup)
                        {
                            Utilities.Startup.EnableStartupTask(_newExePath);
                        }

                        Process.Start(_newExePath);

                        Shutdown();
                    }
                    else if (showInfo)
                    {
                        MessageBox.Show(Constants.Generic.UPDATEMSG, Constants.Generic.PROGRAMNAME, MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly);
                    }
                }
            }
            catch (WebException)
            {
                if (showInfo)
                {
                    MessageBox.Show(Constants.Generic.UPDATEERROR, Constants.Generic.UPDATEERRORTITLE, MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly);
                }
            }
        }
Exemplo n.º 18
0
        public async Task Update(string updateUrl, string appName = null)
        {
            appName = appName ?? getAppNameFromDirectory();

            this.Log().Info("Starting update, downloading from " + updateUrl);

            // NB: Always basing the rootAppDirectory relative to ours allows us to create Portable
            // Applications
            var ourDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..");

            using (var mgr = new UpdateManager(updateUrl, appName, FrameworkVersion.Net45, ourDir)) {
                bool ignoreDeltaUpdates = false;

            retry:
                try {
                    var updateInfo = await mgr.CheckForUpdate(ignoreDeltaUpdates: ignoreDeltaUpdates, progress: x => Console.WriteLine(x / 3));
                    await mgr.DownloadReleases(updateInfo.ReleasesToApply, x => Console.WriteLine(33 + x / 3));
                    await mgr.ApplyReleases(updateInfo, x => Console.WriteLine(66 + x / 3));
                } catch (Exception ex) {
                    if (ignoreDeltaUpdates) {
                        this.Log().ErrorException("Really couldn't apply updates!", ex);
                        throw;
                    }

                    this.Log().WarnException("Failed to apply updates, falling back to full updates", ex);
                    ignoreDeltaUpdates = true;
                    goto retry;
                }

                var updateTarget = Path.Combine(mgr.RootAppDirectory, "Update.exe");

                await this.ErrorIfThrows(() =>
                    mgr.CreateUninstallerRegistryEntry(),
                    "Failed to create uninstaller registry entry");
            }
        }
 private async void ShowAboutWindow()
 {
     using (var mgr = new UpdateManager("http://arkmanager.teamitf.co.uk/iNGen/Releases/", "iNGen"))
     {
         try
         {
             UpdateInfo updateInfo = await mgr.CheckForUpdate();
             if (updateInfo.FutureReleaseEntry != null)
             {
                 if (updateInfo.CurrentlyInstalledVersion != null)
                 {
                     XElement xelement = XElement.Load("http://arkmanager.teamitf.co.uk/iNGen/version.xml");
                     StringReader reader = new StringReader(xelement.ToString());
                     System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(Models.AppUpdates));
                     Models.AppUpdates appUpdates = (Models.AppUpdates)xmlSerializer.Deserialize(reader);
                     string changes = MakeChangeLog(appUpdates);
                     var updateDialog = new Views.AboutApp(updateInfo, changes) { Owner = this };
                     var result = updateDialog.ShowDialog();
                     if (result == false) return;
                     CheckForUpdates();
                 }
             }
         }
         catch (Exception ex)
         { }
     }
 }
		private static async Task<bool> SquirrelUpdate(SplashScreenWindow splashScreenWindow, UpdateManager mgr, bool ignoreDelta = false)
		{
			try
			{
				Log.Info($"Checking for updates (ignoreDelta={ignoreDelta})");
				splashScreenWindow.StartSkipTimer();
				var updateInfo = await mgr.CheckForUpdate(ignoreDelta);
				if(!updateInfo.ReleasesToApply.Any())
				{
					Log.Info("No new updated available");
					return false;
				}
				var latest = updateInfo.ReleasesToApply.LastOrDefault()?.Version;
				var current = mgr.CurrentlyInstalledVersion();
				if(latest <= current)
				{
					Log.Info($"Installed version ({current}) is greater than latest release found ({latest}). Not downloading updates.");
					return false;
				}
				if(IsRevisionIncrement(current?.Version, latest?.Version))
				{
					Log.Info($"Latest update ({latest}) is revision increment. Updating in background.");
					splashScreenWindow.SkipUpdate = true;
				}
				Log.Info($"Downloading {updateInfo.ReleasesToApply.Count} {(ignoreDelta ? "" : "delta ")}releases, latest={latest?.Version}");
				await mgr.DownloadReleases(updateInfo.ReleasesToApply, splashScreenWindow.Updating);
				Log.Info("Applying releases");
				await mgr.ApplyReleases(updateInfo, splashScreenWindow.Installing);
				await mgr.CreateUninstallerRegistryEntry();
				Log.Info("Done");
				return true;
			}
			catch(Exception ex)
			{
				if(ignoreDelta)
					return false;
				if(ex is Win32Exception)
					Log.Info("Not able to apply deltas, downloading full release");
				return await SquirrelUpdate(splashScreenWindow, mgr, true);
			}
		}
        private async void CheckForUpdates()
        {
            using (var mgr = new UpdateManager("http://arkmanager.teamitf.co.uk/iNGen/Releases/", "iNGen"))
            {
                SquirrelAwareApp.HandleEvents(
                    onInitialInstall: v => mgr.CreateShortcutForThisExe(),
                    onAppUpdate: v => mgr.CreateShortcutForThisExe(),
                    onAppUninstall: v => mgr.RemoveShortcutForThisExe());

                try
                {
                    UpdateInfo updateInfo = await mgr.CheckForUpdate();
                    if (updateInfo.FutureReleaseEntry != null)
                    {
                        if (updateInfo.CurrentlyInstalledVersion != null)
                        {
                            XElement xelement = XElement.Load("http://arkmanager.teamitf.co.uk/iNGen/version.xml");
                            StringReader reader = new StringReader(xelement.ToString());
                            System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(Models.AppUpdates));
                            Models.AppUpdates appUpdates = (Models.AppUpdates)xmlSerializer.Deserialize(reader);
                            string changes = MakeChangeLog(appUpdates);
                            if (updateInfo.CurrentlyInstalledVersion.Version == updateInfo.FutureReleaseEntry.Version) return;
                            var updateDialog = new Views.AppUpdate(updateInfo, changes) { Owner = this };
                            var result = updateDialog.ShowDialog();
                            if (result == false) return;
                            await mgr.UpdateApp();
                            var oldPath = System.IO.Path.Combine(mgr.RootAppDirectory, "app-" + updateInfo.CurrentlyInstalledVersion.Version.ToString(), "UserData");
                            var newPath = System.IO.Path.Combine(mgr.RootAppDirectory, "app-" + updateInfo.FutureReleaseEntry.Version.ToString(), "UserData");
                            DirectoryInfo d = new DirectoryInfo(oldPath);
                            var files = d.GetFiles();
                            foreach (var file in files)
                            {
                                file.CopyTo(System.IO.Path.Combine(newPath, file.Name), true);
                            }

                            MessageBox.Show("iNGen Has been Updated. Please Re-Launch It.");
                            Application.Current.Shutdown(0);
                        }
                        else
                        {
                            await mgr.UpdateApp();
                            MessageBox.Show("iNGen Has been Updated. Please Re-Launch It.");
                            Application.Current.Shutdown(0);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Checking for Updates Failed: " + ex.Message);
                }
            }
        }
Exemplo n.º 22
0
 public async Task WhenUrlResultsInWebExceptionWeShouldThrow()
 {
     // This should result in a WebException (which gets caught) unless you can actually access http://lol
     using (var fixture = new UpdateManager("http://lol", "theApp")) {
         await Assert.ThrowsAsync(typeof(WebException), () => fixture.CheckForUpdate());
     }
 }
Exemplo n.º 23
0
        private IObservable<UpdateAvailableNotification> CheckForUpdates()
        {
            return Observable.Create<UpdateAvailableNotification>(async obs =>
            {
                string updateUrl = AppModel.GetRegistrySetting("UpdateUrl");
                Log.DebugFormat("UpdateUrl = {0}", updateUrl);
                using (var updateManager = new UpdateManager(updateUrl ?? @"http://bradleygrainger.com/GitBlame/download", "GitBlame", FrameworkVersion.Net45))
                {
                    try
                    {
                        UpdateInfo updateInfo = await updateManager.CheckForUpdate();
                        var releases = updateInfo == null ? new List<ReleaseEntry>() : updateInfo.ReleasesToApply.ToList();
                        if (updateInfo == null)
                            Log.Info("CheckForUpdate returned (null)");
                        else
                            Log.InfoFormat("CheckForUpdate: Current=({0}), Future=({1}), {2} ReleasesToApply", ToLog(updateInfo.CurrentlyInstalledVersion), ToLog(updateInfo.FutureReleaseEntry), releases.Count);

                        if (releases.Count != 0)
                        {
                            await updateManager.DownloadReleases(releases);
                            Log.Info("Downloaded releases");
                            var newDirectory = await updateManager.ApplyReleases(updateInfo);
                            Log.InfoFormat("ApplyReleases: {0}", newDirectory);

                            if (!string.IsNullOrEmpty(newDirectory))
                            {
                                var newPath = Path.Combine(newDirectory, "GitBlame.exe");
                                VisualStudioIntegration.ReintegrateWithVisualStudio(newPath);
                                obs.OnNext(new UpdateAvailableNotification(newPath));
                            }
                        }
                    }
                    catch (TimeoutException ex)
                    {
                        // Failed to check for updates; try again the next time the app is run
                        Log.ErrorFormat("CheckForUpdates timed out: {0}", ex, ex.Message);
                    }
                    catch (Exception ex)
                    {
                        // Squirrel throws a new Exception in many failure scenarios
                        Log.ErrorFormat("CheckForUpdates failed: {0}", ex, ex.Message);
                        if (ex.InnerException != null)
                            Log.ErrorFormat("CheckForUpdates inner exception: {0}", ex.InnerException, ex.InnerException.Message);
                    }
                }
                obs.OnCompleted();
            });
        }
Exemplo n.º 24
0
            public async Task WhenReleasesFileDoesntExistThrowACustomError()
            {
                string tempDir;
                using (Utility.WithTempDirectory(out tempDir)) {
                    var fixture = new UpdateManager(tempDir, "MyAppName");

                    using (fixture) {
                        await Assert.ThrowsAsync<Exception>(() => fixture.CheckForUpdate());
                    }
                }
            }
Exemplo n.º 25
0
            public async Task WhenReleasesFileIsBlankThrowAnException()
            {
                string tempDir;
                using (Utility.WithTempDirectory(out tempDir)) {
                    var fixture = new UpdateManager(tempDir, "MyAppName");
                    File.WriteAllText(Path.Combine(tempDir, "RELEASES"), "");

                    using (fixture) {
                        await Assert.ThrowsAsync(typeof(Exception), () => fixture.CheckForUpdate());
                    }
                }
            }
Exemplo n.º 26
0
            public async Task WhenTwoRemoteUpdatesAreAvailableChoosesDeltaVersion()
            {
                string tempDir;
                using (Utility.WithTempDirectory(out tempDir))
                {
                    var appDir = Path.Combine(tempDir, "theApp");
                    var localPackages = Path.Combine(appDir, "packages");
                    var remotePackages = Path.Combine(tempDir, "releases");
                    Directory.CreateDirectory(localPackages);
                    Directory.CreateDirectory(remotePackages);

                    new[] { "Squirrel.Core.1.0.0.0-full.nupkg", }.ForEach(x => {
                        var path = IntegrationTestHelper.GetPath("fixtures", x);
                        File.Copy(path, Path.Combine(localPackages, x));
                    });

                    new[] {
                        "Squirrel.Core.1.0.0.0-full.nupkg",
                        "Squirrel.Core.1.1.0.0-delta.nupkg",
                        "Squirrel.Core.1.1.0.0-full.nupkg",
                    }.ForEach(x => {
                        var path = IntegrationTestHelper.GetPath("fixtures", x);
                        File.Copy(path, Path.Combine(remotePackages, x));
                    });

                    var fixture = new UpdateManager.ApplyReleasesImpl(appDir);

                    // sync both release files
                    await fixture.updateLocalReleasesFile();
                    ReleaseEntry.BuildReleasesFile(remotePackages);

                    using (var mgr = new UpdateManager(remotePackages, "theApp", tempDir, new FakeUrlDownloader())) {
                        UpdateInfo updateInfo;
                        updateInfo = await mgr.CheckForUpdate();
                        Assert.True(updateInfo.ReleasesToApply.First().IsDelta);

                        updateInfo = await mgr.CheckForUpdate(ignoreDeltaUpdates: true);
                        Assert.False(updateInfo.ReleasesToApply.First().IsDelta);
                    }
                }
            }
Exemplo n.º 27
0
            public async Task WhenFolderDoesNotExistThrowHelpfulError()
            {
                string tempDir;
                using (Utility.WithTempDirectory(out tempDir)) {
                    var directory = Path.Combine(tempDir, "missing-folder");
                    var fixture = new UpdateManager(directory, "MyAppName");

                    using (fixture) {
                        await Assert.ThrowsAsync<Exception>(() => fixture.CheckForUpdate());
                    }
                }
            }
Exemplo n.º 28
0
            public async Task WhenRemoteReleasesDoNotHaveDeltasNoUpdatesAreApplied()
            {
                string tempDir;
                using (Utility.WithTempDirectory(out tempDir))
                {
                    var appDir = Path.Combine(tempDir, "theApp");
                    var localPackages = Path.Combine(appDir, "packages");
                    var remotePackages = Path.Combine(tempDir, "releases");
                    Directory.CreateDirectory(localPackages);
                    Directory.CreateDirectory(remotePackages);

                    new[] {
                        "Squirrel.Core.1.0.0.0-full.nupkg",
                        "Squirrel.Core.1.1.0.0-delta.nupkg",
                        "Squirrel.Core.1.1.0.0-full.nupkg",
                    }.ForEach(x => {
                        var path = IntegrationTestHelper.GetPath("fixtures", x);
                        File.Copy(path, Path.Combine(localPackages, x));
                    });

                    new[] {
                        "Squirrel.Core.1.0.0.0-full.nupkg",
                        "Squirrel.Core.1.1.0.0-full.nupkg",
                    }.ForEach(x => {
                        var path = IntegrationTestHelper.GetPath("fixtures", x);
                        File.Copy(path, Path.Combine(remotePackages, x));
                    });

                    var fixture = new UpdateManager.ApplyReleasesImpl(appDir);

                    // sync both release files
                    await fixture.updateLocalReleasesFile();
                    ReleaseEntry.BuildReleasesFile(remotePackages);

                    UpdateInfo updateInfo;
                    using (var mgr = new UpdateManager(remotePackages, "theApp", tempDir, new FakeUrlDownloader())) {
                        updateInfo = await mgr.CheckForUpdate();
                    }

                    Assert.NotNull(updateInfo);
                    Assert.Empty(updateInfo.ReleasesToApply);
                }
            }
Exemplo n.º 29
0
        public async Task<string> Download(string updateUrl, string appName = null)
        {
            appName = appName ?? getAppNameFromDirectory();

            this.Log().Info("Fetching update information, downloading from " + updateUrl);
            using (var mgr = new UpdateManager(updateUrl, appName)) {
                var updateInfo = await mgr.CheckForUpdate(progress: x => Console.WriteLine(x / 3));
                await mgr.DownloadReleases(updateInfo.ReleasesToApply, x => Console.WriteLine(33 + x / 3));

                var releaseNotes = updateInfo.FetchReleaseNotes();

                var sanitizedUpdateInfo = new {
                    currentVersion = updateInfo.CurrentlyInstalledVersion.Version.ToString(),
                    futureVersion = updateInfo.FutureReleaseEntry.Version.ToString(),
                    releasesToApply = updateInfo.ReleasesToApply.Select(x => new {
                        version = x.Version.ToString(),
                        releaseNotes = releaseNotes.ContainsKey(x) ? releaseNotes[x] : "",
                    }).ToArray(),
                };

                return SimpleJson.SerializeObject(sanitizedUpdateInfo);
            }
        }
Exemplo n.º 30
0
        public async Task Update(string updateUrl, string appName = null)
        {
            appName = appName ?? getAppNameFromDirectory();

            this.Log().Info("Starting update, downloading from " + updateUrl);

            using (var mgr = new UpdateManager(updateUrl, appName)) {
                bool ignoreDeltaUpdates = false;
                this.Log().Info("About to update to: " + mgr.RootAppDirectory);

            retry:
                try {
                    var updateInfo = await mgr.CheckForUpdate(ignoreDeltaUpdates: ignoreDeltaUpdates, progress: x => Console.WriteLine(x / 3));
                    await mgr.DownloadReleases(updateInfo.ReleasesToApply, x => Console.WriteLine(33 + x / 3));
                    await mgr.ApplyReleases(updateInfo, x => Console.WriteLine(66 + x / 3));
                } catch (Exception ex) {
                    if (ignoreDeltaUpdates) {
                        this.Log().ErrorException("Really couldn't apply updates!", ex);
                        throw;
                    }

                    this.Log().WarnException("Failed to apply updates, falling back to full updates", ex);
                    ignoreDeltaUpdates = true;
                    goto retry;
                }

                var updateTarget = Path.Combine(mgr.RootAppDirectory, "Update.exe");

                await this.ErrorIfThrows(() =>
                    mgr.CreateUninstallerRegistryEntry(),
                    "Failed to create uninstaller registry entry");
            }
        }
Exemplo n.º 31
0
        /// <summary>
        /// Handles the Click event of the buttonUpdate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private async void ButtonUpdate_Click(object sender, EventArgs e)
        {
            string updateUrl = @"http://journaley.s3.amazonaws.com/stable";

            string updateSrcFile = Path.Combine(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                "UpdateSource");

            if (File.Exists(updateSrcFile))
            {
                updateUrl = File.ReadAllText(updateSrcFile, System.Text.Encoding.UTF8).Trim();
            }

            // Update Check
            if (this.Owner is MainForm)
            {
                ++((MainForm)this.Owner).UpdateProcessCount;
            }

            try
            {
                using (var mgr = new UpdateManager(updateUrl))
                {
                    // Disable update check when in develop mode.
                    if (!mgr.IsInstalledApp)
                    {
                        MessageBox.Show("Checking for update is disabled in develop mode.", "Update Journaley");
                        return;
                    }

                    var updateInfo = await mgr.CheckForUpdate();

                    if (updateInfo == null)
                    {
                        MessageBox.Show("Failed to check for update.", "Update Journaley");
                        return;
                    }

                    if (updateInfo.ReleasesToApply.Any())
                    {
                        await mgr.DownloadReleases(updateInfo.ReleasesToApply);
                        await mgr.ApplyReleases(updateInfo);

                        MessageBox.Show(
                            "Journaley has been updated to v" +
                            updateInfo.ReleasesToApply.Max(x => x.Version) + ".\n" +
                            "Restart Journaley to use the new version.",
                            "Update Journaley");

                        this.UpdateAvailable = false;
                        if (this.Owner is MainForm)
                        {
                            ((MainForm)this.Owner).UpdateAvailable = false;
                        }
                    }
                    else
                    {
                        MessageBox.Show("Journaley is already up to date!", "Update Journaley");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occurred while updating.", "Update Journaley");
                Logger.Log(ex.Message);
                Logger.Log(ex.StackTrace);
            }
            finally
            {
                if (this.Owner is MainForm)
                {
                    --((MainForm)this.Owner).UpdateProcessCount;
                }
            }
        }
Exemplo n.º 32
-1
        static void Main(string[] args)
        {
            Console.WriteLine("Starting application...");
            var pathToUpdateFolder = @"\\mindelo\KohortClientRelease\" + ConfigurationManager.AppSettings["AppName"];
            using (var mgr = new UpdateManager(pathToUpdateFolder))
            {
                var updateInfo = mgr.CheckForUpdate().Result;
                if (updateInfo.ReleasesToApply.Count > 0)
                {
                    Console.WriteLine("Updating...");
                    var result = mgr.UpdateApp().Result;
                    Console.WriteLine("Update complete, press enter to exit and then you can start the application anew!");
                    Console.ReadLine();
                    return;
                }
            }

            Console.WriteLine("MyTestApplication has started (version {0}).", Assembly.GetEntryAssembly().GetName().Version);
            Console.WriteLine();

            Console.WriteLine("My sample app setting key has currently \"{0}\" as value.", ConfigurationManager.AppSettings["MySampleSetting"]);

            Console.WriteLine();
            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }