示例#1
0
        /// <summary>
        /// Gets the pages in the selected namespace.
        /// </summary>
        /// <returns>The pages.</returns>
        private IList <PageContent> GetPages(NamespaceInfo nspace)
        {
            List <PageContent> pages = Pages.GetPages(currentWiki, nspace);

            var orphanPages           = new List <string>(Pages.GetOrphanedPages(currentWiki, nspace));
            List <PageContent> result = new List <PageContent>(pages.Count);

            string filter = txtFilter.Text.Trim().ToLower(System.Globalization.CultureInfo.CurrentCulture);

            foreach (PageContent page in pages)
            {
                if (NameTools.GetLocalName(page.FullName).ToLower(System.Globalization.CultureInfo.CurrentCulture).Contains(filter))
                {
                    if (chkOrphansOnly.Checked && !orphanPages.Contains(page.FullName))
                    {
                        continue;
                    }
                    else
                    {
                        result.Add(page);
                    }
                }
            }

            result.Sort(new PageNameComparer());

            return(result);
        }
示例#2
0
 public DummyJournalManager(Configuration conf, URI u, NamespaceInfo nsInfo)
 {
     // Set static vars so the test case can verify them.
     TestGenericJournalConf.DummyJournalManager.conf   = conf;
     TestGenericJournalConf.DummyJournalManager.uri    = u;
     TestGenericJournalConf.DummyJournalManager.nsInfo = nsInfo;
 }
示例#3
0
        /// <summary>
        /// Detects the permissions for the current user.
        /// </summary>
        /// <remarks><b>currentPage</b> should be set before calling this method.</remarks>
        private void DetectPermissions()
        {
            string currentUser = SessionFacade.GetCurrentUsername();

            string[] currentGroups = SessionFacade.GetCurrentGroupNames(currentWiki);

            AuthChecker authChecker = new AuthChecker(Collectors.CollectorsBox.GetSettingsProvider(currentWiki));

            if (currentPage != null)
            {
                Pages.CanEditPage(currentPage.Provider.CurrentWiki, currentPage.FullName, currentUser, currentGroups, out canEdit, out canEditWithApproval);
                canCreateNewPages      = false;            // Least privilege
                canCreateNewCategories = authChecker.CheckActionForNamespace(Pages.FindNamespace(currentWiki, NameTools.GetNamespace(currentPage.FullName)),
                                                                             Actions.ForNamespaces.ManageCategories, currentUser, currentGroups);
                canManagePageCategories = authChecker.CheckActionForPage(currentPage.FullName, Actions.ForPages.ManageCategories, currentUser, currentGroups);
                canDownloadAttachments  = authChecker.CheckActionForPage(currentPage.FullName, Actions.ForPages.DownloadAttachments, currentUser, currentGroups);
            }
            else
            {
                NamespaceInfo ns = DetectNamespaceInfo();
                canCreateNewPages       = authChecker.CheckActionForNamespace(ns, Actions.ForNamespaces.CreatePages, currentUser, currentGroups);
                canCreateNewCategories  = authChecker.CheckActionForNamespace(ns, Actions.ForNamespaces.ManageCategories, currentUser, currentGroups);
                canManagePageCategories = canCreateNewCategories;
                canDownloadAttachments  = authChecker.CheckActionForNamespace(ns, Actions.ForNamespaces.DownloadAttachments, currentUser, currentGroups);
            }
        }
示例#4
0
        /// <summary>
        /// Activates the page editor.
        /// </summary>
        private void ActivatePageEditor()
        {
            lblCurrentPage.Text = txtCurrentPage.Value;
            txtNewName.Text     = NameTools.GetLocalName(txtCurrentPage.Value);

            // Enable/disable page sections
            PageContent   page        = Pages.FindPage(currentWiki, txtCurrentPage.Value);
            NamespaceInfo nspace      = Pages.FindNamespace(currentWiki, NameTools.GetNamespace(page.FullName));
            string        currentUser = SessionFacade.GetCurrentUsername();

            string[] currentGroups = SessionFacade.GetCurrentGroupNames(currentWiki);

            AuthChecker authChecker = new AuthChecker(Collectors.CollectorsBox.GetSettingsProvider(currentWiki));

            bool canApproveReject    = AdminMaster.CanApproveDraft(page.Provider.CurrentWiki, page.FullName, currentUser, currentGroups);
            bool canDeletePages      = authChecker.CheckActionForNamespace(nspace, Actions.ForNamespaces.DeletePages, currentUser, currentGroups);
            bool canManageAllPages   = authChecker.CheckActionForNamespace(nspace, Actions.ForNamespaces.ManagePages, currentUser, currentGroups);
            bool canManagePage       = authChecker.CheckActionForPage(page.FullName, Actions.ForPages.ManagePage, currentUser, currentGroups);
            bool canManageDiscussion = authChecker.CheckActionForPage(page.FullName, Actions.ForPages.ManageDiscussion, currentUser, currentGroups);
            bool namespaceAvailable  = PopulateTargetNamespaces(page);

            // Approve/reject
            // Rename
            // Migrate
            // Rollback
            // Delete Backups
            // Clear discussion
            // Delete

            pnlApproveRevision.Enabled = canApproveReject;
            pnlRename.Enabled          = canDeletePages;
            pnlMigrate.Enabled         = canManageAllPages && namespaceAvailable;
            pnlRollback.Enabled        = canManagePage;
            pnlDeleteBackups.Enabled   = canManagePage;
            pnlClearDiscussion.Enabled = canManageDiscussion;
            pnlDelete.Enabled          = canDeletePages;

            // Disable rename, migrate, delete for default page
            NamespaceInfo currentNamespace   = Pages.FindNamespace(currentWiki, lstNamespace.SelectedValue);
            string        currentDefaultPage = currentNamespace != null ? currentNamespace.DefaultPageFullName : Settings.GetDefaultPage(currentWiki);

            if (txtCurrentPage.Value == currentDefaultPage)
            {
                btnRename.Enabled     = false;
                btnMigrate.Enabled    = false;
                btnDeletePage.Enabled = false;
            }

            LoadDraft(txtCurrentPage.Value);

            LoadBackups(txtCurrentPage.Value);

            btnRollback.Enabled      = lstRevision.Items.Count > 0;
            btnDeleteBackups.Enabled = lstBackup.Items.Count > 0;

            pnlList.Visible     = false;
            pnlEditPage.Visible = true;

            ClearResultLabels();
        }
示例#5
0
		static Image LoadImage (NamespaceInfo ns)
		{
			var isIcon = IsIcon(ns.Namespace);
			if (isIcon)
				return Icon.FromResource(ns.Namespace, ns.Assembly);
			return Bitmap.FromResource(ns.Namespace, ns.Assembly);
		}
        public void Two_namespaces_should_be_equal_if_alias_and_connection_string_are_case_insensitive_equal(string alias1, string alias2)
        {
            var namespaceInfo1 = new NamespaceInfo(alias1, ConnectionStringValue.Sample);
            var namespaceInfo2 = new NamespaceInfo(alias2, ConnectionStringValue.Sample);

            Assert.AreEqual(namespaceInfo1, namespaceInfo2);
        }
示例#7
0
        public WikiInfo(string userAgent, string baseUrl = null, string apiPath = null, IEnumerable<Namespace> namespaces = null)
        {
            PagesSourcePageSize = 50;

            if (string.IsNullOrWhiteSpace(userAgent))
                throw new ArgumentException("User agent has to be set.", "userAgent");
            UserAgent = userAgent;

            if (baseUrl == null)
                baseUrl = "en.wikipedia.org";

            if (!baseUrl.StartsWith("http"))
                baseUrl = "http://" + baseUrl;

            BaseUrl = new Uri(baseUrl);

            if (apiPath == null)
                apiPath = "/w/api.php";

            ApiUrl = new Uri(BaseUrl, apiPath);

            Downloader = new Downloader(this);

            if (namespaces == null)
                Namespaces = new NamespaceInfo(this);
            else
                Namespaces = new NamespaceInfo(namespaces);
        }
        public virtual void SetUp()
        {
            mockDnConf = Org.Mockito.Mockito.Mock <DNConf>();
            Org.Mockito.Mockito.DoReturn(VersionInfo.GetVersion()).When(mockDnConf).GetMinimumNameNodeVersion
                ();
            DataNode mockDN = Org.Mockito.Mockito.Mock <DataNode>();

            Org.Mockito.Mockito.DoReturn(true).When(mockDN).ShouldRun();
            Org.Mockito.Mockito.DoReturn(mockDnConf).When(mockDN).GetDnConf();
            BPOfferService mockBPOS = Org.Mockito.Mockito.Mock <BPOfferService>();

            Org.Mockito.Mockito.DoReturn(mockDN).When(mockBPOS).GetDataNode();
            actor      = new BPServiceActor(InvalidAddr, mockBPOS);
            fakeNsInfo = Org.Mockito.Mockito.Mock <NamespaceInfo>();
            // Return a a good software version.
            Org.Mockito.Mockito.DoReturn(VersionInfo.GetVersion()).When(fakeNsInfo).GetSoftwareVersion
                ();
            // Return a good layout version for now.
            Org.Mockito.Mockito.DoReturn(HdfsConstants.NamenodeLayoutVersion).When(fakeNsInfo
                                                                                   ).GetLayoutVersion();
            DatanodeProtocolClientSideTranslatorPB fakeDnProt = Org.Mockito.Mockito.Mock <DatanodeProtocolClientSideTranslatorPB
                                                                                          >();

            Org.Mockito.Mockito.When(fakeDnProt.VersionRequest()).ThenReturn(fakeNsInfo);
            actor.SetNameNode(fakeDnProt);
        }
        /// <summary>Format a block pool slice storage.</summary>
        /// <param name="dnCurDir">DataStorage current directory</param>
        /// <param name="nsInfo">the name space info</param>
        /// <exception cref="System.IO.IOException">Signals that an I/O exception has occurred.
        ///     </exception>
        internal virtual void Format(FilePath dnCurDir, NamespaceInfo nsInfo)
        {
            FilePath curBpDir = GetBpRoot(nsInfo.GetBlockPoolID(), dnCurDir);

            Storage.StorageDirectory bpSdir = new Storage.StorageDirectory(curBpDir);
            Format(bpSdir, nsInfo);
        }
示例#10
0
        public virtual void TestCapabilitiesInited()
        {
            NamespaceInfo nsInfo = new NamespaceInfo();

            NUnit.Framework.Assert.IsTrue(nsInfo.IsCapabilitySupported(NamespaceInfo.Capability
                                                                       .StorageBlockReportBuffers));
        }
示例#11
0
        private bool TryFindNamespaceNode(
            SyntaxNode syntaxRoot,
            NamespaceInfo namespaceInfo,
#if VS2022
            out BaseNamespaceDeclarationSyntax?fNamespace
#else
            out NamespaceDeclarationSyntax?fNamespace
示例#12
0
 /// <exception cref="System.IO.IOException"/>
 public override void Format(NamespaceInfo ns)
 {
     // Formatting file journals is done by the StorageDirectory
     // format code, since they may share their directory with
     // checkpoints, etc.
     throw new NotSupportedException();
 }
示例#13
0
        /// <summary>
        /// Retrieves the subjects that have ACL entries set for a namespace.
        /// </summary>
        /// <param name="nspace">The namespace (<c>null</c> for the root).</param>
        /// <returns>The subjects.</returns>
        public SubjectInfo[] RetrieveSubjectsForNamespace(NamespaceInfo nspace)
        {
            string resourceName = Actions.ForNamespaces.ResourceMasterPrefix;

            if (nspace != null)
            {
                resourceName += nspace.Name;
            }

            AclEntry[] entries = _settingsProvider.AclManager.RetrieveEntriesForResource(resourceName);

            List <SubjectInfo> result = new List <SubjectInfo>(entries.Length);

            for (int i = 0; i < entries.Length; i++)
            {
                SubjectType type = AuthTools.IsGroup(entries[i].Subject) ? SubjectType.Group : SubjectType.User;

                // Remove the subject qualifier ('U.' or 'G.')
                string name = entries[i].Subject.Substring(2);

                if (result.Find(delegate(SubjectInfo x) { return(x.Name == name && x.Type == type); }) == null)
                {
                    result.Add(new SubjectInfo(name, type));
                }
            }

            return(result.ToArray());
        }
	// Constructor.
	public XmlNamespaceManager(XmlNameTable nameTable)
			{
				// Validate the parameters.
				if(nameTable == null)
				{
					throw new ArgumentNullException("nameTable");
				}

				// Record the name table for later.
				this.nameTable = nameTable;

				// Add special namespaces for "xml" and "xmlns".
				xmlCompareQuick = nameTable.Add("xml");
				xmlNsCompareQuick = nameTable.Add("xmlns");
				namespaces = new NamespaceInfo
					(xmlCompareQuick,
					 nameTable.Add(XmlDocument.xmlnsXml),
					 null);
				namespaces = new NamespaceInfo
					(xmlNsCompareQuick,
					 nameTable.Add(XmlDocument.xmlns),
					 namespaces);

				// Mark the position of the outermost scope level.
				namespaces = new NamespaceInfo(null, String.Empty, namespaces);
			}
示例#15
0
        /// <summary>
        /// Detects the correct <see cref="T:NamespaceInfo" /> object associated to the current namespace using the <b>NS</b> parameter in the query string.
        /// </summary>
        /// <returns>The correct <see cref="T:NamespaceInfo" /> object, or <c>null</c>.</returns>
        public static NamespaceInfo DetectCurrentNamespaceInfo()
        {
            var           nspace = HttpContext.Current.Request["NS"];
            NamespaceInfo nsinfo = nspace != null?Pages.FindNamespace(nspace) : null;

            return(nsinfo);
        }
示例#16
0
		public ResourceExtension(string resourceName, string assemblyName)
		{
			if (!string.IsNullOrEmpty(assemblyName))
				Resource = new NamespaceInfo(resourceName, Assembly.Load(assemblyName));
			else
				Resource = new NamespaceInfo(resourceName);
		}
示例#17
0
        /// <summary>
        /// Gets the pages in the selected namespace.
        /// </summary>
        /// <returns>The pages.</returns>
        private IList <PageInfo> GetPages()
        {
            NamespaceInfo   nspace      = Pages.FindNamespace(lstNamespace.SelectedValue);
            List <PageInfo> pages       = Pages.GetPages(nspace);
            var             orphanPages = Pages.GetOrphanedPages(pages);

            var result = new List <PageInfo>(pages.Count);

            var filter = txtFilter.Text.Trim().ToLower(System.Globalization.CultureInfo.CurrentCulture);

            foreach (PageInfo page in pages)
            {
                if (NameTools.GetLocalName(page.FullName).ToLower(System.Globalization.CultureInfo.CurrentCulture).Contains(filter))
                {
                    if (chkOrphansOnly.Checked && !orphanPages.Contains(page.FullName))
                    {
                        continue;
                    }
                    else
                    {
                        result.Add(page);
                    }
                }
            }

            result.Sort(new PageNameComparer());

            return(result);
        }
示例#18
0
        public DefaultNamespaceManager()
        {
            var asm = typeof(Eto.Forms.Application).Assembly;

            DefaultNamespace = new NamespaceInfo("Eto.Forms", asm);
            Namespaces.Add("drawing", new NamespaceInfo("Eto.Drawing", asm));
        }
示例#19
0
        public void AssertOnNamespace(Address addr, NamespaceInfo namespaceInfo)
        {
            const string NS1 = "myspace";
            const string NS2 = "myspace.subspace";
            const string NS3 = "spacetest";
            const string NS4 = "nis1porttest";

            Debug.WriteLine(string.Format("AssertOnNamespace: NamespaceInfo received for namespace '{0}', owned by {1}", namespaceInfo.NamespaceId, addr.Pretty));
            Assert.AreEqual(Config.TACCOUNT_TO_WATCH2, namespaceInfo.Owner.Pretty);
            switch (namespaceInfo.NamespaceId)
            {
            case NS1:
                Assert.AreEqual((ulong)1516704, namespaceInfo.Height);
                break;

            case NS2:
                Assert.AreEqual((ulong)1516704, namespaceInfo.Height);
                break;

            case NS3:
                Assert.AreEqual((ulong)1494919, namespaceInfo.Height);
                break;

            case NS4:
                Assert.AreEqual((ulong)1494918, namespaceInfo.Height);
                break;

            default:
                throw new Exception("AssertOnOwnedNamespace: Unsupported Namespace");
            }
        }
示例#20
0
 /// <exception cref="System.IO.IOException"/>
 internal QuorumJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo,
                               AsyncLogger.Factory loggerFactory)
 {
     // Timeouts for which the QJM will wait for each of the following actions.
     // Since these don't occur during normal operation, we can
     // use rather lengthy timeouts, and don't need to make them
     // configurable.
     Preconditions.CheckArgument(conf != null, "must be configured");
     this.conf              = conf;
     this.uri               = uri;
     this.nsInfo            = nsInfo;
     this.loggers           = new AsyncLoggerSet(CreateLoggers(loggerFactory));
     this.connectionFactory = URLConnectionFactory.NewDefaultURLConnectionFactory(conf
                                                                                  );
     // Configure timeouts.
     this.startSegmentTimeoutMs = conf.GetInt(DFSConfigKeys.DfsQjournalStartSegmentTimeoutKey
                                              , DFSConfigKeys.DfsQjournalStartSegmentTimeoutDefault);
     this.prepareRecoveryTimeoutMs = conf.GetInt(DFSConfigKeys.DfsQjournalPrepareRecoveryTimeoutKey
                                                 , DFSConfigKeys.DfsQjournalPrepareRecoveryTimeoutDefault);
     this.acceptRecoveryTimeoutMs = conf.GetInt(DFSConfigKeys.DfsQjournalAcceptRecoveryTimeoutKey
                                                , DFSConfigKeys.DfsQjournalAcceptRecoveryTimeoutDefault);
     this.finalizeSegmentTimeoutMs = conf.GetInt(DFSConfigKeys.DfsQjournalFinalizeSegmentTimeoutKey
                                                 , DFSConfigKeys.DfsQjournalFinalizeSegmentTimeoutDefault);
     this.selectInputStreamsTimeoutMs = conf.GetInt(DFSConfigKeys.DfsQjournalSelectInputStreamsTimeoutKey
                                                    , DFSConfigKeys.DfsQjournalSelectInputStreamsTimeoutDefault);
     this.getJournalStateTimeoutMs = conf.GetInt(DFSConfigKeys.DfsQjournalGetJournalStateTimeoutKey
                                                 , DFSConfigKeys.DfsQjournalGetJournalStateTimeoutDefault);
     this.newEpochTimeoutMs = conf.GetInt(DFSConfigKeys.DfsQjournalNewEpochTimeoutKey,
                                          DFSConfigKeys.DfsQjournalNewEpochTimeoutDefault);
     this.writeTxnsTimeoutMs = conf.GetInt(DFSConfigKeys.DfsQjournalWriteTxnsTimeoutKey
                                           , DFSConfigKeys.DfsQjournalWriteTxnsTimeoutDefault);
 }
示例#21
0
        public virtual void TestEmptyInprogressLedger()
        {
            URI                      uri  = BKJMUtil.CreateJournalURI("/hdfsjournal-emptyInprogressLedger");
            NamespaceInfo            nsi  = NewNSInfo();
            BookKeeperJournalManager bkjm = new BookKeeperJournalManager(conf, uri, nsi);

            bkjm.Format(nsi);
            EditLogOutputStream @out = bkjm.StartLogSegment(1, NameNodeLayoutVersion.CurrentLayoutVersion
                                                            );

            for (long i = 1; i <= 100; i++)
            {
                FSEditLogOp op = FSEditLogTestUtil.GetNoOpInstance();
                op.SetTransactionId(i);
                @out.Write(op);
            }
            @out.Close();
            bkjm.FinalizeLogSegment(1, 100);
            @out = bkjm.StartLogSegment(101, NameNodeLayoutVersion.CurrentLayoutVersion);
            @out.Close();
            bkjm.Close();
            bkjm = new BookKeeperJournalManager(conf, uri, nsi);
            bkjm.RecoverUnfinalizedSegments();
            @out = bkjm.StartLogSegment(101, NameNodeLayoutVersion.CurrentLayoutVersion);
            for (long i_1 = 1; i_1 <= 100; i_1++)
            {
                FSEditLogOp op = FSEditLogTestUtil.GetNoOpInstance();
                op.SetTransactionId(i_1);
                @out.Write(op);
            }
            @out.Close();
            bkjm.FinalizeLogSegment(101, 200);
            bkjm.Close();
        }
示例#22
0
        public virtual void TestSimpleRead()
        {
            NamespaceInfo            nsi  = NewNSInfo();
            BookKeeperJournalManager bkjm = new BookKeeperJournalManager(conf, BKJMUtil.CreateJournalURI
                                                                             ("/hdfsjournal-simpleread"), nsi);

            bkjm.Format(nsi);
            long numTransactions     = 10000;
            EditLogOutputStream @out = bkjm.StartLogSegment(1, NameNodeLayoutVersion.CurrentLayoutVersion
                                                            );

            for (long i = 1; i <= numTransactions; i++)
            {
                FSEditLogOp op = FSEditLogTestUtil.GetNoOpInstance();
                op.SetTransactionId(i);
                @out.Write(op);
            }
            @out.Close();
            bkjm.FinalizeLogSegment(1, numTransactions);
            IList <EditLogInputStream> @in = new AList <EditLogInputStream>();

            bkjm.SelectInputStreams(@in, 1, true);
            try
            {
                NUnit.Framework.Assert.AreEqual(numTransactions, FSEditLogTestUtil.CountTransactionsInStream
                                                    (@in[0]));
            }
            finally
            {
                @in[0].Close();
            }
        }
        protected void btnNormal_Click(object sender, EventArgs e)
        {
            NamespaceInfo nspace = Pages.FindNamespace(txtCurrentNamespace.Value);

            RemoveAllPermissions(nspace);

            // Set permissions
            AuthWriter.SetPermissionForNamespace(AuthStatus.Grant, nspace, Actions.FullControl,
                                                 Users.FindUserGroup(Settings.AdministratorsGroup));

            AuthWriter.SetPermissionForNamespace(AuthStatus.Grant, nspace, Actions.ForNamespaces.CreatePages,
                                                 Users.FindUserGroup(Settings.UsersGroup));
            AuthWriter.SetPermissionForNamespace(AuthStatus.Grant, nspace, Actions.ForNamespaces.ManageCategories,
                                                 Users.FindUserGroup(Settings.UsersGroup));
            AuthWriter.SetPermissionForNamespace(AuthStatus.Grant, nspace, Actions.ForNamespaces.PostDiscussion,
                                                 Users.FindUserGroup(Settings.UsersGroup));
            AuthWriter.SetPermissionForNamespace(AuthStatus.Grant, nspace, Actions.ForNamespaces.DownloadAttachments,
                                                 Users.FindUserGroup(Settings.UsersGroup));

            AuthWriter.SetPermissionForNamespace(AuthStatus.Grant, nspace, Actions.ForNamespaces.ReadPages,
                                                 Users.FindUserGroup(Settings.AnonymousGroup));
            AuthWriter.SetPermissionForNamespace(AuthStatus.Grant, nspace, Actions.ForNamespaces.ReadDiscussion,
                                                 Users.FindUserGroup(Settings.AnonymousGroup));
            AuthWriter.SetPermissionForNamespace(AuthStatus.Grant, nspace, Actions.ForNamespaces.DownloadAttachments,
                                                 Users.FindUserGroup(Settings.AnonymousGroup));

            RefreshPermissionsManager();
        }
示例#24
0
        public virtual void TestSimpleRecovery()
        {
            NamespaceInfo            nsi  = NewNSInfo();
            BookKeeperJournalManager bkjm = new BookKeeperJournalManager(conf, BKJMUtil.CreateJournalURI
                                                                             ("/hdfsjournal-simplerecovery"), nsi);

            bkjm.Format(nsi);
            EditLogOutputStream @out = bkjm.StartLogSegment(1, NameNodeLayoutVersion.CurrentLayoutVersion
                                                            );

            for (long i = 1; i <= 100; i++)
            {
                FSEditLogOp op = FSEditLogTestUtil.GetNoOpInstance();
                op.SetTransactionId(i);
                @out.Write(op);
            }
            @out.SetReadyToFlush();
            @out.Flush();
            @out.Abort();
            @out.Close();
            NUnit.Framework.Assert.IsNull(zkc.Exists(bkjm.FinalizedLedgerZNode(1, 100), false
                                                     ));
            NUnit.Framework.Assert.IsNotNull(zkc.Exists(bkjm.InprogressZNode(1), false));
            bkjm.RecoverUnfinalizedSegments();
            NUnit.Framework.Assert.IsNotNull(zkc.Exists(bkjm.FinalizedLedgerZNode(1, 100), false
                                                        ));
            NUnit.Framework.Assert.IsNull(zkc.Exists(bkjm.InprogressZNode(1), false));
        }
示例#25
0
        protected List <TreeElement> ctPages_Populate(object sender, PopulateEventArgs e)
        {
            List <TreeElement> result = new List <TreeElement>(100);

            NamespaceInfo selectedNamespace = Pages.FindNamespace(currentWiki, lstNamespace.SelectedValue);
            NamespaceInfo currentNamespace  = DetectNamespaceInfo();

            foreach (PageContent pi in Pages.GetPages(currentWiki, selectedNamespace))
            {
                string formattedTitle    = FormattingPipeline.PrepareTitle(currentWiki, pi.Title, false, FormattingContext.Other, pi.FullName);
                string onClickJavascript = "javascript:";
                // Populate the page title box if the title is different to the page name
                if (pi.FullName != pi.Title)
                {
                    // Supply the page title to the Javascript that sets the page title on the page
                    // We can safely escape the \ character, but the " character is interpreted by the browser even if it is escaped to Javascript, so we can't allow it.
                    // The non-wysiwyg version escapes ' and replaces " with escaped ', but ' breaks the html insertion, so remove it altogether
                    // Similarly, < on it's own is fine, but causes problems when combined with text and > to form a tag.  Safest to remove < characters to prevent
                    // breaking the drop-down.
                    onClickJavascript += "SetValue('txtPageTitle', '" + pi.Title.Replace("\\", "\\\\").Replace("'", "").Replace("\"", "").Replace("<", "") + "');";
                }
                else
                {
                    onClickJavascript += "SetValue('txtPageTitle', '');";
                }
                // Populate the page name (#468: add ++ to all ReverseFormatter to work)
                onClickJavascript += "return SetValue('txtPageName', '" + (selectedNamespace != currentNamespace ? "++" : "") + pi.FullName + "');";
                TreeElement item = new TreeElement((selectedNamespace != currentNamespace ? "++" : "") + pi.FullName, formattedTitle, onClickJavascript);
                result.Add(item);
            }
            return(result);
        }
示例#26
0
        public virtual void TestTwoWriters()
        {
            long                     start = 1;
            NamespaceInfo            nsi   = NewNSInfo();
            BookKeeperJournalManager bkjm1 = new BookKeeperJournalManager(conf, BKJMUtil.CreateJournalURI
                                                                              ("/hdfsjournal-dualWriter"), nsi);

            bkjm1.Format(nsi);
            BookKeeperJournalManager bkjm2 = new BookKeeperJournalManager(conf, BKJMUtil.CreateJournalURI
                                                                              ("/hdfsjournal-dualWriter"), nsi);
            EditLogOutputStream out1 = bkjm1.StartLogSegment(start, NameNodeLayoutVersion.CurrentLayoutVersion
                                                             );

            try
            {
                bkjm2.StartLogSegment(start, NameNodeLayoutVersion.CurrentLayoutVersion);
                NUnit.Framework.Assert.Fail("Shouldn't have been able to open the second writer");
            }
            catch (IOException ioe)
            {
                Log.Info("Caught exception as expected", ioe);
            }
            finally
            {
                out1.Close();
            }
        }
示例#27
0
        /// <summary>
        /// Adds a new Navigation Path.
        /// </summary>
        /// <param name="nspace">The target namespace (<c>null</c> for the root).</param>
        /// <param name="name">The Name.</param>
        /// <param name="pages">The Pages.</param>
        /// <param name="provider">The Provider to use for the new Navigation Path, or <c>null</c> for the default provider.</param>
        /// <returns>True if the Path is added successfully.</returns>
        public static bool AddNavigationPath(NamespaceInfo nspace, string name, List <PageInfo> pages, IPagesStorageProviderV30 provider)
        {
            var namespaceName = nspace != null ? nspace.Name : null;
            var fullName      = NameTools.GetFullName(namespaceName, name);

            if (Exists(fullName))
            {
                return(false);
            }

            if (provider == null)
            {
                provider = Collectors.PagesProviderCollector.GetProvider(Settings.DefaultPagesProvider);
            }

            NavigationPath newPath = provider.AddNavigationPath(namespaceName, name, pages.ToArray());

            if (newPath != null)
            {
                Log.LogEntry("Navigation Path " + fullName + " added", EntryType.General, Log.SystemUsername);
            }
            else
            {
                Log.LogEntry("Creation failed for Navigation Path " + fullName, EntryType.Error, Log.SystemUsername);
            }
            return(newPath != null);
        }
示例#28
0
        /// <summary>
        /// Adds some ACL entries for a subject.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="nspace">The namespace (<c>null</c> for the root).</param>
        /// <param name="grants">The granted actions.</param>
        /// <param name="denials">The denied actions.</param>
        /// <returns><c>true</c> if the operation succeeded, <c>false</c> otherwise.</returns>
        private bool AddAclEntriesForNamespace(string subject, string nspace, string[] grants, string[] denials)
        {
            bool isGroup = subject.StartsWith("G.");

            subject = subject.Substring(2);

            NamespaceInfo namespaceInfo = Pages.FindNamespace(nspace);

            UserGroup group = null;
            UserInfo  user  = null;

            if (isGroup)
            {
                group = Users.FindUserGroup(subject);
            }
            else
            {
                user = Users.FindUser(subject);
            }

            foreach (string action in grants)
            {
                bool done = false;
                if (isGroup)
                {
                    done = AuthWriter.SetPermissionForNamespace(AuthStatus.Grant,
                                                                namespaceInfo, action, group);
                }
                else
                {
                    done = AuthWriter.SetPermissionForNamespace(AuthStatus.Grant,
                                                                namespaceInfo, action, user);
                }
                if (!done)
                {
                    return(false);
                }
            }

            foreach (string action in denials)
            {
                bool done = false;
                if (isGroup)
                {
                    done = AuthWriter.SetPermissionForNamespace(AuthStatus.Deny,
                                                                namespaceInfo, action, group);
                }
                else
                {
                    done = AuthWriter.SetPermissionForNamespace(AuthStatus.Deny,
                                                                namespaceInfo, action, user);
                }
                if (!done)
                {
                    return(false);
                }
            }

            return(true);
        }
示例#29
0
        public virtual void TestEditLogFileNotExistsWhenReadingMetadata()
        {
            URI                      uri  = BKJMUtil.CreateJournalURI("/hdfsjournal-editlogfile");
            NamespaceInfo            nsi  = NewNSInfo();
            BookKeeperJournalManager bkjm = new BookKeeperJournalManager(conf, uri, nsi);

            bkjm.Format(nsi);
            try
            {
                // start new inprogress log segment with txid=1
                // and write transactions till txid=50
                string zkpath1 = StartAndFinalizeLogSegment(bkjm, 1, 50);
                // start new inprogress log segment with txid=51
                // and write transactions till txid=100
                string zkpath2 = StartAndFinalizeLogSegment(bkjm, 51, 100);
                // read the metadata from ZK. Here simulating the situation
                // when reading,the edit log metadata can be removed by purger thread.
                ZooKeeper zkspy = Org.Mockito.Mockito.Spy(BKJMUtil.ConnectZooKeeper());
                bkjm.SetZooKeeper(zkspy);
                Org.Mockito.Mockito.DoThrow(new KeeperException.NoNodeException(zkpath2 + " doesn't exists"
                                                                                )).When(zkspy).GetData(zkpath2, false, null);
                IList <EditLogLedgerMetadata> ledgerList = bkjm.GetLedgerList(false);
                NUnit.Framework.Assert.AreEqual("List contains the metadata of non exists path.",
                                                1, ledgerList.Count);
                NUnit.Framework.Assert.AreEqual("LogLedgerMetadata contains wrong zk paths.", zkpath1
                                                , ledgerList[0].GetZkPath());
            }
            finally
            {
                bkjm.Close();
            }
        }
示例#30
0
        /// <summary>
        /// Populates the namespaces list for migration.
        /// </summary>
        /// <param name="page">The selected page.</param>
        /// <returns><c>true</c> if there is at least one valid target namespace, <c>false</c> otherwise.</returns>
        private bool PopulateTargetNamespaces(PageInfo page)
        {
            string currentUser = SessionFacade.GetCurrentUsername();

            string[] currentGroups = SessionFacade.GetCurrentGroupNames();

            lstTargetNamespace.Items.Clear();

            NamespaceInfo pageNamespace = Pages.FindNamespace(NameTools.GetNamespace(page.FullName));

            if (pageNamespace != null)
            {
                // Try adding Root as target namespace
                bool canManagePages = AuthChecker.CheckActionForNamespace(null, Actions.ForNamespaces.ManagePages, currentUser, currentGroups);
                if (canManagePages)
                {
                    lstTargetNamespace.Items.Add(new ListItem("<root>", ""));
                }
            }

            // Try adding all other namespaces
            foreach (NamespaceInfo nspace in Pages.GetNamespaces().FindAll(n => n.Provider == page.Provider))
            {
                if (pageNamespace == null || (pageNamespace != null && nspace.Name != pageNamespace.Name))
                {
                    bool canManagePages = AuthChecker.CheckActionForNamespace(nspace, Actions.ForNamespaces.ManagePages, currentUser, currentGroups);
                    if (canManagePages)
                    {
                        lstTargetNamespace.Items.Add(new ListItem(nspace.Name, nspace.Name));
                    }
                }
            }

            return(lstTargetNamespace.Items.Count > 0);
        }
        protected void btnRename_Click(object sender, EventArgs e)
        {
            lblRenameResult.CssClass = "";
            lblRenameResult.Text     = "";

            txtNewName.Text = txtNewName.Text.Trim();

            Page.Validate("rename");
            if (!Page.IsValid)
            {
                return;
            }

            NamespaceInfo nspace = Pages.FindNamespace(txtCurrentNamespace.Value);
            string        theme  = Settings.GetTheme(nspace.Name);

            if (Pages.RenameNamespace(nspace, txtNewName.Text))
            {
                Settings.SetTheme(txtNewName.Text, theme);
                RefreshList();
                lblRenameResult.CssClass = "resultok";
                lblRenameResult.Text     = Properties.Messages.NamespaceRenamed;
                ReturnToList();
            }
            else
            {
                lblRenameResult.CssClass = "resulterror";
                lblRenameResult.Text     = Properties.Messages.CouldNotRenameNamespace;
            }
        }
示例#32
0
        /// <summary>
        /// Removes all the ACL Entries for a namespace that are bound to a subject.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="nspace">The namespace (<c>null</c> for the root).</param>
        /// <returns><c>true</c> if the operation succeeded, <c>false</c> otherwise.</returns>
        private bool RemoveEntriesForNamespace(string subject, NamespaceInfo nspace)
        {
            string resourceName = Actions.ForNamespaces.ResourceMasterPrefix;

            if (nspace != null)
            {
                resourceName += nspace.Name;
            }

            AclEntry[] entries = _settingsProvider.AclManager.RetrieveEntriesForSubject(subject);

            foreach (AclEntry entry in entries)
            {
                if (entry.Resource == resourceName)
                {
                    // This call automatically logs the operation result
                    bool done = SetPermissionForNamespace(AuthStatus.Delete, nspace, entry.Action, subject);
                    if (!done)
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
        /// <summary>
        /// Loads the available pages and selects the current one.
        /// </summary>
        private void LoadDefaultPages()
        {
            // Populate default page, if there is a namespace selected
            if (!string.IsNullOrEmpty(txtCurrentNamespace.Value))
            {
                NamespaceInfo nspace = Pages.FindNamespace(
                    txtCurrentNamespace.Value != RootName ? txtCurrentNamespace.Value : null);

                List <PageInfo> pages = Pages.GetPages(nspace);

                string currentDefaultPage = nspace != null ? nspace.DefaultPage.FullName : Settings.DefaultPage;

                lstDefaultPage.Items.Clear();
                foreach (PageInfo page in pages)
                {
                    ListItem item = new ListItem(NameTools.GetLocalName(page.FullName), page.FullName);
                    if (page.FullName == currentDefaultPage)
                    {
                        item.Selected = true;
                    }

                    lstDefaultPage.Items.Add(item);
                }
            }
        }
示例#34
0
        /// <summary>
        /// Retrieves the subjects that have ACL entries set for a namespace.
        /// </summary>
        /// <param name="nspace">The namespace (<c>null</c> for the root).</param>
        /// <returns>The subjects.</returns>
        public static SubjectInfo[] RetrieveSubjectsForNamespace(NamespaceInfo nspace)
        {
            var resourceName = Actions.ForNamespaces.ResourceMasterPrefix;

            if (nspace != null)
            {
                resourceName += nspace.Name;
            }

            var entries = SettingsProvider.AclManager.RetrieveEntriesForResource(resourceName);

            var result = new List <SubjectInfo>();

            foreach (var entry in entries)
            {
                SubjectType type = AuthTools.IsGroup(entry.Subject) ? SubjectType.Group : SubjectType.User;

                // Remove the subject qualifier ('U.' or 'G.')
                var name = entry.Subject.Substring(2);

                if (result.Find(delegate(SubjectInfo x) { return(x.Name == name && x.Type == type); }) == null)
                {
                    result.Add(new SubjectInfo(name, type));
                }
            }

            return(result.ToArray());
        }
示例#35
0
        /// <summary>
        /// Adds a new Navigation Path.
        /// </summary>
        /// <param name="nspace">The target namespace (<c>null</c> for the root).</param>
        /// <param name="name">The Name.</param>
        /// <param name="pages">The Pages.</param>
        /// <param name="provider">The Provider to use for the new Navigation Path, or <c>null</c> for the default provider.</param>
        /// <returns>True if the Path is added successfully.</returns>
        public static bool AddNavigationPath(NamespaceInfo nspace, string name, List<PageInfo> pages, IPagesStorageProviderV30 provider)
        {
            string namespaceName = nspace != null ? nspace.Name : null;
            string fullName = NameTools.GetFullName(namespaceName, name);

            if(Exists(fullName)) return false;

            if(provider == null) provider = Collectors.PagesProviderCollector.GetProvider(Settings.DefaultPagesProvider);

            NavigationPath newPath = provider.AddNavigationPath(namespaceName, name, pages.ToArray());
            if(newPath != null) Log.LogEntry("Navigation Path " + fullName + " added", EntryType.General, Log.SystemUsername);
            else Log.LogEntry("Creation failed for Navigation Path " + fullName, EntryType.Error, Log.SystemUsername);
            return newPath != null;
        }
示例#36
0
 /// <summary>
 /// Gets the list of Navigation Paths in a namespace.
 /// </summary>
 /// <param name="nspace">The namespace (<c>null</c> for the root).</param>
 /// <returns>The navigation paths.</returns>
 public NavigationPath[] GetNavigationPaths(NamespaceInfo nspace)
 {
     return NavigationPaths.GetNavigationPaths(nspace).ToArray();
 }
示例#37
0
 /// <summary>
 /// Gets the List of Categories in a namespace.
 /// </summary>
 /// <param name="nspace">The namespace (<c>null</c> for the root).</param>
 /// <returns>The categories.</returns>
 public CategoryInfo[] GetCategories(NamespaceInfo nspace)
 {
     return Pages.GetCategories(nspace).ToArray();
 }
示例#38
0
        /// <summary>
        /// Checks whether an action is allowed for a namespace.
        /// </summary>
        /// <param name="nspace">The namespace (<c>null</c> for the root).</param>
        /// <param name="action">The action (see <see cref="Actions.ForNamespaces" /> class)</param>
        /// <param name="user">The user.</param>
        /// <returns><c>true</c> if the action is allowed, <c>false</c> otherwise.</returns>
        /// <exception cref="ArgumentNullException">If <b>action</b> or <b>user</b> are <c>null</c>.</exception>
        /// <exception cref="ArgumentException">If <b>action</b> is empty.</exception>
        public bool CheckActionForNamespace(NamespaceInfo nspace, string action, UserInfo user)
        {
            if(action == null) throw new ArgumentNullException("action");
            if(action.Length == 0) throw new ArgumentException("Action cannot be empty", "action");

            var temp = user != null ? user : Users.GetAnonymousAccount();

            return AuthChecker.CheckActionForNamespace(nspace, action, temp.Username, temp.Groups);
        }
 private void AssertNamespaceInfosAreEqual(NamespaceInfo expected, NamespaceInfo actual, bool checkProvider)
 {
     Assert.AreEqual(expected.Name, actual.Name, "Wrong name");
     if(expected.DefaultPage == null) Assert.IsNull(actual.DefaultPage, "DefaultPage should be null");
     else AssertPageInfosAreEqual(expected.DefaultPage, actual.DefaultPage, true);
     if(checkProvider) Assert.AreSame(expected.Provider, actual.Provider);
 }
示例#40
0
        /// <summary>
        /// Gets all the Categories in a namespace.
        /// </summary>
        /// <param name="nspace">The namespace.</param>
        /// <returns>All the Categories in the namespace, sorted by name.</returns>
        public CategoryInfo[] GetCategories(NamespaceInfo nspace)
        {
            lock(this) {
                CategoryInfo[] allCategories = GetAllCategories(); // Sorted

                // Preallocate assuming that there are 4 namespaces and that they are distributed evenly among them:
                // categories might be a few dozens at most, so preallocating a smaller number of items is not a problem
                List<CategoryInfo> selectedCategories = new List<CategoryInfo>(allCategories.Length / 4);

                // Select categories that have the same namespace as the requested one,
                // either null-null or same name
                foreach(CategoryInfo cat in allCategories) {
                    string catNamespace = NameTools.GetNamespace(cat.FullName);
                    if(nspace == null && catNamespace == null) selectedCategories.Add(cat);
                    else if(nspace != null && catNamespace != null && StringComparer.OrdinalIgnoreCase.Compare(nspace.Name, catNamespace) == 0) selectedCategories.Add(cat);
                }

                return selectedCategories.ToArray();
            }
        }
示例#41
0
 /// <summary>
 /// Fires the NamespaceActivity event.
 /// </summary>
 /// <param name="nspace">The namespace the activity refers to.</param>
 /// <param name="nspaceOldName">The old name of the renamed namespace, or <c>null</c>.</param>
 /// <param name="activity">The activity.</param>
 public void OnNamespaceActivity(NamespaceInfo nspace, string nspaceOldName, NamespaceActivity activity)
 {
     if(NamespaceActivity != null) {
         NamespaceActivity(this, new NamespaceActivityEventArgs(nspace, nspaceOldName, activity));
     }
 }
示例#42
0
 /// <summary>
 /// Gets the list of the Wiki Pages in a namespace.
 /// </summary>
 /// <param name="nspace">The namespace (<c>null</c> for the root).</param>
 /// <returns>The pages.</returns>
 public PageInfo[] GetPages(NamespaceInfo nspace)
 {
     return Pages.GetPages(nspace).ToArray();
 }
示例#43
0
        /// <summary>
        /// Gets the canonical URL tag for a page.
        /// </summary>
        /// <param name="requestUrl">The request URL.</param>
        /// <param name="currentPage">The current page.</param>
        /// <param name="nspace">The namespace.</param>
        /// <returns>The canonical URL, or an empty string if <paramref name="requestUrl"/> is already canonical.</returns>
        public static string GetCanonicalUrlTag(string requestUrl, PageInfo currentPage, NamespaceInfo nspace)
        {
            string url = "";
            if(nspace == null && currentPage.FullName == Settings.DefaultPage) url = Settings.GetMainUrl().ToString();
            else url = Settings.GetMainUrl().ToString().TrimEnd('/') + "/" + currentPage.FullName + Settings.PageExtension;

            // Case sensitive
            if(url == requestUrl) return "";
            else return "<link rel=\"canonical\" href=\"" + url + "\" />";
        }
示例#44
0
        /// <summary>
        /// Gets all the pages in a namespace that are bound to zero categories.
        /// </summary>
        /// <param name="nspace">The namespace (<c>null</c> for the root).</param>
        /// <returns>The pages, sorted by name.</returns>
        public PageInfo[] GetUncategorizedPages(NamespaceInfo nspace)
        {
            lock(this) {
                PageInfo[] pages = GetPages(nspace);
                CategoryInfo[] categories = GetCategories(nspace);

                List<PageInfo> result = new List<PageInfo>(pages.Length);

                foreach(PageInfo p in pages) {
                    bool found = false;
                    foreach(CategoryInfo c in categories) {
                        foreach(string name in c.Pages) {
                            if(StringComparer.OrdinalIgnoreCase.Compare(name, p.FullName) == 0) {
                                found = true;
                                break;
                            }
                        }
                    }
                    if(!found) result.Add(p);
                }

                return result.ToArray();
            }
        }
示例#45
0
 /// <summary>
 /// Gets the theme in use for a namespace.
 /// </summary>
 /// <param name="nspace">The namespace (<c>null</c> for the root).</param>
 /// <returns>The theme.</returns>
 public string GetTheme(NamespaceInfo nspace)
 {
     return Settings.GetTheme(nspace != null ? nspace.Name : null);
 }
示例#46
0
        /// <summary>
        /// Finds a namespace.
        /// </summary>
        /// <param name="name">The name of the namespace to find.</param>
        /// <param name="namespaces">The namespaces array.</param>
        /// <returns>The found namespace, or <c>null</c>.</returns>
        private NamespaceInfo FindNamespace(string name, NamespaceInfo[] namespaces)
        {
            if(name == null) return null;

            NamespaceInfo target = new NamespaceInfo(name, this, null);
            NamespaceComparer comp = new NamespaceComparer();

            NamespaceInfo result = Array.Find(namespaces, delegate(NamespaceInfo n) { return comp.Compare(n, target) == 0; });

            return result;
        }
示例#47
0
        /// <summary>
        /// Sets the default page of a namespace.
        /// </summary>
        /// <param name="nspace">The namespace of which to set the default page.</param>
        /// <param name="page">The page to use as default page, or <c>null</c>.</param>
        /// <returns>The correct <see cref="T:NamespaceInfo" /> object.</returns>
        /// <exception cref="ArgumentNullException">If <b>nspace</b> is <c>null</c>.</exception>
        public NamespaceInfo SetNamespaceDefaultPage(NamespaceInfo nspace, PageInfo page)
        {
            if(nspace == null) throw new ArgumentNullException("nspace");

            lock(this) {
                // Find requested namespace and page: if they don't exist, return null
                NamespaceInfo[] allNamespaces = GetNamespaces();
                NamespaceInfo targetNamespace = FindNamespace(nspace.Name, allNamespaces);
                if(targetNamespace == null) return null;

                LocalPageInfo localPage = null;

                if(page != null) {
                    localPage = LoadLocalPageInfo(page);
                    if(localPage == null) return null;
                }

                targetNamespace.DefaultPage = localPage;
                DumpNamespaces(allNamespaces);
                namespacesCache = null;

                return new NamespaceInfo(targetNamespace.Name, this, targetNamespace.DefaultPage);
            }
        }
示例#48
0
        /// <summary>
        /// Moves the backups of a page into a new namespace.
        /// </summary>
        /// <param name="page">The page that is being moved.</param>
        /// <param name="destination">The destination namespace (<c>null</c> for the root).</param>
        /// <remarks>This method should be invoked <b>before</b> moving the corresponding page.</remarks>
        private void MoveBackups(PageInfo page, NamespaceInfo destination)
        {
            lock(this) {
                int[] backups = GetBackups(page);
                if(backups == null) return; // Page does not exist

                LocalPageInfo local = (LocalPageInfo)page;
                string extension = Path.GetExtension(local.File);
                string currDir = GetNamespacePartialPathForPageContent(NameTools.GetNamespace(page.FullName));
                string newDir = GetNamespacePartialPathForPageContent(destination != null ? destination.Name : null);
                string currPartialName = currDir + Path.GetFileNameWithoutExtension(local.File) + ".";
                string newPartialName = newDir + NameTools.GetLocalName(page.FullName) + ".";

                for(int i = 0; i < backups.Length; i++) {
                    File.Move(GetFullPathForPageContent(currPartialName + Tools.GetVersionString(backups[i]) + extension),
                        GetFullPathForPageContent(newPartialName + Tools.GetVersionString(backups[i]) + extension));
                }
            }
        }
示例#49
0
        /// <summary>
        /// Removes a namespace.
        /// </summary>
        /// <param name="nspace">The namespace to remove.</param>
        /// <returns><c>true</c> if the namespace is removed, <c>false</c> otherwise.</returns>
        /// <exception cref="ArgumentNullException">If <b>nspace</b> is <c>null</c>.</exception>
        public bool RemoveNamespace(NamespaceInfo nspace)
        {
            if(nspace == null) throw new ArgumentNullException("nspace");

            lock(this) {
                // Load all namespaces and remove the one to remove
                List<NamespaceInfo> allNamespaces = new List<NamespaceInfo>(GetNamespaces());
                NamespaceComparer comp = new NamespaceComparer();
                int index = allNamespaces.FindIndex(delegate(NamespaceInfo x) { return comp.Compare(x, nspace) == 0; });

                if(index >= 0) {
                    // Delete all categories
                    foreach(CategoryInfo cat in GetCategories(nspace)) {
                        RemoveCategory(cat);
                    }

                    // Delete all pages in the namespace (RemovePage removes the page from the search engine index)
                    nspace.DefaultPage = null; // TODO: Remove this trick (needed in order to delete the default page)
                    foreach(PageInfo page in GetPages(nspace)) {
                        RemovePage(page);
                    }

                    // Update namespaces file
                    allNamespaces.RemoveAt(index);
                    DumpNamespaces(allNamespaces.ToArray());

                    // Remove namespace folder
                    Directory.Delete(GetFullPathForPageContent(GetNamespacePartialPathForPageContent(nspace.Name)), true);

                    // Remove drafts folder
                    string oldDraftsFullPath = GetFullPathForPageDrafts(nspace.Name);
                    if(Directory.Exists(oldDraftsFullPath)) {
                        Directory.Delete(oldDraftsFullPath, true);
                    }

                    // Remove messages folder
                    Directory.Delete(GetFullPathForMessages(GetNamespacePartialPathForPageContent(nspace.Name)), true);

                    namespacesCache = null;
                    pagesCache = null;
                    categoriesCache = null;

                    return true;
                }
                else return false;
            }
        }
示例#50
0
 /// <summary>
 /// Dumps namespaces on disk.
 /// </summary>
 /// <param name="namespaces">The namespaces to dump.</param>
 private void DumpNamespaces(NamespaceInfo[] namespaces)
 {
     StringBuilder sb = new StringBuilder(namespaces.Length * 20);
     foreach(NamespaceInfo ns in namespaces) {
         sb.Append(ns.Name);
         sb.Append("|");
         sb.Append(ns.DefaultPage != null ? ns.DefaultPage.FullName : "");
         sb.Append("\r\n");
     }
     File.WriteAllText(GetFullPath(NamespacesFile), sb.ToString());
 }
示例#51
0
        /// <summary>
        /// Sets a permission for a namespace.
        /// </summary>
        /// <param name="status">The authorization status.</param>
        /// <param name="nspace">The namespace (<c>null</c> for the root).</param>
        /// <param name="action">The action of which to modify the authorization status.</param>
        /// <param name="subject">The subject of the authorization change.</param>
        /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns>
        private static bool SetPermissionForNamespace(AuthStatus status, NamespaceInfo nspace, string action, string subject)
        {
            if(action == null) throw new ArgumentNullException("action");
            if(action.Length == 0) throw new ArgumentException("Action cannot be empty", "action");
            if(action != Actions.FullControl && !AuthTools.IsValidAction(action, Actions.ForNamespaces.All)) {
                throw new ArgumentException("Invalid action", "action");
            }

            string namespaceName = nspace != null ? nspace.Name : "";

            if(status == AuthStatus.Delete) {
                bool done = SettingsProvider.AclManager.DeleteEntry(Actions.ForNamespaces.ResourceMasterPrefix + namespaceName,
                    action, subject);

                if(done) {
                    Log.LogEntry(MessageDeleteSuccess + GetLogMessage(Actions.ForNamespaces.ResourceMasterPrefix, namespaceName,
                        action, subject, Delete), EntryType.General, Log.SystemUsername);
                }
                else {
                    Log.LogEntry(MessageDeleteFailure + GetLogMessage(Actions.ForNamespaces.ResourceMasterPrefix, namespaceName,
                        action, subject, Delete), EntryType.Error, Log.SystemUsername);
                }

                return done;
            }
            else {
                bool done = SettingsProvider.AclManager.StoreEntry(Actions.ForNamespaces.ResourceMasterPrefix + namespaceName,
                    action, subject, status == AuthStatus.Grant ? Value.Grant : Value.Deny);

                if(done) {
                    Log.LogEntry(MessageSetSuccess + GetLogMessage(Actions.ForNamespaces.ResourceMasterPrefix, namespaceName,
                        action, subject, Set + status.ToString()), EntryType.General, Log.SystemUsername);
                }
                else {
                    Log.LogEntry(MessageSetFailure + GetLogMessage(Actions.ForNamespaces.ResourceMasterPrefix, namespaceName,
                        action, subject, Set + status.ToString()), EntryType.Error, Log.SystemUsername);
                }

                return done;
            }
        }
示例#52
0
        /// <summary>
        /// Renames a namespace.
        /// </summary>
        /// <param name="nspace">The namespace to rename.</param>
        /// <param name="newName">The new name of the namespace.</param>
        /// <returns>The correct <see cref="T:NamespaceInfo" /> object.</returns>
        /// <exception cref="ArgumentNullException">If <b>nspace</b> or <b>newName</b> are <c>null</c>.</exception>
        /// <exception cref="ArgumentException">If <b>newName</b> is empty.</exception>
        public NamespaceInfo RenameNamespace(NamespaceInfo nspace, string newName)
        {
            if(nspace == null) throw new ArgumentNullException("nspace");
            if(newName == null) throw new ArgumentNullException("newName");
            if(newName.Length == 0) throw new ArgumentException("New Name cannot be empty", "newName");

            lock(this) {
                if(NamespaceExists(newName)) return null;

                string oldName = nspace.Name;

                // Remove all pages and their messages from search engine index
                foreach(PageInfo page in GetPages(nspace)) {
                    PageContent content = GetContent(page);
                    UnindexPage(content);

                    Message[] messages = GetMessages(page);
                    foreach(Message msg in messages) {
                        UnindexMessageTree(page, msg);
                    }
                }

                // Load namespace list and change name
                NamespaceInfo[] allNamespaces = GetNamespaces();
                NamespaceComparer comp = new NamespaceComparer();
                NamespaceInfo result = FindNamespace(nspace.Name, allNamespaces);
                if(result == null) return null;
                result.Name = newName;
                // Change default page full name
                if(result.DefaultPage != null) {
                    result.DefaultPage = new LocalPageInfo(NameTools.GetFullName(newName, NameTools.GetLocalName(result.DefaultPage.FullName)),
                        this, result.DefaultPage.CreationDateTime,
                        GetNamespacePartialPathForPageContent(newName) + Path.GetFileName(((LocalPageInfo)result.DefaultPage).File));
                }

                DumpNamespaces(allNamespaces);

                // Update Category list with new namespace name
                CategoryInfo[] allCategories = GetAllCategories();
                for(int k = 0; k < allCategories.Length; k++) {
                    CategoryInfo category = allCategories[k];
                    string catNamespace = NameTools.GetNamespace(category.FullName);
                    if(catNamespace != null && StringComparer.OrdinalIgnoreCase.Compare(catNamespace, oldName) == 0) {
                        category.FullName = NameTools.GetFullName(newName, NameTools.GetLocalName(category.FullName));
                        for(int i = 0; i < category.Pages.Length; i++) {
                            category.Pages[i] = NameTools.GetFullName(newName, NameTools.GetLocalName(category.Pages[i]));
                        }
                    }
                }
                DumpCategories(allCategories);

                // Rename namespace folder
                Directory.Move(GetFullPathForPageContent(GetNamespacePartialPathForPageContent(oldName)),
                    GetFullPathForPageContent(GetNamespacePartialPathForPageContent(newName)));

                // Rename drafts folder
                string oldDraftsFullPath = GetFullPathForPageDrafts(nspace.Name);
                if(Directory.Exists(oldDraftsFullPath)) {
                    string newDraftsFullPath = GetFullPathForPageDrafts(newName);

                    Directory.Move(oldDraftsFullPath, newDraftsFullPath);
                }

                // Rename messages folder
                Directory.Move(GetFullPathForMessages(GetNamespacePartialPathForPageContent(oldName)),
                    GetFullPathForMessages(GetNamespacePartialPathForPageContent(newName)));

                // Update Page list with new namespace name and file
                PageInfo[] allPages = GetAllPages();
                foreach(PageInfo page in allPages) {
                    string pageNamespace = NameTools.GetNamespace(page.FullName);
                    if(pageNamespace != null && StringComparer.OrdinalIgnoreCase.Compare(pageNamespace, oldName) == 0) {
                        LocalPageInfo local = (LocalPageInfo)page;
                        local.FullName = NameTools.GetFullName(newName, NameTools.GetLocalName(local.FullName));
                        local.File = GetNamespacePartialPathForPageContent(newName) + Path.GetFileName(local.File);
                    }
                }
                DumpPages(allPages);

                namespacesCache = null;
                pagesCache = null;
                categoriesCache = null;

                // Re-add all pages and their messages to the search engine index
                foreach(PageInfo page in GetPages(result)) { // result contains the new name
                    PageContent content = GetContent(page);
                    IndexPage(content);

                    Message[] messages = GetMessages(page);
                    foreach(Message msg in messages) {
                        IndexMessageTree(page, msg);
                    }
                }

                return result;
            }
        }
示例#53
0
        /// <summary>
        /// Sets a permission for a namespace.
        /// </summary>
        /// <param name="status">The authorization status.</param>
        /// <param name="nspace">The namespace (<c>null</c> for the root).</param>
        /// <param name="action">The action of which to modify the authorization status.</param>
        /// <param name="user">The user subject of the authorization change.</param>
        /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns>
        public static bool SetPermissionForNamespace(AuthStatus status, NamespaceInfo nspace, string action, UserInfo user)
        {
            if(user == null) throw new ArgumentNullException("user");

            return SetPermissionForNamespace(status, nspace, action, AuthTools.PrepareUsername(user.Username));
        }
示例#54
0
        /// <summary>
        /// Moves a page from its namespace into another.
        /// </summary>
        /// <param name="page">The page to move.</param>
        /// <param name="destination">The destination namespace (null for the root).</param>
        /// <param name="copyCategories">A value indicating whether to copy the page categories in the destination 
        /// namespace, if not already available.</param>
        /// <returns>The correct instance of <see cref="T:PageInfo" />.</returns>
        /// <exception cref="ArgumentNullException">If <b>page</b> is <c>null</c>.</exception>
        public PageInfo MovePage(PageInfo page, NamespaceInfo destination, bool copyCategories)
        {
            if(page == null) throw new ArgumentNullException("page");

            string destinationName = destination != null ? destination.Name : null;

            NamespaceInfo currentNs = FindNamespace(NameTools.GetNamespace(page.FullName), GetNamespaces());
            NamespaceComparer nsComp = new NamespaceComparer();
            if((currentNs == null && destination == null) || nsComp.Compare(currentNs, destination) == 0) return null;

            if(PageExists(new PageInfo(NameTools.GetFullName(destinationName, NameTools.GetLocalName(page.FullName)), this, page.CreationDateTime))) return null;
            if(!NamespaceExists(destinationName)) return null;

            if(currentNs != null && currentNs.DefaultPage != null) {
                // Cannot move the default page
                if(new PageNameComparer().Compare(currentNs.DefaultPage, page) == 0) return null;
            }

            // Store categories for copying them, if needed
            CategoryInfo[] pageCategories = GetCategoriesForPage(page);
            // Update categories names with new namespace (don't modify the same instance because it's actually the cache!)
            for(int i = 0; i < pageCategories.Length; i++) {
                string[] pages = pageCategories[i].Pages;
                pageCategories[i] = new CategoryInfo(NameTools.GetFullName(destinationName, NameTools.GetLocalName(pageCategories[i].FullName)), this);
                pageCategories[i].Pages = new string[pages.Length];
                for(int k = 0; k < pages.Length; k++) {
                    pageCategories[i].Pages[k] = NameTools.GetFullName(destinationName, NameTools.GetLocalName(pages[k]));
                }
            }

            // Delete category bindings
            RebindPage(page, new string[0]);

            // Change namespace and file
            PageInfo[] allPages = GetAllPages();
            PageNameComparer comp = new PageNameComparer();
            PageInfo newPage = null;
            foreach(PageInfo current in allPages) {
                if(comp.Compare(current, page) == 0) {
                    // Page found, update data

                    // Change namespace and file
                    LocalPageInfo local = (LocalPageInfo)current;

                    // Update search engine index
                    PageContent oldPageContent = GetContent(local);
                    UnindexPage(oldPageContent);
                    foreach(Message msg in GetMessages(local)) {
                        UnindexMessageTree(local, msg);
                    }

                    // Move backups in new folder
                    MoveBackups(page, destination);

                    string newFile = GetNamespacePartialPathForPageContent(destinationName) + Path.GetFileName(local.File);

                    // Move data file
                    File.Move(GetFullPathForPageContent(local.File), GetFullPathForPageContent(newFile));

                    // Move messages file
                    string messagesFullPath = GetFullPathForMessages(local.File);
                    if(File.Exists(messagesFullPath)) {
                        File.Move(messagesFullPath, GetFullPathForMessages(newFile));
                    }

                    // Move draft file
                    string draftFullPath = GetFullPathForPageDrafts(local.File);
                    if(File.Exists(draftFullPath)) {
                        string newDraftFullPath = GetFullPathForPageDrafts(newFile);
                        if(!Directory.Exists(Path.GetDirectoryName(newDraftFullPath))) {
                            Directory.CreateDirectory(Path.GetDirectoryName(newDraftFullPath));
                        }
                        File.Move(draftFullPath, newDraftFullPath);
                    }

                    //local.Namespace = destinationName;
                    local.FullName = NameTools.GetFullName(destinationName, NameTools.GetLocalName(local.FullName));
                    local.File = newFile;
                    newPage = local;

                    DumpPages(allPages);

                    // Update search engine index
                    IndexPage(new PageContent(newPage, oldPageContent.Title, oldPageContent.User, oldPageContent.LastModified,
                        oldPageContent.Comment, oldPageContent.Content, oldPageContent.Keywords, oldPageContent.Description));
                    foreach(Message msg in GetMessages(local)) {
                        IndexMessageTree(newPage, msg);
                    }

                    break;
                }
            }

            // Rebind page, if needed
            if(copyCategories) {
                // Foreach previously bound category, verify that is present in the destination namespace, if not then create it
                List<string> newCategories = new List<string>(pageCategories.Length);
                foreach(CategoryInfo oldCategory in pageCategories) {
                    if(!CategoryExists(new CategoryInfo(oldCategory.FullName, this))) {
                        AddCategory(destination != null ? destination.Name : null, NameTools.GetLocalName(oldCategory.FullName));
                    }
                    newCategories.Add(oldCategory.FullName);
                }
                RebindPage(newPage, newCategories.ToArray());
            }

            namespacesCache = null;
            pagesCache = null;
            categoriesCache = null;
            return newPage;
        }
示例#55
0
		public ResourceExtension(string resourceName)
		{
			Resource = new NamespaceInfo(resourceName);
		}
示例#56
0
        /// <summary>
        /// Removes all the ACL Entries for a namespace that are bound to a subject.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="nspace">The namespace (<c>null</c> for the root).</param>
        /// <returns><c>true</c> if the operation succeeded, <c>false</c> otherwise.</returns>
        private static bool RemoveEntriesForNamespace(string subject, NamespaceInfo nspace)
        {
            string resourceName = Actions.ForNamespaces.ResourceMasterPrefix;
            if(nspace != null) resourceName += nspace.Name;

            AclEntry[] entries = SettingsProvider.AclManager.RetrieveEntriesForSubject(subject);

            foreach(AclEntry entry in entries) {
                if(entry.Resource == resourceName) {
                    // This call automatically logs the operation result
                    bool done = SetPermissionForNamespace(AuthStatus.Delete, nspace, entry.Action, subject);
                    if(!done) return false;
                }
            }

            return true;
        }
示例#57
0
        /// <summary>
        /// Gets all the Navigation Paths in a Namespace.
        /// </summary>
        /// <param name="nspace">The Namespace.</param>
        /// <returns>All the Navigation Paths, sorted by name.</returns>
        public NavigationPath[] GetNavigationPaths(NamespaceInfo nspace)
        {
            lock(this) {
                NavigationPath[] allNavigationPaths = GetAllNavigationPaths();

                List<NavigationPath> selectedNavigationPaths = new List<NavigationPath>(allNavigationPaths.Length / 4);

                foreach(NavigationPath path in allNavigationPaths) {
                    string pathNamespace = NameTools.GetNamespace(path.FullName);
                    if(nspace == null && pathNamespace == null) selectedNavigationPaths.Add(path);
                    if(nspace != null && pathNamespace != null && StringComparer.OrdinalIgnoreCase.Compare(nspace.Name, pathNamespace) == 0) selectedNavigationPaths.Add(path);
                }

                selectedNavigationPaths.Sort(new NavigationPathComparer());

                return selectedNavigationPaths.ToArray();
            }
        }
示例#58
0
        /// <summary>
        /// Sets a permission for a namespace.
        /// </summary>
        /// <param name="status">The authorization status.</param>
        /// <param name="nspace">The namespace (<c>null</c> for the root).</param>
        /// <param name="action">The action of which to modify the authorization status.</param>
        /// <param name="group">The group subject of the authorization change.</param>
        /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns>
        public static bool SetPermissionForNamespace(AuthStatus status, NamespaceInfo nspace, string action, UserGroup group)
        {
            if(group == null) throw new ArgumentNullException("group");

            return SetPermissionForNamespace(status, nspace, action, AuthTools.PrepareGroup(group.Name));
        }
示例#59
0
		public override object ProvideValue(IServiceProvider serviceProvider)
		{
			var provideValue = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
			var propertyInfo = provideValue?.TargetProperty as PropertyInfo;

			var contextProvider = serviceProvider.GetService(typeof(IXamlSchemaContextProvider)) as IXamlSchemaContextProvider;
			if (contextProvider != null)
			{
				var context = contextProvider.SchemaContext as EtoXamlSchemaContext;
				if (context != null && context.DesignMode)
				{
					// TODO: Lookup resource file using ide service so we can actually show the image or use the resource
					if (propertyInfo != null)
					{
						if (typeof(Bitmap).IsAssignableFrom(propertyInfo.PropertyType))
							return new Bitmap(24, 24, PixelFormat.Format32bppRgba);
						
						if (typeof(Icon).IsAssignableFrom(propertyInfo.PropertyType))
							return new Icon(1, new Bitmap(24, 24, PixelFormat.Format32bppRgba));

						// return its current value if not a known type to handle
						return propertyInfo.GetValue(provideValue.TargetObject, null);
					}
					return null;
				}
			}

			Assembly assembly;
			NamespaceInfo resource;
			if (!string.IsNullOrEmpty(AssemblyName))
			{
				assembly = Assembly.Load(new AssemblyName(AssemblyName));
				resource = new NamespaceInfo(ResourceName, assembly);
			}
			else
			{
				try
				{
					resource = new NamespaceInfo(ResourceName);
				}
				catch (ArgumentException)
				{
					var rootProvider = serviceProvider.GetService(typeof(IRootObjectProvider)) as IRootObjectProvider;
					if (rootProvider == null)
						throw;
					assembly = rootProvider.RootObject.GetType().GetTypeInfo().Assembly; 
					resource = new NamespaceInfo(ResourceName, assembly);
				}
			}

			if (propertyInfo != null && !propertyInfo.PropertyType.GetTypeInfo().IsAssignableFrom(typeof(Stream).GetTypeInfo()))
			{
				var converter = TypeDescriptor.GetConverter(propertyInfo.PropertyType);
				if (converter != null)
				{
					if (converter.CanConvertFrom(typeof(NamespaceInfo)))
						return converter.ConvertFrom(resource);
					if (converter.CanConvertFrom(typeof(Stream)))
						return converter.ConvertFrom(resource.FindResource());
				}
				var streamArgs = new [] { typeof(Stream) };
				var constructor = propertyInfo.PropertyType.GetConstructor(streamArgs);
				if (constructor != null)
				{
					return constructor.Invoke(new[] { resource.FindResource() });
				}
			}
			Stream stream = null;
			if (resource != null && resource.Assembly != null)
				stream = resource.FindResource();
			return stream;
		}
示例#60
0
        /// <summary>
        /// Gets all the Pages in a namespace.
        /// </summary>
        /// <param name="nspace">The namespace (<c>null</c> for the root).</param>
        /// <returns>All the Pages in the namespace. The array is not sorted.</returns>
        public PageInfo[] GetPages(NamespaceInfo nspace)
        {
            lock(this) {
                PageInfo[] allPages = GetAllPages();

                // Preallocate assuming that there are 2 namespaces and that they are evenly distributed across them:
                // pages can be as much as many thousands, so preallocating a smaller number can cause a performance loss
                List<PageInfo> selectedPages = new List<PageInfo>(allPages.Length / 2);

                // Select pages that have the same namespace as the requested one,
                // either null-null or same name
                foreach(PageInfo page in allPages) {
                    string pageNamespace = NameTools.GetNamespace(page.FullName);
                    if(nspace == null && pageNamespace == null) selectedPages.Add(page);
                    if(nspace != null && pageNamespace != null && StringComparer.OrdinalIgnoreCase.Compare(nspace.Name, pageNamespace) == 0) selectedPages.Add(page);
                }

                return selectedPages.ToArray();
            }
        }