public void CreateWelcomeContent_CreatesIntroBlogPostAndCategories()
        {
            // arrange
            var installationManager = new InstallationManager(new Mock<IInstaller>().Object, null);
            var repository = new Mock<ObjectProvider>();
            var entryPublisher = new Mock<IEntryPublisher>();
            Entry entry = null;
            entryPublisher.Setup(p => p.Publish(It.Is<Entry>(e => e.PostType == PostType.BlogPost))).Callback<Entry>(e => entry = e);
            var urlHelper = new Mock<UrlHelper>();
            urlHelper.Setup(u => u.AdminUrl("")).Returns("/admin/default.aspx");
            urlHelper.Setup(u => u.EntryUrl(It.Is<Entry>(e => e.PostType == PostType.Story))).Returns<Entry>(e => "/articles/" + e.EntryName + ".aspx");
            urlHelper.Setup(u => u.HostAdminUrl("default.aspx")).Returns("/hostadmin/default.aspx");
            var context = new Mock<ISubtextContext>();
            context.SetupUrlHelper(urlHelper);
            context.Setup(c => c.Repository).Returns(repository.Object);
            var blog = new Blog {Id = 123, Author = "TestAuthor"};

            // act
            installationManager.CreateWelcomeContent(context.Object, entryPublisher.Object, blog);

            // assert
            Assert.AreEqual(entry.Title, "Welcome to Subtext!");
            Assert.AreEqual(entry.EntryName, "welcome-to-subtext");
            Assert.Contains(entry.Body, @"<a href=""/admin/default.aspx");
            Assert.Contains(entry.Body, @"<a href=""/articles/welcome-to-subtext-article.aspx");
            Assert.Contains(entry.Body, @"<a href=""/hostadmin/default.aspx");
            Assert.IsTrue(entry.AllowComments);
            Assert.IsTrue(!entry.Body.Contains(@"<a href=""{0}"));
            Assert.IsTrue(!entry.Body.Contains(@"<a href=""{1}"));
            Assert.IsTrue(!entry.Body.Contains(@"<a href=""{2}"));
        }
Example #2
0
        /// <summary>
        /// Checks for update.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="progress">The progress.</param>
        /// <returns>Task{CheckForUpdateResult}.</returns>
        public override async Task <CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
                                                                                    IProgress <double> progress)
        {
            var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);

            // Fake this with a really high number
            // With the idea of multiple servers there's no point in making server version a part of this
            var serverVersion = new Version(10, 0, 0, 0);

            var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, "MBTheater", null, serverVersion, ConfigurationManager.CommonConfiguration.SystemUpdateLevel);

            var versionObject = version == null || string.IsNullOrWhiteSpace(version.versionStr) ? null : new Version(version.versionStr);

            return(versionObject != null ? new CheckForUpdateResult {
                AvailableVersion = versionObject.ToString(), IsUpdateAvailable = versionObject > ApplicationVersion, Package = version
            } :
                   new CheckForUpdateResult {
                AvailableVersion = ApplicationVersion.ToString(), IsUpdateAvailable = false
            });
        }
Example #3
0
        private void CheckUpdatesAvailableAsync()
        {
            string pluginPath = Path.GetFullPath(Application.StartupPath);
            var    task       = Task.Factory.StartNew <bool>(() => {
                var installationManager = new InstallationManager(pluginPath);
                IEnumerable <IPluginDescription> installedPlugins = pluginManager.Plugins.OfType <IPluginDescription>();
                var remotePlugins = installationManager.GetRemotePluginList();
                // if there is a local plugin with same name and same major and minor version then it's an update
                var pluginsToUpdate = from remotePlugin in remotePlugins
                                      let matchingLocalPlugins = from installedPlugin in installedPlugins
                                                                 where installedPlugin.Name == remotePlugin.Name
                                                                 where installedPlugin.Version.Major == remotePlugin.Version.Major
                                                                 where installedPlugin.Version.Minor == remotePlugin.Version.Minor
                                                                 where Util.IsNewerThan(remotePlugin, installedPlugin)
                                                                 select installedPlugin
                                                                 where matchingLocalPlugins.Count() > 0
                                                                 select remotePlugin;
                return(pluginsToUpdate.Count() > 0);
            });

            task.ContinueWith(t => {
                try {
                    t.Wait();
                    updatesAvailable = t.Result;
                    UpdateApplicationsList();
                }
                catch (AggregateException ae) {
                    ae.Handle(ex => {
                        if (ex is InstallationManagerException)
                        {
                            // this is expected when no internet connection is available => do nothing
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    });
                }
            });
        }
Example #4
0
        /// <summary>
        /// Registers resources that classes will depend on
        /// </summary>
        /// <returns>Task.</returns>
        protected virtual Task RegisterResources()
        {
            return(Task.Run(() =>
            {
                RegisterSingleInstance(ConfigurationManager);
                RegisterSingleInstance <IApplicationHost>(this);

                RegisterSingleInstance <IApplicationPaths>(ApplicationPaths);

                TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, Logger);

                RegisterSingleInstance(JsonSerializer);
                RegisterSingleInstance(XmlSerializer);

                RegisterSingleInstance(LogManager);
                RegisterSingleInstance(Logger);

                RegisterSingleInstance(TaskManager);

                FileSystemManager = CreateFileSystemManager();
                RegisterSingleInstance(FileSystemManager);

                HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, Logger, CreateHttpClient, FileSystemManager);
                RegisterSingleInstance(HttpClient);

                NetworkManager = CreateNetworkManager();
                RegisterSingleInstance(NetworkManager);

                SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, NetworkManager);
                RegisterSingleInstance(SecurityManager);

                InstallationManager = new InstallationManager(Logger, this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, NetworkManager, ConfigurationManager);
                RegisterSingleInstance(InstallationManager);

                ZipClient = new ZipClient();
                RegisterSingleInstance(ZipClient);

                IsoManager = new IsoManager();
                RegisterSingleInstance(IsoManager);
            }));
        }
Example #5
0
        protected void btnInsertRootOnly_Click(object sender, EventArgs e)
        {
            InstallationManager im = Installer;

            try
            {
                cvRootAndStart.IsValid = true;
                cvRoot.IsValid         = ddlRootAndStart.SelectedIndex > 0;
                if (!cvRoot.IsValid)
                {
                    return;
                }

                ContentItem root = im.InsertRootNode(Type.GetType(ddlRootAndStart.SelectedValue), "start", "Start Page");

                if (root.ID == Status.RootItemID && root.ID == Status.StartPageID)
                {
                    ltRootNode.Text  = "<span class='ok'>Root node inserted.</span>";
                    phSame.Visible   = false;
                    phDiffer.Visible = false;
                    RootId           = root.ID;
                    Installer.UpdateStatus(SystemStatusLevel.UpAndRunning);
                    ShowTab("Finish");
                }
                else
                {
                    ltRootNode.Text = string.Format(
                        "<span class='warning'>Root node inserted but you must update web.config with root item id: <b>{0}</b></span> ",
                        root.ID);
                    phSame.Visible   = true;
                    phDiffer.Visible = false;
                    RootId           = root.ID;
                    StartId          = root.ID;
                }
                phSame.DataBind();
            }
            catch (Exception ex)
            {
                ltRootNode.Text = string.Format("<span class='warning'>{0}</span><!--\n{1}\n-->", ex.Message, ex);
            }
        }
        internal async void DoUpdate(IAppVersion availableUpdate)
        {
            var       aetxUri      = new Uri(HockeyClient.Current.AsInternal().ApiBaseVersion2 + "apps/" + HockeyClient.Current.AsInternal().AppIdentifier + ".aetx", UriKind.Absolute);
            var       downloadUri  = new Uri(HockeyClient.Current.AsInternal().ApiBaseVersion2 + "apps/" + HockeyClient.Current.AsInternal().AppIdentifier + "/app_versions/" + availableUpdate.Id + ".appx", UriKind.Absolute);
            Exception installError = null;

            try
            {
                var result = await InstallationManager.AddPackageAsync(availableUpdate.Title, downloadUri);
            }
            catch (Exception e)
            {
                installError = e;
                HockeyClient.Current.AsInternal().HandleInternalUnhandledException(e);
            }
            if (installError != null)
            {
                await new MessageDialog(String.Format(LocalizedStrings.LocalizedResources.UpdateAPIError, installError.Message)).ShowAsync();
                await Launcher.LaunchUriAsync(downloadUri).AsTask();
            }
        }
Example #7
0
        protected void btnTest_Click(object sender, EventArgs e)
        {
            try
            {
                InstallationManager im = Installer;

                using (IDbConnection conn = im.GetConnection())
                {
                    conn.Open();
                    lblStatus.CssClass = "ok";
                    lblStatus.Text     = "Connection OK";
                }
            }
            catch (Exception ex)
            {
                lblStatus.CssClass = "warning";
                lblStatus.Text     = "Connection problem, hopefully this error message can help you figure out what's wrong: <br/>" +
                                     ex.Message;
                lblStatus.ToolTip = ex.StackTrace;
            }
        }
Example #8
0
        /// <summary>
        /// Registers resources that classes will depend on
        /// </summary>
        /// <returns>Task.</returns>
        protected virtual Task RegisterResources(IProgress <double> progress)
        {
            RegisterSingleInstance(ConfigurationManager);
            RegisterSingleInstance <IApplicationHost>(this);

            RegisterSingleInstance <IApplicationPaths>(ApplicationPaths);

            TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, Logger);

            RegisterSingleInstance(JsonSerializer);
            RegisterSingleInstance(XmlSerializer);

            RegisterSingleInstance(LogManager);
            RegisterSingleInstance(Logger);

            RegisterSingleInstance(TaskManager);

            RegisterSingleInstance(FileSystemManager);

            HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, Logger, FileSystemManager);
            RegisterSingleInstance(HttpClient);

            NetworkManager = CreateNetworkManager(LogManager.GetLogger("NetworkManager"));
            RegisterSingleInstance(NetworkManager);

            SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LogManager);
            RegisterSingleInstance(SecurityManager);

            InstallationManager = new InstallationManager(Logger, this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ConfigurationManager, FileSystemManager);
            RegisterSingleInstance(InstallationManager);

            ZipClient = new ZipClient();
            RegisterSingleInstance(ZipClient);

            IsoManager = new IsoManager();
            RegisterSingleInstance(IsoManager);

            RegisterModules();
            return(Task.FromResult(true));
        }
Example #9
0
        public MainWindow()
        {
            FileList.Add(new Tuple <string, string>("Assembly-CSharp-firstpass.dll", "Hook Dependency"));
            FileList.Add(new Tuple <string, string>("I18N.dll", "SQL Dependency"));
            FileList.Add(new Tuple <string, string>("I18N.West.dll", "SQL Dependency (West)"));
            FileList.Add(new Tuple <string, string>("System.Management.dll", "Management Dependency"));
            FileList.Add(new Tuple <string, string>("TsunamiHack.dll", "Function Dependency"));

            Manager = new InstallationManager(this);

            InitializeComponent();

            DbAccess = new db(this);
            DbAccess.GetData();

            //Disabled = true;

            if (Disabled)
            {
                grdContainer.IsEnabled = false;
                var win = new BlockedWindow(Reason);
                var ret = win.ShowDialog();
                if (ret != null)
                {
                    Environment.Exit(0);
                }
            }



            //set sidebar to out and set lengths
            sideBarState      = true;
            cgSidebar.Width   = new GridLength(2, GridUnitType.Star);
            cgContent.Width   = new GridLength(8, GridUnitType.Star);
            btnResize.Content = "<";

            current = Displayed.Home;
            //set container instance
        }
Example #10
0
        public void TestIsPackageInstalledWithPackageAlias()
        {
            var managerMock = new Mock <InstallationManager>()
            {
                CallBase = true,
            };

            manager = managerMock.Object;
            package.Setup((o) => o.GetPackageType()).Returns("foo");
            package.Setup((o) => o.GetName()).Returns("foobar");
            var packageAlias = new PackageAlias(package.Object, "1.2.0.0", "1.2");

            repository.Setup((o) => o.HasPackage(packageAlias)).Returns(true);
            repository.Setup((o) => o.HasPackage(package.Object)).Returns(true);
            installer.Setup((o) => o.IsSupports("foo")).Returns(true);
            installer.Setup((o) => o.IsInstalled(repository.Object, package.Object))
            .Returns(true);
            manager.AddInstaller(installer.Object);

            Assert.AreEqual(true, manager.IsPackageInstalled(repository.Object, packageAlias));
            managerMock.Verify((o) => o.IsPackageInstalled(repository.Object, package.Object));
        }
Example #11
0
        private void InstallIfNeeded(IVsShell shellService)
        {
            if (shellService == null)
            {
                ShellDialogs.Error(this, Resources.ErrorMessage_ShellServiceUnavailable);
                return;
            }

            ThreadHelper.ThrowIfNotOnUIThread();
            shellService.GetProperty((int)__VSSPROPID2.VSSPROPID_VisualStudioDir, out object documentsDirObj);
            string           documentsDir     = documentsDirObj.ToString();
            string           targetPath       = Path.Combine(documentsDir, "Visualizers");
            InstallationInfo installedVersion = InstallationManager.GetInstallationInfo(targetPath);
            InstallationInfo availableVersion = InstallationManager.AvailableVersion;

            if (installedVersion.Installed && (installedVersion.Version == null || installedVersion.Version >= availableVersion.Version))
            {
                return;
            }

            InstallationManager.Install(targetPath, out string error, out string warning);
            if (error != null)
            {
                ShellDialogs.Error(this, Res.ErrorMessageFailedToInstall(targetPath, error));
            }
            else if (warning != null)
            {
                ShellDialogs.Warning(this, Res.WarningMessageInstallationFinishedWithWarning(targetPath, warning));
            }
            else if (installedVersion.Installed && installedVersion.Version != null)
            {
                ShellDialogs.Info(this, Res.InfoMessageUpgradeFinished(installedVersion.Version, availableVersion.Version, targetPath));
            }
            else
            {
                ShellDialogs.Info(this, Res.InfoMessageInstallationFinished(availableVersion.Version, targetPath));
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            InstallationManager.ResetInstallationStatusCache();

            if (paraBlogLink != null)
            {
                paraBlogLink.Visible = false;
            }
            if (paraBlogAdminLink != null)
            {
                paraBlogAdminLink.Visible = false;
            }
            if (paraBlogmlImport != null)
            {
                paraBlogmlImport.Visible = false;
            }

            if (Config.CurrentBlog != null)
            {
                if (lnkBlog != null && paraBlogLink != null)
                {
                    paraBlogLink.Visible = true;
                    lnkBlog.HRef         = Url.BlogUrl();
                }

                if (lnkBlogAdmin != null && paraBlogAdminLink != null)
                {
                    paraBlogAdminLink.Visible = true;
                    lnkBlogAdmin.HRef         = AdminUrl.Home();
                }

                if (lnkBlogMl != null && paraBlogmlImport != null)
                {
                    paraBlogmlImport.Visible = true;
                    lnkBlogMl.HRef           = AdminUrl.ImportExport();
                }
            }
        }
Example #13
0
        static int launch(int L)
        {
            if (!LuaCommon.CheckAndShowArgsError(L, LConst.String))
            {
                return(0);
            }

            string appId    = Lua.Lua_tostring(L, 2).Trim();
            var    cropApps = InstallationManager.FindPackagesForCurrentPublisher();
            var    app      = cropApps.Where(a => a.Id.ProductId.TrimStart('{').TrimEnd('}').Equals(appId, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

            if (app != null)
            {
                app.Launch(string.Empty);
            }
            else
            {
                string error = string.Concat("appId:", appId);
                LogLib.RYTLog.ShowMessage(error, "企业App启动失败");
            }

            return(0);
        }
        public void CreateWelcomeContent_CreatesIntroArticle()
        {
            // arrange
            var installationManager = new InstallationManager(new Mock<IInstaller>().Object, null);
            var repository = new Mock<ObjectProvider>();
            var entryPublisher = new Mock<IEntryPublisher>();
            Entry article = null;
            entryPublisher.Setup(p => p.Publish(It.Is<Entry>(e => e.PostType == PostType.Story))).Callback<Entry>(e => article = e);
            var urlHelper = new Mock<UrlHelper>();
            urlHelper.Setup(u => u.AdminUrl("articles")).Returns("/admin/articles/default.aspx");
            var context = new Mock<ISubtextContext>();
            context.SetupUrlHelper(urlHelper);
            context.Setup(c => c.Repository).Returns(repository.Object);
            var blog = new Blog { Id = 123, Author = "TestAuthor" };

            // act
            installationManager.CreateWelcomeContent(context.Object, entryPublisher.Object, blog);

            // assert
            Assert.AreEqual(article.Title, "Welcome to Subtext!");
            Assert.Contains(article.Body, @"<a href=""/admin/articles/");
            Assert.IsTrue(!article.Body.Contains(@"<a href=""{0}"));
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string userName = txtUserName.Text;
                string password = txtPassword.Text;
                string email    = txtEmail.Text;

                // Create the HostInfo record.
                if (HostInfo.CreateHost(userName, password, email))
                {
                    if (Config.BlogCount == 0)
                    {
                        //Changed the following method to public so all authentication tickets are handled by the same code.
                        SubtextContext.HttpContext.SetAuthenticationTicket(Blog, "HostAdmin", false, "HostAdmin");
                        string queryString = !String.IsNullOrEmpty(txtEmail.Text)
                                                 ? "?email=" + HttpUtility.UrlEncode(txtEmail.Text)
                                                 : string.Empty;
                        Response.Redirect(NextStepUrl + queryString);
                    }
                    else
                    {
                        InstallationManager.ResetInstallationStatusCache();
                        Response.Redirect("InstallationComplete.aspx");
                    }
                }
                else
                {
                    const string errorMessage = "I'm sorry, but we had a problem creating your initial "
                                                +
                                                "configuration. Please <a href=\"http://code.google.com/p/subtext/issues/\" title=\"Subtext at Google Code\">report "
                                                + "this issue</a> to the Subtext team.";

                    throw new InvalidOperationException(errorMessage);
                }
            }
        }
Example #16
0
        protected void btnInsert_Click(object sender, EventArgs e)
        {
            InstallationManager im = Installer;

            try
            {
                cvRootAndStart.IsValid = ddlRoot.SelectedIndex > 0 && ddlStartPage.SelectedIndex > 0;
                cvRoot.IsValid         = true;
                if (!cvRootAndStart.IsValid)
                {
                    return;
                }

                ContentItem root      = im.InsertRootNode(Type.GetType(ddlRoot.SelectedValue), "root", "Root Node");
                ContentItem startPage = im.InsertStartPage(Type.GetType(ddlStartPage.SelectedValue), root, "start", "Start Page");

                if (startPage.ID == Status.StartPageID && root.ID == Status.RootItemID)
                {
                    ltRootNode.Text = "<span class='ok'>Root and start pages inserted.</span>";
                }
                else
                {
                    ltRootNode.Text = string.Format(
                        "<span class='warning'>Start page inserted but you must update web.config with root item id: <b>{0}</b> and start page id: <b>{1}</b></span>", root.ID, startPage.ID);
                    phSame.Visible   = false;
                    phDiffer.Visible = true;
                    RootId           = root.ID;
                    StartId          = startPage.ID;
                }
                phDiffer.DataBind();
            }
            catch (Exception ex)
            {
                ltRootNode.Text = string.Format("<span class='warning'>{0}</span><!--\n{1}\n-->", ex.Message, ex);
            }
        }
        public void CreateWelcomeContent_CreatesIntroBlogPostAndCategories()
        {
            // arrange
            var   installationManager = new InstallationManager(new Mock <IInstaller>().Object, null);
            var   repository          = new Mock <ObjectRepository>();
            var   entryPublisher      = new Mock <IEntryPublisher>();
            Entry entry = null;

            entryPublisher.Setup(p => p.Publish(It.Is <Entry>(e => e.PostType == PostType.BlogPost))).Callback <Entry>(e => entry = e);
            var urlHelper = new Mock <BlogUrlHelper>();

            urlHelper.Setup(u => u.AdminUrl("")).Returns("/admin/default.aspx");
            urlHelper.Setup(u => u.EntryUrl(It.Is <Entry>(e => e.PostType == PostType.Story))).Returns <Entry>(e => "/articles/" + e.EntryName + ".aspx");
            urlHelper.Setup(u => u.HostAdminUrl("default.aspx")).Returns("/hostadmin/default.aspx");
            var context = new Mock <ISubtextContext>();

            context.SetupUrlHelper(urlHelper);
            context.Setup(c => c.Repository).Returns(repository.Object);
            var blog = new Blog {
                Id = 123, Author = "TestAuthor"
            };

            // act
            installationManager.CreateWelcomeContent(context.Object, entryPublisher.Object, blog);

            // assert
            Assert.AreEqual(entry.Title, "Welcome to Subtext!");
            Assert.AreEqual(entry.EntryName, "welcome-to-subtext");
            Assert.Contains(entry.Body, @"<a href=""/admin/default.aspx");
            Assert.Contains(entry.Body, @"<a href=""/articles/welcome-to-subtext-article.aspx");
            Assert.Contains(entry.Body, @"<a href=""/hostadmin/default.aspx");
            Assert.IsTrue(entry.AllowComments);
            Assert.IsTrue(!entry.Body.Contains(@"<a href=""{0}"));
            Assert.IsTrue(!entry.Body.Contains(@"<a href=""{1}"));
            Assert.IsTrue(!entry.Body.Contains(@"<a href=""{2}"));
        }
Example #18
0
        /// <summary>
        /// Executes the installation of the Programm
        /// </summary>
        static void Install()
        {
            InstallationManager helper = new InstallationManager(_logManager.GetLogger(LoggerType.Installer));

            helper.Install();
        }
        public UpdateTranslationKeyMigration(IRepository <ContentDetail> repository, IRepository <ContentItem> itemRepository, InstallationManager installer)
        {
            this.detailRepository = repository;
            this.itemRepository   = itemRepository;
            this.installer        = installer;

            Title       = "Update translation keys to v2.2 model";
            Description = "The information previously known as LanguageKey detail is now stored as a TranslationKey property";
        }
Example #20
0
 /// <summary>
 /// Sets the installation manager instance.
 /// </summary>
 public void SetInstallationManager(InstallationManager manager)
 {
     installationManager = manager;
 }
Example #21
0
 protected override void PurgePackages(IRepositoryInstalled repositoryInstalled, InstallationManager installationManager)
 {
     // noop.
 }
Example #22
0
        /// <summary>
        /// Updates the application.
        /// </summary>
        /// <param name="package">The package that contains the update</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="progress">The progress.</param>
        /// <returns>Task.</returns>
        public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress <double> progress)
        {
            await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);

            OnApplicationUpdated(package);
        }
        public void IsInstallationActionRequired_WithInstallerReturningSameVersionAsAssembly_ReturnsFalse()
        {
            //arrange
            var installer = new Mock<IInstaller>();
            installer.Setup(i => i.GetCurrentInstallationVersion()).Returns(new Version(1, 0, 0, 0));
            var installManager = new InstallationManager(installer.Object, new TestCache());

            //act
            bool result = installManager.InstallationActionRequired(new Version(1, 0, 0, 0), null);

            //assert
            Assert.IsFalse(result);
        }
        public void IsInstallationActionRequired_WithInstallerReturningNull_ReturnsTrue()
        {
            //arrange
            var installer = new Mock<IInstaller>();
            installer.Setup(i => i.GetCurrentInstallationVersion()).Returns((Version)null);
            var cache = new TestCache();
            cache["NeedsInstallation"] = null;
            var manager = new InstallationManager(installer.Object, cache);

            //act
            bool result = manager.InstallationActionRequired(new Version(), null);

            //assert
            Assert.IsTrue(result);
        }
Example #25
0
 protected override void InitializeDefaultInstallers(InstallationManager installationManager, Bucket bucket, IIO io)
 {
     // noop.
 }
        public void IsInstallationActionRequired_WithCachedInstallationStatusOfNeedsInstallation_ReturnsTrue()
        {
            //arrange
            var installer = new Mock<IInstaller>();
            installer.Setup(i => i.GetCurrentInstallationVersion()).Throws(new InvalidOperationException());
            var cache = new TestCache();
            cache["NeedsInstallation"] = InstallationState.NeedsInstallation;
            var manager = new InstallationManager(installer.Object, cache);

            //act
            bool result = manager.InstallationActionRequired(new Version(), null);

            //assert
            Assert.IsTrue(result);
        }
        public void CreateWelcomeContent_CreatesIntroComment()
        {
            // arrange
            var installationManager = new InstallationManager(new Mock<IInstaller>().Object, null);
            var repository = new Mock<ObjectProvider>();
            var entryPublisher = new Mock<IEntryPublisher>();
            var urlHelper = new Mock<UrlHelper>();
            urlHelper.Setup(u => u.AdminUrl("feedback")).Returns("/admin/feedback/default.aspx");
            var context = new Mock<ISubtextContext>();
            context.SetupUrlHelper(urlHelper);
            context.Setup(c => c.Repository).Returns(repository.Object);
            var blog = new Blog { Id = 123, Author = "TestAuthor" };
            FeedbackItem comment = null;
            repository.Setup(r => r.Create(It.IsAny<FeedbackItem>())).Callback<FeedbackItem>(c => comment = c);

            // act
            installationManager.CreateWelcomeContent(context.Object, entryPublisher.Object, blog);

            // assert
            Assert.IsTrue(comment.Approved);
            Assert.AreEqual(comment.Title, "re: Welcome to Subtext!");
            Assert.Contains(comment.Body, @"<a href=""/admin/feedback/");
            Assert.IsTrue(!comment.Body.Contains(@"<a href=""{1}"));
        }
Example #28
0
 /// <summary>
 /// Purge packages that are not installed.
 /// </summary>
 protected virtual void PurgePackages(IRepositoryInstalled repositoryInstalled, InstallationManager installationManager)
 {
     foreach (var package in repositoryInstalled.GetPackages())
     {
         if (!installationManager.IsPackageInstalled(repositoryInstalled, package))
         {
             repositoryInstalled.RemovePackage(package);
         }
     }
 }
Example #29
0
        public UpdateAlteredPermissionsMigration(IRepository <int, ContentItem> repository, InstallationManager installer)
        {
            this.repository = repository;
            this.installer  = installer;

            Title       = "Update altered permissions information";
            Description = "In order to increase performance some information is now stored in the n2item table. Not running this migration on existing content will cause security protected content to become visible to anyone until it is re-saved.";
        }
Example #30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            // Register localization services
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            services.AddOptions <List <Database> >().Bind(Configuration.GetSection(SettingKeys.AvailableDatabasesSection));

            services.AddServerSideBlazor()
            .AddCircuitOptions(options =>
            {
                if (_env.IsDevelopment())
                {
                    options.DetailedErrors = true;
                }
            });

            // setup HttpClient for server side in a client side compatible fashion ( with auth cookie )
            services.TryAddHttpClientWithAuthenticationCookie();

            // register custom authorization policies
            services.AddOqtaneAuthorizationPolicies();

            // register scoped core services
            services.AddScoped <IAuthorizationHandler, PermissionHandler>()
            .AddOqtaneScopedServices();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddIdentityCore <IdentityUser>(options => { })
            .AddEntityFrameworkStores <TenantDBContext>()
            .AddSignInManager()
            .AddDefaultTokenProviders()
            .AddClaimsPrincipalFactory <ClaimsPrincipalFactory <IdentityUser> >();  // role claims

            services.ConfigureOqtaneIdentityOptions();

            services.AddAuthentication(Constants.AuthenticationScheme)
            .AddCookie(Constants.AuthenticationScheme);

            services.ConfigureOqtaneCookieOptions();

            services.AddAntiforgery(options =>
            {
                options.HeaderName          = Constants.AntiForgeryTokenHeaderName;
                options.Cookie.HttpOnly     = false;
                options.Cookie.Name         = Constants.AntiForgeryTokenCookieName;
                options.Cookie.SameSite     = SameSiteMode.Strict;
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
            });

            // register singleton scoped core services
            services.AddSingleton(Configuration)
            .AddOqtaneSingletonServices();

            // install any modules or themes ( this needs to occur BEFORE the assemblies are loaded into the app domain )
            InstallationManager.InstallPackages(_env.WebRootPath, _env.ContentRootPath);

            // register transient scoped core services
            services.AddOqtaneTransientServices();

            // load the external assemblies into the app domain, install services
            services.AddOqtane(_runtime, _supportedCultures);
            services.AddOqtaneDbContext();


            services.AddMvc()
            .AddNewtonsoftJson()
            .AddOqtaneApplicationParts() // register any Controllers from custom modules
            .ConfigureOqtaneMvc();       // any additional configuration from IStart classes.

            services.TryAddSwagger(_useSwagger);
        }
        public void ResetInstallationStatusCache_WithApplicationNeedingInstallation_SetsStatusToNull()
        {
            // arrange
            var cache = new TestCache();
            cache["NeedsInstallation"] = InstallationState.NeedsInstallation;
            var installManager = new InstallationManager(null, cache);

            // act
            installManager.ResetInstallationStatusCache();

            // assert
            Assert.IsNull(cache["NeedsInstallation"]);
        }
Example #32
0
        public UpdateTemplateKeyMigration(IRepository <int, ContentDetail> repository, InstallationManager installer)
        {
            this.repository = repository;
            this.installer  = installer;

            Title       = "Update template keys";
            Description = "The information previously known as TemplateName detail is now stored as a TemplateKey property";
        }
        public void Upgrade_ResetsInstallationStatusCache()
        {
            // arrange
            var cache = new TestCache();
            cache["NeedsInstallation"] = InstallationState.NeedsInstallation;
            var installer = new Mock<IInstaller>();
            installer.Setup(i => i.Upgrade(It.IsAny<Version>()));
            var installManager = new InstallationManager(installer.Object, cache);

            // act
            installManager.Upgrade(new Version());

            // assert
            Assert.IsNull(cache["NeedsInstallation"]);
        }
Example #34
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            // Register localization services
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            services.AddServerSideBlazor();

            // setup HttpClient for server side in a client side compatible fashion ( with auth cookie )
            if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
            {
                services.AddScoped(s =>
                {
                    // creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
                    var navigationManager   = s.GetRequiredService <NavigationManager>();
                    var httpContextAccessor = s.GetRequiredService <IHttpContextAccessor>();
                    var authToken           = httpContextAccessor.HttpContext.Request.Cookies[".AspNetCore.Identity.Application"];
                    var client = new HttpClient(new HttpClientHandler {
                        UseCookies = false
                    });
                    if (authToken != null)
                    {
                        client.DefaultRequestHeaders.Add("Cookie", ".AspNetCore.Identity.Application=" + authToken);
                    }
                    client.BaseAddress = new Uri(navigationManager.Uri);
                    return(client);
                });
            }

            // register custom authorization policies
            services.AddAuthorizationCore(options =>
            {
                options.AddPolicy("ViewPage", policy => policy.Requirements.Add(new PermissionRequirement(EntityNames.Page, PermissionNames.View)));
                options.AddPolicy("EditPage", policy => policy.Requirements.Add(new PermissionRequirement(EntityNames.Page, PermissionNames.Edit)));
                options.AddPolicy("ViewModule", policy => policy.Requirements.Add(new PermissionRequirement(EntityNames.Module, PermissionNames.View)));
                options.AddPolicy("EditModule", policy => policy.Requirements.Add(new PermissionRequirement(EntityNames.Module, PermissionNames.Edit)));
                options.AddPolicy("ViewFolder", policy => policy.Requirements.Add(new PermissionRequirement(EntityNames.Folder, PermissionNames.View)));
                options.AddPolicy("EditFolder", policy => policy.Requirements.Add(new PermissionRequirement(EntityNames.Folder, PermissionNames.Edit)));
                options.AddPolicy("ListFolder", policy => policy.Requirements.Add(new PermissionRequirement(EntityNames.Folder, PermissionNames.Browse)));
            });

            // register scoped core services
            services.AddScoped <SiteState>();
            services.AddScoped <IAuthorizationHandler, PermissionHandler>();
            services.AddScoped <IInstallationService, InstallationService>();
            services.AddScoped <IModuleDefinitionService, ModuleDefinitionService>();
            services.AddScoped <IThemeService, ThemeService>();
            services.AddScoped <IAliasService, AliasService>();
            services.AddScoped <ITenantService, TenantService>();
            services.AddScoped <ISiteService, SiteService>();
            services.AddScoped <IPageService, PageService>();
            services.AddScoped <IModuleService, ModuleService>();
            services.AddScoped <IPageModuleService, PageModuleService>();
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IProfileService, ProfileService>();
            services.AddScoped <IRoleService, RoleService>();
            services.AddScoped <IUserRoleService, UserRoleService>();
            services.AddScoped <ISettingService, SettingService>();
            services.AddScoped <IPackageService, PackageService>();
            services.AddScoped <ILogService, LogService>();
            services.AddScoped <IJobService, JobService>();
            services.AddScoped <IJobLogService, JobLogService>();
            services.AddScoped <INotificationService, NotificationService>();
            services.AddScoped <IFolderService, FolderService>();
            services.AddScoped <IFileService, FileService>();
            services.AddScoped <ISiteTemplateService, SiteTemplateService>();
            services.AddScoped <ISqlService, SqlService>();
            services.AddScoped <ISystemService, SystemService>();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddDbContext <MasterDBContext>(options =>
                                                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")
                                                                         .Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory")?.ToString())
                                                                         ));
            services.AddDbContext <TenantDBContext>(options => { });

            services.AddIdentityCore <IdentityUser>(options => { })
            .AddEntityFrameworkStores <TenantDBContext>()
            .AddSignInManager()
            .AddDefaultTokenProviders();

            var localizationSection = Configuration.GetSection("Localization");
            var localizationOptions = localizationSection.Get <LocalizationOptions>();

            services.Configure <LocalizationOptions>(localizationSection);

            services.Configure <IdentityOptions>(options =>
            {
                // Password settings
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireLowercase       = false;

                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(30);
                options.Lockout.MaxFailedAccessAttempts = 10;
                options.Lockout.AllowedForNewUsers      = true;

                // User settings
                options.User.RequireUniqueEmail = false;
            });

            services.AddAuthentication(IdentityConstants.ApplicationScheme)
            .AddCookie(IdentityConstants.ApplicationScheme);

            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.HttpOnly          = false;
                options.Events.OnRedirectToLogin = context =>
                {
                    context.Response.StatusCode = 401;
                    return(Task.CompletedTask);
                };
            });

            // register custom claims principal factory for role claims
            services.AddTransient <IUserClaimsPrincipalFactory <IdentityUser>, ClaimsPrincipalFactory <IdentityUser> >();

            // register singleton scoped core services
            services.AddSingleton(Configuration);
            services.AddSingleton <IInstallationManager, InstallationManager>();
            services.AddSingleton <ISyncManager, SyncManager>();
            services.AddSingleton <IDatabaseManager, DatabaseManager>();

            // install any modules or themes ( this needs to occur BEFORE the assemblies are loaded into the app domain )
            InstallationManager.InstallPackages("Modules,Themes", _webRoot);

            // register transient scoped core services
            services.AddTransient <IModuleDefinitionRepository, ModuleDefinitionRepository>();
            services.AddTransient <IThemeRepository, ThemeRepository>();
            services.AddTransient <IUserPermissions, UserPermissions>();
            services.AddTransient <ITenantResolver, TenantResolver>();
            services.AddTransient <IAliasRepository, AliasRepository>();
            services.AddTransient <ITenantRepository, TenantRepository>();
            services.AddTransient <ISiteRepository, SiteRepository>();
            services.AddTransient <IPageRepository, PageRepository>();
            services.AddTransient <IModuleRepository, ModuleRepository>();
            services.AddTransient <IPageModuleRepository, PageModuleRepository>();
            services.AddTransient <IUserRepository, UserRepository>();
            services.AddTransient <IProfileRepository, ProfileRepository>();
            services.AddTransient <IRoleRepository, RoleRepository>();
            services.AddTransient <IUserRoleRepository, UserRoleRepository>();
            services.AddTransient <IPermissionRepository, PermissionRepository>();
            services.AddTransient <ISettingRepository, SettingRepository>();
            services.AddTransient <ILogRepository, LogRepository>();
            services.AddTransient <ILogManager, LogManager>();
            services.AddTransient <ILocalizationManager, LocalizationManager>();
            services.AddTransient <IJobRepository, JobRepository>();
            services.AddTransient <IJobLogRepository, JobLogRepository>();
            services.AddTransient <INotificationRepository, NotificationRepository>();
            services.AddTransient <IFolderRepository, FolderRepository>();
            services.AddTransient <IFileRepository, FileRepository>();
            services.AddTransient <ISiteTemplateRepository, SiteTemplateRepository>();
            services.AddTransient <ISqlRepository, SqlRepository>();
            services.AddTransient <IUpgradeManager, UpgradeManager>();

            // load the external assemblies into the app domain, install services
            services.AddOqtane(_runtime,
                               localizationOptions.SupportedCultures.IsNullOrEmpty()
                    ? DefaultSupportedCultures
                    : localizationOptions.SupportedCultures);

            services.AddMvc()
            .AddNewtonsoftJson()
            .AddOqtaneApplicationParts() // register any Controllers from custom modules
            .ConfigureOqtaneMvc();       // any additional configuration from IStart classes.

            if (_useSwagger)
            {
                services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {
                        Title = "Oqtane", Version = "v1"
                    }); });
            }
        }
Example #35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LockerBuilder"/> class.
 /// </summary>
 public LockerBuilder(IPackage[] packages, Func <ConfigLocker, bool> doSetLockData, InstallationManager installationManager, IIO io = null)
 {
     this.packages            = packages;
     this.doSetLockData       = doSetLockData;
     this.installationManager = installationManager;
     dumper  = new DumperPackage();
     process = new BucketProcessExecutor(io);
 }
Example #36
0
        public ErrorHandler(IErrorNotifier notifier, IWebContext context, ISecurityManager security, InstallationManager installer, IMailSender mailSender,
                            ConfigurationManagerWrapper configuration)
        {
            this.notifier   = notifier;
            this.context    = context;
            this.security   = security;
            this.installer  = installer;
            this.mailSender = mailSender;

            fixClassUrl               = configuration.Sections.Management.Installer.FixClassUrl;
            action                    = configuration.Sections.Engine.Errors.Action;
            mailTo                    = configuration.Sections.Engine.Errors.MailTo;
            mailFrom                  = configuration.Sections.Engine.Errors.MailFrom;
            maxErrorReportsPerHour    = configuration.Sections.Engine.Errors.MaxErrorReportsPerHour;
            handleWrongClassException = configuration.Sections.Engine.Errors.HandleWrongClassException;
            mailSender                = new SmtpMailSender();
        }
 protected virtual void OnInstallClick(object sender, EventArgs e)
 {
     InstallationManager.Install(VersionInfo.CurrentAssemblyVersion);
     Response.Redirect(NextStepUrl);
 }
        public void IsInstallationActionRequired_WithHostDataDoesNotExistException_ReturnsTrue()
        {
            //arrange
            var installer = new Mock<IInstaller>();
            var installManager = new InstallationManager(installer.Object, new TestCache());

            //act
            bool result = installManager.InstallationActionRequired(new Version(), new HostDataDoesNotExistException());

            //assert
            Assert.IsTrue(result);
        }
Example #39
0
        // Performs one of the following tasks when a LOB app is tapped: installs the app, starts the app, or stops
        // the installation of the app.
        private void CompanyAppList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            LongListSelector companyAppList = (LongListSelector)sender;

            try
            {
                // If selected item is null (no selection) do nothing.
                if (companyAppList.SelectedItem == null)
                {
                    return;
                }

                CompanyAppViewModel selectedApp = companyAppList.SelectedItem as CompanyAppViewModel;

                // Clear the selection in the list.
                companyAppList.SelectedItem = null;

                // App is not installed yet, so start installing it.
                if (selectedApp.Status == Status.NotInstalled || selectedApp.Status == Status.Canceled)
                {
                    Windows.Foundation.IAsyncOperationWithProgress <PackageInstallResult, uint> result;
                    selectedApp.Status        = Status.Installing;
                    selectedApp.ProgressValue = 0;
                    result = InstallationManager.AddPackageAsync(selectedApp.Title, selectedApp.XapPath);

                    result.Completed   = InstallCompleted;
                    result.Progress    = InstallProgress;
                    selectedApp.Result = result;
                }

                // App is already installed, so start it.
                else if (selectedApp.Status == Status.Installed)
                {
                    this.LaunchApp(selectedApp.ProductId);
                }

                // App is in the process of installing; determine if the user is trying to stop the installation.
                else if (selectedApp.Status == Status.Installing || selectedApp.Status == Status.InstallFailed)
                {
                    if (selectedApp.Result != null)
                    {
                        MessageBoxResult result = MessageBox.Show("Are you sure you want to stop the company app installation?",
                                                                  "Stop installation?",
                                                                  MessageBoxButton.OKCancel);

                        if (result == MessageBoxResult.OK)
                        {
                            selectedApp.Result.Cancel();
                            selectedApp.Status = Status.Canceled;
                        }
                    }
                    else
                    {
                        foreach (var installingPackage in InstallationManager.GetPendingPackageInstalls())
                        {
                            installingPackage.Cancel();
                        }

                        selectedApp.Status = Status.Canceled;
                    }
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
                companyAppList.SelectedItem = null;
            }
        }