Ejemplo n.º 1
0
        private void beginInstallUpdateDelayedMsi(ApplicationUpdate update, int secondDelay = 5, bool restartApplication = true)
        {
            // TODO: Implement cross platform stuff.

            if (!File.Exists(update.UpdateFileLocalPath))
            {
                throw new Exception("Target update installer does not exist at the expected location.");
            }

            ProcessStartInfo updaterStartupInfo;

            var systemFolder = Environment.GetFolderPath(Environment.SpecialFolder.System);

            if (restartApplication)
            {
                var executingProcess = Process.GetCurrentProcess().MainModule.FileName;
                var args             = string.Format("\"{0}\\cmd.exe\" /C TIMEOUT {1} && \"{2}\\msiexec\" /I \"{3}\" {4} && \"{5}\"", systemFolder, secondDelay, systemFolder, update.UpdateFileLocalPath, update.UpdaterArguments, executingProcess);
                Console.WriteLine(args);
                updaterStartupInfo = new ProcessStartInfo(args);
            }
            else
            {
                var args = string.Format("\"{0}\\cmd.exe\" /C TIMEOUT {1} && \"{2}\\msiexec\" /I \"{3}\" {4}", systemFolder, secondDelay, systemFolder, update.UpdateFileLocalPath, update.UpdaterArguments);
                Console.WriteLine(args);
                updaterStartupInfo = new ProcessStartInfo(args);
            }

            updaterStartupInfo.UseShellExecute = false;
            //updaterStartupInfo.WindowStyle = ProcessWindowStyle.Hidden;
            updaterStartupInfo.CreateNoWindow = true;
            updaterStartupInfo.Arguments      = update.UpdaterArguments;
            Process.Start(updaterStartupInfo);
        }
Ejemplo n.º 2
0
        public void AskForUpdate_NewVersionYes_StartUpdate()
        {
            var dialogs    = Substitute.For <IDialogs>();
            var fileSystem = Substitute.For <IFileSystem>();
            var processApi = Substitute.For <IProcess>();
            var sut        = new ApplicationUpdate(dialogs, fileSystem, processApi);
            var releases   = GithubReleaseExtensionTests.CreateRelease("2.1");

            dialogs.ShowMessageBox(
                Arg.Any <string>(),
                Arg.Any <string>(),
                MessageBoxButton.YesNo, Arg.Any <MessageBoxImage>(),
                Arg.Any <MessageBoxResult>(), Arg.Any <MessageBoxOptions>())
            .Returns(MessageBoxResult.Yes);

            sut.AskForUpdate(releases, "2.0").Should().BeTrue();
            dialogs.DidNotReceive().ShowMessageBox(
                Arg.Any <string>(),
                Arg.Any <string>(),
                MessageBoxButton.OK, Arg.Any <MessageBoxImage>(),
                Arg.Any <MessageBoxResult>(), Arg.Any <MessageBoxOptions>());
            dialogs.Received(1).ShowMessageBox(
                Arg.Any <string>(),
                Arg.Any <string>(),
                MessageBoxButton.YesNo, Arg.Any <MessageBoxImage>(),
                Arg.Any <MessageBoxResult>(), Arg.Any <MessageBoxOptions>());
        }
Ejemplo n.º 3
0
        public void StartUpdateProcess_NewVersionYes_StartUpdate()
        {
            var dialogs    = Substitute.For <IDialogs>();
            var fileSystem = Substitute.For <IFileSystem>();
            var processApi = Substitute.For <IProcess>();

            processApi.Start(Arg.Any <ProcessStartInfo>())
            .Returns(Process.Start(new ProcessStartInfo("cmd.exe", "/c ping 127.0.0.1")));
            var sut = new ApplicationUpdate(dialogs, fileSystem, processApi)
            {
                WaitTimeMilliseconds = 0
            };
            var releases = GithubReleaseExtensionTests.CreateRelease("2.1");

            dialogs.ShowMessageBox(
                Arg.Any <string>(),
                Arg.Any <string>(),
                MessageBoxButton.YesNo, Arg.Any <MessageBoxImage>(),
                Arg.Any <MessageBoxResult>(), Arg.Any <MessageBoxOptions>())
            .Returns(MessageBoxResult.Yes);
            sut.AskForUpdate(releases, "2.0").Should().BeTrue();

            sut.StartUpdateProcess().Should().BeTrue();

            fileSystem.Received(1).WriteAllTextIntoFile(
                Arg.Is <string>(x => x.Contains(Path.GetTempPath())), Arg.Any <string>());
            processApi.Received(1).Start(Arg.Is <ProcessStartInfo>(i => i.FileName == "powershell"));
        }
Ejemplo n.º 4
0
        private void beginInstallUpdateExe(ApplicationUpdate update, bool restartApplication = true)
        {
            if (!File.Exists(update.UpdateFileLocalPath))
            {
                throw new Exception("Target update installer does not exist at the expected location.");
            }

            var systemFolder = Environment.GetFolderPath(Environment.SpecialFolder.System);

            string filename, args;

            if (restartApplication)
            {
                string executingProcess = Process.GetCurrentProcess().MainModule.FileName;

                filename = update.UpdateFileLocalPath;
                args     = $"\"{filename}\" /passive /waitforexit"; // The /waitforexit argument makes sure FilterServiceProvider.exe is stopped before displaying its UI.
            }
            else
            {
                filename = update.UpdateFileLocalPath;
                args     = $"\"{filename}\" /passive /waitforexit";
            }

            try
            {
                if (!ProcessCreation.CreateElevatedProcessInCurrentSession(filename, args))
                {
                    logger.Error($"Failed to create elevated process with {System.Runtime.InteropServices.Marshal.GetLastWin32Error()}");
                }
            } catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
        public async Task ApplicationUpdatePresenter_DownloadClicked_ShowsMessageBoxWhenDownloadFails()
        {
            // Arrange
            using (var artifacts = new ArtifactFolder())
            {
                var updateFile = new ApplicationUpdateFile {
                    Description = "Foo", Name = "Foo.zip", HttpAddress = @"C:\DoesNotExist\Foo.zip"
                };
                var update = new ApplicationUpdate
                {
                    UpdateFiles = new List <ApplicationUpdateFile> {
                        updateFile
                    }
                };
                var model = new ApplicationUpdateModel(update);
                model.SelectedUpdateFile = update.UpdateFiles.First();

                var messageBox = new MockMessageBoxPresenter();
                using (var presenter = new MockDialogApplicationUpdatePresenter(model, messageBox))
                {
                    presenter.ShowDialog(null);
                    Assert.IsTrue(presenter.MockDialog.Shown);
                    // Act
                    var saveFile = new MockFileDialogPresenterReturnsFileName(_ => DialogResult.OK, artifacts.GetRandomFilePath());
                    await presenter.DownloadClick(saveFile);

                    // Assert
                    Assert.AreEqual(1, messageBox.Invocations.Count);
                    Assert.IsTrue(presenter.MockDialog.Shown);
                    Assert.AreEqual(1, saveFile.Invocations.Count);
                }
            }
        }
Ejemplo n.º 6
0
        private static ICollection <ListItem> BuildUpdateFilesList(ApplicationUpdate update)
        {
            var list = update?.UpdateFiles?
                       .Select(x => new ListItem(x.Description, x))
                       .ToList();

            return(list ?? new List <ListItem>());
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Begins the external installation after a N second delay specified.
        /// </summary>
        /// <param name="secondDelay">
        /// The number of seconds to wait before starting the actual update.
        /// </param>
        /// <exception cref="Exception">
        /// If the file designated at UpdateFileLocalPath does not exist at the time of this call,
        /// this method will throw.
        /// </exception>
        public void BeginInstallUpdate(ApplicationUpdate update, bool restartApplication = true)
        {
            switch (update.Kind)
            {
            case UpdateKind.InstallerPackage:
                beginInstallUpdateDelayedMsi(update, 5, restartApplication);
                break;

            case UpdateKind.ExecutablePackage:
                beginInstallUpdateExe(update, restartApplication);
                break;
            }
        }
Ejemplo n.º 8
0
        // Edit
        public ActionResult Edit(int id)
        {
            var service = CreateApplicationService();
            var detail  = service.GetApplicationDetail(id);
            var model   =
                new ApplicationUpdate
            {
                HousingId     = detail.HousingId,
                FirstName     = detail.FirstName,
                LastName      = detail.LastName,
                MonthlyIncome = detail.MonthlyIncome
            };

            return(View(model));
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> Update(Guid appId, [FromBody] ApplicationUpdate applicationMetadata)
        {
            var app = await _applicationRepository.Get(appId);

            if (app == null)
            {
                return(NotFound());
            }

            app.CustomData = applicationMetadata.CustomData;

            var updatedApp = await _applicationRepository.Upsert(app);

            return(Ok(GetResponseModel(updatedApp)));
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> Create([FromBody] ApplicationUpdate applicationMetadata)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var app = await _applicationRepository.Upsert(new Application
            {
                Id         = Guid.NewGuid(),
                CustomData = applicationMetadata.CustomData
            });

            return(CreatedAtAction(nameof(Get), new { appId = app.Id }, GetResponseModel(app)));
        }
        public async Task GetAllReleasesAsync_ReturnKnownVersions()
        {
            var dialogs    = Substitute.For <IDialogs>();
            var fileSystem = Substitute.For <IFileSystem>();
            var processApi = Substitute.For <IProcess>();
            var sut        = new ApplicationUpdate(dialogs, fileSystem, processApi);

            var task = sut.GetAllReleasesAsync();

            (await this.Awaiting(x => task).Should().CompleteWithinAsync(10.Seconds()))
            .Which.Should().Contain(
                r => r.TagName == "2.0.0" &&
                r.Assets.Any(
                    a => a.BrowserDownloadUrl.EndsWith("SimpleAccounting.zip", StringComparison.Ordinal)));
        }
Ejemplo n.º 12
0
        public async Task TestGetVersion()
        {
            ApplicationUpdate     applicationUpdate = new ApplicationUpdate(TimeSpan.FromSeconds(30));
            Version               version           = new Version("1.0.0.0");
            ApplicationUpdateInfo info = await applicationUpdate.GetUpdateApplicationInfo(version);

            if (info != null)
            {
                Assert.IsTrue(info.Version > version);
                Assert.IsTrue(info.DownloadUrl.EndsWith(".zip"));

                info = await applicationUpdate.GetUpdateApplicationInfo(info.Version);

                Assert.IsNull(info);
            }
        }
        // Update
        public bool UpdateApplication(ApplicationUpdate model)
        {
            using (var ctx = new ApplicationDbContext())
            {
                var entity =
                    ctx
                    .Applications
                    .Single(e => e.Id == model.Id);

                entity.HousingId     = model.HousingId;
                entity.FirstName     = model.FirstName;
                entity.LastName      = model.LastName;
                entity.MonthlyIncome = model.MonthlyIncome;

                return(ctx.SaveChanges() == 1);
            }
        }
        private static ApplicationUpdateModel CreateUpdateModel(string sourceFile, ApplicationUpdateFileType updateType)
        {
            File.WriteAllText(sourceFile, "FoobarFizzbizz");

            string sourceFileName = Path.GetFileName(sourceFile);
            var    updateFile     = new ApplicationUpdateFile {
                Description = "Foo", Name = sourceFileName, HttpAddress = sourceFile, Size = (int)new FileInfo(sourceFile).Length, UpdateType = (int)updateType
            };
            var update = new ApplicationUpdate
            {
                UpdateFiles = new List <ApplicationUpdateFile> {
                    updateFile
                }
            };

            return(new ApplicationUpdateModel(update));
        }
Ejemplo n.º 15
0
        public void StartUpdateProcess_UpdateProcessFailed_UpdateAborted()
        {
            var dialogs    = Substitute.For <IDialogs>();
            var fileSystem = Substitute.For <IFileSystem>();
            var processApi = Substitute.For <IProcess>();

            processApi.Start(Arg.Any <ProcessStartInfo>())
            .Returns(Process.Start(new ProcessStartInfo("cmd.exe", "/c exit 5")));
            var sut = new ApplicationUpdate(dialogs, fileSystem, processApi)
            {
                WaitTimeMilliseconds = 1000
            };
            var releases = GithubReleaseExtensionTests.CreateRelease("2.1");

            sut.AskForUpdate(releases, "2.0");

            sut.StartUpdateProcess().Should().BeFalse();
            dialogs.Received(1).ShowMessageBox(
                Arg.Is <string>(s => s.Contains("code 5.")), Resources.Header_CheckForUpdates, icon: MessageBoxImage.Error);
        }
Ejemplo n.º 16
0
        private void beginInstallUpdateExe(ApplicationUpdate update, bool restartApplication = true)
        {
            if (!File.Exists(update.UpdateFileLocalPath))
            {
                throw new Exception("Target update installer does not exist at the expected location.");
            }

            var    systemFolder = Environment.GetFolderPath(Environment.SpecialFolder.System);
            var    email = PlatformTypes.New <IAuthenticationStorage>().UserEmail;
            var    fingerPrint = FingerprintService.Default.Value;
            var    userId = email + ":" + fingerPrint;
            string filename, args;

            if (restartApplication)
            {
                string executingProcess = Process.GetCurrentProcess().MainModule.FileName;

                filename = update.UpdateFileLocalPath;
                args     = $"\"{filename}\" /upgrade /passive /waitforexit /userid={userId}"; // The /waitforexit argument makes sure FilterServiceProvider.exe is stopped before displaying its UI.
            }
            else
            {
                filename = update.UpdateFileLocalPath;
                args     = $"\"{filename}\" /upgrade /passive /waitforexit /userid={userId}";
            }

            try
            {
                logger.Info("Starting update process " + filename + " " + args);
                if (!ProcessCreation.CreateElevatedProcessInCurrentSession(filename, args))
                {
                    logger.Error($"Failed to create elevated process with {System.Runtime.InteropServices.Marshal.GetLastWin32Error()}");
                }
            } catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
Ejemplo n.º 17
0
        public void ApplicationUpdateModel_Load_UpdateFileList_IsCreatedFromUpdateFiles()
        {
            // Arrange
            var update = new ApplicationUpdate
            {
                UpdateFiles = new List <ApplicationUpdateFile>
                {
                    new ApplicationUpdateFile {
                        Description = "Foo"
                    },
                    new ApplicationUpdateFile {
                        Description = "Bar"
                    }
                }
            };
            var model = new ApplicationUpdateModel(update);

            // Act
            model.Load();
            // Assert
            Assert.IsNotNull(model.UpdateFilesList);
            Assert.AreEqual(2, model.UpdateFilesList.Count);
        }
Ejemplo n.º 18
0
        public ActionResult Edit(int id, ApplicationUpdate model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (model.Id != id)
            {
                ModelState.AddModelError("", "ID Mismatch");
                return(View(model));
            }

            var service = CreateApplicationService();

            if (service.UpdateApplication(model))
            {
                TempData["SaveResult"] = "Application was updated";
                return(RedirectToAction("Index"));
            }

            ModelState.AddModelError("", "Application could not be updated");
            return(View(model));
        }
Ejemplo n.º 19
0
        //! Check for updates, prompting the end-user to download and install if found.
        private void CheckForUpdates()
        {
            UpdateProcess = ApplicationUpdate.CheckForUpdate();
            if (UpdateProcess == null)
            {
                const string msg = "Velvet Pearl Lottery could not check for updates.\n\nThis may be caused by a lack of internet connection or Enjin being down for maintenance. " +
                                   "If the problem persists, contact denDAY at \nwww.enjin.com/profile/493549.";
                WndDialogMessage.Show(this, msg, "Update Check Failed", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            else if (!UpdateProcess.UpdateAvailable)
            {
                return;
            }

            var choice = WndDialogMessage.Show(this, "A new update is available.\n\nDownload and install?", "New Update", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (choice != MessageBoxResult.Yes)
            {
                return;
            }

            // Download and register the install function (event handler) and cancel token.
            if (!UpdateProcess.DownloadUpdateAsync(InstallUpdate))
            {
                return;
            }
            var cancelToken = new CancellationTokenSource();

            cancelToken.Token.Register(CancelUpdate);
            UpdateStatusWnd = new WndUpdateStatus(cancelToken)
            {
                StatusText = "Downloading update ...", Owner = this
            };
            UpdateStatusWnd.ShowDialog();
        }
Ejemplo n.º 20
0
 public ApplicationUpdateModel(ApplicationUpdate update)
 {
     Update = update;
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Checks for application updates, and notifies the GUI of the result.
        /// </summary>
        /// <param name="isCheckButton"></param>
        /// <param name="update"></param>
        /// <returns></returns>
        public UpdateCheckResult ProbeMasterForApplicationUpdates(bool isCheckButton)
        {
            bool hadError            = false;
            UpdateCheckResult result = UpdateCheckResult.CheckFailed;

            try
            {
                m_appcastUpdaterLock.EnterWriteLock();

                if (m_policyConfiguration.Configuration != null)
                {
                    var config = m_policyConfiguration.Configuration;
                    m_lastFetchedUpdate = m_updater.GetLatestUpdate(config != null ? config.UpdateChannel : string.Empty).Result;
                }
                else
                {
                    m_logger.Info("No configuration downloaded yet. Skipping application update checks.");
                }

                result = UpdateCheckResult.UpToDate;

                if (m_lastFetchedUpdate?.IsNewerThan(m_lastFetchedUpdate?.CurrentVersion) == true)
                {
                    m_logger.Info("Found update. Asking clients to accept update.");

                    if (!isCheckButton && AppSettings.Default.CanUpdate())
                    {
                        m_systemServices.EnsureGuiRunning();
                        Task.Delay(500).Wait();

                        m_ipcServer.Send <ApplicationUpdate>(IpcCall.Update, m_lastFetchedUpdate);
                        m_ipcServer.Send <UpdateCheckInfo>(IpcCall.CheckForUpdates, new UpdateCheckInfo(AppSettings.Default.LastUpdateCheck, result));
                    }

                    result = UpdateCheckResult.UpdateAvailable;
                }
                else if (m_lastFetchedUpdate != null)
                {
                    result = UpdateCheckResult.UpToDate;

                    // We send an update check response here for only !isCheckButton because the other case returns a reply directly to its request message.
                    if (!isCheckButton)
                    {
                        m_ipcServer.Send <UpdateCheckInfo>(IpcCall.CheckForUpdates, new UpdateCheckInfo(AppSettings.Default.LastUpdateCheck, result));
                    }
                }
            }
            catch (Exception e)
            {
                LoggerUtil.RecursivelyLogException(m_logger, e);
                hadError = true;
            }
            finally
            {
                try
                {
                    switch (result)
                    {
                    case UpdateCheckResult.UpdateAvailable:
                    case UpdateCheckResult.UpToDate:
                        AppSettings.Default.LastUpdateCheck = DateTime.Now;
                        break;
                    }

                    AppSettings.Default.UpdateCheckResult = result;
                    AppSettings.Default.Save();
                }
                catch (Exception ex)
                {
                    m_logger.Error(ex, "AppSettings update threw.");
                }

                m_appcastUpdaterLock.ExitWriteLock();
            }

            if (!hadError)
            {
                // Notify all clients that we just successfully made contact with the server.
                // We don't set the status here, because we'd have to store it and set it
                // back, so we just directly issue this msg.
                m_ipcServer.NotifyStatus(FilterStatus.Synchronized);
            }

            return(result);
        }
Ejemplo n.º 22
0
        public void Application()
        {
            string  dummyString;
            bool    dummyBool;
            int     dummyInt;
            Service service = Connect();

            EntityCollection <Application> apps = service.GetApplications();

            foreach (Application app in apps.Values)
            {
                try
                {
                    ApplicationSetup applicationSetup = app.Setup();
                    string           setupXml         = applicationSetup.SetupXml;
                }
                catch (Exception)
                {
                    // silent exception, if setup doesn't exist, exception occurs
                }

                ApplicationArchive applicationArchive = app.Archive();
                dummyString = app.Author;
                dummyBool   = app.CheckForUpdates;
                dummyString = app.Description;
                dummyString = app.Label;
                dummyBool   = app.Refreshes;
                dummyString = app.Version;
                dummyBool   = app.IsConfigured;
                if (service.VersionCompare("5.0") < 0)
                {
                    dummyBool = app.IsManageable;
                }
                dummyBool = app.IsVisible;
                dummyBool = app.StateChangeRequiresRestart;
                ApplicationUpdate applicationUpdate = app.AppUpdate();
                dummyString = applicationUpdate.Checksum;
                dummyString = applicationUpdate.ChecksumType;
                dummyString = applicationUpdate.Homepage;
                dummyInt    = applicationUpdate.UpdateSize;
                dummyString = applicationUpdate.UpdateName;
                dummyString = applicationUpdate.AppUrl;
                dummyString = applicationUpdate.Version;
                dummyBool   = applicationUpdate.IsImplicitIdRequired;
            }

            if (apps.ContainsKey("sdk-tests"))
            {
                service = this.CleanApp("sdk-tests", service);
            }

            apps = service.GetApplications();
            Assert.IsFalse(apps.ContainsKey("sdk-tests"), assertRoot + "#1");

            Args createArgs = new Args();

            createArgs.Add("author", "me");
            if (service.VersionCompare("4.2.4") >= 0)
            {
                createArgs.Add("configured", false);
            }
            createArgs.Add("description", "this is a description");
            createArgs.Add("label", "SDKTEST");
            if (service.VersionCompare("5.0") < 0)
            {
                createArgs.Add("manageable", false);
            }
            createArgs.Add("template", "barebones");
            createArgs.Add("visible", false);
            apps.Create("sdk-tests", createArgs);
            Assert.IsTrue(apps.ContainsKey("sdk-tests"), assertRoot + "#2");
            Application app2 = apps.Get("sdk-tests");

            dummyBool = app2.CheckForUpdates;
            Assert.AreEqual("SDKTEST", app2.Label, assertRoot + "#3");
            Assert.AreEqual("me", app2.Author, assertRoot + "#4");
            Assert.IsFalse(app2.IsConfigured, assertRoot + "#5");
            if (service.VersionCompare("5.0") < 0)
            {
                Assert.IsFalse(app2.IsManageable, assertRoot + "#6");
            }
            Assert.IsFalse(app2.IsVisible, assertRoot + "#7");

            // update the app
            app2.Author      = "not me";
            app2.Description = "new description";
            app2.Label       = "new label";
            app2.IsVisible   = false;
            if (service.VersionCompare("5.0") < 0)
            {
                app2.IsManageable = false;
            }
            app2.Version = "5.0.0";
            app2.Update();

            // check to see if args took.
            Assert.AreEqual("not me", app2.Author, assertRoot + "#8");
            Assert.AreEqual("new description", app2.Description, assertRoot + "#9");
            Assert.AreEqual("new label", app2.Label, assertRoot + "#10");
            Assert.IsFalse(app2.IsVisible, assertRoot + "#11");
            Assert.AreEqual("5.0.0", app2.Version, assertRoot + "#12");

            // archive (package) the application
            ApplicationArchive appArchive = app2.Archive();

            Assert.IsTrue(appArchive.AppName.Length > 0, assertRoot + "#13");
            Assert.IsTrue(appArchive.FilePath.Length > 0, assertRoot + "#14");
            Assert.IsTrue(appArchive.Url.Length > 0, assertRoot + "#15");

            ApplicationUpdate appUpdate = app2.AppUpdate();

            Assert.IsTrue(appUpdate.ContainsKey("eai:acl"), assertRoot + "#16");

            service = this.CleanApp("sdk-tests", service);
            apps    = service.GetApplications();
            Assert.IsFalse(apps.ContainsKey("sdk-tests"), assertRoot + "#17");
        }
Ejemplo n.º 23
0
 public UpdatePresenterTests()
 {
     var checker = new UpdateChecker();
      _update = checker.CheckForUpdate("uniqueId", Path.Combine(Environment.CurrentDirectory, "ApplicationUpdateLocal.xml"));
 }