Inheritance: IUpdateManager, IEnableLogger
Ejemplo n.º 1
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);
            }
        }
Ejemplo n.º 2
0
 private async void CheckForAppUpdates()
 {
     using (var updateManager = new UpdateManager(APP_UPDATE_URL, APPLICATION_ID, FrameworkVersion.Net45))
     {
         await updateManager.UpdateApp();
     }
 }
        public async Task UpgradeRunsSquirrelAwareAppsWithUpgradeFlag()
        {
            string tempDir;
            string remotePkgDir;

            using (Utility.WithTempDirectory(out tempDir))
            using (Utility.WithTempDirectory(out remotePkgDir)) {
                IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir);
                var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
                ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));

                using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
                    await fixture.FullInstall(false, new ProgressSource());
                }

                await Task.Delay(1000);

                IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir);
                pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
                ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));

                using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
                    await fixture.UpdateApp();
                }

                await Task.Delay(1000);

                Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args2.txt")));
                Assert.True(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt")));

                var text = File.ReadAllText(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt"), Encoding.UTF8);
                Assert.Contains("updated|0.2.0", text);
            }
        }
Ejemplo 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;
                }
            }
        }
Ejemplo n.º 5
0
 async static void SquirrellUpdate()
 {
     using (var mgr = new UpdateManager(@"C:\DHT\TsunamiLocal\GUI_WPF\bin\x64"))
     {
         await mgr.UpdateApp();
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the App class.
        /// </summary>
        static App()
        {
            Logger.Info(
                "Popcorn starting...");
            var watchStart = Stopwatch.StartNew();

            AppDomain.CurrentDomain.ProcessExit += (sender, args) => UpdateManager.Dispose();

            Directory.CreateDirectory(Helpers.Constants.Logging);

            DispatcherHelper.Initialize();

            LocalizeDictionary.Instance.SetCurrentThreadCulture = true;

            UpdateManager = new UpdateManager(Helpers.Constants.UpdateServerUrl, Helpers.Constants.ApplicationName);

            watchStart.Stop();
            var elapsedStartMs = watchStart.ElapsedMilliseconds;
            Logger.Info(
                $"Popcorn started in {elapsedStartMs} milliseconds.");

            Task.Run(async () =>
            {
                await StartUpdateProcessAsync();
            });
        }
Ejemplo n.º 7
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;
            }
        }
            public async Task InitialInstallSmokeTest()
            {
                string tempDir;
                using (Utility.WithTempDirectory(out tempDir)) {
                    var remotePackageDir = Directory.CreateDirectory(Path.Combine(tempDir, "remotePackages"));
                    var localAppDir = Path.Combine(tempDir, "theApp");

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

                    using (var fixture = new UpdateManager(remotePackageDir.FullName, "theApp", FrameworkVersion.Net45, tempDir)) {
                        await fixture.FullInstall();
                    }

                    var releasePath = Path.Combine(localAppDir, "packages", "RELEASES");
                    File.Exists(releasePath).ShouldBeTrue();

                    var entries = ReleaseEntry.ParseReleaseFile(File.ReadAllText(releasePath, Encoding.UTF8));
                    entries.Count().ShouldEqual(1);

                    new[] {
                        "ReactiveUI.dll",
                        "NSync.Core.dll",
                    }.ForEach(x => File.Exists(Path.Combine(localAppDir, "app-1.0.0.0", x)).ShouldBeTrue());
                }
            }
Ejemplo n.º 9
0
 public async void ProcessStaging()
 {
     using (var mgr = new UpdateManager("https://path/to/my/update/folder"))
     {
         await mgr.UpdateApp();
     }
 }
Ejemplo n.º 10
0
 private void App_OnStartup(object sender, StartupEventArgs e)
 {
     if (e.Args.Length > 0)
     {
         using (var mgr = new UpdateManager("http://zizit.lt"))
         {
             // Note, in most of these scenarios, the app exits after this method
             // completes!
             SquirrelAwareApp.HandleEvents(
                 onInitialInstall: v =>
                 {
                     mgr.CreateShortcutForThisExe();
                     Shutdown();
                 },
                 onAppUpdate: v =>
                 {
                     mgr.CreateShortcutForThisExe();
                     Shutdown();
                 },
                 onAppUninstall: v =>
                 {
                     mgr.RemoveShortcutForThisExe();
                     Shutdown();
                 },
                 onFirstRun: () =>
                 {
                     MessageBox.Show("Success", "Installation successful", MessageBoxButton.OK);
                     Shutdown();
                 });
         }
     }
 }
Ejemplo n.º 11
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);
            }
        }
Ejemplo n.º 12
0
 public App()
 {
     InitializeComponent();
     AppearanceManager.Current.ThemeSource = AppearanceManager.DarkThemeSource;
     Task.Factory.StartNew(async () =>
     {
         AboutViewModel.Instance.State = "Updater process started";
         await Task.Delay(TimeSpan.FromSeconds(1));
         while (true)
         {
             try
             {
                 AboutViewModel.Instance.State = "Ready for the first check...";
                 using (var updateManager = new UpdateManager(Releases))
                 {
                     AboutViewModel.Instance.State = "Updating...";
                     await updateManager.UpdateApp();
                     AboutViewModel.Instance.State = "Updated!";
                 }
             }
             catch (Exception x)
             {
                 AboutViewModel.Instance.State = x.Message;
                 return;
             }
             await Task.Delay(TimeSpan.FromHours(1));
         }
     });
 }
Ejemplo n.º 13
0
            public async Task CallingMethodTwiceShouldUpdateInstaller()
            {
                string remotePkgPath;
                string path;

                using (Utility.WithTempDirectory(out path)) {
                    using (Utility.WithTempDirectory(out remotePkgPath))
                    using (var mgr = new UpdateManager(remotePkgPath, "theApp", path)) {
                        IntegrationTestHelper.CreateFakeInstalledApp("1.0.0.1", remotePkgPath);
                        await mgr.FullInstall();
                    }

                    using (var mgr = new UpdateManager("http://lol", "theApp", path)) {
                        await mgr.CreateUninstallerRegistryEntry();
                        var regKey = await mgr.CreateUninstallerRegistryEntry();

                        Assert.False(String.IsNullOrWhiteSpace((string)regKey.GetValue("DisplayName")));

                        mgr.RemoveUninstallerRegistryEntry();
                    }

                    // NB: Squirrel-Aware first-run might still be running, slow
                    // our roll before blowing away the temp path
                    Thread.Sleep(1000);
                }

                var key = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default)
                    .OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall");

                using (key) {
                    Assert.False(key.GetSubKeyNames().Contains("theApp"));
                }
            }
        public async Task CleanInstallRunsSquirrelAwareAppsWithInstallFlag()
        {
            string tempDir;
            string remotePkgDir;

            using (Utility.WithTempDirectory(out tempDir))
            using (Utility.WithTempDirectory(out remotePkgDir)) {
                IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir);
                var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
                ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));

                using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
                    await fixture.FullInstall(false, new ProgressSource());

                    // NB: We execute the Squirrel-aware apps, so we need to give
                    // them a minute to settle or else the using statement will
                    // try to blow away a running process
                    await Task.Delay(1000);

                    Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args2.txt")));
                    Assert.True(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt")));

                    var text = File.ReadAllText(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt"), Encoding.UTF8);
                    Assert.Contains("firstrun", text);
                }
            }
        }
Ejemplo n.º 15
0
        public ShellViewModel(
            EndpointsViewModel endpoints,
            MessageListViewModel messageList,
            MessageViewerViewModel messageViewer,
            HeadersViewModel headers)
        {
            Version = GetType().Assembly
                .GetCustomAttributes(false)
                .OfType<AssemblyInformationalVersionAttribute>()
                .First()
                .InformationalVersion;

            RefreshCommand = ServiceControl.Instance.IsValid.ToCommand(p => DoRefresh());

            Anchorables = new IContainerViewModel[] { endpoints, messageList };
            Documents = new IContainerViewModel[] { messageViewer, headers };

            Task.Run(async () =>
            {
                using (var mgr = new UpdateManager(@"https://s3.amazonaws.com/serviceinsight/"))
                {
                    await mgr.UpdateApp();
                }
            });
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Execute when app is uninstalling
        /// </summary>
        /// <param name="version"><see cref="Version"/> version</param>
        private static void OnAppUninstall(Version version)
        {
            using (var manager = new UpdateManager(Constants.UpdateServerUrl))
            {
                manager.RemoveShortcutsForExecutable("Popcorn.exe", ShortcutLocation.Desktop);
                manager.RemoveShortcutsForExecutable("Popcorn.exe", ShortcutLocation.StartMenu);
                manager.RemoveShortcutsForExecutable("Popcorn.exe", ShortcutLocation.AppRoot);

                manager.RemoveUninstallerRegistryEntry();
            }
        }
        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);
                }
            }
        }
Ejemplo n.º 18
0
 private void RegisterSquirrelEvents()
 {
     var location = UpdateHelper.AppUpdateCheckLocation;
     var appName = Assembly.GetExecutingAssembly().GetName().Name;
     using (var mgr = new UpdateManager(location, appName, FrameworkVersion.Net45))
     {
         SquirrelAwareApp.HandleEvents(
             onInitialInstall: v => mgr.CreateShortcutForThisExe(),
             onAppUpdate: v => mgr.CreateShortcutForThisExe(),
             onAppUninstall: v => mgr.RemoveShortcutForThisExe()
         );
     }
 }
Ejemplo n.º 19
0
        static void Main()
        {
            try {
                using (var mgr = new UpdateManager("https://s3.amazonaws.com/steamdesktopauthenticator/releases"))
                {
                    // Note, in most of these scenarios, the app exits after this method
                    // completes!
                    SquirrelAwareApp.HandleEvents(
                      onInitialInstall: v => mgr.CreateShortcutForThisExe(),
                      onAppUpdate: v => mgr.CreateShortcutForThisExe(),
                      onAppUninstall: v => mgr.RemoveShortcutForThisExe(),
                      onFirstRun: () => ShowTheWelcomeWizard = true);
                }
            }
            catch
            {
                // Not using a squirrel app
            }

            // run the program only once
            if (PriorProcess() != null)
            {
                MessageBox.Show("Another instance of the app is already running.");
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Manifest man = Manifest.GetManifest();
            if(man.FirstRun)
            {
                // Install VC++ Redist and wait
                new InstallRedistribForm().ShowDialog();

                if (man.Entries.Count > 0)
                {
                    // Already has accounts, just run
                    Application.Run(new MainForm());
                }
                else
                {
                    // No accounts, run welcome form
                    Application.Run(new WelcomeForm());
                }
            }
            else
            {
                Application.Run(new MainForm());
            }
        }
Ejemplo n.º 20
0
        public static void OnAppUninstall(Version version)
        {
            var exePath = Assembly.GetEntryAssembly().Location;
            string appName = Path.GetFileName(exePath);

            var updatePath = ConfigurationManager.AppSettings["UpdatePathFolder"];
            var packageId = ConfigurationManager.AppSettings["PackageID"];

            using (var mgr = new UpdateManager(updatePath, packageId, FrameworkVersion.Net45))
            {
                // Remove Desktop and Start Menu shortcuts
                mgr.RemoveShortcutsForExecutable(appName, DefaultLocations);
            }
        }
        private async void toolStripButtonCheckForUpdates_Click(object sender, EventArgs e)
        {
            // NB: For this version, always say your app is using .NET 4.5, even if it's
            // totally not
            using (var mgr = new UpdateManager(textBoxPathForUpdate.Text))
            {
               var release = await mgr.UpdateApp();

               if (release != null)
               {
                   MessageBox.Show("New App Version Installed " + release.Version + " \n Close and reopen to load new version.");
               }
            }
        }
Ejemplo n.º 22
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;
      }
  }
Ejemplo n.º 23
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();
        }
Ejemplo n.º 24
0
 private static void OnAppUninstall(Version version)
 {
     try
     {
         Log.InfoFormat("OnAppUninstall for version {0}", version);
         using (var updateManager = new UpdateManager(Program.PackageUrl, Program.PackageId))
         {
             updateManager.RemoveShortcutsForExecutable("Nuts.exe", ShortcutLocation.Desktop);
         }
     }
     catch (Exception exception)
     {
         Log.Error("OnAppUninstall encountered and exception", exception);
         throw;
     }
 }
Ejemplo n.º 25
0
 private async void ButtonUpdateDo_OnClick(object sender, RoutedEventArgs e)
 {
     try
     {
         using (var mgr = new UpdateManager(ConfigurationManager.AppSettings["UpdatePath"]))
         {
             var release = await mgr.UpdateApp();
            
             this.UpdateDoResult.Text = release.EntryAsString;
         }
     }
     catch (Exception test)
     {
         this.UpdateDoResult.Text = "Updated to: " + test.Message;
     }
 }
Ejemplo n.º 26
0
        public InteractiveModule(HostControl hostControl)
        {
            StaticConfiguration.DisableErrorTraces = false;

            Get["/version"] = _ =>
            {
                var updateManager = new UpdateManager(null);
                return Response.AsJson(updateManager.CurrentlyInstalledVersion()?.ToString());
            };

            Post["/stop"] = _ =>
            {
                Task.Run(() => hostControl.Stop());
                return HttpStatusCode.OK;
            };
        }
 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);
 }
Ejemplo n.º 28
0
 private void MainWindow_Loaded(object sender, RoutedEventArgs e)
 {
     Task.Run(async () =>
     {
         using (var mgr = new UpdateManager(@"https://s3-eu-west-1.amazonaws.com/squirrelpackager"))
         {
             try
             {
                 await mgr.UpdateApp();
             }
             catch (Exception ex)
             {
                 MessageBox.Show("From Update Manager : " + Environment.NewLine + ex.InnerException.Message + Environment.NewLine + ex.Message);
             }
         }
     });
 }
Ejemplo n.º 29
0
 private void CheckForUpdate(long x)
 {
     #if !DEBUG
     Task.Run(async () => {
         try {
             using (var mgr = new UpdateManager(UpdateFolder)) {
                 var release = await mgr.UpdateApp();
                 if (release.Version > mgr.CurrentlyInstalledVersion()) {
                     OnNewVersionAvailable(release);
                 }
             }
         } catch (Exception e) {
             _logger.Error(e, "Failed checking for updates: {0}", e.Message);
             _crashManager.Report(e, "squirrel");
         }
     });
     #endif
 }
Ejemplo n.º 30
0
 static void Update(UpdateManager mgr)
 {
     mgr.CreateShortcutForThisExe();
     RunVcRedist();
 }
Ejemplo n.º 31
0
        private async Task <Boolean> githubCheck()
        {
            Boolean isSquirrelInstall = false;

            isBusy = true;
            try {
                //*** Only required for final ClickOnce offboarding release - remove afterwards!
                if (!System.IO.File.Exists("..\\Update.exe") && System.IO.File.Exists("Update.exe"))
                {
                    log.Debug("Copying Update.exe to parent directory...");
                    System.IO.File.Copy("Update.exe", "..\\Update.exe");
                }
                using (var updateManager = new Squirrel.UpdateManager(null)) {
                    //This just checks if there is an Update.exe file in the parent directory of the OGCS executable
                    isSquirrelInstall = updateManager.IsInstalledApp;
                }
            } catch (System.Exception ex) {
                log.Error("Failed to determine if app is a Squirrel install. Assuming not.");
                OGCSexception.Analyse(ex);
                if (this.isManualCheck)
                {
                    MessageBox.Show("Could not retrieve new version of the application.\n" + ex.Message, "Update Check Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            log.Info("This " + (isSquirrelInstall ? "is" : "is not") + " a Squirrel " + (Program.IsClickOnceInstall ? "aware ClickOnce " : "") + "install.");
            if (isSquirrelInstall)
            {
                log.Debug("Checking for Squirrel update...");
                UpdateManager updateManager = null;
                try {
                    String installRootDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                    if (string.IsNullOrEmpty(nonGitHubReleaseUri))
                    {
                        updateManager = await Squirrel.UpdateManager.GitHubUpdateManager("https://github.com/phw198/OutlookGoogleCalendarSync");
                    }
                    else
                    {
                        updateManager = new Squirrel.UpdateManager(nonGitHubReleaseUri, "OutlookGoogleCalendarSync", installRootDir);
                    }

                    UpdateInfo updates = await updateManager.CheckForUpdate();

                    if (updates.ReleasesToApply.Any())
                    {
                        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)
                            {
                                /*
                                 * 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("Beginning the migration to Squirrel/github release...");
                                var migrator = new ClickOnceToSquirrelMigrator.InClickOnceAppMigrator(updateManager, Application.ProductName);
                                log.Info("RootAppDirectory: " + updateManager.RootAppDirectory);
                                await migrator.Execute();

                                log.Debug("Moving the Update.exe file");
                                System.IO.File.Move("..\\Update.exe", updateManager.RootAppDirectory + "\\Update.exe");

                                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.");
                                restartRequested = true;
                                restartUpdateExe = updateManager.RootAppDirectory + "\\Update.exe";
                            }
                            else
                            {
                                log.Info("User chose not to upgrade.");
                            }
                            break;
                        }
                        return(true);
                    }
                    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);
                        }
                        return(false);
                    }
                } catch (System.Exception ex) {
                    OGCSexception.Analyse(ex, true);
                    if (ex.InnerException != null)
                    {
                        log.Error(ex.InnerException.Message);
                    }
                } finally {
                    isBusy = false;
                    updateManager.Dispose();
                }
            }
            isBusy = false;
            return(false);
        }
Ejemplo n.º 32
0
        /// <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,
                                                                                     new Squirrel.FileDownloader(new Extensions.OgcsWebClient()), 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.");
                            Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.upgrade, squirrelAnalyticsLabel + ";later");
                        }
                        else if (dr == DialogResult.Ignore)
                        {
                            Telemetry.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.");
                                Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.download, squirrelAnalyticsLabel + ";timedout");
                                if (OgcsMessageBox.Show("The update failed to download.", "Download timed out", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Retry)
                                {
                                    if (!updateManager.DownloadReleases(new[] { update }).Wait(60 * 1000))
                                    {
                                        Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.download, squirrelAnalyticsLabel + ";retry-timedout");
                                        if (OgcsMessageBox.Show("The update failed to download again.\nTo download from the project website, click Yes.", "Download timed out", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                                        {
                                            Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.download, squirrelAnalyticsLabel + ";from-website");
                                            System.Diagnostics.Process.Start("https://phw198.github.io/OutlookGoogleCalendarSync/");
                                        }
                                        else
                                        {
                                            Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.download, squirrelAnalyticsLabel + ";gave-up");
                                        }
                                        break;
                                    }
                                }
                                else
                                {
                                    if (OgcsMessageBox.Show("Would you like to download directly from the project website?", "Go to OGCS website", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                                    {
                                        Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.download, squirrelAnalyticsLabel + ";from-website");
                                        System.Diagnostics.Process.Start("https://phw198.github.io/OutlookGoogleCalendarSync/");
                                    }
                                    else
                                    {
                                        Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.download, squirrelAnalyticsLabel + ";gave-up");
                                    }
                                    break;
                                }
                            }

                            try {
                                log.Debug("Download complete.");
                                Telemetry.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.");
                                OgcsMessageBox.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
                    {
                        OgcsMessageBox.Show("You are already running the latest version of OGCS.", "Latest Version", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            } catch (ApplicationException ex) {
                Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.download, ex.Data["analyticsLabel"] + ";failed");
                throw;
            } catch (System.AggregateException ae) {
                log.Fail("Failed checking for update.");
                foreach (System.Exception ex in ae.InnerExceptions)
                {
                    OGCSexception.Analyse(OGCSexception.LogAsFail(ex), true);
                    throw;
                }
            } catch (System.Exception ex) {
                OGCSexception.Analyse("Failed checking for update.", OGCSexception.LogAsFail(ex), true);
                throw;
            } finally {
                isBusy = false;
                updateManager.Dispose();
            }
            return(false);
        }
Ejemplo n.º 33
0
        /// <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,
                                                                                     new Squirrel.FileDownloader(new Extensions.OgcsWebClient()), prerelease : Settings.Instance.AlphaReleases);
                }
                else
                {
                    updateManager = new Squirrel.UpdateManager(nonGitHubReleaseUri, "OutlookGoogleCalendarSync", installRootDir);
                }

                UpdateInfo updates = await updateManager.CheckForUpdate();

                if ((Settings.Instance.AlphaReleases && updates.ReleasesToApply.Any()) ||
                    updates.ReleasesToApply.Any(r => r.Version.SpecialVersion != "alpha"))
                {
                    if (updates.CurrentlyInstalledVersion != null)
                    {
                        log.Info("Currently installed version: " + updates.CurrentlyInstalledVersion.Version.ToString());
                    }
                    log.Info("Found " + updates.ReleasesToApply.Count() + " newer releases available.");
                    log.Info("Download directory = " + updates.PackageDirectory);

                    DialogResult dr = DialogResult.Cancel;
                    String       squirrelAnalyticsLabel = "";
                    String       releaseNotes           = "";
                    String       releaseVersion         = "";
                    String       releaseType            = "";

                    foreach (ReleaseEntry update in updates.ReleasesToApply.OrderBy(x => x.Version).Reverse())
                    {
                        log.Info("New " + update.Version.SpecialVersion + " version available: " + 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 localFile = updates.PackageDirectory + "\\" + update.Filename;
                        if (updateManager.CheckIfAlreadyDownloaded(update, localFile))
                        {
                            log.Debug("This has already been downloaded.");
                        }
                        else
                        {
                            try {
                                //"https://github.com/phw198/OutlookGoogleCalendarSync/releases/download/v2.8.6-alpha"
                                if (string.IsNullOrEmpty(nonGitHubReleaseUri))
                                {
                                    String nupkgUrl = "https://github.com/phw198/OutlookGoogleCalendarSync/releases/download/v" + update.Version + "/" + update.Filename;
                                    log.Debug("Downloading " + nupkgUrl);
                                    new Extensions.OgcsWebClient().DownloadFile(nupkgUrl, localFile);
                                }
                                else
                                {
                                    String nupkgUrl = nonGitHubReleaseUri + "\\" + update.Filename;
                                    log.Debug("Downloading " + nupkgUrl);
                                    new System.Net.WebClient().DownloadFile(nupkgUrl, localFile);
                                }
                                log.Debug("Download complete.");
                            } catch (System.Exception ex) {
                                OGCSexception.Analyse("Failed downloading release file " + update.Filename + " for " + update.Version, ex);
                                ex.Data.Add("analyticsLabel", "from=" + Application.ProductVersion + ";download_file=" + update.Filename + ";" + ex.Message);
                                throw new ApplicationException("Failed upgrading OGCS.", ex);
                            }
                        }

                        if (string.IsNullOrEmpty(releaseNotes))
                        {
                            log.Debug("Retrieving release notes.");
                            releaseNotes           = update.GetReleaseNotes(updates.PackageDirectory);
                            releaseVersion         = update.Version.Version.ToString();
                            releaseType            = update.Version.SpecialVersion;
                            squirrelAnalyticsLabel = "from=" + Application.ProductVersion + ";to=" + update.Version.Version.ToString();
                        }
                    }

                    var t = new System.Threading.Thread(() => new Forms.UpdateInfo(releaseVersion, releaseType, releaseNotes, out dr));
                    t.SetApartmentState(System.Threading.ApartmentState.STA);
                    t.Start();
                    t.Join();

                    if (dr == DialogResult.No)
                    {
                        log.Info("User chose not to upgrade right now.");
                        Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.upgrade, squirrelAnalyticsLabel + ";later");
                    }
                    else if (dr == DialogResult.Ignore)
                    {
                        Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.upgrade, squirrelAnalyticsLabel + ";skipped");
                    }
                    else if (dr == DialogResult.Yes)
                    {
                        try {
                            Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.download, squirrelAnalyticsLabel + ";successful");
                            log.Info("Applying the updated release(s)...");
                            //updateManager.UpdateApp().Wait();

                            int ApplyAttempt = 1;
                            while (ApplyAttempt <= 5)
                            {
                                try {
                                    updateManager.ApplyReleases(updates).Wait();
                                    break;
                                } catch (System.AggregateException ex) {
                                    ApplyAttempt++;
                                    if (OGCSexception.GetErrorCode(ex.InnerException) == "0x80070057")   //File does not exist
                                    //File does not exist: C:\Users\Paul\AppData\Local\OutlookGoogleCalendarSync\packages\OutlookGoogleCalendarSync-2.8.4-alpha-full.nupkg
                                    //Extract the nupkg filename
                                    {
                                        String regexMatch = ".*" + updates.PackageDirectory.Replace(@"\", @"\\") + @"\\(.*?([\d\.]+-\w+).*)$";
                                        System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(ex.InnerException.Message, regexMatch);

                                        if (match?.Groups?.Count == 3)
                                        {
                                            log.Warn("Could not update as missing file " + match.Groups[1]);
                                            String nupkgUrl = "https://github.com/phw198/OutlookGoogleCalendarSync/releases/download/v" + match.Groups[2] + "/" + match.Groups[1];
                                            log.Debug("Downloading " + nupkgUrl);
                                            new Extensions.OgcsWebClient().DownloadFile(nupkgUrl, updates.PackageDirectory + "\\" + match.Groups[1]);
                                            log.Debug("Download complete.");
                                        }
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }
                            }

                            log.Info("The application has been successfully updated.");
                            OgcsMessageBox.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);
                        }
                    }
                }
                else
                {
                    log.Info("Already running the latest version of OGCS.");
                    if (this.isManualCheck)   //Was a manual check, so give feedback
                    {
                        OgcsMessageBox.Show("You are already running the latest version of OGCS.", "Latest Version", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            } catch (ApplicationException ex) {
                Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.download, ex.Data["analyticsLabel"] + ";failed");
                throw;
            } catch (System.AggregateException ae) {
                log.Fail("Failed checking for update.");
                foreach (System.Exception ex in ae.InnerExceptions)
                {
                    OGCSexception.Analyse(OGCSexception.LogAsFail(ex), true);
                    throw;
                }
            } catch (System.Exception ex) {
                OGCSexception.Analyse("Failed checking for update.", OGCSexception.LogAsFail(ex), true);
                throw;
            } finally {
                isBusy = false;
                updateManager.Dispose();
            }
            return(false);
        }
Ejemplo n.º 34
-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();
        }