/// <summary> /// Get all parent terms from a source term to root term in the term set. /// </summary> /// <param name="site">The current site collection.</param> /// <param name="termSetId">The term set id.</param> /// <param name="termId">The term.</param> /// <param name="parentFirst">if set to <c>true</c>, includes the [parent first].</param> /// <returns> /// List of terms. /// </returns> public IList <Term> GetTermPathFromRootToTerm(SPSite site, Guid termSetId, Guid termId, bool parentFirst) { IList <Term> termHierarchy = new List <Term>(); var session = new TaxonomySession(site); TermStore termStore = session.DefaultSiteCollectionTermStore; // Always interact with the term sets in the term store's default language int originalWorkingLanguage = termStore.WorkingLanguage; termStore.WorkingLanguage = termStore.DefaultLanguage; var rootTermReached = false; // Get the original term var term = termStore.GetTerm(termSetId, termId); while (term != null && !rootTermReached) { termHierarchy.Add(term); if (term.Parent != null) { term = termStore.GetTerm(termSetId, term.Parent.Id); } else { rootTermReached = true; } } termStore.WorkingLanguage = originalWorkingLanguage; return(parentFirst ? termHierarchy.Reverse().ToList() : termHierarchy); }
public static Term LookupTerm(SPSite site, TermStore tesmStore, TaxonomyFieldDefinition taxFieldModel) { Group currentGroup = null; var termGroupName = taxFieldModel.TermGroupName; var groupId = taxFieldModel.TermGroupId; var isSiteCollectionGroup = taxFieldModel.IsSiteCollectionGroup; if (!string.IsNullOrEmpty(termGroupName)) { currentGroup = tesmStore.Groups.FirstOrDefault(g => g.Name.ToUpper() == termGroupName.ToUpper()); } else if (groupId != null && groupId.HasGuidValue()) { currentGroup = tesmStore.GetGroup(groupId.Value); } else if (isSiteCollectionGroup.HasValue && isSiteCollectionGroup.Value) { currentGroup = tesmStore.GetSiteCollectionGroup(site); } // TODO // that should also check if the TermSet is there, so to scope the term if (currentGroup != null) { if (taxFieldModel.TermId.HasValue) { return(tesmStore.GetTerm(taxFieldModel.TermId.Value)); } if (!string.IsNullOrEmpty(taxFieldModel.TermName)) { return(tesmStore.GetTerms(taxFieldModel.TermName, taxFieldModel.TermLCID, false) .FirstOrDefault(t => t.TermSet.Group.Name == currentGroup.Name)); } } else { if (taxFieldModel.TermId.HasValue) { return(tesmStore.GetTerm(taxFieldModel.TermId.Value)); } if (!string.IsNullOrEmpty(taxFieldModel.TermName)) { return(tesmStore.GetTerms(taxFieldModel.TermName, taxFieldModel.TermLCID, false).FirstOrDefault()); } } return(null); }
public static void CreateTaxonomyFavColor(ClientContext ctx) { TermStore store = ctx.Site.GetDefaultSiteCollectionTermStore(); TermGroup group = store.GetTermGroupByName("School"); if (group == null) { group = store.CreateTermGroup("School", "{13E6924A-196D-4313-A1B4-3A21AF3958CF}".ToGuid(), "description"); } TermSet termSet = group.EnsureTermSet("Fav Color", "{3D4C7DE0-3867-44C3-871A-C36DEC4E1970}".ToGuid(), 1033); Term term = store.GetTerm("{1BB08D14-4464-410C-A27C-BA2EB8EFE9DE}".ToGuid()); ctx.Load(term); ctx.ExecuteQuery(); if (term.ServerObjectIsNull()) { termSet.CreateTerm("Green", 1033, "{1BB08D14-4464-410C-A27C-BA2EB8EFE9DE}".ToGuid()); termSet.CreateTerm("Blue", 1033, "{E96EF7E0-7F9B-4F66-BA1A-C2DBCC73DD78}".ToGuid()); termSet.CreateTerm("Red", 1033, "{13E22744-483D-49D2-B92D-6BD2E0C10D9C}".ToGuid()); ctx.ExecuteQuery(); } }
protected override void ProcessFieldProperties(SPField field, FieldDefinition fieldModel) { // let base setting be setup base.ProcessFieldProperties(field, fieldModel); // process taxonomy field specific properties var taxField = field.WithAssertAndCast <TaxonomyField>("field", value => value.RequireNotNull()); var taxFieldModel = fieldModel.WithAssertAndCast <TaxonomyFieldDefinition>("model", value => value.RequireNotNull()); var site = GetCurrentSite(); var taxSession = new TaxonomySession(site); TermStore tesmStore = null; if (taxFieldModel.UseDefaultSiteCollectionTermStore == true) { tesmStore = taxSession.DefaultSiteCollectionTermStore; } else if (taxFieldModel.SspId.HasValue) { tesmStore = taxSession.TermStores[taxFieldModel.SspId.Value]; } else if (!string.IsNullOrEmpty(taxFieldModel.SspName)) { tesmStore = taxSession.TermStores[taxFieldModel.SspName]; } TermSet termSet = null; if (taxFieldModel.TermSetId.HasValue) { termSet = tesmStore.GetTermSet(taxFieldModel.TermSetId.Value); } else if (!string.IsNullOrEmpty(taxFieldModel.TermSetName)) { termSet = tesmStore.GetTermSets(taxFieldModel.TermSetName, taxFieldModel.TermSetLCID).FirstOrDefault(); } Term term = null; if (taxFieldModel.TermId.HasValue) { term = tesmStore.GetTerm(taxFieldModel.TermId.Value); } else if (!string.IsNullOrEmpty(taxFieldModel.TermName)) { term = tesmStore.GetTerms(taxFieldModel.TermName, taxFieldModel.TermLCID, false).FirstOrDefault(); } taxField.SspId = tesmStore.Id; if (termSet != null) { taxField.TermSetId = termSet.Id; } else if (term != null) { taxField.TermSetId = term.Id; } }
public static void CreateIssueCategoryTermSet(ClientContext ctx) { //TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(ctx); //TermStore store = taxSession.TermStores[0]; TermStore store = ctx.Site.GetDefaultSiteCollectionTermStore(); TermGroup group = store.GetTermGroupByName("OD1Test"); if (group == null) { group = store.CreateTermGroup("OD1Test", "{13E6924A-196D-4313-A1B4-3A21AF3958CF}".ToGuid(), "description"); } TermSet termSet = group.EnsureTermSet("Issue Category", "{3D4C7DE0-3867-44C3-871A-C36DEC4E1970}".ToGuid(), 1033); Term term = store.GetTerm("{1BB08D14-4464-410C-A27C-BA2EB8EFE9DE}".ToGuid()); ctx.Load(term); ctx.ExecuteQuery(); if (term == null) { termSet.CreateTerm("Just Right", 1033, "{1BB08D14-4464-410C-A27C-BA2EB8EFE9DE}".ToGuid()); termSet.CreateTerm("Low Priority", 1033, "{E96EF7E0-7F9B-4F66-BA1A-C2DBCC73DD78}".ToGuid()); termSet.CreateTerm("Urgent", 1033, "{13E22744-483D-49D2-B92D-6BD2E0C10D9C}".ToGuid()); ctx.ExecuteQuery(); } }
private void CreateTerm(ClientContext context, TermStore termStore, ShTerm shTerm, TermSetItem parentTerm) { var spTerm = termStore.GetTerm(shTerm.Id); context.Load(spTerm, t => t.Terms); context.ExecuteQuery(); if (spTerm.ServerObjectIsNull != null && spTerm.ServerObjectIsNull.Value) { spTerm = parentTerm.CreateTerm(shTerm.Title, termStore.DefaultLanguage, shTerm.Id); if (!string.IsNullOrEmpty(shTerm.CustomSortOrder)) { spTerm.CustomSortOrder = shTerm.CustomSortOrder; } spTerm.IsAvailableForTagging = !shTerm.NotAvailableForTagging; foreach (var prop in shTerm.CustomProperties) { spTerm.SetCustomProperty(prop.Key, prop.Value); } foreach (var prop in shTerm.LocalCustomProperties) { spTerm.SetLocalCustomProperty(prop.Key, prop.Value); } context.Load(spTerm); context.ExecuteQuery(); } foreach (ShTerm childTerm in shTerm.Terms) { CreateTerm(context, termStore, childTerm, spTerm); } }
public static Term LookupTerm(SPSite site, TermStore tesmStore, TaxonomyFieldDefinition taxFieldModel) { Group currentGroup = null; var termGroupName = taxFieldModel.TermGroupName; var groupId = taxFieldModel.TermGroupId; var isSiteCollectionGroup = taxFieldModel.IsSiteCollectionGroup; if (!string.IsNullOrEmpty(termGroupName)) { currentGroup = tesmStore.Groups.FirstOrDefault(g => g.Name.ToUpper() == termGroupName.ToUpper()); } else if (groupId != null && groupId.HasGuidValue()) { currentGroup = tesmStore.GetGroup(groupId.Value); } else if (isSiteCollectionGroup.HasValue && isSiteCollectionGroup.Value) { currentGroup = tesmStore.GetSiteCollectionGroup(site); } // TODO // that should also check if the TermSet is there, so to scope the term if (currentGroup != null) { if (taxFieldModel.TermId.HasValue) return tesmStore.GetTerm(taxFieldModel.TermId.Value); if (!string.IsNullOrEmpty(taxFieldModel.TermName)) { return tesmStore.GetTerms(taxFieldModel.TermName, taxFieldModel.TermLCID, false) .FirstOrDefault(t => t.TermSet.Group.Name == currentGroup.Name); } } else { if (taxFieldModel.TermId.HasValue) return tesmStore.GetTerm(taxFieldModel.TermId.Value); if (!string.IsNullOrEmpty(taxFieldModel.TermName)) return tesmStore.GetTerms(taxFieldModel.TermName, taxFieldModel.TermLCID, false).FirstOrDefault(); } return null; }
internal static bool CheckIfTermIdIsUnique(TermStore store, Guid id) { var existingTerm = store.GetTerm(id); store.Context.Load(existingTerm); store.Context.ExecuteQueryRetry(); return(existingTerm.ServerObjectIsNull == true); }
public static Term LookupTerm(TermStore tesmStore, TaxonomyFieldDefinition taxFieldModel) { if (taxFieldModel.TermId.HasValue) return tesmStore.GetTerm(taxFieldModel.TermId.Value); if (!string.IsNullOrEmpty(taxFieldModel.TermName)) return tesmStore.GetTerms(taxFieldModel.TermName, taxFieldModel.TermLCID, false).FirstOrDefault(); return null; }
public static void Test1(ClientContext context) { var termStoreId = new Guid("0b77086dbdd74f9daa23235581e09cef"); var termId = new Guid("df07a9c0-245f-4170-9fd7-c05ab77ca320"); TaxonomySession session = TaxonomySession.GetTaxonomySession(context); TermStore store = session.TermStores.GetById(termStoreId); Term term = store.GetTerm(termId); ClientResult <string> defaultLabel = term.GetDefaultLabel(1033); context.ExecuteQuery(); }
public static Term LookupTerm(TermStore tesmStore, TaxonomyFieldDefinition taxFieldModel) { if (taxFieldModel.TermId.HasValue) { return(tesmStore.GetTerm(taxFieldModel.TermId.Value)); } if (!string.IsNullOrEmpty(taxFieldModel.TermName)) { return(tesmStore.GetTerms(taxFieldModel.TermName, taxFieldModel.TermLCID, false).FirstOrDefault()); } return(null); }
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 Term LookupTerm(SiteModelHost currentSiteModelHost, TermStore termStore, TaxonomyFieldDefinition termModel) { var context = currentSiteModelHost.HostClientContext; Term result = null; if (termModel.TermId.HasValue) { var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { result = termStore.GetTerm(termModel.TermId.Value); context.Load(result); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); } else if (!string.IsNullOrEmpty(termModel.TermName)) { var terms = termStore.GetTerms(new LabelMatchInformation(context) { Lcid = termModel.TermLCID, TermLabel = termModel.TermName, TrimUnavailable = false }); context.Load(terms); context.ExecuteQueryWithTrace(); result = terms.FirstOrDefault(); } if (result != null && result.ServerObjectIsNull == false) { context.Load(result); context.ExecuteQueryWithTrace(); return(result); } return(null); }
public Term GetTerm(ClientContext clientContext, TermStore termStore, TermSet termSet, bool recursive, Expression <Func <Term, object> >[] expressions = null) { Term term = null; if (_id != Guid.Empty) { term = termStore.GetTerm(_id); } else if (!string.IsNullOrEmpty(_title) && termSet != null && termStore != null) { var termName = TaxonomyExtensions.NormalizeName(_title); if (!recursive) { term = termSet.Terms.GetByName(termName); } else { var lmi = new LabelMatchInformation(clientContext) { TrimUnavailable = true, TermLabel = termName }; var termMatches = termSet.GetTerms(lmi); clientContext.Load(termMatches); clientContext.ExecuteQueryRetry(); if (termMatches.AreItemsAvailable) { term = termMatches.FirstOrDefault(); } } } else { throw new PSArgumentException("Not enough parameters specified to succesfully find the term"); } if (expressions != null) { clientContext.Load(term, expressions); } else { clientContext.Load(term); } clientContext.ExecuteQueryRetry(); return(term); }
/// <summary> /// Gets a <see cref="Term"/> object from a Taxonomy field. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="termStore">Term store object.</param> /// <returns>Value in the specified field as a <see cref="Term"/> object.</returns> public virtual Term GetTaxonomy(string fieldName, TermStore termStore) { object value = this[fieldName]; if (value != null) { try { Guid termId = new Guid(value.ToString().Split(TaxonomyField.TaxonomyGuidLabelDelimiter).Last()); if (termId != Guid.Empty) { return(termStore.GetTerm(termId)); } } catch (FormatException) { } } return(null); }
//gavdcodeend 10 //gavdcodebegin 11 static void SpCsCsomFindTermSetAndTermById(ClientContext spCtx) { string termStoreName = "Taxonomy_hVIOdhme2obc+5zqZXqqUQ=="; TaxonomySession myTaxSession = TaxonomySession.GetTaxonomySession(spCtx); TermStore myTermStore = myTaxSession.TermStores.GetByName(termStoreName); TermSet myTermSet = myTermStore.GetTermSet( new Guid("fdf6890f-5e8b-4d69-8a94-af92fdcebf30")); Term myTerm = myTermStore.GetTerm( new Guid("2f5352b2-a929-472e-9e8a-5d2b4c119bd3")); spCtx.Load(myTermSet); spCtx.Load(myTerm); spCtx.ExecuteQuery(); Console.WriteLine(myTermSet.Name + " - " + myTerm.Name); }
public static TermSet GetParent(TermStore termStore, TermQueryModel model, out Term parentTerm) { TermSet termSet = null; parentTerm = null; if (string.IsNullOrEmpty(model.TermSetId)) { parentTerm = termStore.GetTerm(new Guid(model.ParentTermId)); } else { termSet = termStore.GetTermSet(new Guid(model.TermSetId)); } return(termSet); }
private static void AplicarOrdenVerdes(SPWeb web, Term term, string guid) { ResultTable resultTable = RealizarBusqueda(guid); int contador = 0; List <DocumentoSharePoint> primerOrden = OrdenarResultados(resultTable); foreach (DocumentoSharePoint doc in primerOrden) { contador++; Console.WriteLine(doc.Path + " " + contador + "/" + primerOrden.Count); SPListItem item = web.GetFile(doc.Path).Item; if (item.File.CheckOutType == SPFile.SPCheckOutType.None) { TaxonomyField campo = (TaxonomyField)item.Fields.GetField(field); int orden = contador * 100; Console.WriteLine(orden); item[campoOrden] = orden; AplicarTerminoVerdes(term, doc.Path, item, orden); } else { logDesprotegidos.WriteLine("Documento Desprotegido: " + doc.Path); } } if (ramaVirgen) { var borrables = term.Terms.Select(g => new { Guid = g.Id, Path = g.GetPath() }); foreach (var borrar in borrables) { try { Console.WriteLine("Se borrá: " + borrar.Path); logProceso.WriteLine("Se borrá: " + borrar.Path); termStore.GetTerm(borrar.Guid).Delete(); termStore.CommitAll(); } catch (Exception ex) { Console.WriteLine("Error borrando el siguiente término: " + borrar.Path + " " + ex.Message); logProceso.WriteLine("Error borrando el siguiente término: " + borrar.Path + " " + ex.Message); } } } }
internal static void SaveStudent(ClientContext ctx, Student student) { TermStore store = ctx.Site.GetDefaultKeywordsTermStore(); Term term = store.GetTerm(student.FavColorid.ToGuid()); ctx.Load(term); ctx.ExecuteQuery(); List list = ctx.Web.GetListByTitle("Students"); TaxonomyField field = list.GetFieldById <TaxonomyField>("{6D9CF114-04FB-4C91-BF6E-C45770B48A2A}".ToGuid()); ListItem item = list.AddItem(new ListItemCreationInformation()); //item.SetTaxonomyFieldValue("{6D9CF114-04FB-4C91-BF6E-C45770B48A2A}".ToGuid(), term.Name, term.Id); item["Title"] = student.Title; item["School_Address"] = student.Address; item["School_School"] = student.SchoolId; field.SetFieldValueByTerm(item, term, 1033); item.Update(); ctx.ExecuteQuery(); }
private ICollection <int> GetDeletedTermIDs() { if (deletedTerms == null) { deletedTerms = new List <int>(); SPList taxonomyHiddenList = SPExtensionHelper.GetTaxonomyHiddenList(manager.Site); TermStore termStore = manager.TermStore; SPQuery query = new SPQuery { Query = Caml.Equals("IdForTermStore", termStore.Id.ToString()).ToString(), ViewFields = Caml.ViewFields("IdForTerm").ToString() }; foreach (SPListItem item in taxonomyHiddenList.GetItems(query)) { if (termStore.GetTerm(new Guid((string)item["IdForTerm"])) == null) { deletedTerms.Add(item.ID); } } } return(deletedTerms); }
/// <summary> /// Gets a collection of <see cref="Term"/> objects from a multiple Taxonomy field. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="termStore">Term store object.</param> /// <returns>A collection of <see cref="Term"/> objects.</returns> protected virtual IList <Term> GetTaxonomyMultiInternal(string fieldName, TermStore termStore) { Collection <Term> collection = new Collection <Term>(); object value = this[fieldName]; if (value != null) { foreach (string s in value.ToString().Split(TaxonomyField.TaxonomyMultipleTermDelimiter)) { try { Guid termId = new Guid(s.Split(TaxonomyField.TaxonomyGuidLabelDelimiter).Last()); if (termId != Guid.Empty) { Term term = termStore.GetTerm(termId); if (term != null) { collection.Add(term); } } } catch (FormatException) { } } } return(collection); }
public static Term LookupTerm(ClientContext clientContext, TermStore termStore, TermSet termSet, TaxonomyFieldDefinition termModel) { var context = clientContext; var site = clientContext.Site; Term result = null; TermGroup currenGroup = null; var termGroupName = termModel.TermGroupName; var termGroupId = termModel.TermGroupId; var isSiteCollectionGroup = termModel.IsSiteCollectionGroup; if (!string.IsNullOrEmpty(termGroupName)) { currenGroup = termStore.Groups.GetByName(termGroupName); context.Load(currenGroup); context.ExecuteQueryWithTrace(); } else if (termGroupId != null && termGroupId.HasGuidValue()) { currenGroup = termStore.Groups.GetById(termGroupId.Value); context.Load(currenGroup); context.ExecuteQueryWithTrace(); } else if (isSiteCollectionGroup == true) { currenGroup = termStore.GetSiteCollectionGroup(site, false); context.Load(currenGroup); context.ExecuteQueryWithTrace(); } if (currenGroup != null) { if (termModel.TermId.HasValue) { // by ID, the only one match var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { result = termStore.GetTerm(termModel.TermId.Value); context.Load(result); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); } else if (!string.IsNullOrEmpty(termModel.TermName)) { var terms = termStore.GetTerms(new LabelMatchInformation(context) { Lcid = termModel.TermLCID, TermLabel = termModel.TermName, TrimUnavailable = false }); context.Load(terms, t => t.Include( i => i.Id, i => i.Name, i => i.TermSet, i => i.TermSet.Group, i => i.TermSet.Group.Name )); context.ExecuteQueryWithTrace(); result = terms.FirstOrDefault(t => t.TermSet.Group.Name == currenGroup.Name); if ( (result == null) && (termSet != null )) // sometimes label match information does not return the term { var allTerms = termSet.GetAllTerms(); context.Load(allTerms, t => t.Include( i => i.Id, i => i.Name, i => i.TermSet, i => i.TermSet.Group, i => i.TermSet.Group.Name, i => i.Labels )); context.ExecuteQueryWithTrace(); result = allTerms.FirstOrDefault(t => (t.TermSet.Group.Name == currenGroup.Name) && (t.Labels.Any(l=>l.Value == termModel.TermName && l.Language == termModel.TermLCID))); } } } else { if (termModel.TermId.HasValue) { var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { result = termStore.GetTerm(termModel.TermId.Value); context.Load(result); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); } else if (!string.IsNullOrEmpty(termModel.TermName)) { var terms = termStore.GetTerms(new LabelMatchInformation(context) { Lcid = termModel.TermLCID, TermLabel = termModel.TermName, TrimUnavailable = false }); context.Load(terms); context.ExecuteQueryWithTrace(); result = terms.FirstOrDefault(); if ((result == null) && (termSet != null)) // sometimes label match information does not return the termset { var allTerms = termSet.GetAllTerms(); context.Load(allTerms, t => t.Include( i => i.Id, i => i.Name, i => i.TermSet, i => i.TermSet.Group, i => i.TermSet.Group.Name, i => i.Labels )); context.ExecuteQueryWithTrace(); result = allTerms.FirstOrDefault( t => (t.Labels.Any(l=>l.Value == termModel.TermName && l.Language == termModel.TermLCID))); } } } if (result != null && result.ServerObjectIsNull == false) { context.Load(result); context.ExecuteQueryWithTrace(); return result; } return null; }
public void ProcessChanges(ClientContext sourceClientContext, ClientContext targetClientContext, List <string> termSetNames) { List <TermOperation> _list = new List <TermOperation>(); DateTime _startFrom = DateTime.Now.AddYears(-1); Console.WriteLine("Opening the taxonomy session"); TaxonomySession _sourceTaxonomySession = TaxonomySession.GetTaxonomySession(sourceClientContext); TermStore sourceTermStore = _sourceTaxonomySession.GetDefaultKeywordsTermStore(); sourceClientContext.Load(sourceTermStore); sourceClientContext.ExecuteQuery(); Console.WriteLine("Reading the changes"); ChangeInformation _ci = new ChangeInformation(sourceClientContext); _ci.StartTime = _startFrom; ChangedItemCollection _cic = sourceTermStore.GetChanges(_ci); sourceClientContext.Load(_cic); sourceClientContext.ExecuteQuery(); if (_cic.Count > 0) { bool noError = true; // Load up the taxonomy item names. TaxonomySession targetTaxonomySession = TaxonomySession.GetTaxonomySession(targetClientContext); TermStore targetTermStore = targetTaxonomySession.GetDefaultKeywordsTermStore(); targetClientContext.Load(targetTermStore, store => store.Name, store => store.DefaultLanguage, store => store.Groups.Include( group => group.Name, group => group.Id)); targetClientContext.ExecuteQuery(); foreach (ChangedItem _changeItem in _cic) { Guid g = _changeItem.Id; if (_changeItem.ItemType == ChangedItemType.Group) { TermGroup sourceTermGroup = sourceTermStore.GetGroup(_changeItem.Id); sourceClientContext.Load(sourceTermGroup, group => group.Name, group => group.Id, group => group.IsSystemGroup, group => group.Description); sourceClientContext.ExecuteQuery(); if (sourceTermGroup.ServerObjectIsNull.Value) { continue; } else { if (sourceTermGroup.IsSystemGroup) { Console.WriteLine("Group \"" + sourceTermGroup.Name + "\" is a system group"); continue; } } if (_changeItem.Operation == ChangedOperationType.DeleteObject) { TermGroup targetTermGroup = targetTermStore.GetGroup(_changeItem.Id); targetClientContext.Load(targetTermGroup, group => group.Name, group => group.Id, group => group.TermSets.Include( termSet => termSet.Name, termSet => termSet.Id)); targetClientContext.ExecuteQuery(); foreach (TermSet ts in targetTermGroup.TermSets) { Console.WriteLine("Deleting termset: " + ts.Name); TermOperation op = new TermOperation(); op.Term = ts.Name; op.Id = ts.Id.ToString(); op.Operation = "Delete"; op.Type = "TermSet"; _list.Add(op); ts.DeleteObject(); } Console.WriteLine("Deleting group: " + sourceTermGroup.Name); targetTermGroup.DeleteObject(); TermOperation op2 = new TermOperation(); op2.Term = sourceTermGroup.Name; op2.Id = _changeItem.Id.ToString(); op2.Operation = "Delete"; op2.Type = "TermGroup"; _list.Add(op2); targetClientContext.ExecuteQuery(); } else if (_changeItem.Operation == ChangedOperationType.Add) { TermGroup targetTermGroup = targetTermStore.GetGroup(_changeItem.Id); targetClientContext.Load(targetTermGroup, group => group.Name, group => group.Id, group => group.TermSets.Include( termSet => termSet.Name, termSet => termSet.Id)); targetClientContext.ExecuteQuery(); if (targetTermGroup.ServerObjectIsNull.Value) { TermGroup targetTermGroupTest = targetTermStore.Groups.GetByName(sourceTermGroup.Name); targetClientContext.Load(targetTermGroupTest, group => group.Name); try { targetClientContext.ExecuteQuery(); if (!targetTermGroupTest.ServerObjectIsNull.Value) { if (sourceTermGroup.Name.ToLower() == "system" || sourceTermGroup.Name.ToLower() == "people") { Console.WriteLine("Group: " + sourceTermGroup.Name + " already exists"); continue; } else { InvalidOperationException uEx = new InvalidOperationException("A group named: \"" + sourceTermGroup.Name + "\" already exists but with a different ID. Please delete the term group from the target termstore"); break; } } } catch { } Console.WriteLine("Adding group: " + sourceTermGroup.Name); TermGroup _targetTermGroup = targetTermStore.CreateGroup(sourceTermGroup.Name, _changeItem.Id); if (!string.IsNullOrEmpty(sourceTermGroup.Description)) { _targetTermGroup.Description = sourceTermGroup.Description; } targetClientContext.ExecuteQuery(); targetTermStore.CommitAll(); targetTermStore.RefreshLoad(); TermOperation op = new TermOperation(); op.Term = sourceTermGroup.Name; op.Id = _changeItem.Id.ToString(); op.Operation = "Add"; op.Type = "TermGroup"; _list.Add(op); } } else if (_changeItem.Operation == ChangedOperationType.Edit) { TermGroup targetTermGroup = targetTermStore.GetGroup(_changeItem.Id); targetClientContext.Load(targetTermGroup, group => group.Name, group => group.Id, group => group.TermSets.Include( termSet => termSet.Name, termSet => termSet.Id)); targetClientContext.ExecuteQuery(); if (targetTermGroup.ServerObjectIsNull.Value) { targetTermGroup = targetTermStore.Groups.GetByName(sourceTermGroup.Name); targetClientContext.Load(targetTermGroup, group => group.Name); targetClientContext.ExecuteQuery(); if (targetTermGroup.ServerObjectIsNull.Value) { noError = false; break; } } if (targetTermGroup.Name != sourceTermGroup.Name) { Console.WriteLine("Modifying group: " + sourceTermGroup.Name); targetTermGroup.Name = sourceTermGroup.Name; TermOperation op = new TermOperation(); op.Term = sourceTermGroup.Name; op.Id = _changeItem.Id.ToString(); op.Operation = "Modify"; op.Type = "TermGroup"; _list.Add(op); targetClientContext.ExecuteQuery(); } } } if (_changeItem.ItemType == ChangedItemType.TermSet) { TermSet sourceTermset = sourceTermStore.GetTermSet(_changeItem.Id); sourceClientContext.Load(sourceTermset, termset => termset.Name, termset => termset.Id, termset => termset.Description, termset => termset.Contact, termset => termset.CustomProperties, termset => termset.Group, group => group.Id); sourceClientContext.ExecuteQuery(); if (sourceTermset.ServerObjectIsNull.Value) { continue; } if (!termSetNames.Contains(sourceTermset.Name)) { continue; } if (_changeItem.Operation == ChangedOperationType.DeleteObject) { TermSet targetTermset = targetTermStore.GetTermSet(_changeItem.Id); targetClientContext.Load(targetTermset); targetClientContext.ExecuteQuery(); Console.WriteLine("Deleting termset: " + targetTermset.Name); targetTermset.DeleteObject(); targetClientContext.ExecuteQuery(); TermOperation op = new TermOperation(); op.Term = targetTermset.Name; op.Id = _changeItem.Id.ToString(); op.Operation = "Delete"; op.Type = "TermSet"; _list.Add(op); } else if (_changeItem.Operation == ChangedOperationType.Add) { TermGroup targetTermGroup = targetTermStore.GetGroup(sourceTermset.Group.Id); targetClientContext.Load(targetTermGroup, group => group.Name, group => group.IsSystemGroup, group => group.TermSets.Include( termSet => termSet.Name, termSet => termSet.Id)); targetClientContext.ExecuteQuery(); if (targetTermGroup.ServerObjectIsNull.Value) { //Group may exist with another name targetTermGroup = targetTermStore.Groups.GetByName(sourceTermset.Group.Name); targetClientContext.Load(targetTermGroup, group => group.Name, group => group.IsSystemGroup, group => group.TermSets.Include( termSet => termSet.Name, termSet => termSet.Id)); targetClientContext.ExecuteQuery(); if (targetTermGroup.ServerObjectIsNull.Value) { noError = false; break; } } TermSet targetTermSetCheck = targetTermGroup.TermSets.GetByName(sourceTermset.Name); targetClientContext.Load(targetTermSetCheck); try { targetClientContext.ExecuteQuery(); if (!targetTermSetCheck.ServerObjectIsNull.Value) { Console.WriteLine("Termset: " + sourceTermset.Name + " already exists"); continue; } } catch { } Console.WriteLine("Adding termset: " + sourceTermset.Name); targetTermGroup.CreateTermSet(sourceTermset.Name, _changeItem.Id, targetTermStore.DefaultLanguage); TermOperation op = new TermOperation(); op.Term = sourceTermset.Name; op.Id = _changeItem.Id.ToString(); op.Operation = "Add"; op.Type = "TermSet"; targetClientContext.ExecuteQuery(); targetTermStore.CommitAll(); targetTermStore.RefreshLoad(); _list.Add(op); } else if (_changeItem.Operation == ChangedOperationType.Edit) { TermGroup targetTermGroup = null; TermSet sourceTermSet = sourceTermStore.GetTermSet(_changeItem.Id); sourceClientContext.Load(sourceTermSet, termset => termset.Name); sourceClientContext.ExecuteQuery(); TermSet targetTermSet = targetTermStore.GetTermSet(_changeItem.Id); targetClientContext.Load(targetTermSet, termset => termset.Name); targetClientContext.ExecuteQuery(); if (targetTermSet.ServerObjectIsNull.Value) { targetTermGroup = targetTermStore.GetGroup(sourceTermset.Group.Id); targetClientContext.Load(targetTermGroup, group => group.Name, group => group.IsSystemGroup); targetClientContext.ExecuteQuery(); if (!targetTermGroup.ServerObjectIsNull.Value) { targetTermSet = targetTermGroup.TermSets.GetByName(sourceTermSet.Name); targetClientContext.Load(targetTermSet, termset => termset.Name); targetClientContext.ExecuteQuery(); } } if (!targetTermSet.ServerObjectIsNull.Value) { if (targetTermSet.Name != sourceTermSet.Name) { Console.WriteLine("Modifying termset: " + sourceTermSet.Name); targetTermSet.Name = sourceTermSet.Name; TermOperation op = new TermOperation(); op.Term = sourceTermSet.Name; op.Id = _changeItem.Id.ToString(); op.Operation = "Modify"; op.Type = "TermSet"; _list.Add(op); } } else { Console.WriteLine("Termset: " + sourceTermset.Name + " not found, creating it"); targetTermGroup.CreateTermSet(sourceTermset.Name, _changeItem.Id, targetTermStore.DefaultLanguage); TermOperation op = new TermOperation(); op.Term = sourceTermset.Name; op.Id = _changeItem.Id.ToString(); op.Operation = "Add"; op.Type = "TermSet"; _list.Add(op); } } } if (_changeItem.ItemType == ChangedItemType.Term) { Term sourceTerm = sourceTermStore.GetTerm(_changeItem.Id); sourceClientContext.Load(sourceTerm, term => term.Name, term => term.Description, term => term.Id, term => term.TermSet, termset => termset.Id); sourceClientContext.ExecuteQuery(); if (!sourceTerm.ServerObjectIsNull.Value) { TermSet sourceTermSet = sourceTermStore.GetTermSet(sourceTerm.TermSet.Id); sourceClientContext.Load(sourceTermSet, termset => termset.Name, termset => termset.Id, termset => termset.Group); sourceClientContext.ExecuteQuery(); if (!sourceTermSet.ServerObjectIsNull.Value) { if (!termSetNames.Contains(sourceTermSet.Name)) { continue; } } TermSet targetTermSet = targetTermStore.GetTermSet(sourceTerm.TermSet.Id); targetClientContext.Load(targetTermSet, termset => termset.Name); targetClientContext.ExecuteQuery(); if (targetTermSet.ServerObjectIsNull.Value) { noError = false; break; } if (_changeItem.Operation == ChangedOperationType.DeleteObject) { Term targetTerm = targetTermStore.GetTerm(_changeItem.Id); targetClientContext.Load(targetTerm); targetClientContext.ExecuteQuery(); Console.WriteLine("Deleting term: " + sourceTerm.Name); targetTerm.DeleteObject(); TermOperation op = new TermOperation(); op.Term = sourceTerm.Name; op.Id = _changeItem.Id.ToString(); op.Operation = "Delete"; op.Type = "Term"; _list.Add(op); } else if (_changeItem.Operation == ChangedOperationType.Add) { Term targetTerm = targetTermStore.GetTerm(sourceTerm.Id); targetClientContext.Load(targetTerm); targetClientContext.ExecuteQuery(); if (targetTerm.ServerObjectIsNull.Value) { Console.WriteLine("Creating term: " + sourceTerm.Name); Term _targetTerm = targetTermSet.CreateTerm(sourceTerm.Name, targetTermStore.DefaultLanguage, _changeItem.Id); if (!string.IsNullOrEmpty(sourceTerm.Description)) { _targetTerm.SetDescription(sourceTerm.Description, targetTermStore.DefaultLanguage); } //GetLabels from Source targetClientContext.ExecuteQuery(); TermOperation op = new TermOperation(); op.Term = sourceTerm.Name; op.Id = _changeItem.Id.ToString(); op.Operation = "Add"; op.Type = "Term"; _list.Add(op); } } else if (_changeItem.Operation == ChangedOperationType.Edit) { Term targetTerm = targetTermStore.GetTerm(_changeItem.Id); targetClientContext.Load(targetTerm, term => term.Name); targetClientContext.ExecuteQuery(); if (!targetTerm.ServerObjectIsNull.Value) { if (targetTerm.Name != sourceTerm.Name) { targetTerm.Name = sourceTerm.Name; TermOperation op = new TermOperation(); op.Term = sourceTerm.Name; op.Id = _changeItem.Id.ToString(); op.Operation = "Modify"; op.Type = "Term"; _list.Add(op); } } else { try { Term _targetTerm = targetTermSet.CreateTerm(sourceTerm.Name, targetTermStore.DefaultLanguage, _changeItem.Id); if (!string.IsNullOrEmpty(sourceTerm.Description)) { _targetTerm.SetDescription(sourceTerm.Description, targetTermStore.DefaultLanguage); } targetClientContext.ExecuteQuery(); Console.WriteLine("Term: " + sourceTerm.Name + " not found, creating it"); TermOperation op = new TermOperation(); op.Term = sourceTerm.Name; op.Id = _changeItem.Id.ToString(); op.Operation = "Add"; op.Type = "Term"; _list.Add(op); } catch { } } } } } } if (noError) { targetClientContext.ExecuteQuery(); targetTermStore.CommitAll(); } } }
public static void RePin() { Guid termSetGUID = new Guid("7ab9e8b0-e1e1-4a7c-9b20-d6c5030103df"); Guid srcTermSetGUID = new Guid("4d8916d8-e226-45f6-83bd-9f2b134cc264"); Guid srcDepartmentGUID = new Guid("eea07c73-7e2b-418d-96ff-1a2cdb4eb25c"); string siteUrl = "http://win-f33ohjutmmi/sites/cms"; ClientContext clientContext = new ClientContext(siteUrl); TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); taxonomySession.UpdateCache(); clientContext.Load(taxonomySession, ts => ts.TermStores); clientContext.ExecuteQuery(); if (taxonomySession.TermStores.Count == 0) { throw new InvalidOperationException("The Taxonomy Service is offline or missing"); } TermStore termStore = taxonomySession.TermStores[0]; clientContext.Load(termStore, ts => ts.Name, ts => ts.WorkingLanguage); clientContext.ExecuteQuery(); // Does the TermSet object already exist? TermSet existingTermSet; TermGroup siteCollectionGroup; siteCollectionGroup = termStore.GetSiteCollectionGroup(clientContext.Site, createIfMissing: true); existingTermSet = termStore.GetTermSet(termSetGUID); clientContext.Load(existingTermSet); clientContext.ExecuteQuery(); if (!existingTermSet.ServerObjectIsNull.Value) { existingTermSet.DeleteObject(); termStore.CommitAll(); clientContext.ExecuteQuery(); } TermSet termSet = siteCollectionGroup.CreateTermSet("CMSNavigationTermSet", termSetGUID, termStore.WorkingLanguage); clientContext.Load(termSet); termStore.CommitAll(); clientContext.ExecuteQuery(); //*******below code does not work, so commented it out*******// //NavigationTermSet navTermSet = NavigationTermSet.GetAsResolvedByWeb(clientContext, // termSet, clientContext.Web, "GlobalNavigationTaxonomyProvider"); //navTermSet.IsNavigationTermSet = true; //termStore.CommitAll(); //clientContext.ExecuteQuery(); //******* *******// Term srcTerm = null; Term targetTerm = null; //get the source termset srcTerm = termStore.GetTerm(srcDepartmentGUID); clientContext.Load(srcTerm); clientContext.ExecuteQuery(); if (!srcTerm.ServerObjectIsNull.Value) { targetTerm = termSet.ReuseTermWithPinning(srcTerm); targetTerm.CustomSortOrder = srcTerm.CustomSortOrder; termStore.CommitAll(); clientContext.ExecuteQuery(); } WebNavigationSettings navigationSettings = new WebNavigationSettings(clientContext, clientContext.Web); //******* this is weird, we have to reset the navigation to something else, then change it back to TaxonomyProvider, this way works. navigationSettings.GlobalNavigation.Source = StandardNavigationSource.PortalProvider; navigationSettings.Update(taxonomySession); clientContext.ExecuteQuery(); //*********************************// navigationSettings.GlobalNavigation.Source = StandardNavigationSource.TaxonomyProvider; navigationSettings.GlobalNavigation.TermStoreId = termStore.Id; navigationSettings.GlobalNavigation.TermSetId = termSet.Id; navigationSettings.Update(taxonomySession); //clientContext.Load(navigationSettings); clientContext.ExecuteQuery(); }
public static Term LookupTerm(SiteModelHost currentSiteModelHost, TermStore termStore, TaxonomyFieldDefinition termModel) { var context = currentSiteModelHost.HostClientContext; Term result = null; if (termModel.TermId.HasValue) { var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { result = termStore.GetTerm(termModel.TermId.Value); context.Load(result); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); } else if (!string.IsNullOrEmpty(termModel.TermName)) { var terms = termStore.GetTerms(new LabelMatchInformation(context) { Lcid = termModel.TermLCID, TermLabel = termModel.TermName, TrimUnavailable = false }); context.Load(terms); context.ExecuteQueryWithTrace(); result = terms.FirstOrDefault(); } if (result != null && result.ServerObjectIsNull == false) { context.Load(result); context.ExecuteQueryWithTrace(); return result; } return null; }
protected override void ExecuteCmdlet() { DefaultRetrievalExpressions = new Expression <Func <Term, object> >[] { g => g.Name, g => g.TermsCount, g => g.Id }; var taxonomySession = TaxonomySession.GetTaxonomySession(ClientContext); // Get Term Store TermStore termStore = null; if (TermStore == null) { termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); } else { if (TermStore.StringValue != null) { termStore = taxonomySession.TermStores.GetByName(TermStore.StringValue); } else if (TermStore.IdValue != Guid.Empty) { termStore = taxonomySession.TermStores.GetById(TermStore.IdValue); } else { if (TermStore.Item != null) { termStore = TermStore.Item; } } } if (ParameterSetName == ParameterSet_TERM) { if (Identity.IdValue != Guid.Empty) { term = termStore.GetTerm(Identity.IdValue); ClientContext.Load(term, RetrievalExpressions); ClientContext.ExecuteQueryRetry(); if (IncludeChildTerms.IsPresent && term.TermsCount > 0) { LoadChildTerms(term); } WriteObject(term); } else { WriteError(new ErrorRecord(new Exception("Insufficient parameters"), "INSUFFICIENTPARAMETERS", ErrorCategory.SyntaxError, this)); } } else { TermGroup termGroup = null; if (TermGroup != null && TermGroup.Id != Guid.Empty) { termGroup = termStore.Groups.GetById(TermGroup.Id); } else if (TermGroup != null && !string.IsNullOrEmpty(TermGroup.Name)) { termGroup = termStore.Groups.GetByName(TermGroup.Name); } TermSet termSet = null; if (TermSet != null) { if (TermSet.Id != Guid.Empty) { termSet = termGroup.TermSets.GetById(TermSet.Id); } else if (!string.IsNullOrEmpty(TermSet.Title)) { termSet = termGroup.TermSets.GetByName(TermSet.Title); } else { termSet = TermSet.Item; } } if (Identity != null) { term = null; if (Identity.IdValue != Guid.Empty) { term = termStore.GetTerm(Identity.IdValue); } else { var termName = TaxonomyExtensions.NormalizeName(Identity.StringValue); if (!Recursive) { term = termSet.Terms.GetByName(termName); } else { var lmi = new LabelMatchInformation(ClientContext) { TrimUnavailable = true, TermLabel = termName }; var termMatches = termSet.GetTerms(lmi); ClientContext.Load(termMatches); ClientContext.ExecuteQueryRetry(); if (termMatches.AreItemsAvailable) { term = termMatches.FirstOrDefault(); } } } ClientContext.Load(term, RetrievalExpressions); ClientContext.ExecuteQueryRetry(); if (IncludeChildTerms.IsPresent && term.TermsCount > 0) { LoadChildTerms(term); } WriteObject(term); } else { var query = termSet.Terms.IncludeWithDefaultProperties(RetrievalExpressions); var terms = ClientContext.LoadQuery(query); ClientContext.ExecuteQueryRetry(); if (IncludeChildTerms.IsPresent) { foreach (var collectionTerm in terms) { if (collectionTerm.TermsCount > 0) { LoadChildTerms(collectionTerm); } } } WriteObject(terms, true); } } }
protected override void ExecuteCmdlet() { DefaultRetrievalExpressions = new Expression <Func <Term, object> >[] { g => g.Name, g => g.TermsCount, g => g.Id }; var taxonomySession = TaxonomySession.GetTaxonomySession(ClientContext); // Get Term Store TermStore termStore = null; if (TermStore == null) { termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); } else { termStore = TermStore.GetTermStore(taxonomySession); } if (ParameterSetName == ParameterSet_TERMID) { if (Identity.Id != Guid.Empty) { term = termStore.GetTerm(Identity.Id); ClientContext.Load(term, RetrievalExpressions); ClientContext.ExecuteQueryRetry(); if (IncludeChildTerms.IsPresent && term.TermsCount > 0) { LoadChildTerms(term); } WriteObject(term); } else { throw new PSArgumentException("Insufficient Parameters specified to determine the term to retrieve"); } } else { TermGroup termGroup = TermGroup.GetGroup(termStore); TermSet termSet = TermSet.GetTermSet(termGroup); if (Identity != null && ParentTerm == null) { var term = Identity.GetTerm(ClientContext, termStore, termSet, Recursive, RetrievalExpressions); if (IncludeChildTerms.IsPresent && term.TermsCount > 0) { LoadChildTerms(term); } WriteObject(term); } else if (Identity != null && ParentTerm != null) { var term = ParentTerm.GetTerm(ClientContext, termStore, termSet, Recursive, RetrievalExpressions); if (IncludeChildTerms.IsPresent && term.TermsCount > 0) { LoadChildTerms(term); } WriteObject(term); } else { var query = termSet.Terms.IncludeWithDefaultProperties(RetrievalExpressions); var terms = ClientContext.LoadQuery(query); ClientContext.ExecuteQueryRetry(); if (IncludeChildTerms.IsPresent) { foreach (var collectionTerm in terms) { if (collectionTerm.TermsCount > 0) { LoadChildTerms(collectionTerm); } } } WriteObject(terms, true); } } }
private void CreateNewTargetTermGroup(ClientContext sourceClientContext, ClientContext targetClientContext, TermGroup sourceTermGroup, TermStore targetTermStore, List<int> languagesToProcess) { TermGroup destinationTermGroup = targetTermStore.CreateGroup(sourceTermGroup.Name, sourceTermGroup.Id); if (!string.IsNullOrEmpty(sourceTermGroup.Description)) { destinationTermGroup.Description = sourceTermGroup.Description; } TermSetCollection sourceTermSetCollection = sourceTermGroup.TermSets; if (sourceTermSetCollection.Count > 0) { foreach (TermSet sourceTermSet in sourceTermSetCollection) { sourceClientContext.Load(sourceTermSet, set => set.Name, set => set.Description, set => set.Id, set => set.Contact, set => set.CustomProperties, set => set.IsAvailableForTagging, set => set.IsOpenForTermCreation, set => set.CustomProperties, set => set.Terms.Include( term => term.Name, term => term.Description, term => term.Id, term => term.IsAvailableForTagging, term => term.LocalCustomProperties, term => term.CustomProperties, term => term.IsDeprecated, term => term.Labels.Include(label => label.Value, label => label.Language, label => label.IsDefaultForLanguage))); sourceClientContext.ExecuteQuery(); TermSet targetTermSet = destinationTermGroup.CreateTermSet(sourceTermSet.Name, sourceTermSet.Id, targetTermStore.DefaultLanguage); targetClientContext.Load(targetTermSet, set => set.CustomProperties); targetClientContext.ExecuteQuery(); UpdateTermSet(sourceClientContext, targetClientContext, sourceTermSet, targetTermSet); foreach (Term sourceTerm in sourceTermSet.Terms) { Term reusedTerm = targetTermStore.GetTerm(sourceTerm.Id); targetClientContext.Load(reusedTerm); targetClientContext.ExecuteQuery(); Term targetTerm; if (reusedTerm.ServerObjectIsNull.Value) { try { targetTerm = targetTermSet.CreateTerm(sourceTerm.Name, targetTermStore.DefaultLanguage, sourceTerm.Id); targetClientContext.Load(targetTerm, term => term.IsDeprecated, term => term.CustomProperties, term => term.LocalCustomProperties); targetClientContext.ExecuteQuery(); UpdateTerm(sourceClientContext, targetClientContext, sourceTerm, targetTerm, languagesToProcess); } catch (ServerException ex) { if (ex.Message.IndexOf("Failed to read from or write to database. Refresh and try again.") > -1) { // This exception was due to caching issues and generally is thrown when there's term reuse accross groups targetTerm = targetTermSet.ReuseTerm(reusedTerm, false); } else { throw ex; } } } else { targetTerm = targetTermSet.ReuseTerm(reusedTerm, false); } targetClientContext.Load(targetTerm); targetClientContext.ExecuteQuery(); targetTermStore.UpdateCache(); //Refresh session and termstore references to force reload of the term just added. This is //needed cause there can be a update change event following next and without this trick //the newly created termset cannot be obtained from the server targetTermStore = GetTermStoreObject(targetClientContext); //recursively add the other terms ProcessSubTerms(sourceClientContext, targetClientContext, targetTermSet, targetTerm, sourceTerm, languagesToProcess, targetTermStore.DefaultLanguage); } } } targetClientContext.ExecuteQuery(); }
private void CreateTerm(ClientContext context, TermStore termStore, ShTerm shTerm, TermSetItem parentTerm) { var spTerm = termStore.GetTerm(shTerm.Id); context.Load(spTerm, t => t.Terms); context.ExecuteQuery(); if (spTerm.ServerObjectIsNull != null && spTerm.ServerObjectIsNull.Value) { spTerm = parentTerm.CreateTerm(shTerm.Title, termStore.DefaultLanguage, shTerm.Id); if (!string.IsNullOrEmpty(shTerm.CustomSortOrder)) spTerm.CustomSortOrder = shTerm.CustomSortOrder; spTerm.IsAvailableForTagging = !shTerm.NotAvailableForTagging; foreach(var prop in shTerm.CustomProperties) { spTerm.SetCustomProperty(prop.Key, prop.Value); } foreach (var prop in shTerm.LocalCustomProperties) { spTerm.SetLocalCustomProperty(prop.Key, prop.Value); } context.Load(spTerm); context.ExecuteQuery(); } foreach (ShTerm childTerm in shTerm.Terms) { CreateTerm(context, termStore, childTerm, spTerm); } }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] GetTermPropertyRequest request, TraceWriter log) { string siteUrl = request.SiteURL; try { if (string.IsNullOrWhiteSpace(request.SiteURL)) { throw new ArgumentException("Parameter cannot be null", "SiteURL"); } if (string.IsNullOrWhiteSpace(request.TermGUID)) { throw new ArgumentException("Parameter cannot be null", "TermGUID"); } if (string.IsNullOrWhiteSpace(request.PropertyName)) { throw new ArgumentException("Parameter cannot be null", "PropertyName"); } if (string.IsNullOrWhiteSpace(request.FallbackValue)) { request.FallbackValue = ""; } var clientContext = await ConnectADAL.GetClientContext(siteUrl, log); TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); clientContext.Load(taxonomySession); clientContext.ExecuteQueryRetry(); TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); var term = termStore.GetTerm(new Guid(request.TermGUID)); clientContext.Load(term, t => t.LocalCustomProperties); clientContext.ExecuteQueryRetry(); var propertyValue = string.Empty; do { if (term.LocalCustomProperties.Keys.Contains(request.PropertyName)) { propertyValue = term.LocalCustomProperties[request.PropertyName]; } else { term = term.Parent; clientContext.Load(term, t => t.LocalCustomProperties); clientContext.ExecuteQueryRetry(); } } while (string.IsNullOrWhiteSpace(propertyValue)); var getTermPropertyResponse = new GetTermPropertyResponse { PropertyValue = propertyValue }; return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new ObjectContent <GetTermPropertyResponse>(getTermPropertyResponse, new JsonMediaTypeFormatter()) })); } catch (Exception) { var getTermPropertyResponse = new GetTermPropertyResponse { PropertyValue = request.FallbackValue }; return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new ObjectContent <GetTermPropertyResponse>(getTermPropertyResponse, new JsonMediaTypeFormatter()) })); } }
public static Term LookupTerm(ClientContext clientContext, TermStore termStore, TermSet termSet, TaxonomyFieldDefinition termModel) { var context = clientContext; var site = clientContext.Site; Term result = null; TermGroup currenGroup = null; var termGroupName = termModel.TermGroupName; var termGroupId = termModel.TermGroupId; var isSiteCollectionGroup = termModel.IsSiteCollectionGroup; if (!string.IsNullOrEmpty(termGroupName)) { currenGroup = termStore.Groups.GetByName(termGroupName); context.Load(currenGroup); context.ExecuteQueryWithTrace(); } else if (termGroupId != null && termGroupId.HasGuidValue()) { currenGroup = termStore.Groups.GetById(termGroupId.Value); context.Load(currenGroup); context.ExecuteQueryWithTrace(); } else if (isSiteCollectionGroup == true) { currenGroup = termStore.GetSiteCollectionGroup(site, false); context.Load(currenGroup); context.ExecuteQueryWithTrace(); } if (currenGroup != null) { if (termModel.TermId.HasValue) { // by ID, the only one match var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { result = termStore.GetTerm(termModel.TermId.Value); context.Load(result); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); } else if (!string.IsNullOrEmpty(termModel.TermName)) { var terms = termStore.GetTerms(new LabelMatchInformation(context) { Lcid = termModel.TermLCID, TermLabel = termModel.TermName, TrimUnavailable = false }); context.Load(terms, t => t.Include( i => i.Id, i => i.Name, i => i.TermSet, i => i.TermSet.Group, i => i.TermSet.Group.Name )); context.ExecuteQueryWithTrace(); result = terms.FirstOrDefault(t => t.TermSet.Group.Name == currenGroup.Name); if ((result == null) && (termSet != null)) // sometimes label match information does not return the term { var allTerms = termSet.GetAllTerms(); context.Load(allTerms, t => t.Include( i => i.Id, i => i.Name, i => i.TermSet, i => i.TermSet.Group, i => i.TermSet.Group.Name, i => i.Labels )); context.ExecuteQueryWithTrace(); result = allTerms.FirstOrDefault(t => (t.TermSet.Group.Name == currenGroup.Name) && (t.Labels.Any(l => l.Value == termModel.TermName && l.Language == termModel.TermLCID))); } } } else { if (termModel.TermId.HasValue) { var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { result = termStore.GetTerm(termModel.TermId.Value); context.Load(result); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); } else if (!string.IsNullOrEmpty(termModel.TermName)) { var terms = termStore.GetTerms(new LabelMatchInformation(context) { Lcid = termModel.TermLCID, TermLabel = termModel.TermName, TrimUnavailable = false }); context.Load(terms); context.ExecuteQueryWithTrace(); result = terms.FirstOrDefault(); if ((result == null) && (termSet != null)) // sometimes label match information does not return the termset { var allTerms = termSet.GetAllTerms(); context.Load(allTerms, t => t.Include( i => i.Id, i => i.Name, i => i.TermSet, i => i.TermSet.Group, i => i.TermSet.Group.Name, i => i.Labels )); context.ExecuteQueryWithTrace(); result = allTerms.FirstOrDefault( t => (t.Labels.Any(l => l.Value == termModel.TermName && l.Language == termModel.TermLCID))); } } } if (result != null && result.ServerObjectIsNull == false) { context.Load(result); context.ExecuteQueryWithTrace(); return(result); } return(null); }