public JsonResult InstallPackages(string packages)
        {
            try
            {
                var packagesToInstall = new JavaScriptSerializer().Deserialize<IEnumerable<PackageModel>>(packages);

                var context = new SelfUpdaterEntities();

                foreach (var self in packagesToInstall.Select(pack => new SelfUpdatingPackages { PackageId = pack.Name, PackageVersion = pack.Version, Source = pack.Source, Install = pack.Install}))
                {
                    context.AddToSelfUpdatingPackages(self);
                }

                context.SaveChanges();

                var config = WebConfigurationManager.OpenWebConfiguration("~/");
                var section = config.GetSection("system.web/httpRuntime");
                ((HttpRuntimeSection)section).WaitChangeNotification = 123456789;
                ((HttpRuntimeSection)section).MaxWaitChangeNotification = 123456789;
                config.Save();

                return Json("Ok");
            }
            catch(Exception e)
            {
                ErrorHandler.Publish(LogLevel.Error, e);
                Response.StatusCode = 500;
                return Json(e.Message);
            }
        }
Example #2
0
        private static void CheckForSelfUpdates()
        {
            try {

                SelfUpdaterEntities context = new SelfUpdaterEntities();

                var packagesToUpdate = context.SelfUpdatingPackages.AsQueryable();

                if (packagesToUpdate.Count() > 0) {

                    /*This forces a site restart for each update scheduled */
                    /*Must be improved trying to updated all at once */

                    var packageToUpdate = packagesToUpdate.First();
                    var projectManager = GetProjectManagers().Where(d => d.SourceRepository.Source.ToLower().Trim() == packageToUpdate.Source.ToLower().Trim()).First();
                    var packageName = packageToUpdate.PackageId;
                    IPackage installedPackage = projectManager.GetInstalledPackages(true).Where(d => d.Id == packageName).First();
                    IPackage update = projectManager.GetUpdate(installedPackage);

                    if (update != null) {
                        ErrorHandler.Publish(LogLevel.Info, String.Format("SelfUpdater: Updating {0} from {1} to {2}", packageName, installedPackage.Version, update.Version));
                        try {
                            projectManager.UpdatePackage(update);
                        } catch (Exception exc) {
                            ErrorHandler.Publish(LogLevel.Info, String.Format("SelfUpdater: Error updating {0} from {1} to {2}", packageName, installedPackage.Version, update.Version), exc);
                            context.SelfUpdatingPackages.DeleteObject(packageToUpdate);
                        }
                    } else {
                        ErrorHandler.Publish(LogLevel.Info, "SelfUpdater: " + packageName + " update applied !");
                        context.SelfUpdatingPackages.DeleteObject(packageToUpdate);
                    }

                    context.SaveChanges();

                } else {
                    ErrorHandler.Publish(LogLevel.Info, "SelfUpdater: Nothing to update");
                }
            } catch (Exception exc) {

                ErrorHandler.Publish(LogLevel.Error, exc);
            }
        }
Example #3
0
        /// <summary>
        /// Runs when the application starts.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.EventArgs"/> instance containing the event data.
        /// </param>
        /// <remarks>
        /// </remarks>
        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.MapHubs();
            var context = HttpContext.Current;

            // moved from PortalSettings
            var f = FileVersionInfo.GetVersionInfo(Assembly.GetAssembly(typeof(Portal)).Location);
            HttpContext.Current.Application.Lock();
            HttpContext.Current.Application["CodeVersion"] = 1894; //f.FilePrivatePart;
            HttpContext.Current.Application["NugetSelfUpdatesToInstall"] = false;
            HttpContext.Current.Application.UnLock();

            ErrorHandler.Publish(
                LogLevel.Info, string.Format("Application Started: code version {0}", Portal.CodeVersion));

            if (Config.CheckForFilePermission) {
                try {
                    var newDir = Path.Combine(Framework.Settings.Path.ApplicationPhysicalPath, "_createnewdir");

                    if (!Directory.Exists(newDir)) {
                        Directory.CreateDirectory(newDir);
                    }

                    if (Directory.Exists(newDir)) {
                        Directory.Delete(newDir);
                    }
                } catch (Exception ex) {
                    throw new AppleseedException(
                        LogLevel.Fatal,
                        HttpStatusCode.ServiceUnavailable,
                        "ASPNET Account does not have rights to the file system",
                        ex); // Jes1111
                }
            }

            // Start scheduler
            if (Config.SchedulerEnable) {
                PortalSettings.Scheduler =
                    CachedScheduler.GetScheduler(
                        context.Server.MapPath(Framework.Settings.Path.ApplicationRoot),
                        Config.SqlConnectionString,
                        Config.SchedulerPeriod,
                        Config.SchedulerCacheSize);
                PortalSettings.Scheduler.Start();
            }

            // Start proxy
            if (Config.UseProxyServerForServerWebRequests) {
                WebRequest.DefaultWebProxy = PortalSettings.GetProxy();
            }

            try {
                UpdateDB();

                //while (CheckForSelfUpdates());

                /* MVCContrib PortableAreas*/

                //Handlers for bus messages
                Bus.AddMessageHandler(typeof(BusMessageHandler));
                Bus.AddMessageHandler(typeof(DBScriptsHandler));

                //Register first core portable area (just in case...)
                Appleseed.Core.PortableAreaUtils.RegisterArea<Appleseed.Core.AppleseedCoreRegistration>(RouteTable.Routes, PortableAreaUtils.RegistrationState.Initializing);

                //Then, register all portable areas
                AreaRegistration.RegisterAllAreas(PortableAreaUtils.RegistrationState.Bootstrapping);
                RegisterRoutes(RouteTable.Routes);

                if (ConfigurationManager.AppSettings["RouteTesting"] != null &&
                    bool.Parse(ConfigurationManager.AppSettings["RouteTesting"]) ) {
                    //RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);

                }

                ErrorHandler.Publish(LogLevel.Info, "Registing Routes");

                InputBuilder.BootStrap();
                ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

                ViewEngines.Engines.Clear();
                ViewEngines.Engines.Add(new AppleseedWebFormViewEngine());
                ViewEngines.Engines.Add(new AppleseedRazorViewEngine());

            } catch (Exception exc) {

                ErrorHandler.Publish(LogLevel.Error, exc);
            }

            try
            {
                var dbContext = new SelfUpdaterEntities();
                if (dbContext.SelfUpdatingPackages.Any())
                {
                    var selfUpdatesThread = new SelfUpdateThread();
                    var workerThread = new Thread(selfUpdatesThread.CheckForSelfUpdates);
                    workerThread.Start();
                    HttpContext.Current.Application.Lock();
                    HttpContext.Current.Application["NugetSelfUpdatesToInstall"] = true; //f.FilePrivatePart;
                    HttpContext.Current.Application.UnLock();

                    // Delete Session logger
                    //HttpContext.Current.Session["NugetLogger"] = String.Empty;
                    HttpContext.Current.Application["NugetLogger"] = String.Empty;

                }

            }
            catch (Exception exc)
            {

                ErrorHandler.Publish(LogLevel.Error, exc);
            }
        }
        public void CheckForSelfUpdates()
        {
            var sb = new StringBuilder();
            try
            {
                var hub = GlobalHost.ConnectionManager.GetHubContext<SelfUpdater.SignalR.SelfUpdaterHub>();

                var context = new SelfUpdaterEntities();

                var packagesToUpdate = context.SelfUpdatingPackages.AsQueryable();

                //updateNeeded = (packagesToUpdate.Count() > 0);

                if (packagesToUpdate.Any())
                {

                    var packagesToInstall = packagesToUpdate.Where(packages => packages.Install == true);

                    foreach (var package in packagesToInstall)
                    {
                        try
                        {
                            var projectManager =
                                GetProjectManagers().Where(p => p.SourceRepository.Source == package.Source).First();

                            hub.Clients.All.openPopUp();

                            projectManager.addLog("Installing " + package.PackageId);

                            ErrorHandler.Publish(LogLevel.Info,
                                                 String.Format("SelfUpdater: Installing {0} to version {1}",
                                                               package.PackageId, package.PackageVersion));

                            projectManager.InstallPackage(package.PackageId, new SemanticVersion(package.PackageVersion));

                            context.SelfUpdatingPackages.DeleteObject(package);

                            sb.AppendFormat("The package {0} version {1} was correctly installed", package.PackageId,
                                            package.PackageVersion);
                            sb.AppendLine();
                        }
                        catch(Exception e)
                        {
                            ErrorHandler.Publish(LogLevel.Error, e);
                            sb.AppendFormat("There was an error installing package {0} version {1} . Exception: {2}", package.PackageId,
                                            package.PackageVersion, e.Message);
                            sb.AppendLine();
                        }
                    }

                    var packagesToUpgrade = packagesToUpdate.Where(packages => packages.Install == false);
                    foreach (var package in packagesToUpgrade)
                    {
                        try
                        {
                            hub.Clients.All.openPopUp();

                            var projectManager =
                                GetProjectManagers().First(p => p.SourceRepository.Source == package.Source);

                            projectManager.addLog("Updating " + package.PackageId);

                            IPackage installedPackage = GetInstalledPackage(projectManager, package.PackageId);

                            IPackage update = projectManager.GetUpdatedPackage(installedPackage);

                            projectManager.UpdatePackage(update);

                            context.SelfUpdatingPackages.DeleteObject(package);

                            sb.AppendFormat("The package {0} version {1} was correctly updated", package.PackageId,
                                            update.Version);
                            sb.AppendLine();
                        }
                        catch(Exception e)
                        {
                            ErrorHandler.Publish(LogLevel.Error, e);
                            sb.AppendFormat("There was an error updating package {0} version {1} . Exception: {2}", package.PackageId,
                                            package.PackageVersion, e.Message);
                            sb.AppendLine();
                        }
                    }

                    //var pManager = GetProjectManagers().First();
                    //var installedPackages = GetInstalledPackages(pManager);
                    //var packagesList = installedPackages.GroupBy(x => x.Id);
                    //var installednotLatest = new List<IPackage>();
                    //foreach (var package in packagesList)
                    //{
                    //    var version = package.Max(x => x.Version);
                    //    installednotLatest.AddRange(package.Where(pack => pack.Version != version));
                    //}

                    //foreach (var package in installednotLatest)
                    //{
                    //    pManager.RemovePackageFromLocalRepository(package);
                    //}

                    context.SaveChanges();

                    var config = WebConfigurationManager.OpenWebConfiguration("~/");
                    var section = config.GetSection("system.web/httpRuntime");
                    ((HttpRuntimeSection)section).WaitChangeNotification = 10;
                    ((HttpRuntimeSection)section).MaxWaitChangeNotification = 10;
                    config.Save();

                    sb.AppendLine("All changes were applied succesfully");

                }
                else
                {
                    ErrorHandler.Publish(LogLevel.Info, "SelfUpdater: Nothing to update");
                }

                hub.Clients.All.reloadPage();

            }
            catch (Exception exc)
            {

                ErrorHandler.Publish(LogLevel.Error, exc);

                sb.AppendFormat("There was an error on updating. Exception: {0}", exc.Message);
                sb.AppendLine();

            }

            try
            {
                var body = sb.ToString();
                var emailDir = ConfigurationManager.AppSettings["SelfUpdaterMailconfig"];
                if (!string.IsNullOrEmpty(body) && !string.IsNullOrEmpty(emailDir))
                {
                    var mail = new MailMessage();
                    mail.From = new MailAddress("*****@*****.**");

                    mail.To.Add(new MailAddress(emailDir));
                    mail.Subject = string.Format("Updates Manager changes");

                    mail.Body = body;
                    mail.IsBodyHtml = false;

                    using (var client = new SmtpClient())
                    {
                        client.Send(mail);

                    }
                }
            }
            catch (Exception e)
            {
                ErrorHandler.Publish(LogLevel.Error, e);
            }
        }
        public void Execute(IJobExecutionContext context_)
        {
            var context = (JobExecutionContextImpl)context_;

            var executeJob = bool.Parse(context.JobDetail.JobDataMap["ExcecuteJob"].ToString());

            if(executeJob)
            {
                var projectManagers = ProjectManagerHelper.GetProjectManagers();
                var updateList = new List<InstallationState>();
                foreach (var projectManager in projectManagers)
                {
                    var availablePackages = ProjectManagerHelper.GetAvailablePackagesLatestList(projectManager);

                    var installedPackages = ProjectManagerHelper.GetInstalledPackagesLatestList(projectManager, true);

                    foreach (var installedPackage in installedPackages)
                    {
                        var update = projectManager.GetUpdatedPackage(availablePackages, installedPackage);
                        if (update != null)
                        {
                            var package = new InstallationState();
                            package.Installed = installedPackage;
                            package.Update = update;
                            package.Source = projectManager.SourceRepository.Source;

                            if (updateList.Any(d => d.Installed.Id == package.Installed.Id))
                            {
                                var addedPackage = updateList.First(d => d.Installed.Id == package.Installed.Id);
                                if (package.Update != null)
                                {
                                    if (addedPackage.Update == null || addedPackage.Update.Version < package.Update.Version)
                                    {
                                        updateList.Remove(addedPackage);
                                        updateList.Add(package);
                                    }
                                }
                            }
                            else
                            {
                                updateList.Add(package);
                            }
                        }
                    }
                }

                // UpdateList is a list with packages that has updates
                if (updateList.Any())
                {
                    var sb = new StringBuilder();
                    try
                    {
                        var entities = new SelfUpdaterEntities();

                        foreach (
                            var self in
                                updateList.Select(
                                    pack =>
                                    new SelfUpdatingPackages
                                    {
                                        PackageId = pack.Installed.Id,
                                        PackageVersion = pack.Update.Version.ToString(),
                                        Source = pack.Source,
                                        Install = false
                                    }))
                        {
                            if (!entities.SelfUpdatingPackages.Any(x => x.PackageId == self.PackageId && x.PackageVersion == self.PackageVersion))
                            {
                                entities.AddToSelfUpdatingPackages(self);
                                sb.AppendFormat("Adding package {0} version {1} to update.", self.PackageId,
                                                self.PackageVersion);
                                sb.AppendLine();
                            }
                        }

                        entities.SaveChanges();

                        var config = WebConfigurationManager.OpenWebConfiguration("~/");
                        var section = config.GetSection("system.web/httpRuntime");
                        ((HttpRuntimeSection)section).WaitChangeNotification = 123456789;
                        ((HttpRuntimeSection)section).MaxWaitChangeNotification = 123456789;
                        config.Save();

                    }
                    catch (Exception e)
                    {
                        ErrorHandler.Publish(LogLevel.Error, e);
                    }

                    try
                    {
                        var body = sb.ToString();
                        var emailDir = ConfigurationManager.AppSettings["SelfUpdaterMailconfig"];
                        if (!string.IsNullOrEmpty(body) && !string.IsNullOrEmpty(emailDir))
                        {
                            var mail = new MailMessage();
                            mail.From = new MailAddress("*****@*****.**");

                            mail.To.Add(new MailAddress(emailDir));
                            mail.Subject = string.Format("Updates Manager chekcker job");

                            mail.Body = body;
                            mail.IsBodyHtml = false;

                            using (var client = new SmtpClient())
                            {
                                client.Send(mail);

                            }
                        }
                    }
                    catch (Exception e)
                    {
                        ErrorHandler.Publish(LogLevel.Error, e);
                    }

                }
            }
        }