public static void ConnectTaxonomyField(TaxonomyField field, SPSite site, string termGroup, string termSetName, bool isOpen = false, bool createValuesInEditForm = false) { if (site == null) { return; } TaxonomySession session = new TaxonomySession(site); ConnectTaxonomyField(field, session, termGroup, termSetName, isOpen, createValuesInEditForm); }
public override void AddFieldTo(SPFieldCollection fieldCollection) { AddFieldTo(fieldCollection, f => { TaxonomyField field = (TaxonomyField)f; if( TermStoreGuid != System.Guid.Empty && TermSetGuid != System.Guid.Empty ) { field.SspId = TermStoreGuid; field.TermSetId = TermSetGuid; } else { TaxonomySession session = new TaxonomySession(field.ParentList.ParentWeb.Site); TermStore store = session.DefaultSiteCollectionTermStore != null ? session.DefaultSiteCollectionTermStore : session.TermStores[0]; Group group = store.Groups[TermGroup]; TermSet set = group.TermSets[TermSet]; field.SspId = store.Id; field.TermSetId = set.Id; } field.AllowMultipleValues = AllowMultipleValues; }); }
public void Import(TaxonomySession ts) { if (ts == null) throw new ArgumentNullException("ts", "The TaxonomySession object is null."); XmlNodeList termStoreNodes = _xml.SelectNodes("//TermStore"); if (termStoreNodes == null || termStoreNodes.Count == 0) return; foreach (XmlElement termStoreElement in termStoreNodes) { string termStoreName = termStoreElement.GetAttribute("Name"); Logger.Write("Importing Term Store: {0}", termStoreName); TermStore termStore = ts.TermStores[termStoreName]; if (termStore == null) { Logger.WriteWarning("Unable to locate target Term Store: {0}", termStoreName); continue; } XmlNodeList groupNodes = termStoreElement.SelectNodes("./Groups/Group"); if (groupNodes == null || groupNodes.Count == 0) { Logger.WriteWarning("No Group elements were defined in the import file for the Term Store."); continue; } foreach (XmlElement groupElement in groupNodes) { Import(groupElement, termStore); } if (!_whatIf) termStore.CommitAll(); } }
/// <summary> /// Function that returns a term given us all the values within the taxonomy /// </summary> /// <param name="term"></param> /// <returns></returns> public IDictionary<string, TaxonomyValue> GetTerms(string term) { try { var session = new TaxonomySession(SpSite); var termStore = session.TermStores[NameTermStore]; var group = termStore.Groups[NameGroup]; var terms = group.TermSets[term]; if (terms.Terms.Count == 0) { return null; } var result = new Dictionary<string, TaxonomyValue>(); foreach (var item in terms.Terms) { var listCustomProperties = item.CustomProperties.Select(itemProperties => new CustomProperties { Name = itemProperties.Key, Value = itemProperties.Value }).ToList(); result.Add(item.Id.ToString(), new TaxonomyValue { Name = item.Name, Properties = listCustomProperties }); } return result; } catch (Exception exception) { Logger.Error(string.Concat("Error GetAllTerms", exception.Message)); return null; } }
/// <summary> /// Sets the web navigation settings. /// </summary> /// <param name="web">The web.</param> /// <param name="settings">The settings.</param> public void SetWebNavigationSettings(SPWeb web, ManagedNavigationInfo settings) { var taxonomySession = new TaxonomySession(web.Site); if (taxonomySession.TermStores.Count > 0) { var termStore = settings.TermSet.ResolveParentTermStore(taxonomySession); var group = settings.TermSet.ResolveParentGroup(taxonomySession, web.Site); var termSet = this.taxonomyService.GetTermSetFromGroup(termStore, group, settings.TermSet.Label); // Flag the term set as a navigation term set termSet.SetCustomProperty(SystemIsNavigationTermSet, "True"); termStore.CommitAll(); var navigationSettings = new WebNavigationSettings(web); navigationSettings.GlobalNavigation.Source = StandardNavigationSource.TaxonomyProvider; navigationSettings.GlobalNavigation.TermStoreId = termStore.Id; navigationSettings.GlobalNavigation.TermSetId = termSet.Id; navigationSettings.CurrentNavigation.Source = StandardNavigationSource.TaxonomyProvider; navigationSettings.CurrentNavigation.TermStoreId = termStore.Id; navigationSettings.CurrentNavigation.TermSetId = termSet.Id; navigationSettings.AddNewPagesToNavigation = settings.AddNewPagesToNavigation; navigationSettings.CreateFriendlyUrlsForNewPages = settings.CreateFriendlyUrlsForNewsPages; navigationSettings.Update(taxonomySession); if (settings.PreserveTaggingOnTermSet) { termSet.IsAvailableForTagging = true; termStore.CommitAll(); } } }
internal static TermStore FindTermStore(SPSite site, string termStorename, Guid? termStoreId, bool? useDefaultSiteCollectionTermStore) { var session = new TaxonomySession(site); TermStore termStore = null; if (useDefaultSiteCollectionTermStore.HasValue && useDefaultSiteCollectionTermStore.Value == true) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Resolving Term Store as useDefaultSiteCollectionTermStore"); termStore = session.DefaultSiteCollectionTermStore; } else if (termStoreId.HasGuidValue()) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving Term Store by ID: [{0}]", termStoreId.Value); termStore = session.TermStores[termStoreId.Value]; } else if (!string.IsNullOrEmpty(termStorename)) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving Term Store by Name: [{0}]", termStorename); termStore = session.TermStores[termStorename]; } return termStore; }
public void GetTermsAsSimpleLinkNavNodeForTermSet_WhenNoChildTerms_ShouldReturnAllFirstLevelTerms() { using (var testScope = SiteTestScope.BlankSite()) { // Arrange var testTermSetInfo = new TermSetInfo(Guid.NewGuid(), "Test Term Set"); var levelOneTermA = new SimpleLinkTermInfo(Guid.NewGuid(), "Term A", testTermSetInfo, "URL-A"); var levelOneTermB = new SimpleLinkTermInfo(Guid.NewGuid(), "Term B", testTermSetInfo, "URL-B"); var levelOneTermC = new SimpleLinkTermInfo(Guid.NewGuid(), "Term C", testTermSetInfo, "URL-C"); var expecteNumberOfTerms = 3; var session = new TaxonomySession(testScope.SiteCollection); var defaultSiteCollectionTermStore = session.DefaultSiteCollectionTermStore; var defaultSiteCollectionGroup = defaultSiteCollectionTermStore.GetSiteCollectionGroup(testScope.SiteCollection); var newTermSet = defaultSiteCollectionGroup.CreateTermSet(testTermSetInfo.Label, testTermSetInfo.Id); var createdTermA = newTermSet.CreateTerm(levelOneTermA.Label, Language.English.Culture.LCID, levelOneTermA.Id); createdTermA.SetLocalCustomProperty(CustomPropertyKey, levelOneTermA.SimpleLinkTarget); var createdTermB = newTermSet.CreateTerm(levelOneTermB.Label, Language.English.Culture.LCID, levelOneTermB.Id); createdTermB.SetLocalCustomProperty(CustomPropertyKey, levelOneTermB.SimpleLinkTarget); var createdTermC = newTermSet.CreateTerm(levelOneTermC.Label, Language.English.Culture.LCID, levelOneTermC.Id); createdTermC.SetLocalCustomProperty(CustomPropertyKey, levelOneTermC.SimpleLinkTarget); defaultSiteCollectionTermStore.CommitAll(); using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { var taxonomyService = injectionScope.Resolve<ITaxonomyService>(); // Act var retrievedTerms = taxonomyService.GetTermsAsSimpleLinkNavNodeForTermSet(testScope.SiteCollection, defaultSiteCollectionGroup.Name, newTermSet.Name); // Assert Assert.IsNotNull(retrievedTerms); Assert.AreEqual(retrievedTerms.Count, expecteNumberOfTerms); Assert.AreEqual(retrievedTerms[0].SimpleLinkTarget, levelOneTermA.SimpleLinkTarget); Assert.AreEqual(retrievedTerms[0].Label, levelOneTermA.Label); Assert.AreEqual(retrievedTerms[0].ChildTerms.Count(), 0); Assert.AreEqual(retrievedTerms[1].SimpleLinkTarget, levelOneTermB.SimpleLinkTarget); Assert.AreEqual(retrievedTerms[1].Label, levelOneTermB.Label); Assert.AreEqual(retrievedTerms[1].ChildTerms.Count(), 0); Assert.AreEqual(retrievedTerms[2].SimpleLinkTarget, levelOneTermC.SimpleLinkTarget); Assert.AreEqual(retrievedTerms[2].Label, levelOneTermC.Label); Assert.AreEqual(retrievedTerms[2].ChildTerms.Count(), 0); } // Cleanup term set so that we don't pollute the metadata store newTermSet.Delete(); defaultSiteCollectionTermStore.CommitAll(); } }
public void AssignTermSetToListColumn(SPList list, Guid fieldId, string termStoreName, string termStoreGroupName, string termSetName, string termSubsetName) { if (list.Fields.Contains(fieldId)) { TaxonomySession session = new TaxonomySession(list.ParentWeb.Site); TermStore termStore = session.TermStores[termStoreName]; TaxonomyField field = (TaxonomyField)list.Fields[fieldId]; InternalAssignTermSetToTaxonomyField(termStore, field, termStoreGroupName, termSetName, termSubsetName); } }
public void AssignTermSetToListColumn(SPList list, Guid fieldId, Guid termStoreGroupId, Guid termSetId, Guid termSubsetId) { if (list.Fields.Contains(fieldId)) { var session = new TaxonomySession(list.ParentWeb.Site); var termStore = session.DefaultSiteCollectionTermStore; var field = (TaxonomyField)list.Fields[fieldId]; InternalAssignTermSetToTaxonomyField(termStore, field, termStoreGroupId, termSetId, termSubsetId); } }
/// <summary> /// Fires when feature is activated /// </summary> /// <param name="properties">Feature properties</param> public override void FeatureActivated(SPFeatureReceiverProperties properties) { using (var scope = NavContainerProxy.BeginFeatureLifetimeScope(properties.Feature)) { var site = properties.Feature.Parent as SPSite; var navTermSetConfig = scope.Resolve<INavTermSetConfig>(); if (site != null) { var taxonomySession = new TaxonomySession(site); // Assume the Default term store is properly configured var termStore = taxonomySession.DefaultSiteCollectionTermStore; Group termGroup = null; if (!string.IsNullOrEmpty(navTermSetConfig.TermGroupName)) { // Ensure presence of configured term group bool termGroupExists = termStore.Groups.Cast<Group>().Any(g => g.Name == navTermSetConfig.TermGroupName); if (!termGroupExists) { termGroup = termStore.CreateGroup(navTermSetConfig.TermGroupName); termStore.CommitAll(); } else { termGroup = termStore.Groups[navTermSetConfig.TermGroupName]; } } else { // Return site collection-specific term group termGroup = termStore.GetSiteCollectionGroup(site); } // Ensure presence of term sets in term group bool navPositionTermSetExists = termGroup.TermSets.Cast<TermSet>().Any(ts => ts.Name == navTermSetConfig.NavPositionTermSetName); if (!navPositionTermSetExists) { termGroup.CreateTermSet(navTermSetConfig.NavPositionTermSetName); termStore.CommitAll(); } bool navControlsTermSetExists = termGroup.TermSets.Cast<TermSet>().Any(ts => ts.Name == navTermSetConfig.NavControlsTermSetName); if (!navControlsTermSetExists) { termGroup.CreateTermSet(navTermSetConfig.NavControlsTermSetName); termStore.CommitAll(); } } } }
public void AssignTermSetToSiteColumn(SPWeb web, Guid fieldId, string termStoreName, string termStoreGroupName, string termSetName, string termSubsetName) { if (web.Fields.Contains(fieldId)) { TaxonomySession session = new TaxonomySession(web.Site); TermStore termStore = session.TermStores[termStoreName]; TaxonomyField field = (TaxonomyField)web.Site.RootWeb.Fields[fieldId]; InternalAssignTermSetToTaxonomyField(termStore, field, termStoreGroupName, termSetName, termSubsetName); AssignTermSetToAllListUsagesOfSiteColumn(web.Site, termStore, fieldId, termStoreGroupName, termSetName, termSubsetName); } }
public static void ExportTermGroup(string directoryPath, Guid groupId, string siteUrl) { using (SPSite site = new SPSite(siteUrl)) { TaxonomySession __taxonomySession = new TaxonomySession(site, true); TermStore __defaultSiteCollectionTermStore = __taxonomySession.DefaultSiteCollectionTermStore; Group group = __defaultSiteCollectionTermStore.GetGroup(groupId); ExcelExport.ExportTermGroup(directoryPath, group); } }
public static void SetupTermStore(ClientContext clientContext) { var taxSession = TaxonomySession.GetTaxonomySession(clientContext); var termStore = taxSession.GetDefaultSiteCollectionTermStore(); AddLanguages(clientContext, termStore); var termGroup = AddGroup(clientContext, termStore); var termSet = AddTermSet(clientContext, termStore, termGroup); AddTerm(clientContext, termSet, "Departments", "Départements", "Abteilungen", "Avdelningar"); AddTerm(clientContext, termSet, "Employee", "Employé", "Mitarbeiter", "Anställd"); AddTerm(clientContext, termSet, "News", "Actualités", "Nachricht", "Nyheter"); AddTerm(clientContext, termSet, "Search", "Rechercher", "Suche", "Sök"); }
static void GetTaxonomyFieldInfo(ClientContext clientContext, string TermsetName, out Guid termStoreId, out Guid termSetId) { termStoreId = Guid.Empty; termSetId = Guid.Empty; TaxonomySession session = TaxonomySession.GetTaxonomySession(clientContext); TermStore termStore = session.GetDefaultSiteCollectionTermStore(); TermSetCollection termSets = termStore.GetTermSetsByName(TermsetName, 1033); clientContext.Load(termSets, tsc => tsc.Include(ts => ts.Id)); clientContext.Load(termStore, ts => ts.Id); clientContext.ExecuteQuery(); termStoreId = termStore.Id; termSetId = termSets.FirstOrDefault().Id; }
static void Main(string[] args) { ClientContext context = new ClientContext("http://ecm.wingtip.com"); TaxonomySession session = TaxonomySession.GetTaxonomySession(context); context.Load(session, taxSession => taxSession.TermStores.Include( taxStore => taxStore.Groups.Include( taxGroup => taxGroup.TermSets.Include(tax => tax.Name) ))); context.ExecuteQuery(); TermStore termStore = session.TermStores[0]; TermGroup termGroup = termStore.Groups[0]; TermSet termSet = termGroup.TermSets[0]; //// get UNITED STATES term //var terms = termSet.Terms; //context.Load(terms); //context.ExecuteQuery(); //Term unitedStatesTerm = terms[0]; //context.Load(unitedStatesTerm); //context.ExecuteQuery(); //// add region //Term newRegion = unitedStatesTerm.CreateTerm("Pacific", 1033, Guid.NewGuid()); //newRegion.SetCustomProperty("PrimaryPOC", "Rob Walters"); //newRegion.IsAvailableForTagging = false; //// add state //Term newState = newRegion.CreateTerm("Hawaii", 1033, Guid.NewGuid()); // search for PACIFIC term var searchQuery = new LabelMatchInformation(context) { TermLabel = "Pacific", TrimUnavailable = false }; var foundTerms = termSet.GetTerms(searchQuery); context.Load(foundTerms); context.ExecuteQuery(); // update term foundTerms[0].Name = "Pacific Region"; // save changes termStore.CommitAll(); context.ExecuteQuery(); }
public static TermGroup GetTermGroupByName(this Site site, string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } TaxonomySession session = TaxonomySession.GetTaxonomySession(site.Context); var store = session.GetDefaultSiteCollectionTermStore(); IEnumerable <TermGroup> groups = site.Context.LoadQuery(store.Groups.Include(g => g.Name, g => g.Id, g => g.TermSets)).Where(g => g.Name == name); site.Context.ExecuteQuery(); return(groups.FirstOrDefault()); }
protected override void ExecuteCmdlet() { List <string> exportedTerms; if (ParameterSetName == "TermSet") { if (Delimiter != "|" && Delimiter == ";#") { throw new Exception("Restricted delimiter specified"); } if (!string.IsNullOrEmpty(TermStoreName)) { var taxSession = TaxonomySession.GetTaxonomySession(ClientContext); var termStore = taxSession.TermStores.GetByName(TermStoreName); exportedTerms = ClientContext.Site.ExportTermSet(TermSetId.Id, IncludeID, termStore, Delimiter); } else { exportedTerms = ClientContext.Site.ExportTermSet(TermSetId.Id, IncludeID, Delimiter); } } else { exportedTerms = ClientContext.Site.ExportAllTerms(IncludeID, Delimiter); } if (Path == null) { WriteObject(exportedTerms); } else { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } if (File.Exists(Path)) { if (Force || ShouldContinue(string.Format(Resources.File0ExistsOverwrite, Path), Resources.Confirm)) { File.WriteAllLines(Path, exportedTerms); } } else { File.WriteAllLines(Path, exportedTerms); } } }
public SPOTermStorePipeBind(int index) { var ctx = SPOSiteContext.CurrentSiteContext.Context; TaxonomySession ts = TaxonomySession.GetTaxonomySession(ctx); ctx.Load(ts.TermStores); ctx.ExecuteQuery(); _termStore = ts.TermStores[0]; ctx.Load(_termStore); ctx.Load(_termStore, ts1 => ts1.ContentTypePublishingHub); ctx.ExecuteQuery(); _termStoreId = _termStore.Id; }
public static void SearchTermsByLabel(SPSite site, string prefix) { TaxonomySession session = new TaxonomySession(site); // Search all Terms that start with the provide prefix from // all TermStores associated with the provided site. TermCollection terms = session.GetTerms(prefix, true, // Only search in default labels StringMatchOption.StartsWith, 5, // The maximum number of terms returned from each TermStore true); // The results should not contain unavailable terms Console.WriteLine("The number of matching Terms is " + terms.Count); }
protected override void ExecuteCmdlet() { TaxonomySession session = ClientContext.Site.GetTaxonomySession(); var termStore = session.GetDefaultSiteCollectionTermStore(); var termGroup = termStore.GetSiteCollectionGroup(ClientContext.Site, false); ClientContext.Load(termGroup, g => g.Id, g => g.Name); ClientContext.ExecuteQueryRetry(); if (!termGroup.ServerObjectIsNull.GetValueOrDefault(true)) { WriteObject(termGroup); } }
public void CanProvisionTokenizedTermsTwiceIdMatch() { var template = new ProvisioningTemplate(); const string termGroupName = "TestProvisioningGroup"; var termGroup = new TermGroup(_termGroupGuid, termGroupName, null); const string termSiteName = "TestProvisioningTermSet - {sitename}"; var termSet1 = new TermSet(_termSetGuid, termSiteName, null, true, false, null, null); var term1Id = Guid.NewGuid(); const string term1Name = "TestProvisioningTerm - {siteid}"; var term1 = new Term(term1Id, term1Name, null, null, null, null, null); termSet1.Terms.Add(term1); termGroup.TermSets.Add(termSet1); template.TermGroups.Add(termGroup); for (int index = 0; index < 2; index++) { using (ClientContext ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectTermGroups().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); TaxonomySession session = TaxonomySession.GetTaxonomySession(ctx); var store = session.GetDefaultKeywordsTermStore(); var group = store.GetGroup(_termGroupGuid); var set = store.GetTermSet(_termSetGuid); ctx.Load(group); ctx.Load(set, s => s.Id, s => s.Name, s => s.Terms); ctx.ExecuteQueryRetry(); Assert.IsInstanceOfType(group, typeof(Microsoft.SharePoint.Client.Taxonomy.TermGroup)); StringAssert.Matches(group.Name, new Regex(Regex.Escape(termGroupName))); Assert.AreEqual(_termGroupGuid, group.Id); Assert.IsInstanceOfType(set, typeof(Microsoft.SharePoint.Client.Taxonomy.TermSet)); Assert.AreEqual(1, set.Terms.Count); Assert.AreEqual(_termSetGuid, set.Id); StringAssert.DoesNotMatch(set.Name, new Regex(Regex.Escape(termSiteName))); var remoteTerm1 = set.Terms[0]; Assert.AreEqual(term1Id, remoteTerm1.Id); StringAssert.DoesNotMatch(remoteTerm1.Name, new Regex(Regex.Escape(term1Name))); } } }
public void Import(TaxonomySession ts) { if (ts == null) throw new ArgumentNullException("ts", "The TaxonomySession object is null."); XmlNodeList termStoreNodes = _xml.SelectNodes("//TermStore"); if (termStoreNodes == null || termStoreNodes.Count == 0) return; var termStores = ts.TermStores; _ctx.Load(termStores); _ctx.ExecuteQuery(); foreach (XmlElement termStoreElement in termStoreNodes) { TermStore termStore = null; if (termStoreNodes.Count == 1 && termStores.Count == 1) { termStore = termStores[0]; } else { string termStoreName = termStoreElement.GetAttribute("Name"); termStore = ts.TermStores.GetByName(termStoreName); _ctx.ExecuteQuery(); if (termStore == null || termStore.ServerObjectIsNull.Value) { _cmdlet.WriteWarning(string.Format("Unable to locate target Term Store: {0}", termStoreName)); continue; } } LoadWorkingLanguage(termStore); _cmdlet.WriteVerbose(string.Format("Importing into Term Store: {0}", termStore.Name)); XmlNodeList groupNodes = termStoreElement.SelectNodes("./Groups/Group"); if (groupNodes == null || groupNodes.Count == 0) { _cmdlet.WriteWarning("No Group elements were defined in the import file for the Term Store."); continue; } foreach (XmlElement groupElement in groupNodes) { Import(groupElement, termStore); } termStore.CommitAll(); termStore.Context.ExecuteQuery(); } }
protected override void ExecuteCmdlet() { var taxonomySession = TaxonomySession.GetTaxonomySession(ClientContext); // Get Term Store TermStore termStore = null; if (TermStore == null) { termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); } else { termStore = TermStore.GetTermStore(taxonomySession); } termStore.EnsureProperty(ts => ts.DefaultLanguage); var term = termStore.GetTerm(ParentTermId); if (Id == Guid.Empty) { Id = Guid.NewGuid(); } var termName = TaxonomyExtensions.NormalizeName(Name); var termTerm = term.CreateTerm(termName, Lcid, Id); ClientContext.Load(term); ClientContext.ExecuteQueryRetry(); termTerm.SetDescription(Description, Lcid); var customProperties = CustomProperties ?? new Hashtable(); foreach (var key in customProperties.Keys) { termTerm.SetCustomProperty(key as string, customProperties[key] as string); } var localCustomProperties = LocalCustomProperties ?? new Hashtable(); foreach (var key in localCustomProperties.Keys) { termTerm.SetLocalCustomProperty(key as string, localCustomProperties[key] as string); } termStore.CommitAll(); ClientContext.Load(termTerm); ClientContext.ExecuteQueryRetry(); WriteObject(termTerm); }
public static NavigationTermSet CriarItemNaTermStore(string url, string urlweb, Guid NavTermSetId, Guid TaggingTermSetId) { SPSite site = new SPSite(url); SPWeb web = site.AllWebs[url]; TaxonomySession taxonomySession = new TaxonomySession(site); if (taxonomySession.TermStores.Count == 0) { throw new InvalidOperationException("O Serviço de taxonomia não existe"); } TermStore termStore = taxonomySession.TermStores[0]; TermSet existingTermSet = termStore.GetTermSet(NavTermSetId); if (existingTermSet != null) { existingTermSet.Delete(); termStore.CommitAll(); } Group siteCollectionGroup = termStore.GetSiteCollectionGroup(web.Site); TermSet termSet = siteCollectionGroup.CreateTermSet("Teste01", NavTermSetId); NavigationTermSet navTermSet = NavigationTermSet.GetAsResolvedByWeb(termSet, web, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider); navTermSet.IsNavigationTermSet = true; navTermSet.TargetUrlForChildTerms.Value = "~site/Pages/Topics/Topic.aspx"; NavigationTerm term1 = navTermSet.CreateTerm("Term 1", NavigationLinkType.SimpleLink); term1.SimpleLinkUrl = "https://ekisiot.sharepoint.com/"; NavigationTerm term2 = navTermSet.CreateTerm("Term 2", NavigationLinkType.FriendlyUrl); NavigationTerm term2a = term2.CreateTerm("Term 2 A", NavigationLinkType.FriendlyUrl); NavigationTerm term2b = term2.CreateTerm("Term 2 B", NavigationLinkType.FriendlyUrl); NavigationTerm term3 = navTermSet.CreateTerm("Term 3", NavigationLinkType.FriendlyUrl); termStore.CommitAll(); return(navTermSet); }
private static void GetTermItem(String setName, ClientContext context, Int32 englishLCID, Guid id, Int32 currentLCID, List <SPTerm> terms, SortOrdersCollection <Guid> sortOrders) { var lsession = TaxonomySession.GetTaxonomySession(context); var ltermSets = lsession.GetTermSetsByName(setName, englishLCID); context.Load(lsession, s => s.TermStores); context.Load(ltermSets); context.ExecuteQuery(); var ltermSet = ltermSets.First(); var term = ltermSet.GetTerm(id); context.Load(term); context.ExecuteQuery(); var name = term.Name; var spTerm = new SPTerm { Id = term.Id, Name = name, Path = term.PathOfTerm, Properties = term.LocalCustomProperties }; if (currentLCID != englishLCID) // If lcid label not avaliable or lcid==1033 keep default label { var langLabel = term.GetAllLabels(currentLCID); context.Load(langLabel); context.ExecuteQuery(); if (langLabel.Count != 0) { spTerm.Name = langLabel.First().Value; } } terms.Add(spTerm); if (!String.IsNullOrEmpty(term.CustomSortOrder)) { sortOrders.AddSortOrder(term.CustomSortOrder); } }
public static void ConnectTaxonomyField(TaxonomyField field, TaxonomySession session, string termGroup, string termSetName, bool isOpen = false, bool createValuesInEditForm = false) { TermStore termStore; if (field != null && field.SspId != default(Guid)) { termStore = session.TermStores.SingleOrDefault(ts => ts.Id == field.SspId) ?? session.DefaultKeywordsTermStore; } else { termStore = session.DefaultKeywordsTermStore; } ConnectTaxonomyField(field, session, termStore, termGroup, termSetName, isOpen, createValuesInEditForm); }
/// <summary> /// Given a taxonomy session, fetches the parent term store for the current term set. /// </summary> /// <param name="currentSession">The current taxonomy session</param> /// <returns>The SharePoint managed metadata service instance</returns> public TermStore ResolveParentTermStore(TaxonomySession currentSession) { if (this.Group == null || (this.Group != null && this.Group.TermStore == null)) { // Whenever the parent TermGroupInfo is absent or the grandparent TermStoreInfo // is missing, by convention, we assume we're working with the default site collection // term store. return(currentSession.DefaultSiteCollectionTermStore); } else { // Grandparent TermStoreInfo isnt't null so we can fetch the specific store return(currentSession.TermStores[this.Group.TermStore.Name]); } }
//gavdcodeend 02 //gavdcodebegin 03 static void SpCsCsomFindTermGroups(ClientContext spCtx) { string termStoreName = "Taxonomy_hVIOdhme2obc+5zqZXqqUQ=="; TaxonomySession myTaxSession = TaxonomySession.GetTaxonomySession(spCtx); TermStore myTermStore = myTaxSession.TermStores.GetByName(termStoreName); spCtx.Load(myTermStore, tStore => tStore.Name, tStore => tStore.Groups); spCtx.ExecuteQuery(); foreach (TermGroup oneGroup in myTermStore.Groups) { Console.WriteLine(oneGroup.Name); } }
/// <summary> /// Checks for the group /// </summary> /// <param name="groupName"></param> /// <returns></returns> private bool ExistGroup(string groupName) { try { var session = new TaxonomySession(SpSite); var termStore = session.TermStores[NameTermStore]; var exist = termStore.Groups[groupName]; return(exist != null); } catch (Exception exception) { Logger.Error(string.Concat("Error AddGroup", exception.Message)); return(false); } }
public override string GetReplaceValue() { if (CacheValue == null) { TaxonomySession session = TaxonomySession.GetTaxonomySession(TokenContext); var termStore = session.GetDefaultSiteCollectionTermStore(); TokenContext.Load(termStore, t => t.Id); TokenContext.ExecuteQueryRetry(); if (termStore != null) { CacheValue = termStore.Id.ToString(); } } return(CacheValue); }
//gavdcodeend 07 //gavdcodebegin 08 static void SpCsCsomFindOneTerm(ClientContext spCtx) { string termStoreName = "Taxonomy_hVIOdhme2obc+5zqZXqqUQ=="; TaxonomySession myTaxSession = TaxonomySession.GetTaxonomySession(spCtx); TermStore myTermStore = myTaxSession.TermStores.GetByName(termStoreName); TermGroup myTermGroup = myTermStore.Groups.GetByName("CsCsomTermGroup"); TermSet myTermSet = myTermGroup.TermSets.GetByName("CsCsomTermSet"); Term myTerm = myTermSet.Terms.GetByName("CsCsomTerm"); spCtx.Load(myTerm); spCtx.ExecuteQuery(); Console.WriteLine(myTerm.Name); }
public static TermStore LookupTermStore(SPSite site, TaxonomyFieldDefinition taxFieldModel) { var taxSession = new TaxonomySession(site); if (taxFieldModel.UseDefaultSiteCollectionTermStore == true) return taxSession.DefaultSiteCollectionTermStore; if (taxFieldModel.SspId.HasValue) return taxSession.TermStores[taxFieldModel.SspId.Value]; if (!string.IsNullOrEmpty(taxFieldModel.SspName)) return taxSession.TermStores[taxFieldModel.SspName]; return null; }
public static void ExportFullTaxonomy(string directoryPath, string managedServiceName, string siteUrl) { using (SPSite site = new SPSite(siteUrl)) { TaxonomySession __taxonomySession = new TaxonomySession(site, true); TermStore __defaultSiteCollectionTermStore = __taxonomySession.TermStores[managedServiceName]; foreach (Group group in __defaultSiteCollectionTermStore.Groups) { ExcelExport.ExportTermGroup(directoryPath, group); } } }
public static TermSetCollection GetTermSetsByName(this Site site, string name, int lcid = 1033) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } TaxonomySession session = TaxonomySession.GetTaxonomySession(site.Context); TermStore store = session.GetDefaultSiteCollectionTermStore(); var termsets = store.GetTermSetsByName(name, lcid); site.Context.Load(termsets); site.Context.ExecuteQuery(); return(termsets); }
public TermStore GetTermStore(ClientContext context) { TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(context); taxonomySession.UpdateCache(); context.Load(taxonomySession); context.ExecuteQuery(); TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); context.Load(termStore, x => x.Groups, x => x.Id, x => x.DefaultLanguage); context.ExecuteQuery(); return(termStore); }
protected void btnCreateGroup_Click(object sender, EventArgs e) { // Update Term set drop down for the taxonomy field creation. var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var ctx = spContext.CreateUserClientContextForSPHost()) { TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(ctx); TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); termStore.CreateGroup("Samples", SampleGroupId); ctx.ExecuteQuery(); } // Update drop downs GenerateTaxonomyDropDowns(); }
public static void SearchTermsByCustomProperty(SPSite site, string customPropertyName) { TaxonomySession session = new TaxonomySession(site); // Search all Terms that contain a custom property with the provided name // from all TermStores associated with the provided site. TermCollection terms = session.GetTermsWithCustomProperty( customPropertyName, true); // The results should not contain unavailable Terms Console.WriteLine("The number of matching Terms is " + terms.Count); }
private void CreatePlantTaxonomy(string contextToken, string hostWeb) { using (var clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority)) { //Create Taxonomy //To manage terms, we must create a new Taxonomy Session object TaxonomySession session = TaxonomySession.GetTaxonomySession(clientContext); //Get the termstore //TermStore termstore = session.TermStores["Managed Metadata Service"]; TermStore termStore = session.GetDefaultSiteCollectionTermStore(); //Create a term group //Group plantsGroup = termstore.CreateGroup("Plants", Guid.NewGuid()); TermGroup plantsGroup = termStore.CreateGroup("Plants", Guid.NewGuid()); //Create a term set TermSet flowersTermSet = plantsGroup.CreateTermSet("Flowers", Guid.NewGuid(), 1033); //Create some terms Term tulipsTerm = flowersTermSet.CreateTerm("Tulips", 1033, Guid.NewGuid()); Term orchidsTerm = flowersTermSet.CreateTerm("Orchids", 1033, Guid.NewGuid()); Term daffodilsTerm = flowersTermSet.CreateTerm("Daffodils", 1033, Guid.NewGuid()); //Create a child term within the Orchids term Term vanillaTerm = orchidsTerm.CreateTerm("Vanilla", 1033, Guid.NewGuid()); //You should set properties for every term. In this example, we'll //do just one for brevity vanillaTerm.SetDescription("A common orchid whose pods are used in desserts", 1033); //Use CreateLabel to add synomyns and alternates vanillaTerm.CreateLabel("Vanilla planifolia", 1033, false); vanillaTerm.CreateLabel("Flat-leaved vanilla", 1033, false); //When we are finished making changes, we must commit them try { //termstore.CommitAll(); clientContext.ExecuteQuery(); resultsLabel.Text = "Taxonomy created successfully"; } catch (Exception ex) { resultsLabel.Text = "There was an error: " + ex.Message; } } }
public void SetTaxonomyFieldValueTest() { var fieldName = "Test2_" + DateTime.Now.ToFileTime(); var fieldId = Guid.NewGuid(); using (var clientContext = TestCommon.CreateClientContext()) { // Retrieve list var list = clientContext.Web.Lists.GetById(_listId); clientContext.Load(list); clientContext.ExecuteQuery(); // Retrieve Termset TaxonomySession session = TaxonomySession.GetTaxonomySession(clientContext); var termSet = session.GetDefaultSiteCollectionTermStore().GetTermSet(_termSetId); clientContext.Load(termSet); clientContext.ExecuteQuery(); // Create taxonomyfield first TaxonomyFieldCreationInformation fieldCI = new TaxonomyFieldCreationInformation() { Id = fieldId, DisplayName = fieldName, InternalName = fieldName, Group = "Test Fields Group", TaxonomyItem = termSet }; var field = list.CreateTaxonomyField(fieldCI); // Create Item ListItemCreationInformation itemCi = new ListItemCreationInformation(); var item = list.AddItem(itemCi); item.Update(); clientContext.Load(item); clientContext.ExecuteQuery(); item.SetTaxonomyFieldValue(fieldId, _termName, _termId); clientContext.Load(item, i => i[fieldName]); clientContext.ExecuteQuery(); var value = item[fieldName] as TaxonomyFieldValue; Assert.AreEqual(_termId.ToString(), value.TermGuid, "Term not set correctly"); } }
private void btnLoadSite_Click_Worker() { // do work that does not affect ui here var lst = new List <TreeNode>(); var msg = ""; try { using (var site = new SPSite(txtSiteUrl.Text)) { var txsn = new TaxonomySession(site, true); foreach (TermStore _termStore in txsn.TermStores) { TreeNode tn = new TreeNode(); tn.Name = _termStore.Id.ToString(); tn.Text = _termStore.Name; lst.Add(tn); } } } catch (Exception exc) { msg = exc.ToString(); } // update parent thread gui this.Invoke((MethodInvoker) delegate { tvMMD.Nodes.Clear(); if (msg == "") { foreach (TreeNode treeNode in lst) { tvMMD.Nodes.Add(treeNode); } cout("TermStore(s) Loaded."); } else { cout("ERROR", msg); } StopWait(); }); }
public override TokenParser ProvisionObjects(Tenant tenant, Model.ProvisioningHierarchy hierarchy, string sequenceId, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(this.Name)) { foreach (var sequence in hierarchy.Sequences) { this.reusedTerms = new List <TermGroupHelper.ReusedTerm>(); var context = tenant.Context as ClientContext; TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(context); TermStore termStore = null; try { termStore = taxSession.GetDefaultKeywordsTermStore(); context.Load(termStore, ts => ts.Languages, ts => ts.DefaultLanguage, ts => ts.Groups.Include( tg => tg.Name, tg => tg.Id, tg => tg.TermSets.Include( tset => tset.Name, tset => tset.Id))); context.ExecuteQueryRetry(); } catch (ServerException) { WriteMessage("Failed to retrieve existing terms", ProvisioningMessageType.Error); return(parser); } foreach (var modelTermGroup in sequence.TermStore.TermGroups) { this.reusedTerms.AddRange(TermGroupHelper.ProcessGroup(context, taxSession, termStore, modelTermGroup, null, parser, scope)); } foreach (var reusedTerm in this.reusedTerms) { TermGroupHelper.TryReuseTerm(context, reusedTerm.ModelTerm, reusedTerm.Parent, reusedTerm.TermStore, parser, scope); } } } return(parser); }
/// <summary> /// Member to return all the Taxonomy fields /// </summary> /// <param name="cc"></param> private static void GetMMSTermsFromCloud(ClientContext cc) { // // Load up the taxonomy item names. // TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(cc); TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); cc.Load(termStore, store => store.Name, store => store.Groups.Include( group => group.Name, group => group.TermSets.Include( termSet => termSet.Name, termSet => termSet.Terms.Include( term => term.Name) ) ) ); cc.ExecuteQuery(); // //Writes the taxonomy item names. // if (taxonomySession != null) { if (termStore != null) { foreach (TermGroup group in termStore.Groups) { Console.WriteLine("Group " + group.Name); foreach (TermSet termSet in group.TermSets) { Console.WriteLine("TermSet " + termSet.Name); //cc.Load(termSet,ts=>ts.CustomProperties);cc.ExecuteQuery(); foreach (Term term in termSet.Terms) { cc.Load(term, tt => tt.CustomProperties, tt1 => tt1.LocalCustomProperties); cc.ExecuteQuery(); //Writes root-level terms only. Console.WriteLine("Term " + term.Name); } } } } } }
public static NavigationTermSet RecreateSampleNavTermSet(TestContext testContext, TaxonomySession taxonomySession, SPWeb web) { Console.WriteLine(testContext, "RecreateSampleNavTermSet(): START"); // Use the first TermStore object in the list. if (taxonomySession.TermStores.Count == 0) throw new InvalidOperationException("The Taxonomy Service is offline or missing."); TermStore termStore = taxonomySession.TermStores[0]; // Does the TermSet object already exist? TermSet existingTermSet = termStore.GetTermSet(TestConfig.NavTermSetId); if (existingTermSet != null) { Console.WriteLine(testContext, "RecreateSampleNavTermSet(): Deleting old TermSet"); existingTermSet.Delete(); termStore.CommitAll(); } Console.WriteLine(testContext, "RecreateSampleNavTermSet(): Creating new TermSet"); // Create a new TermSet object. Group siteCollectionGroup = termStore.GetSiteCollectionGroup(web.Site); TermSet termSet = siteCollectionGroup.CreateTermSet("Navigation Demo", TestConfig.NavTermSetId); NavigationTermSet navTermSet = NavigationTermSet.GetAsResolvedByWeb(termSet, web, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider); navTermSet.IsNavigationTermSet = true; navTermSet.TargetUrlForChildTerms.Value = "~site/Pages/Topics/Topic.aspx"; NavigationTerm term1 = navTermSet.CreateTerm("Term 1", NavigationLinkType.SimpleLink); term1.SimpleLinkUrl = "http://www.bing.com/"; NavigationTerm term2 = navTermSet.CreateTerm("Term 2", NavigationLinkType.FriendlyUrl); NavigationTerm term2a = term2.CreateTerm("Term 2 A", NavigationLinkType.FriendlyUrl); NavigationTerm term2b = term2.CreateTerm("Term 2 B", NavigationLinkType.FriendlyUrl); NavigationTerm term3 = navTermSet.CreateTerm("Term 3", NavigationLinkType.FriendlyUrl); termStore.CommitAll(); Console.WriteLine(testContext, "RecreateSampleNavTermSet(): FINISH"); return navTermSet; }
/// <summary> /// Given a site collection and a taxonomy session, fetches the parent term group /// for the current term set. /// </summary> /// <param name="currentSession">The current taxonomy session</param> /// <param name="currentSite"> /// The current site collection - used to resolve the site-collection-specific term group whenever the parent TermGroupInfo on the current TermSetInfo is null. /// </param> /// <returns>The SharePoint taxonomy term group</returns> public Group ResolveParentGroup(TaxonomySession currentSession, SPSite currentSite) { TermStore currentStore = this.ResolveParentTermStore(currentSession); if (this.Group == null && currentSite == null) { string missingSiteErrorMsg = string.Format( CultureInfo.InvariantCulture, "Error while resolving parent term store group of term set ID={0} Name=. Both the TermGroupInfo and currentSite specified were null. Either initialize your TermSetInfo object with a valid TermGroupInfo or specify a currentSite SPSite instance so the SiteCollectionGroup can be resolved.", this.Id, this.Label); throw new NotSupportedException(missingSiteErrorMsg); } if (this.Group == null) { // Whenever the parent TermGroupInfo is null, by convention, we assume we're dealing with // the default site collection term store. if (currentStore == null) { // If the TermGroupInfo is null, then ResolveParentTermStore should have returned us the DefaultSiteCollectionTermStore. string missingGroupErrorMsg = string.Format( CultureInfo.InvariantCulture, "Error while resolving parent term store group of term set ID={0} Name=. Since the parent TermGroupInfo is null, we assume we're dealing with the DefaultSiteCollectionTermStore. However this default term store appears to not be configured. Please configure your managed metadata service as the 'Default location for site columns' or specify a parent TermGroupInfo on your TermSetInfo.", this.Id, this.Label); throw new NotSupportedException(missingGroupErrorMsg); } return(currentStore.GetSiteCollectionGroup(currentSite)); } else if (currentStore != null) { return(currentStore.Groups[this.Group.Name]); } else { string missingStoreErrorMsg = string.Format( CultureInfo.InvariantCulture, "Error while resolving parent term store of term set ID={0} Name=. Please configure your managed metadata service as the 'Default location for site columns' or specify a parent TermGroupInfo and a grandparent TermStoreInfo on your TermSetInfo.", this.Id, this.Label); throw new NotSupportedException(missingStoreErrorMsg); } }
static void Main(string[] args) { using (SPSite site = new SPSite(@"http://*****:*****@"C:\taxonomy.xml"); XElement termStoreCollectionElement = XElement.Parse(text); Importer importer = new Importer(); XElement termStoreElement = termStoreCollectionElement.Elements().First(); importer.ImportTermStore(session.TermStores, termStoreElement , true); } }
public static TermStore termstorefromWebApp(SPSite site) { TaxonomySession session = new TaxonomySession(site); //ThroubleShooting problem during get termstore // http://sharepoint.stackexchange.com/questions/4097/why-are-taxonomy-term-stores-always-empty //http://blog.henryong.com/2012/03/20/sharepoint-dev-getting-null-taxonomysession-and-argumentoutofrangeexception-errors-on-termstore-objects/ // 1st way; termStore = session.TermStores["Managed Metadata Service"]; // 2nd way; // termStore = session.DefaultKeywordsTermStore;//Try session.DefaultSiteCollectionTermStore return termStore; }
public override string GetReplaceValue() { if (string.IsNullOrEmpty(CacheValue)) { // The token is requested. Check if the group exists and if not, create it var site = TokenContext.Site; var session = TaxonomySession.GetTaxonomySession(TokenContext); var termstore = session.GetDefaultSiteCollectionTermStore(); var termGroup = termstore.GetSiteCollectionGroup(site, true); TokenContext.Load(termGroup); TokenContext.ExecuteQueryRetry(); CacheValue = termGroup.Id.ToString(); } return(CacheValue); }
public override void DeployModel(object modelHost, DefinitionBase model) { var siteModelHost = modelHost.WithAssertAndCast<SiteModelHost>("modelHost", value => value.RequireNotNull()); var definition = model.WithAssertAndCast<TaxonomyTermStoreDefinition>("model", value => value.RequireNotNull()); var site = siteModelHost.HostSite; var spObject = FindTermStore(siteModelHost, definition); var assert = ServiceFactory.AssertService .NewAssert(definition, spObject) .ShouldNotBeNull(spObject); if (definition.Id.HasValue) assert.ShouldBeEqual(m => m.Id, o => o.Id); else assert.SkipProperty(m => m.Id, "ID is NULL. Skipping."); if (!string.IsNullOrEmpty(definition.Name)) assert.ShouldBeEqual(m => m.Name, o => o.Name); else assert.SkipProperty(m => m.Name, "Name is NULL. Skipping."); if (definition.UseDefaultSiteCollectionTermStore.HasValue) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.UseDefaultSiteCollectionTermStore); var taxSession = new TaxonomySession(site); var termStore = taxSession.DefaultSiteCollectionTermStore; var isValid = termStore.Id == spObject.Id; return new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }; }); } else assert.SkipProperty(m => m.UseDefaultSiteCollectionTermStore, "UseDefaultSiteCollectionTermStore is NULL. Skipping."); }
private static void GetTermInformation() { //TaxonomySession TaxonomySession session = new TaxonomySession(new Microsoft.SharePoint.SPSite("http://abcuniversity/")); //TermStores TermStoreCollection termStores = session.TermStores; Console.WriteLine("There is/are {0} term stores(s) in this site", termStores.Count); //Groups foreach (TermStore store in termStores) { GroupCollection groups = store.Groups; Console.WriteLine("There is/are {0} groups in Term Store {1}", groups.Count,store.Name); foreach (Group group in groups) { //If you want to add terms... //group.CreateTermSet("Some new group"); Console.WriteLine("Group {0}:", group.Name); //TermSetcollections TermSetCollection terms = group.TermSets; //TermSets foreach (TermSet set in terms) { Console.WriteLine("-Set Name: {0}", set.Name); if (set.Name == "People") { Console.WriteLine("Defined term {0} is described as {1} and has a count of {2}", set.Name, set.Description, set.Terms.Count); //Terms foreach (Term term in set.Terms) { Console.WriteLine("Term '{0}'", term.Name); } } } } } }
/// <summary> /// Applies a term store mapping to a SharePoint field /// </summary> /// <param name="site">The current site collection</param> /// <param name="field">The site or list column to map to the term store</param> /// <param name="columnTermStoreMapping"> /// The term set or sub-term-specific anchor which will determine what's available in the field's taxonomy picker /// </param> public void AssignTermStoreMappingToField(SPSite site, SPField field, TaxonomyContext columnTermStoreMapping) { TaxonomySession session = new TaxonomySession(site); TermStore store = columnTermStoreMapping.TermSet.ResolveParentTermStore(session); Group termStoreGroup = columnTermStoreMapping.TermSet.ResolveParentGroup(session, site); TaxonomyField taxoField = (TaxonomyField)field; if (columnTermStoreMapping.TermSubset != null) { InternalAssignTermSetToTaxonomyField(store, taxoField, termStoreGroup.Id, columnTermStoreMapping.TermSet.Id, columnTermStoreMapping.TermSubset.Id); } else { InternalAssignTermSetToTaxonomyField(store, taxoField, termStoreGroup.Id, columnTermStoreMapping.TermSet.Id, Guid.Empty); } }
public void ExportColumns(string siteUrl, out XElement columns) { columns = new XElement("Fields"); try { columns.SetAttributeValue("SiteCollection", siteUrl); using (SPSite site = new SPSite(siteUrl)) { using (SPWeb web = site.OpenWeb()) { TaxonomySession session = new TaxonomySession(site); foreach (SPField field in web.AvailableFields) { XElement column = new XElement("Field"); column.SetAttributeValue("Name", field.InternalName); column.SetAttributeValue("DisplayName", field.Title); column.SetAttributeValue("Group", field.Group); column.SetAttributeValue("Type", field.TypeAsString); if ((field.TypeAsString == "TaxonomyFieldType") || (field.TypeAsString == "TaxonomyFieldTypeMulti")) { TaxonomyField tf = (from f in web.AvailableFields.OfType<SPField>() where string.CompareOrdinal(f.InternalName, field.InternalName) == 0 select f).Distinct().First() as TaxonomyField; TermStore store = session.TermStores[tf.SspId]; column.SetAttributeValue("TermStore", session.TermStores[tf.SspId].Name); column.SetAttributeValue("TermGroup", session.TermStores[tf.SspId].Name); TermSet termSet = store.GetTermSet(tf.TermSetId); column.SetAttributeValue("TermSet", termSet.Name); column.SetAttributeValue("AnchorID", tf.AnchorId); } columns.Add(column); } } } } catch (Exception e) { } }
/// <summary> ///GetAll Termes Taxonomy /// </summary> /// <returns></returns> public IDictionary<string, string> GetAllTerms() { try { IDictionary<string, string> result = new Dictionary<string, string>(); var session = new TaxonomySession(SpSite); var termStore = session.TermStores[NameTermStore]; var group = termStore.Groups[NameGroup]; foreach (var termSet in group.TermSets) { result.Add(termSet.Id.ToString(), termSet.Name); } return result; } catch (Exception exception) { Logger.Error(string.Concat("Error GetAllTerms", exception.Message)); return null; } }
/// <summary> /// Loading the Term Group Based on Given Name /// </summary> /// <param name="clientContext">Client context</param> /// <param name="taxonomySession">Taxonomy session</param> /// <param name="termGroupName">Term group name </param> /// <returns>Term group </returns> public static TermGroup LoadTermGroup(ClientContext clientContext, TaxonomySession taxonomySession, string termGroupName) { TermStore termStore = taxonomySession.GetDefaultKeywordsTermStore(); clientContext.Load(termStore, store => store.Name, store => store.Groups.Include( group => group.Name, group => group.TermSets.Include( termSet => termSet.Name, termSet => termSet.Terms.Include( term => term.Name, term => term.CustomProperties ) ) ) ); clientContext.ExecuteQuery(); TermGroup termGroup = termStore.Groups.GetByName(termGroupName); return termGroup; }
public static void ExportFullTaxonomy(string directoryPath, string managedServiceName, string siteUrl) { using (SPSite site = new SPSite(siteUrl)) { TaxonomySession __taxonomySession = new TaxonomySession(site, true); TermStore __defaultSiteCollectionTermStore = __taxonomySession.TermStores[managedServiceName]; XDocument __xDoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes")); XElement __rootElt = new XElement("root"); foreach (Group group in __defaultSiteCollectionTermStore.Groups) { XmlExport.ExportTermGroup(__rootElt, group); } __xDoc.Add(__rootElt); __xDoc.Save(Path.Combine(directoryPath, "Taxonomy_" + System.DateTime.Today.ToString("yyyyMMdd") + ".xml")); } }
public static TermSet CreateTermSet(this SPSite site, string termGroup, string name) { var session = new TaxonomySession(site); if (session.TermStores.Count != 0 && session.TermStores.Any(x => x.Name == Constants.TaxonomyTermStore)) { var termStore = session.TermStores[Constants.TaxonomyTermStore]; var group = termStore.Groups[termGroup]; if (@group.TermSets.All(x => x.Name != name)) { var termset = group.CreateTermSet(name); termStore.CommitAll(); return termset; } return group.TermSets.FirstOrDefault(x => x.Name == name); } throw new TermStoreNotFoundException( string.Format("Managed Metadata Service TermStore not found in site {0}", site.Url)); }
public XmlDocument Export(TaxonomySession ts) { if (ts == null) throw new ArgumentNullException("ts", "The TaxonomySession object is null."); XmlElement element = _xml.CreateElement("TermStores"); _xml.AppendChild(element); var tsc = ts.TermStores; if (!ts.IsObjectPropertyInstantiated("TermStores") || !ts.TermStores.AreItemsAvailable) { _ctx.Load(tsc); _ctx.ExecuteQuery(); } foreach (TermStore termStore in tsc) { LoadLanguages(termStore); Export(element, termStore); } return _xml; }
public static TaxonomyFieldValue GetTaxonomyFieldValue(SPSite site, Guid sspId, Guid termSetId, string value, bool addIfDoesNotExist/*, out bool newTermAdded*/) { bool newTermAdded; if (string.IsNullOrEmpty(value)) { return null; } TaxonomySession taxonomySession = new TaxonomySession(site); TermStore termStore = taxonomySession.TermStores[sspId]; TermSet termSet = termStore.GetTermSet(termSetId); TaxonomyFieldValue val = GetTaxonomyFieldValue(termSet, value, addIfDoesNotExist, out newTermAdded); if (newTermAdded) { termStore.CommitAll(); } return val; }
public static void ConnectTaxonomyField(TaxonomyField field, TaxonomySession session, TermStore termStore, string termGroup, string termSetName, bool isOpen = false, bool createValuesInEditForm = false) { if (field == null || session == null || termStore == null) { return; } Group group = termStore.Groups.GetByName(termGroup); if (group != null) { TermSet termSet = group.TermSets.GetByName(termSetName); // connect the field to the specified term if (termSet != null) { field.SspId = termSet.TermStore.Id; field.TermSetId = termSet.Id; field.Open = isOpen && termSet.IsOpenForTermCreation; field.CreateValuesInEditForm = field.Open && createValuesInEditForm; } } field.TargetTemplate = string.Empty; field.AnchorId = Guid.Empty; field.Update(); }
/// 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; }