/// <summary> /// Create client terms /// </summary> /// <param name="TermsData">Data for client terms</param> /// <param name="clientContext">Client Context object</param> private static void CreateTermsForClients(List <CustomClientGroup> TermsData, ClientContext clientContext) { TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); clientContext.Load(taxonomySession.TermStores); //Execute the query to the server clientContext.ExecuteQuery(); TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); clientContext.Load(termStore.Groups); //Execute the query to the server clientContext.ExecuteQuery(); foreach (CustomClientGroup cltGroup in TermsData) { TermGroup group = termStore.Groups.Where(termGroup => termGroup.Name == cltGroup.name).Count() > 0 ? termStore.Groups.GetByName(cltGroup.name) : termStore.CreateGroup(cltGroup.name, Guid.NewGuid()); if (null != group) { TermSet cltTermSet = group.CreateTermSet(ConfigurationManager.AppSettings["clientterm"], Guid.NewGuid(), 1033); TermSet cltIDTermSet = group.CreateTermSet(ConfigurationManager.AppSettings["clientidterm"], Guid.NewGuid(), 1033); foreach (ClientList clients in cltGroup.clt) { Term clientCustom = cltTermSet.CreateTerm(clients.ClientName, 1033, Guid.NewGuid()); cltIDTermSet.CreateTerm(clients.ClientID, 1033, Guid.NewGuid()); clientCustom.SetCustomProperty("ClientID", clients.ClientID); clientCustom.SetCustomProperty("ClientURL", clients.ClientURL); } } } termStore.CommitAll(); clientContext.Load(termStore); //Execute the query to the server clientContext.ExecuteQuery(); }
public void GetTermSetIds(TaxonomyTypes taxonomyType, string termSetName, string groupName, bool createIfNotExisting, out Guid termStoreId, out Guid termSetId) { TermStore termStore; TermSet termSet; Site site = _clientContext.Site; GetTermSet(taxonomyType, termSetName, groupName, createIfNotExisting, out termStore, out termSet); if (termSet == null) { if (!createIfNotExisting) { throw new KeyNotFoundException("Taxonomy missing"); } TermGroup termGroup = groupName == null ? termStore.GetSiteCollectionGroup(site, createIfNotExisting) : termStore.GetTermGroupByName(groupName); termSetId = Guid.NewGuid(); TermSet termSetColl = termGroup.CreateTermSet(termSetName, termSetId, Lcid); termSetColl.IsOpenForTermCreation = true; _clientContext.Load(termGroup.TermSets); _clientContext.ExecuteQuery(); termSet = termGroup.TermSets.FirstOrDefault(ts => ts.Name == termSetName); } _clientContext.Load(termStore, ts => ts.Id); _clientContext.ExecuteQuery(); termStoreId = termStore.Id; termSetId = termSet == null ? Guid.Empty : termSet.Id; }
//ModifyItem //CreateTermSet public void CreateTermSet(ClientContext context) { //English(Default English Locale ID) int lcid = 1033; //Get termSession TaxonomySession taxonomy = TaxonomySession.GetTaxonomySession(context); if (taxonomy != null) { //Get TermStore TermStore termStore = taxonomy.GetDefaultKeywordsTermStore(); if (termStore != null) { //Set TermGroup TermGroup termGroup = termStore.CreateGroup(TERMGROUPNAME, Guid.NewGuid()); //Set TermSet TermSet termSetCollection = termGroup.CreateTermSet(TERMSETNAME, Guid.NewGuid(), lcid); //Set Terms termSetCollection.CreateTerm(TERM_ELEKTRONIK, lcid, Guid.NewGuid()); termSetCollection.CreateTerm(TERM_FORDON, lcid, Guid.NewGuid()); termSetCollection.CreateTerm(TERM_FRITIDOCHHOBBY, lcid, Guid.NewGuid()); termSetCollection.CreateTerm(TERM_HYGIENARTIKLAR, lcid, Guid.NewGuid()); termSetCollection.CreateTerm(TERM_MÖBLER, lcid, Guid.NewGuid()); context.ExecuteQuery(); } } }
public static void CreateProductTaxonomy(ClientContext ctx) { TermStore store = ctx.Site.GetDefaultKeywordsTermStore(); TermGroup productCategoryGroup = store.GetTermGroupByName("OD2"); if (productCategoryGroup == null) { productCategoryGroup = store.CreateTermGroup("OD2", Constants.TAXONOMY_OD2_GROUP_ID.ToGuid(), "Stuff for od2"); } TermSet ts = store.GetTermSet(Constants.TAXONOMY_PRODUCTCAT_TERMSET_ID.ToGuid()); ctx.Load(ts); ctx.ExecuteQuery(); // if term store does not exist create a new one. if (ts.ServerObjectIsNull.Value) { ts = productCategoryGroup.CreateTermSet("Product Category", Constants.TAXONOMY_PRODUCTCAT_TERMSET_ID.ToGuid(), 1033); store.CommitAll(); ctx.Load(ts); ctx.ExecuteQuery(); ts.CreateTerm("Prod Cat 1", 1033, Guid.NewGuid()); ts.CreateTerm("Prod Cat 2", 1033, Guid.NewGuid()); ts.CreateTerm("Prod Cat 3", 1033, Guid.NewGuid()); ts.CreateTerm("Prod Cat 4", 1033, Guid.NewGuid()); store.CommitAll(); ctx.ExecuteQuery(); } }
private static void CreateNecessaryMMSTermsToCloud(ClientContext cc) { // Get access to taxonomy CSOM TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(cc); cc.Load(taxonomySession); cc.ExecuteQuery(); if (taxonomySession != null) { TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); if (termStore != null) { // // Create group, termset, and terms. // TermGroup myGroup = termStore.CreateGroup("Custom", Guid.NewGuid()); TermSet myTermSet = myGroup.CreateTermSet("Colors", Guid.NewGuid(), 1033); myTermSet.CreateTerm("Red", 1033, Guid.NewGuid()); myTermSet.CreateTerm("Orange", 1033, Guid.NewGuid()); myTermSet.CreateTerm("Yellow", 1033, Guid.NewGuid()); myTermSet.CreateTerm("Green", 1033, Guid.NewGuid()); myTermSet.CreateTerm("Blue", 1033, Guid.NewGuid()); myTermSet.CreateTerm("Purple", 1033, Guid.NewGuid()); cc.ExecuteQuery(); } } }
public static void CreateProductCategoriesTermset() { string termSetName = "Product Categories"; var aspnetHttpContext = System.Web.HttpContext.Current; var spContext = SharePointContextProvider.Current.GetSharePointContext(aspnetHttpContext); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { Site siteCollection = clientContext.Site; clientContext.Load(siteCollection, sc => sc.Url); clientContext.ExecuteQuery(); TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); taxonomySession.UpdateCache(); clientContext.Load(taxonomySession, ts => ts.TermStores); clientContext.ExecuteQuery(); TermStore termStore = taxonomySession.TermStores.FirstOrDefault <TermStore>(); Guid localTermStoreID = termStore.Id; TermGroup group = termStore.GetSiteCollectionGroup(siteCollection, true); clientContext.Load(group); clientContext.Load(group.TermSets); clientContext.ExecuteQuery(); // make sure it's deleted if exists foreach (TermSet termset in group.TermSets) { if (termset.Name.Equals(termSetName)) { termset.DeleteObject(); termStore.CommitAll(); clientContext.ExecuteQuery(); } } Guid termSetId = Guid.NewGuid(); TermSet tset = group.CreateTermSet(termSetName, termSetId, 1033); termStore.CommitAll(); clientContext.ExecuteQuery(); foreach (var term in terms) { CreateTopLevelTerm(tset, term); } termStore.CommitAll(); clientContext.ExecuteQuery(); clientContext.ExecuteQuery(); termStore.CommitAll(); } } }
public static TermSet GenerateTermSet(this TermGroup group, string name, Guid guid, int lcid = 1033) { group.Context.Load(group.TermSets); group.Context.ExecuteQuery(); var termSet = group.TermSets.FirstOrDefault(ts => ts.Name == name); if (termSet == null) { termSet = group.CreateTermSet(name, guid, lcid); } return(termSet); }
//gavdcodeend 03 //gavdcodebegin 04 static void SpCsCsomCreateTermSet(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.CreateTermSet( "CsCsomTermSet", Guid.NewGuid(), 1033); spCtx.ExecuteQuery(); }
public SPOTermSet CreateTermSet(string name, Guid id, int lcid, string contact, string description, string customSortOrder, bool isAvailableForTagging, string owner, bool isOpenForTermCreation) { var ctx = _termGroup.Context; TermSet termSet = null; ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx); using (scope.StartScope()) { using (scope.StartTry()) { termSet = _termGroup.TermSets.GetByName(name); ctx.Load(termSet); } using (scope.StartCatch()) { } } ctx.ExecuteQuery(); if (termSet == null || termSet.ServerObjectIsNull == null || termSet.ServerObjectIsNull.Value) { if (lcid == 0) { lcid = GetWorkingLanguage(_termGroup.TermStore); } if (string.IsNullOrEmpty(owner)) { var web = SPOSiteContext.CurrentSiteContext.Context.Web; ctx.Load(web, w => w.CurrentUser); ctx.ExecuteQuery(); owner = web.CurrentUser.LoginName; } termSet = _termGroup.CreateTermSet(name, id, lcid); termSet.Contact = contact; termSet.Description = description; termSet.CustomSortOrder = customSortOrder; termSet.IsAvailableForTagging = isAvailableForTagging; termSet.Owner = owner; termSet.IsOpenForTermCreation = isOpenForTermCreation; ctx.Load(termSet); ctx.ExecuteQuery(); return(new SPOTermSet(termSet)); } else { throw new Exception("The specified term set already exists."); } }
public TermSet CreateTermSet(TermGroup group, string termsetname) { Ctx.Load(group.TermSets); Ctx.ExecuteQuery(); TermSet set = group.TermSets.FirstOrDefault(x => x.Name == termsetname); if (set == null) { set = group.CreateTermSet(termsetname, Guid.NewGuid(), LCID); Ctx.Load(set); Ctx.ExecuteQuery(); } return(set); }
/// <summary> /// Create practice group terms /// </summary> /// <param name="TermsData">Practice group, SAOL and AOL data</param> /// <param name="clientContext">Client context object</param> private static void CreatePGTerms(List <CustomTermGroup> TermsData, ClientContext clientContext) { TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); clientContext.Load(taxonomySession.TermStores); //Execute the query to the server clientContext.ExecuteQuery(); TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); clientContext.Load(termStore.Groups); //Execute the query to the server clientContext.ExecuteQuery(); foreach (CustomTermGroup termGroup in TermsData) { TermGroup group = termStore.Groups.Where(groupProperties => groupProperties.Name == termGroup.name).Count() > 0 ? termStore.Groups.GetByName(termGroup.name) : termStore.CreateGroup(termGroup.name, Guid.NewGuid()); TermSet pracGrp = group.CreateTermSet(ConfigurationManager.AppSettings["pgterm"], Guid.NewGuid(), 1033); foreach (CustomPracticeGroup pg in termGroup.Pg) { if (!string.IsNullOrWhiteSpace(pg.name)) { Console.WriteLine("Creating practice group " + pg.name); Term pgTermSet = pracGrp.CreateTerm(pg.name, 1033, Guid.NewGuid()); if (pg.properties.ContainsKey("PGFolders") && !string.IsNullOrWhiteSpace(pg.properties["PGFolders"])) { pgTermSet.SetCustomProperty("FolderNames", pg.properties["PGFolders"]); } foreach (CustomAreaOfLaw aol in pg.Aol) { if (!string.IsNullOrWhiteSpace(aol.name)) { Console.WriteLine("\tCreating area of law " + aol.name); Term AOLTerm = pgTermSet.CreateTerm(aol.name, 1033, Guid.NewGuid()); if (aol.properties.ContainsKey("AOLFolders") && !string.IsNullOrWhiteSpace(aol.properties["AOLFolders"])) { AOLTerm.SetCustomProperty("FolderNames", aol.properties["AOLFolders"]); } CustomArea(aol, AOLTerm); } } } } } termStore.CommitAll(); clientContext.Load(termStore); //Execute the query to the server clientContext.ExecuteQuery(); }
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; } } }
private static TermSet AddTermSet(ClientContext clientContext, TermStore termStore, TermGroup termGroup) { var termSetId = new Guid("56ca0eea-635e-4cc1-ac35-fc2040f4cfe5"); var termSet = termStore.GetTermSet(termSetId); clientContext.Load(termSet, ts => ts.Terms); clientContext.ExecuteQuery(); if (termSet.ServerObjectIsNull.Value) { termSet = termGroup.CreateTermSet("Taxonomy Navigation", termSetId, 1033); termSet.SetCustomProperty("_Sys_Nav_IsNavigationTermSet", "True"); clientContext.Load(termSet, ts => ts.Terms); clientContext.ExecuteQuery(); } return termSet; }
private static TermSet AddTermSet(ClientContext clientContext, TermStore termStore, TermGroup termGroup) { var termSetId = new Guid("56ca0eea-635e-4cc1-ac35-fc2040f4cfe5"); var termSet = termStore.GetTermSet(termSetId); clientContext.Load(termSet, ts => ts.Terms); clientContext.ExecuteQuery(); if (termSet.ServerObjectIsNull.Value) { termSet = termGroup.CreateTermSet("Taxonomy Navigation", termSetId, 1033); termSet.SetCustomProperty("_Sys_Nav_IsNavigationTermSet", "True"); clientContext.Load(termSet, ts => ts.Terms); clientContext.ExecuteQuery(); } return(termSet); }
// NOTE: The user account referenced in the SPOUserName setting in App.Config file must be a Term Store Administrator // in order to to create Terms in Term Store // This is granted in the SharePoint Admin site (for example:https://<yourtenant>-admin.sharepoint.com/_layouts/15/termstoremanager.aspx) static void CreateTermsInTermStore(string siteUrl, string userName, string userPassword) { try { //get client context ClientContext context = GetUserContext(siteUrl, userName, userPassword); TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(context); context.Load(taxSession); context.ExecuteQuery(); if (taxSession != null) { TermStore termStore = taxSession.GetDefaultSiteCollectionTermStore(); if (termStore != null) { // // Create group, termset, and terms. // TermGroup myGroup = termStore.CreateGroup("Custom", Guid.NewGuid()); TermSet myTermSet = myGroup.CreateTermSet("Countries", Guid.NewGuid(), 1033); myTermSet.CreateTerm("United States of America", 1033, Guid.NewGuid()); myTermSet.CreateTerm("Canada", 1033, Guid.NewGuid()); myTermSet.CreateTerm("Mexico", 1033, Guid.NewGuid()); myTermSet.CreateTerm("India", 1033, Guid.NewGuid()); myTermSet.CreateTerm("Thailand", 1033, Guid.NewGuid()); myTermSet.CreateTerm("Australia", 1033, Guid.NewGuid()); context.ExecuteQuery(); } } } catch (ClientRequestException clientEx) { Console.WriteLine("Client side error occurred: {0} \n{1} " + clientEx.Message + clientEx.InnerException); throw clientEx; } catch (ServerException serverEx) { Console.WriteLine("Server side error occurred: {0} \n{1} " + serverEx.Message + serverEx.InnerException); throw serverEx; } }
static TermSet CreateTermset(ClientContext clientContext, TermGroup termGroup, string termSetName) { // delete termset if it already exists foreach (TermSet termset in termGroup.TermSets) { if (termset.Name.Equals(termSetName)) { termset.DeleteObject(); termGroup.TermStore.CommitAll(); clientContext.ExecuteQuery(); } } Guid termSetId = Guid.NewGuid(); TermSet newTermSet = termGroup.CreateTermSet(termSetName, termSetId, 1033); newTermSet.IsOpenForTermCreation = true; termGroup.TermStore.CommitAll(); clientContext.Load(newTermSet); clientContext.ExecuteQuery(); return newTermSet; }
static TermSet CreateTermset(ClientContext clientContext, TermGroup termGroup, string termSetName) { // delete termset if it already exists foreach (TermSet termset in termGroup.TermSets) { if (termset.Name.Equals(termSetName)) { termset.DeleteObject(); termGroup.TermStore.CommitAll(); clientContext.ExecuteQuery(); } } Guid termSetId = Guid.NewGuid(); TermSet newTermSet = termGroup.CreateTermSet(termSetName, termSetId, 1033); newTermSet.IsOpenForTermCreation = true; termGroup.TermStore.CommitAll(); clientContext.Load(newTermSet); clientContext.ExecuteQuery(); return(newTermSet); }
public void CreateDepartmentTermSet() { TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); clientContext.Load(taxonomySession, ts => ts.TermStores.Include( store => store.Name, store => store.Groups.Include( group => group.Name ) ) ); clientContext.ExecuteQuery(); if (taxonomySession != null) { TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); if (termStore != null) { // // Create group, termset, and terms. // TermGroup myGroup = termStore.CreateGroup("DemoDepartment", Guid.NewGuid()); TermSet myTermSet = myGroup.CreateTermSet("DepartmentSet", Guid.NewGuid(), 1033); myTermSet.CreateTerm("HR", 1033, Guid.NewGuid()); myTermSet.CreateTerm("Finance", 1033, Guid.NewGuid()); myTermSet.CreateTerm("Commercial", 1033, Guid.NewGuid()); myTermSet.CreateTerm("Food and Drink", 1033, Guid.NewGuid()); myTermSet.CreateTerm("Support", 1033, Guid.NewGuid()); var parentIt = myTermSet.CreateTerm("IT", 1033, Guid.NewGuid()); parentIt.CreateTerm("IT Test 1", 1033, Guid.NewGuid()); parentIt.CreateTerm("IT Test 2", 1033, Guid.NewGuid()); clientContext.ExecuteQuery(); } } }
private void CreateTargetNewTermGroup(ClientContext sourceClientContext, ClientContext targetClientContext, TermGroup sourceTermGroup, TermStore targetTermStore) { try { this._destinationTermGroup = targetTermStore.CreateGroup(sourceTermGroup.Name, sourceTermGroup.Id); if(!string.IsNullOrEmpty(sourceTermGroup.Description)) { this._destinationTermGroup.Description = sourceTermGroup.Description; } TermOperation _op = new TermOperation(); _op.Term = sourceTermGroup.Name; _op.Id = sourceTermGroup.Id.ToString(); _op.Operation = "Add"; _op.Type = "TermGroup"; this._termStoreOperations.Add(_op); 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.Terms.Include( term => term.Name, term => term.Id), term => term.Description, term => term.Contact); sourceClientContext.ExecuteQuery(); TermSet _targetTermSet = _destinationTermGroup.CreateTermSet(_sourceTermSet.Name, _sourceTermSet.Id, targetTermStore.DefaultLanguage); if(!string.IsNullOrEmpty(_sourceTermSet.Description)) { _targetTermSet.Description = _sourceTermSet.Description; } foreach(Term _sourceTerm in _sourceTermSet.Terms) { Term _targetTerm = _targetTermSet.CreateTerm(_sourceTerm.Name, targetTermStore.DefaultLanguage, _sourceTerm.Id); _op = new TermOperation(); _op.Term = _sourceTerm.Name; _op.Id = _sourceTerm.Id.ToString(); _op.Operation = "Add"; _op.Type = "Term"; this._termStoreOperations.Add(_op); } } } try { targetClientContext.ExecuteQuery(); targetTermStore.CommitAll(); } catch { throw; } } catch { throw; } }
private void CreateTargetNewTermGroup(ClientContext sourceClientContext, ClientContext targetClientContext, TermGroup sourceTermGroup, TermStore targetTermStore) { try { this._destinationTermGroup = targetTermStore.CreateGroup(sourceTermGroup.Name, sourceTermGroup.Id); if (!string.IsNullOrEmpty(sourceTermGroup.Description)) { this._destinationTermGroup.Description = sourceTermGroup.Description; } TermOperation _op = new TermOperation(); _op.Term = sourceTermGroup.Name; _op.Id = sourceTermGroup.Id.ToString(); _op.Operation = "Add"; _op.Type = "TermGroup"; this._termStoreOperations.Add(_op); 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.Terms.Include( term => term.Name, term => term.Id), term => term.Description, term => term.Contact); sourceClientContext.ExecuteQuery(); TermSet _targetTermSet = _destinationTermGroup.CreateTermSet(_sourceTermSet.Name, _sourceTermSet.Id, targetTermStore.DefaultLanguage); if (!string.IsNullOrEmpty(_sourceTermSet.Description)) { _targetTermSet.Description = _sourceTermSet.Description; } foreach (Term _sourceTerm in _sourceTermSet.Terms) { Term _targetTerm = _targetTermSet.CreateTerm(_sourceTerm.Name, targetTermStore.DefaultLanguage, _sourceTerm.Id); _op = new TermOperation(); _op.Term = _sourceTerm.Name; _op.Id = _sourceTerm.Id.ToString(); _op.Operation = "Add"; _op.Type = "Term"; this._termStoreOperations.Add(_op); } } } try { targetClientContext.ExecuteQuery(); targetTermStore.CommitAll(); } catch { throw; } } catch { throw; } }
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 override TokenParser ProvisionObjects(Web web, Model.ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(this.Name)) { TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(web.Context); var termStore = taxSession.GetDefaultKeywordsTermStore(); web.Context.Load(termStore, ts => ts.DefaultLanguage, ts => ts.Groups.Include( tg => tg.Name, tg => tg.Id, tg => tg.TermSets.Include( tset => tset.Name, tset => tset.Id))); web.Context.ExecuteQueryRetry(); SiteCollectionTermGroupNameToken siteCollectionTermGroupNameToken = new SiteCollectionTermGroupNameToken(web); foreach (var modelTermGroup in template.TermGroups) { #region Group var newGroup = false; TermGroup group = termStore.Groups.FirstOrDefault( g => g.Id == modelTermGroup.Id || g.Name == modelTermGroup.Name); if (group == null) { if (modelTermGroup.Name == "Site Collection" || parser.ParseString(modelTermGroup.Name) == siteCollectionTermGroupNameToken.GetReplaceValue() || modelTermGroup.SiteCollectionTermGroup) { var site = (web.Context as ClientContext).Site; group = termStore.GetSiteCollectionGroup(site, true); web.Context.Load(group, g => g.Name, g => g.Id, g => g.TermSets.Include( tset => tset.Name, tset => tset.Id)); web.Context.ExecuteQueryRetry(); } else { var parsedGroupName = parser.ParseString(modelTermGroup.Name); group = termStore.Groups.FirstOrDefault(g => g.Name == parsedGroupName); if (group == null) { if (modelTermGroup.Id == Guid.Empty) { modelTermGroup.Id = Guid.NewGuid(); } group = termStore.CreateGroup(parsedGroupName, modelTermGroup.Id); group.Description = modelTermGroup.Description; #if !ONPREMISES // Handle TermGroup Contributors, if any if (modelTermGroup.Contributors != null && modelTermGroup.Contributors.Count > 0) { foreach (var c in modelTermGroup.Contributors) { group.AddContributor(c.Name); } } // Handle TermGroup Managers, if any if (modelTermGroup.Managers != null && modelTermGroup.Managers.Count > 0) { foreach (var m in modelTermGroup.Managers) { group.AddGroupManager(m.Name); } } #endif termStore.CommitAll(); web.Context.Load(group); web.Context.ExecuteQueryRetry(); newGroup = true; } } } #endregion #region TermSets foreach (var modelTermSet in modelTermGroup.TermSets) { TermSet set = null; var newTermSet = false; if (!newGroup) { set = group.TermSets.FirstOrDefault(ts => ts.Id == modelTermSet.Id || ts.Name == modelTermSet.Name); } if (set == null) { if (modelTermSet.Id == Guid.Empty) { modelTermSet.Id = Guid.NewGuid(); } set = group.CreateTermSet(parser.ParseString(modelTermSet.Name), modelTermSet.Id, modelTermSet.Language ?? termStore.DefaultLanguage); parser.AddToken(new TermSetIdToken(web, group.Name, modelTermSet.Name, modelTermSet.Id)); newTermSet = true; set.Description = modelTermSet.Description; set.IsOpenForTermCreation = modelTermSet.IsOpenForTermCreation; set.IsAvailableForTagging = modelTermSet.IsAvailableForTagging; foreach (var property in modelTermSet.Properties) { set.SetCustomProperty(property.Key, parser.ParseString(property.Value)); } if (modelTermSet.Owner != null) { set.Owner = modelTermSet.Owner; } termStore.CommitAll(); web.Context.Load(set); web.Context.ExecuteQueryRetry(); } web.Context.Load(set, s => s.Terms.Include(t => t.Id, t => t.Name)); web.Context.ExecuteQueryRetry(); var terms = set.Terms; foreach (var modelTerm in modelTermSet.Terms) { if (!newTermSet) { if (terms.Any()) { var term = terms.FirstOrDefault(t => t.Id == modelTerm.Id); if (term == null) { term = terms.FirstOrDefault(t => t.Name == modelTerm.Name); if (term == null) { var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope); modelTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } else { modelTerm.Id = term.Id; } } else { modelTerm.Id = term.Id; } } else { var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope); modelTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } } else { var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope); modelTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } } // do we need custom sorting? if (modelTermSet.Terms.Any(t => t.CustomSortOrder > -1)) { var sortedTerms = modelTermSet.Terms.OrderBy(t => t.CustomSortOrder); var customSortString = sortedTerms.Aggregate(string.Empty, (a, i) => a + i.Id.ToString() + ":"); customSortString = customSortString.TrimEnd(new[] { ':' }); set.CustomSortOrder = customSortString; termStore.CommitAll(); web.Context.ExecuteQueryRetry(); } } #endregion } } return(parser); }
public override TokenParser ProvisionObjects(Web web, Model.ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(this.Name)) { this.reusedTerms = new List <ReusedTerm>(); TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(web.Context); TermStore termStore = null; TermGroup siteCollectionTermGroup = null; try { termStore = taxSession.GetDefaultKeywordsTermStore(); web.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))); siteCollectionTermGroup = termStore.GetSiteCollectionGroup((web.Context as ClientContext).Site, false); web.Context.Load(siteCollectionTermGroup); web.Context.ExecuteQueryRetry(); } catch (ServerException) { // If the GetDefaultSiteCollectionTermStore method call fails ... raise a specific Warning WriteMessage(CoreResources.Provisioning_ObjectHandlers_TermGroups_Wrong_Configuration, ProvisioningMessageType.Warning); // and exit skipping the current handler return(parser); } SiteCollectionTermGroupNameToken siteCollectionTermGroupNameToken = new SiteCollectionTermGroupNameToken(web); foreach (var modelTermGroup in template.TermGroups) { #region Group var newGroup = false; var normalizedGroupName = TaxonomyItem.NormalizeName(web.Context, modelTermGroup.Name); web.Context.ExecuteQueryRetry(); TermGroup group = termStore.Groups.FirstOrDefault( g => g.Id == modelTermGroup.Id || g.Name == normalizedGroupName.Value); if (group == null) { var parsedGroupName = parser.ParseString(modelTermGroup.Name); var parsedDescription = parser.ParseString(modelTermGroup.Description); if (modelTermGroup.Name == "Site Collection" || parsedGroupName == siteCollectionTermGroupNameToken.GetReplaceValue() || modelTermGroup.SiteCollectionTermGroup) { var site = (web.Context as ClientContext).Site; group = termStore.GetSiteCollectionGroup(site, true); web.Context.Load(group, g => g.Name, g => g.Id, g => g.TermSets.Include( tset => tset.Name, tset => tset.Id)); web.Context.ExecuteQueryRetry(); } else { var parsedNormalizedGroupName = TaxonomyItem.NormalizeName(web.Context, parsedGroupName); web.Context.ExecuteQueryRetry(); group = termStore.Groups.FirstOrDefault(g => g.Name == parsedNormalizedGroupName.Value); if (group == null) { if (modelTermGroup.Id == Guid.Empty) { modelTermGroup.Id = Guid.NewGuid(); } group = termStore.CreateGroup(parsedGroupName, modelTermGroup.Id); group.Description = parsedDescription; #if !ONPREMISES // Handle TermGroup Contributors, if any if (modelTermGroup.Contributors != null && modelTermGroup.Contributors.Count > 0) { foreach (var c in modelTermGroup.Contributors) { group.AddContributor(c.Name); } } // Handle TermGroup Managers, if any if (modelTermGroup.Managers != null && modelTermGroup.Managers.Count > 0) { foreach (var m in modelTermGroup.Managers) { group.AddGroupManager(m.Name); } } #endif termStore.CommitAll(); web.Context.Load(group); web.Context.ExecuteQueryRetry(); newGroup = true; } } } #endregion #region TermSets foreach (var modelTermSet in modelTermGroup.TermSets) { TermSet set = null; var newTermSet = false; var normalizedTermSetName = TaxonomyItem.NormalizeName(web.Context, modelTermSet.Name); web.Context.ExecuteQueryRetry(); if (!newGroup) { set = group.TermSets.FirstOrDefault( ts => ts.Id == modelTermSet.Id || ts.Name == normalizedTermSetName.Value); } if (set == null) { if (modelTermSet.Id == Guid.Empty) { modelTermSet.Id = Guid.NewGuid(); } set = group.CreateTermSet(parser.ParseString(modelTermSet.Name), modelTermSet.Id, modelTermSet.Language ?? termStore.DefaultLanguage); parser.AddToken(new TermSetIdToken(web, group.Name, modelTermSet.Name, modelTermSet.Id)); if (!siteCollectionTermGroup.ServerObjectIsNull.Value) { if (group.Name == siteCollectionTermGroup.Name) { parser.AddToken((new SiteCollectionTermSetIdToken(web, modelTermSet.Name, modelTermSet.Id))); } } newTermSet = true; set.Description = parser.ParseString(modelTermSet.Description); set.IsOpenForTermCreation = modelTermSet.IsOpenForTermCreation; set.IsAvailableForTagging = modelTermSet.IsAvailableForTagging; foreach (var property in modelTermSet.Properties) { set.SetCustomProperty(property.Key, parser.ParseString(property.Value)); } if (modelTermSet.Owner != null) { set.Owner = modelTermSet.Owner; } termStore.CommitAll(); web.Context.Load(set); web.Context.ExecuteQueryRetry(); } web.Context.Load(set, s => s.Terms.Include(t => t.Id, t => t.Name)); web.Context.ExecuteQueryRetry(); var terms = set.Terms; foreach (var modelTerm in modelTermSet.Terms) { if (!newTermSet) { if (terms.Any()) { var term = terms.FirstOrDefault(t => t.Id == modelTerm.Id); if (term == null) { var normalizedTermName = TaxonomyItem.NormalizeName(web.Context, modelTerm.Name); web.Context.ExecuteQueryRetry(); term = terms.FirstOrDefault(t => t.Name == normalizedTermName.Value); if (term == null) { var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope); if (returnTuple != null) { modelTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } } else { modelTerm.Id = term.Id; } } else { modelTerm.Id = term.Id; } if (term != null) { CheckChildTerms(web, modelTerm, term, termStore, parser, scope); } } else { var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope); if (returnTuple != null) { modelTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } } } else { var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope); if (returnTuple != null) { modelTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } } } // do we need custom sorting? if (modelTermSet.Terms.Any(t => t.CustomSortOrder > -1)) { var sortedTerms = modelTermSet.Terms.OrderBy(t => t.CustomSortOrder); var customSortString = sortedTerms.Aggregate(string.Empty, (a, i) => a + i.Id.ToString() + ":"); customSortString = customSortString.TrimEnd(new[] { ':' }); set.CustomSortOrder = customSortString; termStore.CommitAll(); web.Context.ExecuteQueryRetry(); } } #endregion } foreach (var reusedTerm in this.reusedTerms) { TryReuseTerm(web, reusedTerm.ModelTerm, reusedTerm.Parent, reusedTerm.TermStore, parser, scope); } } return(parser); }
/// Creates a TermSet object for demonstration purposes. If it already exists, it will be deleted /// and then recreated. public static NavigationTermSet RecreateSampleNavTermSet( ClientContext clientContext, TaxonomySession taxonomySession, Web web) { clientContext.Load(taxonomySession, ts => ts.TermStores); clientContext.ExecuteQuery(); // 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]; clientContext.Load(termStore, ts => ts.Name, ts => ts.WorkingLanguage); // Does the TermSet object already exist? TermSet existingTermSet; clientContext.ExecuteQuery(); if (!existingTermSet.ServerObjectIsNull.Value) { existingTermSet.DeleteObject(); termStore.CommitAll(); clientContext.ExecuteQuery(); } // Create a new TermSet object. TermGroup siteCollectionGroup = termStore.GetSiteCollectionGroup(clientContext.Site, createIfMissing: true); TermSet termSet = siteCollectionGroup.CreateTermSet("Navigation Demo", TestConfig.NavTermSetId, termStore.WorkingLanguage); termStore.CommitAll(); clientContext.ExecuteQuery(); NavigationTermSet navTermSet = NavigationTermSet.GetAsResolvedByWeb(clientContext, termSet, clientContext.Web, "GlobalNavigationTaxonomyProvider"); navTermSet.IsNavigationTermSet = true; navTermSet.TargetUrlForChildTerms.Value = "~site/Pages/Topics/Topic.aspx"; termStore.CommitAll(); clientContext.ExecuteQuery(); NavigationTerm term1 = navTermSet.CreateTerm("Term 1", NavigationLinkType.SimpleLink, Guid.NewGuid()); term1.SimpleLinkUrl = "http://www.bing.com/"; NavigationTerm term2 = navTermSet.CreateTerm("Term 2", NavigationLinkType.FriendlyUrl, Guid.NewGuid()); NavigationTerm term2a = term2.CreateTerm("Term 2 A", NavigationLinkType.FriendlyUrl, Guid.NewGuid()); NavigationTerm term2b = term2.CreateTerm("Term 2 B", NavigationLinkType.FriendlyUrl, Guid.NewGuid()); NavigationTerm term3 = navTermSet.CreateTerm("Term 3", NavigationLinkType.FriendlyUrl, Guid.NewGuid()); termStore.CommitAll(); clientContext.ExecuteQuery(); return(navTermSet); }
public static void CreateCustomerGeographyTermset() { string termSetName = "Customer Geography"; var aspnetHttpContext = System.Web.HttpContext.Current; var spContext = SharePointContextProvider.Current.GetSharePointContext(aspnetHttpContext); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { Site siteCollection = clientContext.Site; clientContext.Load(siteCollection, sc => sc.Url); clientContext.ExecuteQuery(); TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); taxonomySession.UpdateCache(); clientContext.Load(taxonomySession, ts => ts.TermStores); clientContext.ExecuteQuery(); TermStore termStore = taxonomySession.TermStores.FirstOrDefault <TermStore>(); Guid localTermStoreID = termStore.Id; TermGroup group = termStore.GetSiteCollectionGroup(siteCollection, true); clientContext.Load(group); clientContext.Load(group.TermSets); clientContext.ExecuteQuery(); // make sure it's deleted if exists foreach (TermSet termset in group.TermSets) { if (termset.Name.Equals(termSetName)) { termset.DeleteObject(); termStore.CommitAll(); clientContext.ExecuteQuery(); } } Guid termSetId = Guid.NewGuid(); TermSet tset = group.CreateTermSet(termSetName, termSetId, 1033); Term term1 = tset.CreateTerm("Northern Sales Territory", 1033, Guid.NewGuid()); term1.CreateTerm("New York", 1033, Guid.NewGuid()); term1.CreateTerm("New Jersey", 1033, Guid.NewGuid()); term1.CreateTerm("Connecticut", 1033, Guid.NewGuid()); Term term2 = tset.CreateTerm("Southern Sales Territory", 1033, Guid.NewGuid()); term2.CreateTerm("Georgia", 1033, Guid.NewGuid()); term2.CreateTerm("Alalabama", 1033, Guid.NewGuid()); Term florida = term2.CreateTerm("Florida", 1033, Guid.NewGuid()); florida.CreateTerm("Jacksonville", 1033, Guid.NewGuid()); florida.CreateTerm("Tampa", 1033, Guid.NewGuid()); florida.CreateTerm("Miami", 1033, Guid.NewGuid()); florida.CreateTerm("Key West", 1033, Guid.NewGuid()); termStore.CommitAll(); clientContext.ExecuteQuery(); clientContext.ExecuteQuery(); termStore.CommitAll(); } } }
private void Import(XmlElement termSetElement, TermGroup parentGroup) { string termSetName = termSetElement.GetAttribute("Name"); LoadWorkingLanguage(parentGroup.TermStore); TermSet termSet = null; ExceptionHandlingScope scope = new ExceptionHandlingScope(_ctx); using (scope.StartScope()) { using (scope.StartTry()) { termSet = parentGroup.TermSets.GetByName(termSetName); _ctx.Load(termSet); } using (scope.StartCatch()) { } } _ctx.ExecuteQuery(); if (termSet == null || termSet.ServerObjectIsNull == null || termSet.ServerObjectIsNull.Value) { _cmdlet.WriteVerbose(string.Format("Creating Term Set: {0}", termSetName)); int lcid = _workingLanguage; Guid id = Guid.NewGuid(); if (!string.IsNullOrEmpty(termSetElement.GetAttribute("Id"))) { id = new Guid(termSetElement.GetAttribute("Id")); } termSet = parentGroup.CreateTermSet(termSetName, id, lcid); if (!string.IsNullOrEmpty(termSetElement.GetAttribute("Contact"))) { termSet.Contact = termSetElement.GetAttribute("Contact"); } if (!string.IsNullOrEmpty(termSetElement.GetAttribute("Description"))) { termSet.Description = termSetElement.GetAttribute("Description"); } if (!string.IsNullOrEmpty(termSetElement.GetAttribute("CustomSortOrder"))) { termSet.CustomSortOrder = termSetElement.GetAttribute("CustomSortOrder"); } if (!string.IsNullOrEmpty(termSetElement.GetAttribute("IsAvailableForTagging"))) { termSet.IsAvailableForTagging = bool.Parse(termSetElement.GetAttribute("IsAvailableForTagging")); } if (!string.IsNullOrEmpty(termSetElement.GetAttribute("Owner"))) { termSet.Owner = termSetElement.GetAttribute("Owner"); } termSet.IsOpenForTermCreation = true; parentGroup.TermStore.CommitAll(); _ctx.Load(termSet); _ctx.ExecuteQuery(); } XmlNodeList stakeholderNodes = termSetElement.SelectNodes("./Stakeholders/Stakeholder"); if (stakeholderNodes != null && stakeholderNodes.Count > 0) { bool modified = false; foreach (XmlElement stakeholderElement in stakeholderNodes) { string stakeholder = stakeholderElement.GetAttribute("Value"); if (!termSet.Stakeholders.Contains(stakeholder)) { termSet.AddStakeholder(stakeholder); } } if (modified) { _ctx.ExecuteQuery(); } } XmlNodeList termsNodes = termSetElement.SelectNodes("./Terms/Term"); if (termsNodes != null && termsNodes.Count > 0) { foreach (XmlElement termElement in termsNodes) { Import(termElement, termSet); } } if (!string.IsNullOrEmpty(termSetElement.GetAttribute("IsOpenForTermCreation"))) { bool isOpenForTermCreation = bool.Parse(termSetElement.GetAttribute("IsOpenForTermCreation")); if (isOpenForTermCreation != termSet.IsOpenForTermCreation && termSet.Name != "Hashtags") { var orphanedTermsTermSet = termSet.TermStore.OrphanedTermsTermSet; termSet.Context.Load(orphanedTermsTermSet, o => o.Id); termSet.Context.ExecuteQuery(); if (orphanedTermsTermSet.Id != termSet.Id) { termSet.IsOpenForTermCreation = isOpenForTermCreation; termSet.Context.ExecuteQuery(); } } } _LocalNavTermSetId = termSet.Id; //Feature 152 }
private static void CreateTermSetAndTerms(ClientContext clientContext, XElement termSetElement, TermGroup termGroup) { clientContext.Load(termGroup.TermSets); clientContext.ExecuteQuery(); string termSetElementName = termSetElement.Attribute("Name").Value; string termSetElementGuid = termSetElement.Attribute("ID").Value; TermSet termSet = termGroup.TermSets.FirstOrDefault(e => e.Name.Equals(termSetElementName) == true); if (termSet == null) { termSet = termGroup.CreateTermSet(termSetElementName, new Guid(termSetElementGuid), 1033); } bool isNavTermSet = Convert.ToBoolean(termSetElement.Attribute("IsForSiteNav").Value); if (isNavTermSet) { //set term set to work for site navigation termSet.SetCustomProperty("_Sys_Nav_IsNavigationTermSet", "True"); } clientContext.Load(termSet);clientContext.Load(termSet.Terms); clientContext.ExecuteQuery(); foreach (XElement termElement in termSetElement.Elements()) { #region set properties for each Term string termElementName = termElement.Attribute("Name").Value; Term term = termSet.Terms.FirstOrDefault(e => e.Name.Equals(termElementName) == true); if (term == null) { term = termSet.CreateTerm(termElementName, 1033, Guid.NewGuid()); } //clientContext.Load(term); clientContext.ExecuteQuery(); if (termElement.Attribute("NavNodeTitle").Value.Length>0) { term.SetLocalCustomProperty("_Sys_Nav_Title", termElement.Attribute("NavNodeTitle").Value); } bool showinGlobal = Convert.ToBoolean(termElement.Attribute("ShowinGlobal").Value); bool showinLocal = Convert.ToBoolean(termElement.Attribute("ShowinLocal").Value); if (!showinGlobal || !showinLocal) { if(!showinGlobal && !showinLocal) { term.SetLocalCustomProperty("_Sys_Nav_ExcludedProviders", String.Concat("GlobalNavigationTaxonomyProvider", ",", "CurrentNavigationTaxonomyProvider")); } if(!showinGlobal) { term.SetLocalCustomProperty("_Sys_Nav_ExcludedProviders", "\"GlobalNavigationTaxonomyProvider\""); } else { term.SetLocalCustomProperty("_Sys_Nav_ExcludedProviders", "\"CurrentNavigationTaxonomyProvider\""); } } if(termElement.Attribute("NavNodeSimpleLink").Value.Length>0) { term.SetLocalCustomProperty("_Sys_Nav_SimpleLinkUrl", termElement.Attribute("NavNodeSimpleLink").Value); } if(termElement.Attribute("termFriendlyURLLink").Value.Length>0) { term.SetLocalCustomProperty("_Sys_Nav_FriendlyUrlSegment", termElement.Attribute("termFriendlyURLLink").Value); } if (termElement.Attribute("NavTargetURL").Value.Length > 0) { term.SetLocalCustomProperty("_Sys_Nav_TargetUrl", termElement.Attribute("NavTargetURL").Value); } clientContext.Load(term);clientContext.ExecuteQuery(); #endregion } }
public static void ImportTerms(this Site site, string[] termLines, int lcid, string delimiter) { var clientContext = site.Context; TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); clientContext.Load(termStore); clientContext.ExecuteQuery(); foreach (string line in termLines) { // split up string[] items = line.Split(new string[] { delimiter }, StringSplitOptions.None); if (items.Count() > 0) { string groupItem = items[0]; string groupName = groupItem; Guid groupId = Guid.Empty; if (groupItem.IndexOf(";#") > -1) { groupName = groupItem.Split(new string[] { ";#" }, StringSplitOptions.None)[0]; groupId = new Guid(groupItem.Split(new string[] { ";#" }, StringSplitOptions.None)[1]); } TermGroup termGroup = null; if (groupId != Guid.Empty) { termGroup = termStore.GetGroup(groupId); } else { termGroup = termStore.Groups.GetByName(NormalizeName(groupName)); } try { clientContext.Load(termGroup); clientContext.ExecuteQuery(); } catch { } if (termGroup.ServerObjectIsNull == null) { groupId = Guid.NewGuid(); termGroup = termStore.CreateGroup(NormalizeName(groupName), groupId); clientContext.Load(termGroup); clientContext.ExecuteQuery(); } if (items.Count() > 1) { // TermSet if (termGroup.ServerObjectIsNull == false) { string termsetItem = items[1]; string termsetName = termsetItem; Guid termsetId = Guid.Empty; if (termsetItem.IndexOf(";#") > -1) { termsetName = termsetItem.Split(new string[] { ";#" }, StringSplitOptions.None)[0]; termsetId = new Guid(termsetItem.Split(new string[] { ";#" }, StringSplitOptions.None)[1]); } TermSet termSet = null; if (termsetId != Guid.Empty) { termSet = termGroup.TermSets.GetById(termsetId); } else { termSet = termGroup.TermSets.GetByName(NormalizeName(termsetName)); } clientContext.Load(termSet); try { clientContext.ExecuteQuery(); } catch { } if (termSet.ServerObjectIsNull == null) { termsetId = Guid.NewGuid(); termSet = termGroup.CreateTermSet(NormalizeName(termsetName), termsetId, lcid); clientContext.Load(termSet); clientContext.ExecuteQuery(); } if (items.Count() > 2) { // Term(s) if (termSet.ServerObjectIsNull == false) { string termItem = items[2]; string termName = termItem; Guid termId = Guid.Empty; if (termItem.IndexOf(";#") > -1) { termName = termItem.Split(new string[] { ";#" }, StringSplitOptions.None)[0]; termId = new Guid(termItem.Split(new string[] { ";#" }, StringSplitOptions.None)[1]); } Term term = null; if (termId != Guid.Empty) { term = termSet.Terms.GetById(termId); } else { term = termSet.Terms.GetByName(NormalizeName(termName)); } clientContext.Load(term); try { clientContext.ExecuteQuery(); } catch { } if (term.ServerObjectIsNull == null) { termId = Guid.NewGuid(); term = termSet.CreateTerm(NormalizeName(termName), lcid, termId); clientContext.ExecuteQuery(); } if (items.Count() > 3) { clientContext.Load(term); clientContext.ExecuteQuery(); if (term.ServerObjectIsNull == false) { for (int q = 3; q < items.Count(); q++) { termName = items[q]; termId = Guid.Empty; if (termItem.IndexOf(";#") > -1) { termName = termItem.Split(new string[] { ";#" }, StringSplitOptions.None)[0]; termId = new Guid(termItem.Split(new string[] { ";#" }, StringSplitOptions.None)[1]); } term = term.AddTermToTerm(lcid, termName, termId); } } } } } } } } } }
public override void ProvisionObjects(Microsoft.SharePoint.Client.Web web, Model.ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation) { Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_TermGroups); TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(web.Context); var termStore = taxSession.GetDefaultKeywordsTermStore(); web.Context.Load(termStore, ts => ts.DefaultLanguage, ts => ts.Groups.Include( tg => tg.Name, tg => tg.Id, tg => tg.TermSets.Include( tset => tset.Name, tset => tset.Id))); web.Context.ExecuteQueryRetry(); foreach (var modelTermGroup in template.TermGroups) { #region Group var newGroup = false; TermGroup group = termStore.Groups.FirstOrDefault(g => g.Id == modelTermGroup.Id); if (group == null) { group = termStore.Groups.FirstOrDefault(g => g.Name == modelTermGroup.Name); if (group == null) { if (modelTermGroup.Id == Guid.Empty) { modelTermGroup.Id = Guid.NewGuid(); } group = termStore.CreateGroup(modelTermGroup.Name.ToParsedString(), modelTermGroup.Id); group.Description = modelTermGroup.Description; termStore.CommitAll(); web.Context.Load(group); web.Context.ExecuteQueryRetry(); newGroup = true; } } #endregion #region TermSets foreach (var modelTermSet in modelTermGroup.TermSets) { TermSet set = null; var newTermSet = false; if (!newGroup) { set = group.TermSets.FirstOrDefault(ts => ts.Id == modelTermSet.Id); if (set == null) { set = group.TermSets.FirstOrDefault(ts => ts.Name == modelTermSet.Name); } } if (set == null) { if (modelTermSet.Id == Guid.Empty) { modelTermSet.Id = Guid.NewGuid(); } set = group.CreateTermSet(modelTermSet.Name.ToParsedString(), modelTermSet.Id, modelTermSet.Language ?? termStore.DefaultLanguage); TokenParser.AddToken(new TermSetIdToken(web, modelTermGroup.Name, modelTermSet.Name, modelTermSet.Id)); newTermSet = true; set.IsOpenForTermCreation = modelTermSet.IsOpenForTermCreation; set.IsAvailableForTagging = modelTermSet.IsAvailableForTagging; foreach (var property in modelTermSet.Properties) { set.SetCustomProperty(property.Key, property.Value); } if (modelTermSet.Owner != null) { set.Owner = modelTermSet.Owner; } termStore.CommitAll(); web.Context.Load(set); web.Context.ExecuteQueryRetry(); } web.Context.Load(set, s => s.Terms.Include(t => t.Id, t => t.Name)); web.Context.ExecuteQueryRetry(); var terms = set.Terms; foreach (var modelTerm in modelTermSet.Terms) { if (!newTermSet) { if (terms.Any()) { var term = terms.FirstOrDefault(t => t.Id == modelTerm.Id); if (term == null) { term = terms.FirstOrDefault(t => t.Name == modelTerm.Name); if (term == null) { modelTerm.Id = CreateTerm <TermSet>(web, modelTerm, set, termStore); } else { modelTerm.Id = term.Id; } } else { modelTerm.Id = term.Id; } } else { modelTerm.Id = CreateTerm <TermSet>(web, modelTerm, set, termStore); } } else { modelTerm.Id = CreateTerm <TermSet>(web, modelTerm, set, termStore); } } // do we need custom sorting? if (modelTermSet.Terms.Any(t => t.CustomSortOrder > -1)) { var sortedTerms = modelTermSet.Terms.OrderBy(t => t.CustomSortOrder); var customSortString = sortedTerms.Aggregate(string.Empty, (a, i) => a + i.Id.ToString() + ":"); customSortString = customSortString.TrimEnd(new[] { ':' }); set.CustomSortOrder = customSortString; termStore.CommitAll(); web.Context.ExecuteQueryRetry(); } } #endregion } }
public TermSet CreateTermSet(TermGroup group, string termsetname) { Ctx.Load(group.TermSets); Ctx.ExecuteQuery(); TermSet set = group.TermSets.FirstOrDefault(x => x.Name == termsetname); if (set == null) { set = group.CreateTermSet(termsetname, Guid.NewGuid(), Settings.Instance.LCID); Ctx.Load(set); Ctx.ExecuteQuery(); } return set; }
internal static List <ReusedTerm> ProcessGroup(ClientContext context, TaxonomySession session, TermStore termStore, Model.TermGroup modelTermGroup, TermGroup siteCollectionTermGroup, TokenParser parser, PnPMonitoredScope scope) { List <ReusedTerm> reusedTerms = new List <ReusedTerm>(); SiteCollectionTermGroupNameToken siteCollectionTermGroupNameToken = new SiteCollectionTermGroupNameToken(context.Web); #region Group var newGroup = false; var modelGroupName = parser.ParseString(modelTermGroup.Name); var normalizedGroupName = TaxonomyItem.NormalizeName(context, modelGroupName); context.ExecuteQueryRetry(); TermGroup group = termStore.Groups.FirstOrDefault( g => g.Id == modelTermGroup.Id || g.Name == normalizedGroupName.Value); if (group == null) { var parsedDescription = parser.ParseString(modelTermGroup.Description); if (modelTermGroup.Name == "Site Collection" || modelGroupName == siteCollectionTermGroupNameToken.GetReplaceValue() || modelTermGroup.SiteCollectionTermGroup) { var site = (context as ClientContext).Site; group = termStore.GetSiteCollectionGroup(site, true); context.Load(group, g => g.Name, g => g.Id, g => g.TermSets.Include( tset => tset.Name, tset => tset.Id)); context.ExecuteQueryRetry(); } else { group = termStore.Groups.FirstOrDefault(g => g.Name == normalizedGroupName.Value); if (group == null) { if (modelTermGroup.Id == Guid.Empty) { modelTermGroup.Id = Guid.NewGuid(); } group = termStore.CreateGroup(modelGroupName, modelTermGroup.Id); group.Description = parsedDescription; // Handle TermGroup Contributors, if any if (modelTermGroup.Contributors != null && modelTermGroup.Contributors.Count > 0) { foreach (var c in modelTermGroup.Contributors) { group.AddContributor(c.Name); } } // Handle TermGroup Managers, if any if (modelTermGroup.Managers != null && modelTermGroup.Managers.Count > 0) { foreach (var m in modelTermGroup.Managers) { group.AddGroupManager(m.Name); } } termStore.CommitAll(); context.Load(group); context.Load(termStore); context.ExecuteQueryRetry(); newGroup = true; } } } #endregion session.UpdateCache(); session.Context.ExecuteQueryRetry(); #region TermSets foreach (var modelTermSet in modelTermGroup.TermSets) { TermSet set = null; var newTermSet = false; var normalizedTermSetName = TaxonomyItem.NormalizeName(context, parser.ParseString(modelTermSet.Name)); context.ExecuteQueryRetry(); if (!newGroup) { set = group.TermSets.FirstOrDefault( ts => ts.Id == modelTermSet.Id || ts.Name == normalizedTermSetName.Value); } if (set == null) { if (modelTermSet.Id == Guid.Empty) { modelTermSet.Id = Guid.NewGuid(); } else { if (CheckIfTermSetIdIsUnique(termStore, modelTermSet.Id) == false) { throw new Exception($"Termset ID {modelTermSet.Id} is already present in termstore"); } } var termSetLanguage = modelTermSet.Language.HasValue ? modelTermSet.Language.Value : termStore.DefaultLanguage; set = group.CreateTermSet(normalizedTermSetName.Value, modelTermSet.Id, termSetLanguage); parser.AddToken(new TermSetIdToken(context.Web, group.Name, normalizedTermSetName.Value, modelTermSet.Id)); if (siteCollectionTermGroup != null && !siteCollectionTermGroup.ServerObjectIsNull.Value) { if (group.Name == siteCollectionTermGroup.Name) { parser.AddToken((new SiteCollectionTermSetIdToken(context.Web, normalizedTermSetName.Value, modelTermSet.Id))); } } newTermSet = true; if (!string.IsNullOrEmpty(modelTermSet.Description)) { set.Description = parser.ParseString(modelTermSet.Description); } set.IsOpenForTermCreation = modelTermSet.IsOpenForTermCreation; set.IsAvailableForTagging = modelTermSet.IsAvailableForTagging; foreach (var property in modelTermSet.Properties) { set.SetCustomProperty(property.Key, parser.ParseString(property.Value)); } if (modelTermSet.Owner != null) { set.Owner = parser.ParseString(modelTermSet.Owner); } termStore.CommitAll(); context.Load(set); context.ExecuteQueryRetry(); } context.Load(set, s => s.Terms.Include(t => t.Id, t => t.Name)); context.ExecuteQueryRetry(); var terms = set.Terms; foreach (var modelTerm in modelTermSet.Terms) { if (!newTermSet) { if (terms.Any()) { var term = terms.FirstOrDefault(t => t.Id == modelTerm.Id); if (term == null) { var normalizedTermName = TaxonomyItem.NormalizeName(context, parser.ParseString(modelTerm.Name)); context.ExecuteQueryRetry(); term = terms.FirstOrDefault(t => t.Name == normalizedTermName.Value); if (term == null) { var returnTuple = CreateTerm(context, modelTerm, set, termStore, parser, scope); if (returnTuple != null) { modelTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } reusedTerms.AddRange(returnTuple.Item3); } else { // todo: add handling for reused term? modelTerm.Id = term.Id; } } else { // todo: add handling for reused term? modelTerm.Id = term.Id; } if (term != null) { CheckChildTerms(context, modelTerm, term, termStore, parser, scope); } } else { var returnTuple = CreateTerm(context, modelTerm, set, termStore, parser, scope); if (returnTuple != null) { modelTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } reusedTerms.AddRange(returnTuple.Item3); } } else { var returnTuple = CreateTerm(context, modelTerm, set, termStore, parser, scope); if (returnTuple != null) { modelTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } reusedTerms.AddRange(returnTuple.Item3); } } // do we need custom sorting? if (modelTermSet.Terms.Any(t => t.CustomSortOrder > 0)) { var sortedTerms = modelTermSet.Terms.OrderBy(t => t.CustomSortOrder); var customSortString = sortedTerms.Aggregate(string.Empty, (a, i) => a + i.Id.ToString() + ":"); customSortString = customSortString.TrimEnd(new[] { ':' }); set.CustomSortOrder = customSortString; termStore.CommitAll(); context.ExecuteQueryRetry(); } } #endregion return(reusedTerms); }
public ActionResult Index() { var model = new IndexAdvertisementViewModel(); var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); if (spContext != null) { Session["SpContext"] = spContext; Session["SpHostUrl"] = spContext.SPHostUrl; } else { spContext = Session["SpContext"] as SharePointContext; } using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { ListCollection listCol = clientContext.Web.Lists; TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); User currentUser = clientContext.Web.CurrentUser; clientContext.Load(taxonomySession); clientContext.Load(listCol, y => y.Where(x => x.Title == "Annonser")); clientContext.Load(currentUser); clientContext.ExecuteQuery(); //List list = clientContext.Web.Lists.GetByTitle("Annonser"); Fungerar utan lista?? if (taxonomySession != null) { #region Create Category Taxonomy Session["TaxSession"] = taxonomySession; TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); TermGroupCollection termGroupCol = termStore.Groups; clientContext.Load(termGroupCol, t => t.Where(y => y.Name == "Advertisements")); clientContext.ExecuteQuery(); var termGroup = termGroupCol.FirstOrDefault(); if (termGroup == null) { TermGroup annonsKategorierGroup = termStore.CreateGroup("Advertisements", Guid.NewGuid()); clientContext.ExecuteQuery(); TermSet annonsKateGorierTermSet = annonsKategorierGroup.CreateTermSet("Categories", Guid.NewGuid(), 1033); clientContext.ExecuteQuery(); annonsKateGorierTermSet.CreateTerm("Electronics", 1033, Guid.NewGuid()); annonsKateGorierTermSet.CreateTerm("Appliances", 1033, Guid.NewGuid()); annonsKateGorierTermSet.CreateTerm("Clothing", 1033, Guid.NewGuid()); annonsKateGorierTermSet.CreateTerm("Books", 1033, Guid.NewGuid()); annonsKateGorierTermSet.CreateTerm("Office", 1033, Guid.NewGuid()); annonsKateGorierTermSet.CreateTerm("Other", 1033, Guid.NewGuid()); clientContext.ExecuteQuery(); termGroup = annonsKategorierGroup; } #endregion if (termGroup != null) { TermSet termSet = termGroup.TermSets.GetByName("Categories"); TermCollection terms = termSet.GetAllTerms(); clientContext.Load(termSet); clientContext.Load(terms); clientContext.ExecuteQuery(); foreach (Term term in terms) { SelectListItem newItem = new SelectListItem { Value = term.Id.ToString(), Text = term.Name }; model.Categories.Add(newItem); } } } var list = listCol.FirstOrDefault(); if (list == null) { #region Create Advertisement List ListCreationInformation listCreationInfo = new ListCreationInformation(); listCreationInfo.Title = "Annonser"; listCreationInfo.TemplateType = (int)ListTemplateType.GenericList; var newList = clientContext.Web.Lists.Add(listCreationInfo); FieldCollection fieldCol = newList.Fields; Field defaultTitleField = fieldCol.GetByTitle("Title"); clientContext.Load(fieldCol); clientContext.Load(defaultTitleField); clientContext.ExecuteQuery(); defaultTitleField.Hidden = true; defaultTitleField.SetShowInDisplayForm(false); defaultTitleField.SetShowInEditForm(false); defaultTitleField.SetShowInNewForm(false); defaultTitleField.Required = false; defaultTitleField.Update(); Field rubrikField = newList.Fields.AddFieldAsXml("<Field DisplayName='Rubrik' Type='Text' Name='Rubrik' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView); Field textField = newList.Fields.AddFieldAsXml("<Field DisplayName='Text' Type='Text' Name='Text' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView); Field prisField = newList.Fields.AddFieldAsXml("<Field DisplayName='Pris' Type='Number' Name='Pris' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView); Field datumField = newList.Fields.AddFieldAsXml("<Field DisplayName='Datum' Type='DateTime' Name='Datum' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView); //Field anvandareField = newList.Fields.AddFieldAsXml("<Field DisplayName='Användare' Type='User' Name='Anvandare' StaticName='Anvandare' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView); Field kategoriField = newList.Fields.AddFieldAsXml("<Field DisplayName='Kategori' Type='TaxonomyFieldType' Name='Kategori' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView); FieldNumber rubrikFieldNumber = clientContext.CastTo <FieldNumber>(rubrikField); FieldNumber textFieldNumber = clientContext.CastTo <FieldNumber>(textField); FieldNumber prisFieldNumber = clientContext.CastTo <FieldNumber>(prisField); FieldNumber datumFieldNumber = clientContext.CastTo <FieldNumber>(datumField); //FieldNumber anvandareFieldNumber = clientContext.CastTo<FieldNumber>(anvandareField); //FieldNumber kategoryFieldNumber = clientContext.CastTo<FieldNumber>(anvandareField); Guid termStoreId = Guid.Empty; Guid termSetId = Guid.Empty; GetTaxonomyFieldInfo(clientContext, out termStoreId, out termSetId, "Categories"); TaxonomyField kategoryFieldNumber = clientContext.CastTo <TaxonomyField>(kategoriField); kategoryFieldNumber.SspId = termStoreId; kategoryFieldNumber.TermSetId = termSetId; kategoryFieldNumber.TargetTemplate = String.Empty; kategoryFieldNumber.AnchorId = Guid.Empty; rubrikFieldNumber.Update(); textFieldNumber.Update(); prisFieldNumber.Update(); datumFieldNumber.Update(); //anvandareFieldNumber.Update(); kategoryFieldNumber.Update(); View view = newList.Views.GetByTitle("All Items"); clientContext.Load(view); clientContext.ExecuteQuery(); ViewFieldCollection viewFields = view.ViewFields; viewFields.Remove("LinkTitle"); view.Update(); clientContext.ExecuteQuery(); list = newList; #endregion } CamlQuery cQuery = new CamlQuery(); cQuery.ViewXml = @"<View> <Query> <Where> <Eq> <FieldRef Name='Author' LookupId='True'/> <Value Type='Lookup'>" + currentUser.Id + @"</Value> </Eq> </Where> </Query> </View>"; var listItems = list.GetItems(cQuery); clientContext.Load(listItems); clientContext.ExecuteQuery(); foreach (ListItem listItem in listItems) { AdvertisementViewModel tempObj = new AdvertisementViewModel { Title = listItem["Rubrik"].ToString(), Text = listItem["Text"].ToString(), Price = int.Parse(listItem["Pris"].ToString()), Date = DateTime.Parse(listItem["Datum"].ToString()), User = listItem["Author"] as FieldUserValue, Category = listItem["Kategori"] as TaxonomyFieldValue, ListItemId = listItem["ID"].ToString() }; model.Advertisements.Add(tempObj); } } return(View(model)); } }
private static void CreateTermSetAndTerms(ClientContext clientContext, XElement termSetElement, TermGroup termGroup) { clientContext.Load(termGroup.TermSets); clientContext.ExecuteQuery(); string termSetElementName = termSetElement.Attribute("Name").Value; string termSetElementGuid = termSetElement.Attribute("ID").Value; TermSet termSet = termGroup.TermSets.FirstOrDefault(e => e.Name.Equals(termSetElementName) == true); if (termSet == null) { termSet = termGroup.CreateTermSet(termSetElementName, new Guid(termSetElementGuid), 1033); } bool isNavTermSet = Convert.ToBoolean(termSetElement.Attribute("IsForSiteNav").Value); if (isNavTermSet) { //set term set to work for site navigation termSet.SetCustomProperty("_Sys_Nav_IsNavigationTermSet", "True"); } clientContext.Load(termSet); clientContext.Load(termSet.Terms); clientContext.ExecuteQuery(); foreach (XElement termElement in termSetElement.Elements()) { #region set properties for each Term string termElementName = termElement.Attribute("Name").Value; Term term = termSet.Terms.FirstOrDefault(e => e.Name.Equals(termElementName) == true); if (term == null) { term = termSet.CreateTerm(termElementName, 1033, Guid.NewGuid()); } //clientContext.Load(term); clientContext.ExecuteQuery(); if (termElement.Attribute("NavNodeTitle").Value.Length > 0) { term.SetLocalCustomProperty("_Sys_Nav_Title", termElement.Attribute("NavNodeTitle").Value); } bool showinGlobal = Convert.ToBoolean(termElement.Attribute("ShowinGlobal").Value); bool showinLocal = Convert.ToBoolean(termElement.Attribute("ShowinLocal").Value); if (!showinGlobal || !showinLocal) { if (!showinGlobal && !showinLocal) { term.SetLocalCustomProperty("_Sys_Nav_ExcludedProviders", String.Concat("GlobalNavigationTaxonomyProvider", ",", "CurrentNavigationTaxonomyProvider")); } if (!showinGlobal) { term.SetLocalCustomProperty("_Sys_Nav_ExcludedProviders", "\"GlobalNavigationTaxonomyProvider\""); } else { term.SetLocalCustomProperty("_Sys_Nav_ExcludedProviders", "\"CurrentNavigationTaxonomyProvider\""); } } if (termElement.Attribute("NavNodeSimpleLink").Value.Length > 0) { term.SetLocalCustomProperty("_Sys_Nav_SimpleLinkUrl", termElement.Attribute("NavNodeSimpleLink").Value); } if (termElement.Attribute("termFriendlyURLLink").Value.Length > 0) { term.SetLocalCustomProperty("_Sys_Nav_FriendlyUrlSegment", termElement.Attribute("termFriendlyURLLink").Value); } if (termElement.Attribute("NavTargetURL").Value.Length > 0) { term.SetLocalCustomProperty("_Sys_Nav_TargetUrl", termElement.Attribute("NavTargetURL").Value); } clientContext.Load(term); clientContext.ExecuteQuery(); #endregion } }
private void Import(XmlElement termSetElement, TermGroup parentGroup) { string termSetName = termSetElement.GetAttribute("Name"); LoadWorkingLanguage(parentGroup.TermStore); TermSet termSet = null; ExceptionHandlingScope scope = new ExceptionHandlingScope(_ctx); using (scope.StartScope()) { using (scope.StartTry()) { termSet = parentGroup.TermSets.GetByName(termSetName); _ctx.Load(termSet); } using (scope.StartCatch()) { } } _ctx.ExecuteQuery(); if (termSet == null || termSet.ServerObjectIsNull == null || termSet.ServerObjectIsNull.Value) { _cmdlet.WriteVerbose(string.Format("Creating Term Set: {0}", termSetName)); int lcid = _workingLanguage; Guid id = Guid.NewGuid(); if (!string.IsNullOrEmpty(termSetElement.GetAttribute("Id"))) id = new Guid(termSetElement.GetAttribute("Id")); termSet = parentGroup.CreateTermSet(termSetName, id, lcid); if (!string.IsNullOrEmpty(termSetElement.GetAttribute("Contact"))) termSet.Contact = termSetElement.GetAttribute("Contact"); if (!string.IsNullOrEmpty(termSetElement.GetAttribute("Description"))) termSet.Description = termSetElement.GetAttribute("Description"); if (!string.IsNullOrEmpty(termSetElement.GetAttribute("CustomSortOrder"))) termSet.CustomSortOrder = termSetElement.GetAttribute("CustomSortOrder"); if (!string.IsNullOrEmpty(termSetElement.GetAttribute("IsAvailableForTagging"))) termSet.IsAvailableForTagging = bool.Parse(termSetElement.GetAttribute("IsAvailableForTagging")); if (!string.IsNullOrEmpty(termSetElement.GetAttribute("Owner"))) termSet.Owner = termSetElement.GetAttribute("Owner"); termSet.IsOpenForTermCreation = true; parentGroup.TermStore.CommitAll(); _ctx.Load(termSet); _ctx.ExecuteQuery(); } XmlNodeList stakeholderNodes = termSetElement.SelectNodes("./Stakeholders/Stakeholder"); if (stakeholderNodes != null && stakeholderNodes.Count > 0) { bool modified = false; foreach (XmlElement stakeholderElement in stakeholderNodes) { string stakeholder = stakeholderElement.GetAttribute("Value"); if (!termSet.Stakeholders.Contains(stakeholder)) { termSet.AddStakeholder(stakeholder); } } if (modified) _ctx.ExecuteQuery(); } XmlNodeList termsNodes = termSetElement.SelectNodes("./Terms/Term"); if (termsNodes != null && termsNodes.Count > 0) { foreach (XmlElement termElement in termsNodes) { Import(termElement, termSet); } } if (!string.IsNullOrEmpty(termSetElement.GetAttribute("IsOpenForTermCreation"))) { bool isOpenForTermCreation = bool.Parse(termSetElement.GetAttribute("IsOpenForTermCreation")); if (isOpenForTermCreation != termSet.IsOpenForTermCreation && termSet.Name != "Hashtags") { var orphanedTermsTermSet = termSet.TermStore.OrphanedTermsTermSet; termSet.Context.Load(orphanedTermsTermSet, o => o.Id); termSet.Context.ExecuteQuery(); if (orphanedTermsTermSet.Id != termSet.Id) { termSet.IsOpenForTermCreation = isOpenForTermCreation; termSet.Context.ExecuteQuery(); } } } }
// If Term and TermGroup objects do not already exist, this function creates them as // specified by the TermSetGoal object that was read from the XML // input file. The code also calls the ClientContext.Load() method to query // client object model properties that will be needed later. static TermSet CreateTermSetAndGroup(TermStore termStore, TermSetGoal termSetGoal) { // Load the data Program.clientContext.Load(termStore, termStoreArg => termStoreArg.WorkingLanguage, termStoreArg => termStoreArg.Groups.Include( groupArg => groupArg.Id, groupArg => groupArg.Name ) ); TermSet termSet = termStore.GetTermSet(termSetGoal.Id); Program.clientContext.Load(termSet, termSetArg => termSetArg.Id, termSetArg => termSetArg.Name, termSetArg => termSetArg.Group.Id); Program.ExecuteQuery(); // WCF CALL #1 // Set up the group and the term set. Program.lcid = termStore.WorkingLanguage; TermGroup group = termStore.Groups.ToList().FirstOrDefault(g => g.Name == termSetGoal.GroupName); if (group == null) { // (ServerObjectIsNull is not used here) Log("* Creating missing group \"" + termSetGoal.GroupName + "\""); group = termStore.CreateGroup(termSetGoal.GroupName, Guid.NewGuid()); } if (termSet.ServerObjectIsNull.Value) { Log("* Creating missing term set \"" + termSetGoal.Name + "\""); termSet = group.CreateTermSet(termSetGoal.Name, termSetGoal.Id, Program.lcid); Program.clientContext.Load(termSet, termSetArg => termSetArg.Id, termSetArg => termSetArg.Name, termSetArg => termSetArg.Group.Id); } #if false else { if (termSet.Group.Id != group.Id) { Log("* Moving term set to group \"" + group.Name + "\""); termSet.Move(group); } else { Log("Verified term set \"" + termSetGoal.Name + "\""); } if (termSet.Name != termSetGoal.Name) { termSet.Name = termSetGoal.Name; } } #endif return(termSet); }
public static void CreateSimpleTermset() { string termSetName = "My Termset"; var aspnetHttpContext = System.Web.HttpContext.Current; var spContext = SharePointContextProvider.Current.GetSharePointContext(aspnetHttpContext); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { Site siteCollection = clientContext.Site; clientContext.Load(siteCollection, sc => sc.Url); clientContext.ExecuteQuery(); TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); taxonomySession.UpdateCache(); clientContext.Load(taxonomySession, ts => ts.TermStores); clientContext.ExecuteQuery(); TermStore termStore = taxonomySession.TermStores.FirstOrDefault <TermStore>(); Guid localTermStoreID = termStore.Id; TermGroup group = termStore.GetSiteCollectionGroup(siteCollection, true); clientContext.Load(group); clientContext.Load(group.TermSets); clientContext.ExecuteQuery(); // make sure it's deleted if exists foreach (TermSet termset in group.TermSets) { if (termset.Name.Equals(termSetName)) { termset.DeleteObject(); termStore.CommitAll(); clientContext.ExecuteQuery(); } } Guid termSetId = Guid.NewGuid(); TermSet tset = group.CreateTermSet(termSetName, termSetId, 1033); Term term1 = tset.CreateTerm("Term 1", 1033, Guid.NewGuid()); term1.CreateTerm("Child A", 1033, Guid.NewGuid()); term1.CreateTerm("Child B", 1033, Guid.NewGuid()); term1.CreateTerm("Child C", 1033, Guid.NewGuid()); Term term2 = tset.CreateTerm("Term 2", 1033, Guid.NewGuid()); term2.CreateTerm("Child D", 1033, Guid.NewGuid()); term2.CreateTerm("Child E", 1033, Guid.NewGuid()); term2.CreateTerm("Child F", 1033, Guid.NewGuid()); Term term3 = tset.CreateTerm("Term 3", 1033, Guid.NewGuid()); term3.CreateTerm("Child G", 1033, Guid.NewGuid()); term3.CreateTerm("Child H", 1033, Guid.NewGuid()); term3.CreateTerm("Child I", 1033, Guid.NewGuid()); termStore.CommitAll(); clientContext.ExecuteQuery(); clientContext.ExecuteQuery(); termStore.CommitAll(); } } }