/// <summary> /// Resolved a <see cref="NavigationTerm"/> object with the specified URL against the current site. /// If the specified URL resolves to a navigation term with catalog enabled, and there are remaining segments, /// <paramref name="matchedUrl"/> will be set to a friendly URL resolved from the navigation term without the excess segments. /// </summary> /// <param name="inputUrl">Input URL.</param> /// <param name="navigationTerm">Resolved <see cref="NavigationTerm"/> object if any; otherwise *null*.</param> /// <param name="matchedUrl">Resolved URL for the <see cref="NavigationTerm"/> object if any; otherwise *null*.</param> /// <returns>*true* if the specified URL resolves to a <see cref="NavigationTerm"/> object.</returns> public static bool TryGetNavigationTerm(string inputUrl, out NavigationTerm navigationTerm, out string matchedUrl) { CommonHelper.ConfirmNotNull(inputUrl, "inputUrl"); if (SPContext.Current != null && !String.IsNullOrEmpty(inputUrl) && inputUrl[0] == '/') { int pathEndPos = inputUrl.IndexOfAny(new[] { '?', '#' }); if (pathEndPos > 0) { inputUrl = inputUrl.Substring(0, pathEndPos); } SPSite currentSite = SPContext.Current.Site; while (inputUrl.Length > 0) { string[] segments; if (TaxonomyNavigation.TryParseFriendlyUrl(currentSite, inputUrl, out navigationTerm, out segments)) { matchedUrl = inputUrl; return(true); } inputUrl = inputUrl.Substring(0, inputUrl.LastIndexOf('/')); } } navigationTerm = null; matchedUrl = null; return(false); }
private static NavigationTermSet GetEditableNavigationTermSetByProviderName( Web web, ClientRuntimeContext context, String providerName) { // Get the current taxonomy session and update cache, just in case TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(web.Context); taxonomySession.UpdateCache(); context.ExecuteQueryRetry(); // Retrieve the Navigation TermSet for the current web NavigationTermSet navigationTermSet = TaxonomyNavigation.GetTermSetForWeb(web.Context, web, providerName, true); context.Load(navigationTermSet); context.ExecuteQueryRetry(); // Retrieve an editable TermSet for the current target navigation NavigationTermSet editableNavigationTermSet = navigationTermSet.GetAsEditable(taxonomySession); context.Load(editableNavigationTermSet); context.ExecuteQueryRetry(); return(editableNavigationTermSet); }
public void ConfigureTaxonomyNavigation() { using (SPSite site = new SPSite(TestConfig.ServerUrl)) { using (SPWeb web = site.OpenWeb()) { TaxonomySession taxonomySession = new TaxonomySession(site, updateCache: true); NavigationTermSet termSet = DemoUtilities.RecreateSampleNavTermSet( this.TestContext, taxonomySession, web); // Clear any old settings. WebNavigationSettings webNavigationSettings = new WebNavigationSettings(web); webNavigationSettings.ResetToDefaults(); webNavigationSettings.Update(taxonomySession); TaxonomyNavigation.FlushSiteFromCache(site); this.WaitForSync(); // Verify the TermSet object is not running. NavigationTermSet actualTermSet; actualTermSet = TaxonomyNavigation.GetTermSetForWeb(web, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider, includeInheritedSettings: true); Assert.IsTrue(actualTermSet == null); // Assign the new settings. webNavigationSettings = new WebNavigationSettings(web); // GlobalNavigation = top menu (aka "top nav") // CurrentNavigation = left menu (aka "quick launch") webNavigationSettings.GlobalNavigation.Source = StandardNavigationSource.TaxonomyProvider; webNavigationSettings.GlobalNavigation.TermStoreId = termSet.TermStoreId; webNavigationSettings.GlobalNavigation.TermSetId = termSet.Id; webNavigationSettings.Update(taxonomySession); TaxonomyNavigation.FlushSiteFromCache(site); this.WaitForSync(); actualTermSet = TaxonomyNavigation.GetTermSetForWeb(web, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider, includeInheritedSettings: true); Assert.AreEqual(termSet.Id, actualTermSet.Id); } } }
private IEnumerable <NavigationNode> GetGlobalNavigationTaxonomyNodes(SPWeb web, NavigationQueryParameters queryParameters, IEnumerable <NavigationTerm> navigationTerms = null) { // If navigation terms is null, fetch this initial terms from the taxonomy navigation term set if (navigationTerms == null) { var nodeMatchingSettings = queryParameters.NodeMatchingSettings; if ((nodeMatchingSettings != null) && nodeMatchingSettings.RestrictToCurrentNavigationLevel) { navigationTerms = TaxonomyNavigationContext.Current.NavigationTerm.Parent.Terms; } else { // Create view to return all navigation terms var view = new NavigationTermSetView(web, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider) { ExcludeTermsByProvider = false }; var navigationTermSet = TaxonomyNavigation.GetTermSetForWeb(web, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider, true); // Navigation termset might be null when crawling if (navigationTermSet == null) { return(new NavigationNode[] { }); } navigationTerms = navigationTermSet.GetWithNewView(view).Terms; } } // Gets terms which are not excluded from global navigation // Note: Navigation terms needs to be editable to get the taxonomy term var session = new TaxonomySession(web.Site); var terms = navigationTerms.Where(x => !x.ExcludeFromGlobalNavigation).Select(x => x.GetAsEditable(session)).ToArray(); var nodes = terms.Select(x => new NavigationNode(x)).ToArray(); for (var i = 0; i < terms.Length; i++) { var term = terms[i]; var node = nodes[i]; // If term contains children, recurvise call if (term.Terms.Count > 0) { node.ChildNodes = this.GetGlobalNavigationTaxonomyNodes(web, queryParameters, term.Terms); } } return(nodes); }
/// <summary> /// Get the peer url for a taxonomy navigation page (generated by a term set) /// </summary> /// <param name="currentUrl">The current page url</param> /// <param name="label">The target label to resolve</param> /// <returns>The url of the peer page</returns> public Uri GetPeerCatalogCategoryUrl(Uri currentUrl, VariationLabelInfo label) { // Get current navigation term ID var termId = TaxonomyNavigationContext.Current.NavigationTerm.Id; var labelSiteRelativeUrl = label.TopWebUrl.AbsolutePath; using (var labelWeb = SPContext.Current.Site.OpenWeb(labelSiteRelativeUrl)) { // Create view to return all navigation terms var view = new NavigationTermSetView(labelWeb, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider) { ExcludeTermsByProvider = false }; var navigationTermSet = TaxonomyNavigation.GetTermSetForWeb(labelWeb, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider, true).GetWithNewView(view); // Get the matching label navigation term and return it's friendly URL var navigationTerm = this.navigationHelper.FindNavigationTermById(navigationTermSet.Terms, termId); if (navigationTerm != null) { this.logger.Info( "GetPeerCatalogCategoryUrl: Navigation term found for term id '{0}': '{1}'", termId, navigationTerm.Title); var queryString = string.Empty; // Check if some search keywords are present var searchKeywords = HttpUtility.ParseQueryString(currentUrl.Query).Get("k"); if (!string.IsNullOrEmpty(searchKeywords)) { queryString = "?k=" + HttpUtility.UrlEncode(searchKeywords); } return(new Uri(navigationTerm.GetResolvedDisplayUrl(queryString), UriKind.Relative)); } else { this.logger.Error("GetPeerCatalogCategoryUrl: Navigation term not found for term id '{0}'", termId); return(new Uri( Variations.GetPeerUrl(SPContext.Current.Web, currentUrl.AbsoluteUri, label.Title), UriKind.Relative)); } } }
/// <summary> /// Determines whether the current HTTP request can be resolved to a <see cref="NavigationTermSet"/> object. /// When client is visiting the welcome page of the site where it is set to have a unique managed navigation, /// <see cref="TaxonomyNavigationContext.HasNavigationContext"/> returns *false* even though this page can be referred by the friendly URL resolved by the <see cref="NavigationTermSet"/> object. /// </summary> /// <param name="navigationTermSet">The resolved <see cref="NavigationTermSet"/> object; otherwise *null*.</param> /// <returns>*true* if the current HTTP request can be resolved to a <see cref="NavigationTermSet"/> object.</returns> public static bool IsRequestingNavigationTermSet(out NavigationTermSet navigationTermSet) { if (SPContext.Current != null) { SPWeb currentWeb = SPContext.Current.Web; navigationTermSet = TaxonomyNavigation.GetTermSetForWeb(currentWeb, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider, true); using (new SPSecurity.GrantAdditionalPermissionsInScope(SPBasePermissions.FullMask)) { if (navigationTermSet != null && navigationTermSet.GetResolvedDisplayUrl(null) == currentWeb.ServerRelativeUrl && SPUrlUtility.CombineUrl(currentWeb.ServerRelativeUrl, currentWeb.RootFolder.WelcomePage) == SPUtility.OriginalServerRelativeRequestPath) { return(true); } } } navigationTermSet = null; return(false); }
/// <summary> /// Ensures that the client is requesting the current page by the associated friendly URLs (if any). /// If the client is not requesting the associated friendly URLs, the client will be transfered to the default friendly URL by a redirect response. /// </summary> /// <param name="context">The instance of the <see cref="HttpContext"/> class representing the client.</param> public static void TransferToFriendlyUrl(HttpContext context) { CommonHelper.ConfirmNotNull(context, "context"); if (SPContext.Current != null && !TaxonomyNavigationContext.Current.HasNavigationContext) { SPListItem currentItem = SPContext.Current.ListItem; if (currentItem != null) { string rawRequestPath = context.Request.RawUrl; int pathEndPos = rawRequestPath.IndexOfAny(new[] { '?', '#' }); if (pathEndPos >= 0) { rawRequestPath = rawRequestPath.Substring(0, pathEndPos); } NavigationTermSetItem matchedTerm = TaxonomyNavigation.GetFriendlyUrlsForListItem(currentItem, true).FirstOrDefault(); if (matchedTerm == null) { NavigationTermSet matchedTermSet; if (IsRequestingNavigationTermSet(out matchedTermSet)) { matchedTerm = matchedTermSet; } } if (matchedTerm != null) { string friendlyUrl = matchedTerm.GetResolvedDisplayUrl(null); if (!friendlyUrl.Equals(rawRequestPath, StringComparison.OrdinalIgnoreCase)) { if (pathEndPos >= 0) { NameValueCollection query = HttpUtility.ParseQueryString(context.Request.RawUrl.Substring(pathEndPos + 1)); query.Remove(null); query.Remove("TermStoreId"); query.Remove("TermSetId"); query.Remove("TermId"); friendlyUrl = String.Concat(friendlyUrl, "?", query.ToString()); } SPUtility.Redirect(friendlyUrl, SPRedirectFlags.Default, context); } } } } }
/// <summary> /// Gets a <see cref="NavigationTerm"/> object by the specified unique ID. /// </summary> /// <param name="termId">Term unique identifier.</param> /// <returns>A <see cref="NavigationTerm"/> object.</returns> public static NavigationTerm GetNavigationTerm(Guid termId) { if (SPContext.Current != null && termId != Guid.Empty) { SPWeb currentWeb = SPContext.Current.Web; NavigationTermSet navigationTermSet = TaxonomyNavigation.GetTermSetForWeb(currentWeb, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider, true); if (navigationTermSet != null) { TaxonomySession session = new TaxonomySession(currentWeb, false); Term term = navigationTermSet.GetTaxonomyTermSet(session).GetTerm(termId); if (term != null) { using (SPWeb navigationRootWeb = currentWeb.Site.OpenWeb(navigationTermSet.GetResolvedDisplayUrl(null))) { return(NavigationTerm.GetAsResolvedByWeb(term, navigationRootWeb, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider)); } } } } return(null); }
/// Configures the web to use Taxonomy Navigation with the sample term set. public static NavigationTermSet SetUpSampleNavTermSet(TestContext testContext, TaxonomySession taxonomySession, SPWeb web) { NavigationTermSet termSet = RecreateSampleNavTermSet(testContext, taxonomySession, web); // Clear any old settings. WebNavigationSettings webNavigationSettings = new WebNavigationSettings(web); webNavigationSettings.ResetToDefaults(); webNavigationSettings.GlobalNavigation.Source = StandardNavigationSource.TaxonomyProvider; webNavigationSettings.GlobalNavigation.TermStoreId = termSet.TermStoreId; webNavigationSettings.GlobalNavigation.TermSetId = termSet.Id; webNavigationSettings.CurrentNavigation.Source = StandardNavigationSource.TaxonomyProvider; webNavigationSettings.CurrentNavigation.TermStoreId = termSet.TermStoreId; webNavigationSettings.CurrentNavigation.TermSetId = termSet.Id; webNavigationSettings.Update(taxonomySession); TaxonomyNavigation.FlushSiteFromCache(web.Site); return(termSet); }
public void ConfigureTaxonomyNavigation() { ClientContext clientContext = new ClientContext(TestConfig.ServerUrl); TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); taxonomySession.UpdateCache(); NavigationTermSet termSet = DemoUtilities.RecreateSampleNavTermSet( this.TestContext, clientContext, taxonomySession, clientContext.Web); // Clear out any old settings WebNavigationSettings webNavigationSettings = new WebNavigationSettings(clientContext, clientContext.Web); webNavigationSettings.ResetToDefaults(); webNavigationSettings.Update(taxonomySession); TaxonomyNavigation.FlushSiteFromCache(clientContext, clientContext.Site); clientContext.ExecuteQuery(); this.WaitForSync(); // Verify the TermSet is not running NavigationTermSet actualTermSet; ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { actualTermSet = TaxonomyNavigation.GetTermSetForWeb(clientContext, clientContext.Web, "GlobalNavigationTaxonomyProvider", includeInheritedSettings: true); } using (scope.StartCatch()) { } } clientContext.ExecuteQuery(); Assert.IsTrue(actualTermSet.ServerObjectIsNull.Value); // Assign the new settings webNavigationSettings = new WebNavigationSettings(clientContext, clientContext.Web); clientContext.Load(webNavigationSettings, w => w.GlobalNavigation, w => w.CurrentNavigation ); clientContext.Load(termSet, ts => ts.TermStoreId, ts => ts.Id ); clientContext.ExecuteQuery(); // GlobalNavigation = top menu (aka "top nav") // CurrentNavigation = left menu (aka "quick launch") webNavigationSettings.GlobalNavigation.Source = StandardNavigationSource.TaxonomyProvider; webNavigationSettings.GlobalNavigation.TermStoreId = termSet.TermStoreId; webNavigationSettings.GlobalNavigation.TermSetId = termSet.Id; webNavigationSettings.Update(taxonomySession); TaxonomyNavigation.FlushSiteFromCache(clientContext, clientContext.Site); clientContext.ExecuteQuery(); this.WaitForSync(); actualTermSet = TaxonomyNavigation.GetTermSetForWeb(clientContext, clientContext.Web, "GlobalNavigationTaxonomyProvider", includeInheritedSettings: true); clientContext.Load(actualTermSet, ts => ts.Id); clientContext.ExecuteQuery(); Assert.AreEqual(termSet.Id, actualTermSet.Id); }
private static void GetFriendlyUrl(string siteUrl, string userName, string password) { //list for saving the urls List <string> retVal = new List <string>(); // get client context ClientContext context = GetUserContext(siteUrl, userName, password); // get web Web web = context.Web; context.Load(web, w => w.Url); context.ExecuteQuery(); //check if the current web is a publishing web PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(context, web); context.Load(pubWeb); context.ExecuteQuery(); if (pubWeb != null) { //retrieve the pages list List pagesList = pubWeb.Web.Lists.GetByTitle("Pages"); context.Load(pubWeb); context.ExecuteQuery(); // build CAML query to get all items in the Pages library CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View Scope='RecursiveAll'></View>"; //get all documents in the list ListItemCollection collListItem = pagesList.GetItems(camlQuery); context.Load(collListItem, items => items.Include( item => item.Id, item => item["Title"], item => item["FileRef"])); //FileRef is the relative Url of the page context.ExecuteQuery(); // get navigation terms var navigationTermSet = TaxonomyNavigation.GetTermSetForWeb(context, web, "GlobalNavigationTaxonomyProvider", true); var allNavigationTerms = navigationTermSet.GetAllTerms(); context.Load(allNavigationTerms, t => t.Include( i => i.TargetUrl, i => i.LinkType, i => i.TaxonomyName, i => i.Parent)); context.ExecuteQuery(); // loop thru' all items in the 'Pages' library if (collListItem.Count > 0) { foreach (ListItem oListItem in collListItem) { //get list item context.Load(oListItem); context.ExecuteQuery(); var navigationTermsForPage = allNavigationTerms.Where( t => t.LinkType == NavigationLinkType.FriendlyUrl && t.TargetUrl.Value.Contains(oListItem["FileRef"].ToString())); //context.Web.EnsureProperty(w => w.Url); foreach (var navTerm in navigationTermsForPage) { var pageUrl = ""; context.Load(navTerm); pageUrl = InsertUrlRecursive(navTerm, pageUrl); Console.WriteLine($"{web.Url}{pageUrl}"); } } } } }