/// <summary> /// Used to update the taxonomoy drop downs for creating taxonomy field to host web. /// </summary> private void GenerateTaxonomyDropDowns() { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var ctx = spContext.CreateUserClientContextForSPHost()) { TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(ctx); TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); ctx.Load(termStore, store => store.Name, store => store.Groups.Include( group => group.Name, group => group.Id) ); ctx.ExecuteQuery(); drpGroups.Items.Clear(); foreach (TermGroup group in termStore.Groups) { drpGroups.Items.Add(new System.Web.UI.WebControls.ListItem(group.Name, group.Id.ToString())); } } // Updated term setup drop down UpdateTermSetsBasedOnSelectedGroup(drpGroups.SelectedValue); }
public void CreateTaxonomyFieldTest() { using (var clientContext = TestCommon.CreateClientContext()) { // Retrieve Termset TaxonomySession session = TaxonomySession.GetTaxonomySession(clientContext); var termSet = session.GetDefaultSiteCollectionTermStore().GetTermSet(_termSetId); clientContext.Load(termSet); clientContext.ExecuteQuery(); // Get Test TermSet var web = clientContext.Web; var fieldName = "Test_" + DateTime.Now.ToFileTime(); var fieldId = Guid.NewGuid(); var field = web.CreateTaxonomyField( fieldId, fieldName, fieldName, "Test Fields Group", termSet ); Assert.AreEqual(fieldId, field.Id, "Field IDs do not match."); Assert.AreEqual(fieldName, field.InternalName, "Field internal names do not match."); Assert.AreEqual("TaxonomyFieldType", field.TypeAsString, "Failed to create a TaxonomyField object."); } }
private static string GetValueFromTermStore(string siteCollectionUrl, TraceWriter log) { string value = string.Empty; using (ClientContext context = new AuthenticationContext(siteCollectionUrl).GetAuthenticationContext()) { TaxonomySession session = TaxonomySession.GetTaxonomySession(context); TermStore store = session.GetDefaultSiteCollectionTermStore(); context.Load(store, s => s.Name, s => s.Groups.Include( g => g.Name, g => g.TermSets.Include( ts => ts.Name, ts => ts.CustomProperties, ts => ts.Terms.Include( t => t.Name, t => t.CustomProperties )))); context.ExecuteQueryRetry(); log.Info($"Loaded taxonomy data"); if (session != null && store != null) { value = GetValueFromTermGroup(store, log, context); } } return(value); }
public void CleanUp() { if (!TestCommon.AppOnlyTesting()) { using (var ctx = TestCommon.CreateClientContext()) { try { TaxonomySession session = TaxonomySession.GetTaxonomySession(ctx); var store = session.GetDefaultSiteCollectionTermStore(); var termSet1 = store.GetTermSet(_termSetGuid); var termSet2 = store.GetTermSet(_additionalTermSetGuid); termSet1.DeleteObject(); termSet2.DeleteObject(); store.CommitAll(); ctx.ExecuteQueryRetry(); if (_termGroupGuid != Guid.Empty) { var termGroup = store.GetGroup(_termGroupGuid); termGroup.DeleteObject(); } store.CommitAll(); ctx.ExecuteQueryRetry(); } catch { } } } }
/// <summary> /// Tokenizes the taxonomy field. /// </summary> /// <param name="web">The web.</param> /// <param name="element">The element.</param> /// <returns></returns> protected string TokenizeTaxonomyField(Web web, XElement element) { // Replace Taxonomy field references to SspId, TermSetId with tokens TaxonomySession session = TaxonomySession.GetTaxonomySession(web.Context); TermStore store = session.GetDefaultSiteCollectionTermStore(); var sspIdElement = element.XPathSelectElement("./Customization/ArrayOfProperty/Property[Name = 'SspId']/Value"); if (sspIdElement != null) { sspIdElement.Value = "{sitecollectiontermstoreid}"; } var termSetIdElement = element.XPathSelectElement("./Customization/ArrayOfProperty/Property[Name = 'TermSetId']/Value"); if (termSetIdElement != null) { Guid termSetId = Guid.Parse(termSetIdElement.Value); if (termSetId != Guid.Empty) { Microsoft.SharePoint.Client.Taxonomy.TermSet termSet = store.GetTermSet(termSetId); store.Context.ExecuteQueryRetry(); if (!termSet.ServerObjectIsNull()) { termSet.EnsureProperties(ts => ts.Name, ts => ts.Group); termSetIdElement.Value = String.Format("{{termsetid:{0}:{1}}}", termSet.Group.IsSiteCollectionGroup ? "{sitecollectiontermgroupname}" : termSet.Group.Name, termSet.Name); } } } return(element.ToString()); }
public void CreateTaxonomyFieldLinkedToTermSetTest() { using (var clientContext = TestCommon.CreateClientContext()) { // Retrieve Termset TaxonomySession session = TaxonomySession.GetTaxonomySession(clientContext); var termSet = session.GetDefaultSiteCollectionTermStore().GetTermSet(_termSetId); clientContext.Load(termSet); clientContext.ExecuteQueryRetry(); var list = clientContext.Web.Lists.GetById(_listId); clientContext.Load(list); clientContext.ExecuteQueryRetry(); var fieldName = "Test_" + DateTime.Now.ToFileTime(); var fieldId = Guid.NewGuid(); TaxonomyFieldCreationInformation fieldCI = new TaxonomyFieldCreationInformation() { Id = fieldId, DisplayName = fieldName, InternalName = fieldName, Group = "Test Fields Group", TaxonomyItem = termSet }; var field = list.CreateTaxonomyField(fieldCI); Assert.AreEqual(fieldId, field.Id, "Field IDs do not match."); Assert.AreEqual(fieldName, field.InternalName, "Field internal names do not match."); Assert.AreEqual("TaxonomyFieldType", field.TypeAsString, "Failed to create a TaxonomyField object."); } }
public static void CreateTermSets(TokenParser _TokenParser, XElement _Branding, ClientContext clientContext, string termGroupName) { Console.WriteLine("Processing Term Sets . . . "); // This code assumes: // managed metadata service is running on the farm // default termstore exists for site collection // permission to managed metadata service have been granted // start a taxonomy session and connect to the Term Store TaxonomySession taxonomySession = TaxonomyExtensions.GetTaxonomySession(clientContext.Site); TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); // connect to Site Collection Terms (aka Term Group with Site Collection Name) Microsoft.SharePoint.Client.Taxonomy.TermGroup termGroup = termStore.GetTermGroupByName(termGroupName); //process each termset foreach (var termset in _Branding.GetDescendants("termsets", "termset")) { // fetch file path string termSetFilePath = termset.GetAttributeValue(_TokenParser, "termSetFilePath"); Console.WriteLine("Creating Term Set from contents of: {0}", termSetFilePath); // Create TermSet via File Import Microsoft.SharePoint.Client.Taxonomy.TermSet termSet = TaxonomyExtensions.ImportTermSet(termGroup, termSetFilePath); } }
/// <summary> /// Function to map metadata columns with specific term set /// </summary> /// <param name="clientContext">SP client context</param> /// <param name="fieldCol">Field Collection object</param> internal static void MapMetadataColumns(ClientContext clientContext, FieldCollection fieldCol) { string termsetName = ConfigurationManager.AppSettings["DefaultTermSetName"]; string taxonomyFieldType = ConfigurationManager.AppSettings["TaxonomyFieldType"]; TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); TermSetCollection termSetCollection = termStore.GetTermSetsByName(termsetName, 1033); // Setting LCID=1033, as the default language is English clientContext.Load(termStore); clientContext.Load(termSetCollection); clientContext.ExecuteQuery(); string termStoreId = Convert.ToString(termStore.Id, CultureInfo.InvariantCulture); string termSetId = Convert.ToString(termSetCollection[0].Id, CultureInfo.InvariantCulture); TaxonomyField taxonomyField = null; foreach (Field field in fieldCol) { if (field.TypeAsString.Equals(taxonomyFieldType, StringComparison.OrdinalIgnoreCase)) { taxonomyField = clientContext.CastTo <TaxonomyField>(field); taxonomyField.SspId = new Guid(termStoreId); taxonomyField.TermSetId = new Guid(termSetId); taxonomyField.AnchorId = Guid.Empty; taxonomyField.Update(); } } }
static void Main(string[] args) { Log("\r\nTermSetSync (Client OM): Starting...\r\n"); // Uncomment this section to create a sample input file. #if false GenerateExampleXmlFile(); #else TermSetGoal termSetGoal = LoadTermSetGoal(); Program.clientContext = new ClientContext(siteUrl); TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(Program.clientContext); taxonomySession.UpdateCache(); TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); TermSet termSet = CreateTermSetAndGroup(termStore, termSetGoal); SyncTermSet(termSet, termSetGoal); #endif Log("\r\nThe operation completed successfully."); if (Debugger.IsAttached) { Debugger.Break(); } }
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(); } } }
//CreateTermSet //CheckTermGroupName public bool CheckTermGroupName(ClientContext context) { TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(context); TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); context.Load(termStore, store => store.Name, store => store.Groups.Include( group => group.Name)); context.ExecuteQuery(); if (taxonomySession != null) { if (termStore != null) { foreach (TermGroup group in termStore.Groups) { if (group.Name == TERMGROUPNAME) { return(true); } } } } return(false); }
public static string GetTermIdForTerm(string term, Guid termSetId, ClientContext clientContext) { string termId = string.Empty; //Get term set from ID TaxonomySession tSession = TaxonomySession.GetTaxonomySession(clientContext); TermStore ts = tSession.GetDefaultSiteCollectionTermStore(); TermSet tset = ts.GetTermSet(termSetId); LabelMatchInformation lmi = new LabelMatchInformation(clientContext); lmi.Lcid = 1033; lmi.TrimUnavailable = true; lmi.TermLabel = term; //Search for matching terms in the term set based on label TermCollection termMatches = tset.GetTerms(lmi); clientContext.Load(tSession); clientContext.Load(ts); clientContext.Load(tset); clientContext.Load(termMatches); clientContext.ExecuteQuery(); //Set term ID to first match if (termMatches != null && termMatches.Count() > 0) { termId = termMatches.First().Id.ToString(); } return(termId); }
private async Task <TermSet> EnsureTestTermSet() { var store = TaxonomySession.GetDefaultSiteCollectionTermStore(); var groups = ClientContext.LoadQuery(store.Groups); await ClientContext.ExecuteQueryAsync(); var group = groups.FirstOrDefaultByProperty(x => x.Name, GroupName, StringComparer.Ordinal); if (group == null) { group = store.CreateGroup(GroupName, Guid.NewGuid()); await ClientContext.ExecuteQueryAsync(); } var termSet = group.TermSets.GetById(TermSetId); try { await ClientContext.ExecuteQueryAsync(); } catch (ServerException) { termSet = group.CreateTermSet(TermSetId.ToString("n"), TermSetId, 1033); await ClientContext.ExecuteQueryAsync(); } return(termSet); }
public void ImportTermsToTermStoreTest() { using (var clientContext = TestCommon.CreateClientContext()) { var site = clientContext.Site; var termName1 = "Test_Term_1" + DateTime.Now.ToFileTime(); var termName2 = "Test_Term_2" + DateTime.Now.ToFileTime(); List <string> termLines = new List <string>(); termLines.Add(_termGroupName + "|" + _termSetName + "|" + termName1); termLines.Add(_termGroupName + "|" + _termSetName + "|" + termName2); TaxonomySession session = TaxonomySession.GetTaxonomySession(clientContext); var termStore = session.GetDefaultSiteCollectionTermStore(); site.ImportTerms(termLines.ToArray(), 1033, termStore, "|"); var taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); var termGroup = termStore.Groups.GetByName(_termGroupName); var termSet = termGroup.TermSets.GetByName(_termSetName); var term1 = termSet.Terms.GetByName(termName1); var term2 = termSet.Terms.GetByName(termName2); clientContext.Load(term1); clientContext.Load(term2); clientContext.ExecuteQueryRetry(); Assert.IsNotNull(term1); Assert.IsNotNull(term2); } }
/// <summary> /// Parse {anchorid:*} tokens and replace with the id from the termstore. /// </summary> /// <param name="str">String to parse.</param> /// <param name="context"></param> /// <returns></returns> public static string ParseAnchorTermTokens(this string str, ClientRuntimeContext context) { TaxonomySession session = TaxonomySession.GetTaxonomySession(context); var termStore = session.GetDefaultSiteCollectionTermStore(); context.Load(termStore); context.ExecuteQueryRetry(); if (!termStore.ServerObjectIsNull.Value) { var pattern = @"{anchorid:[^}]*}"; str = str.ParseMatches(pattern, delegate(Capture capture, string parsedString) { string[] properties = Regex.Replace(capture.Value, @"[{}]", string.Empty).Split(':'); var group = termStore.Groups.GetByName(properties[1]); var termset = group.TermSets.GetByName(properties[2]); var term = termset.Terms.GetByName(properties[properties.Length - 1]); context.Load(term, t => t.Id); context.ExecuteQueryRetry(); return(parsedString.Remove(capture.Index, capture.Length).Insert(capture.Index, term.Id.ToString())); }); } return(str); }
private void DisplayPlantTaxonomy(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(); clientContext.Load(termStore, store => store.Name, store => store.Groups.Include( group => group.Name, group => group.TermSets.Include( termSet => termSet.Name, termSet => termSet.Terms.Include( term => term.Name) ) ).Where(group => group.Name == "Plants") ); clientContext.ExecuteQuery(); FormatTermStoreAsHtml(termStore); } }
/// <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 CreateTaxonomyFieldTest4() { using (var clientContext = TestCommon.CreateClientContext()) { // Retrieve Termset and Term TaxonomySession session = TaxonomySession.GetTaxonomySession(clientContext); var termSet = session.GetDefaultSiteCollectionTermStore().GetTermSet(_termSetId); var anchorTerm = termSet.GetTerm(_termId); clientContext.Load(termSet); clientContext.Load(anchorTerm); clientContext.ExecuteQuery(); // Retrieve List var list = clientContext.Web.Lists.GetById(_listId); clientContext.Load(list); clientContext.ExecuteQuery(); // Create field var fieldId = Guid.NewGuid(); var fieldName = "Test_" + DateTime.Now.ToFileTime(); var field = list.CreateTaxonomyField( fieldId, fieldName, "Test Fields Group", _termGroupName, anchorTerm); Assert.AreEqual(fieldId, field.Id, "Field IDs do not match."); Assert.AreEqual(fieldName, field.InternalName, "Field internal names do not match."); Assert.AreEqual("TaxonomyFieldType", field.TypeAsString, "Failed to create a TaxonomyField object."); } }
public static void Initialize(Web web, ProvisioningTemplate template) { if (!web.IsPropertyAvailable("ServerRelativeUrl")) { web.Context.Load(web, w => w.ServerRelativeUrl); web.Context.ExecuteQueryRetry(); } _web = web; _tokens = new List <TokenDefinition>(); _tokens.Add(new SiteCollectionToken(web)); _tokens.Add(new SiteToken(web)); _tokens.Add(new MasterPageCatalogToken(web)); _tokens.Add(new SiteCollectionTermStoreIdToken(web)); _tokens.Add(new KeywordsTermStoreIdToken(web)); _tokens.Add(new ThemeCatalogToken(web)); // Add lists web.Context.Load(web.Lists, ls => ls.Include(l => l.Id, l => l.Title, l => l.RootFolder.ServerRelativeUrl)); web.Context.ExecuteQueryRetry(); foreach (var list in web.Lists) { _tokens.Add(new ListIdToken(web, list.Title, list.Id)); _tokens.Add(new ListUrlToken(web, list.Title, list.RootFolder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length + 1))); } // Add parameters foreach (var parameter in template.Parameters) { _tokens.Add(new ParameterToken(web, parameter.Key, parameter.Value)); } // Add TermSetIds TaxonomySession session = TaxonomySession.GetTaxonomySession(web.Context); var termStore = session.GetDefaultSiteCollectionTermStore(); web.Context.Load(termStore.Groups, g => g.Include( tg => tg.Name, tg => tg.TermSets.Include( ts => ts.Name, ts => ts.Id) )); web.Context.ExecuteQueryRetry(); foreach (var termGroup in termStore.Groups) { foreach (var termSet in termGroup.TermSets) { _tokens.Add(new TermSetIdToken(web, termGroup.Name, termSet.Name, termSet.Id)); } } var sortedTokens = from t in _tokens orderby t.GetTokenLength() descending select t; _tokens = sortedTokens.ToList(); }
protected override void ExecuteCmdlet() { TaxonomySession session = TaxonomySession.GetTaxonomySession(ClientContext); var termStore = session.GetDefaultSiteCollectionTermStore(); ClientContext.Load(termStore, t => t.Id, t => t.Name, t => t.Groups, t => t.KeywordsTermSet); ClientContext.ExecuteQueryRetry(); WriteObject(termStore); }
protected override void ExecuteCmdlet() { TaxonomySession session = TaxonomySession.GetTaxonomySession(ClientContext); var termStore = session.GetDefaultSiteCollectionTermStore(); ClientContext.Load(termStore, t => t.ContentTypePublishingHub); ClientContext.ExecuteQueryRetry(); WriteObject(termStore.ContentTypePublishingHub); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log) { string authenticationToken = await helper.getSharePointToken(log, ConfigurationManager.AppSettings["tenantURL"]); try { ITANavigation itaNavigation = new ITANavigation(); using (var clientContext = helper.GetClientContext(ConfigurationManager.AppSettings["tenantURL"], authenticationToken)) { TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); NavigationTermSet navigationTermset; clientContext.Load(termStore, store => store.Groups.Where(g => g.IsSystemGroup == false && g.IsSiteCollectionGroup == false).Include(group => group.TermSets)); clientContext.ExecuteQuery(); foreach (var group in termStore.Groups) { foreach (var termSet in group.TermSets) { if (termSet.Name == "Offices") { List <ITANavigationItem> navigation = new List <ITANavigationItem>(); navigationTermset = NavigationTermSet.GetAsResolvedByWeb(clientContext, termSet, clientContext.Web, "GlobalNavigationTaxonomyProvider"); clientContext.Load(navigationTermset); clientContext.ExecuteQuery(); var termCollection = navigationTermset.Terms; clientContext.Load(termCollection, tc => tc.Include(t => t.Title, t => t.SimpleLinkUrl)); clientContext.ExecuteQuery(); string accessToken = await helper.getSharePointToken(log, "https://itadev.sharepoint.com"); foreach (var navTerm in termCollection) { navigation.Add(new ITANavigationItem() { title = navTerm.Title.Value, link = navTerm.SimpleLinkUrl, //visible = true, //target = "_blank", children = getChildTerms(navTerm, clientContext) }); } //getStaticLinks(itaNavigation, accessToken); itaNavigation.navigation = navigation; } } } } var output = JsonConvert.SerializeObject(itaNavigation); var response = req.CreateResponse(); response.StatusCode = HttpStatusCode.OK; response.Content = new StringContent(output, Encoding.UTF8, "application/json"); return(response); } catch (Exception ex) { return(req.CreateResponse(HttpStatusCode.OK, "Error occured : " + ex.Message)); } }
public ActionResult BuyAuctions() { var model = new SearchAdvertisementViewModel(); model.FilterList.Add(new SelectListItem { Value = "PriceAsc", Text = "Pris (Stigande)" }); model.FilterList.Add(new SelectListItem { Value = "PriceDesc", Text = "Pris (Fallande)" }); model.FilterList.Add(new SelectListItem { Value = "DateAsc", Text = "Datum (Stigande)" }); model.FilterList.Add(new SelectListItem { Value = "DateDesc", Text = "Datum (Fallande)" }); SharePointContext spContext = Session["SpContext"] as SharePointContext; using (var clientContext = spContext.CreateUserClientContextForSPHost()) { TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); if (taxonomySession != null) { TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); TermGroupCollection termGroupCol = termStore.Groups; clientContext.Load(termGroupCol, t => t.Where(y => y.Name == "Advertisements")); clientContext.ExecuteQuery(); TermGroup termGroup = termGroupCol.FirstOrDefault(); 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.Name, Text = term.Name }; model.CategoryList.Add(newItem); } } } } model.CategoryList.OrderBy(x => x.Text); model.CategoryList.Insert(0, new SelectListItem { Value = "Alla", Text = "Alla" }); return(View(model)); }
public static TermStore GetDefaultSiteCollectionTermStore(this Site site) { TaxonomySession session = TaxonomySession.GetTaxonomySession(site.Context); var termStore = session.GetDefaultSiteCollectionTermStore(); site.Context.Load(termStore); site.Context.ExecuteQuery(); return(termStore); }
protected override void ExecuteCmdlet() { TaxonomySession session = ClientContext.Site.GetTaxonomySession(); var termStore = session.GetDefaultSiteCollectionTermStore(); var termGroup = termStore.GetSiteCollectionGroup(ClientContext.Site, true); ClientContext.Load(termGroup, g => g.Id, g => g.Name); ClientContext.ExecuteQueryRetry(); WriteObject(termGroup); }
private static void InstorctionsToBeSend(ClientContext ctx) { TaxonomySession tSession = TaxonomySession.GetTaxonomySession(ctx); var defaultTermStore = tSession.GetDefaultSiteCollectionTermStore(); ctx.Load(defaultTermStore, ts => ts.Groups); ctx.ExecuteQuery(); Taxonomi.CustomTaxonomi.GenODA1Terms(defaultTermStore); Console.WriteLine("Groups in defaultTermStore:"); defaultTermStore.Groups.Select(g => g.Name).ToList().ForEach(Console.WriteLine); }
public void ExportTermSetFromTermstoreTest() { using (var clientContext = TestCommon.CreateClientContext()) { var site = clientContext.Site; TaxonomySession session = TaxonomySession.GetTaxonomySession(clientContext); var termStore = session.GetDefaultSiteCollectionTermStore(); var lines = site.ExportTermSet(_termSetId, false, termStore); Assert.IsTrue(lines.Any(), "No lines returned"); } }
private void GetTaxonomyFieldInfo(ClientContext clientContext, out Guid termStoreId, out Guid termSetId) { TaxonomySession session = TaxonomySession.GetTaxonomySession(clientContext); TermStore termStore = session.GetDefaultSiteCollectionTermStore(); TermSetCollection termSets = termStore.GetTermSetsByName("Department", 1033); clientContext.Load(termSets, tsc => tsc.Include(ts => ts.Id)); clientContext.Load(termStore); clientContext.ExecuteQuery(); termStoreId = termStore.Id; termSetId = termSets.FirstOrDefault().Id; }
public void GetTermSet(TaxonomyTypes taxonomyType, string termSetName, string groupName, bool createIfMissing, out TermStore termStore, out TermSet termSet) { termSet = null; Site site = _clientContext.Site; termStore = null; TaxonomySession session = TaxonomySession.GetTaxonomySession(_clientContext); switch (taxonomyType) { case TaxonomyTypes.SiteCollection: termStore = session.GetDefaultSiteCollectionTermStore(); break; case TaxonomyTypes.Keywords: termStore = session.GetDefaultKeywordsTermStore(); break; default: throw new Exception("Unexpected Taxonomytype"); } try { if (termStore != null) { _clientContext.Load(termStore); _clientContext.ExecuteQuery(); System.Threading.Thread.Sleep(1000); TermGroup termGroup = groupName == null ? termStore.GetSiteCollectionGroup(site, createIfMissing) : termStore.GetTermGroupByName(groupName); System.Threading.Thread.Sleep(1000); if (termGroup == null || termGroup.TermSets == null) { return; } _clientContext.Load(termGroup); _clientContext.Load(termGroup.TermSets); _clientContext.ExecuteQuery(); System.Threading.Thread.Sleep(1000); termSet = termGroup.TermSets.FirstOrDefault(ts => ts.Name == termSetName); } } catch (Exception ex) { throw; } }
/// <summary> /// Deletes terms from term stores /// </summary> /// <param name="TermsData">Data to be delete from term store</param> /// <param name="clientContext">Client context object</param> private static void DeleteMatterCenterTerms(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 groupCurrent = termStore.Groups.Where(termGroup => termGroup.Name == cltGroup.name).Count() > 0 ? termStore.Groups.GetByName(cltGroup.name) : termStore.CreateGroup(cltGroup.name, Guid.NewGuid()); clientContext.Load(groupCurrent.TermSets); //Execute the query to the server clientContext.ExecuteQuery(); TermSet clientTerm = (from t in groupCurrent.TermSets where t.Name == ConfigurationManager.AppSettings["clientterm"] select t).FirstOrDefault(); TermSet clientID = (from t in groupCurrent.TermSets where t.Name == ConfigurationManager.AppSettings["clientidterm"] select t).FirstOrDefault(); TermSet PGTerm = (from t in groupCurrent.TermSets where t.Name == ConfigurationManager.AppSettings["pgterm"] select t).FirstOrDefault(); if (clientTerm != null) { Console.WriteLine("Deleting clients"); clientTerm.DeleteObject(); } if (clientID != null) { Console.WriteLine("Deleting client ids"); clientID.DeleteObject(); } if (PGTerm != null) { Console.WriteLine("Deleting practice groups"); PGTerm.DeleteObject(); } groupCurrent.DeleteObject(); } //Execute the query to the server clientContext.ExecuteQuery(); Console.WriteLine("Existing taxonomy hierarchy deleted successfully"); }
private XElement ReadNodeAsXElements() { (this.FindForm() as frmBase).progressWorker.ReportProgress(0, "Coping terms from server"); XElement Root; //bgworker.ReportProgress(0, "Reestablishing connection to Sharepoint"); if (IsConnected) { // Get default term store taxonomySession = TaxonomySession.GetTaxonomySession(SiteContext); termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); // load termstore/termgroup/termset and first level terms SiteContext.Load(termStore, store => store.Name, store => store.Id, store => store.Groups.Include( group => group.Name, group => group.Id, group => group.TermSets.Include( termSet => termSet.Name, termSet => termSet.Id, termSet => termSet.Terms.Include( term => term.Name, term => term.TermsCount, term => term.Id) ) ) ); SiteContext.ExecuteQuery(); XElement groupsnode, termsetsnode, termnode; if (taxonomySession != null) { if (termStore != null) { // Create Root node Root = new XElement("Terms"); Root.Add(new XAttribute("Name", termStore.Name)); Root.Add(new XAttribute("Id", termStore.Id.ToString())); Root.Add(new XAttribute("Type", "TermStore")); // Create nodes for Term group foreach (TermGroup group in termStore.Groups) { groupsnode = new XElement("Term"); groupsnode.Add(new XAttribute("Name", group.Name)); groupsnode.Add(new XAttribute("Id", group.Id.ToString())); groupsnode.Add(new XAttribute("Type", "TermGroup")); // Create nodes for Term set foreach (TermSet termSet in group.TermSets) { termsetsnode = new XElement("Term"); termsetsnode.Add(new XAttribute("Name", termSet.Name)); termsetsnode.Add(new XAttribute("Id", termSet.Id.ToString())); termsetsnode.Add(new XAttribute("Type", "TermSet")); // Create nodes for first level terms foreach (Term term in termSet.Terms) { termnode = new XElement("Term"); termnode.Add(new XAttribute("Name", term.Name)); termnode.Add(new XAttribute("Id", term.Id.ToString())); termnode.Add(new XAttribute("Type", "Term")); Readterms(termsetsnode, term); } groupsnode.Add(termsetsnode); } Root.Add(groupsnode); } return Root; } } } return null; }
private static void CreateTaxonomyNavigation(ClientContext clientContext, TaxonomySession taxonomySession) { string taxonomyInputFileName = "mms.xml"; string applicationPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, taxonomyInputFileName); XDocument termsXML = XDocument.Load(applicationPath); #region for each taxonomy sessions, repeat for each term store, term group foreach (XElement termStoreElement in termsXML.Elements()) { TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); clientContext.Load(termStore.Groups); clientContext.ExecuteQuery(); if (termStore != null) { foreach (XElement termGroupElement in termStoreElement.Elements()) { string termgroupElementName = termGroupElement.Attribute("Name").Value; string termgroupElementGuid = termGroupElement.Attribute("ID").Value; TermGroup termGroup = termStore.Groups.FirstOrDefault(e => e.Name.Equals(termgroupElementName) == true); if (termGroup == null) { termGroup = termStore.CreateGroup(termgroupElementName, new Guid(termgroupElementGuid)); } clientContext.Load(termGroup); clientContext.ExecuteQuery(); foreach (XElement termSetElement in termGroupElement.Elements()) { CreateTermSetAndTerms(clientContext, termSetElement, termGroup); } } } termStore.CommitAll(); } #endregion }
/// <summary> /// Method that builds the Taxonamy tree /// </summary> /// <param name="sender">sender who invokes this method</param> /// <param name="e">Do work event arguments</param> private void GetMMSTree(object sender, DoWorkEventArgs e) { Root = null; bgworker = sender as BackgroundWorker; //bgworker.ReportProgress(0, "Reestablishing connection to Sharepoint"); if (LoginControl.IsConnected) { // Get default term store taxonomySession = TaxonomySession.GetTaxonomySession(LoginControl.SiteContext); termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); LoginControl.TermGroupMapper.Clear(); // load termstore/termgroup/termset and first level terms LoginControl.SiteContext.Load(termStore, store => store.Name, store => store.Id, store => store.DefaultLanguage, store => store.Groups.Include( group => group.Name, group => group.Id, group => group.TermSets.Include( termSet => termSet.Name, termSet => termSet.Id, termSet => termSet.Terms.Include( term => term.Name, term => term.TermsCount, term => term.Id) ) ) ); LoginControl.SiteContext.ExecuteQuery(); TreeNode groupsnode, termsetsnode, termnode; if (taxonomySession != null) { if (termStore != null) { // Create Root node Root = new TreeNode(termStore.Name); Root.Tag = termStore.Id; Root.ImageIndex = 0; Root.ContextMenuStrip = nodeContextMenu; // Create nodes for Term group foreach (TermGroup group in termStore.Groups) { groupsnode = new TreeNode(group.Name); groupsnode.Tag = group.Id; LoginControl.TermGroupMapper.Add(group.Name, group); groupsnode.ImageIndex = 1; groupsnode.ContextMenuStrip = nodeContextMenu; // Create nodes for Term set foreach (TermSet termSet in group.TermSets) { bgworker.ReportProgress(0, string.Format("Loading terms from termset \"{0}\"", termSet.Name)); termsetsnode = new TreeNode(termSet.Name); termsetsnode.Tag = termSet.Id; termsetsnode.ImageIndex = 2; termsetsnode.ContextMenuStrip = nodeContextMenu; // Create nodes for first level terms foreach (Term term in termSet.Terms) { termnode = new TreeNode(term.Name); termnode.Tag = term.Id; termnode.ImageIndex = 3; termnode.ContextMenuStrip = nodeContextMenu; Readterms(termsetsnode, term); } groupsnode.Nodes.Add(termsetsnode); } Root.Nodes.Add(groupsnode); } } } bgworker.ReportProgress(0, "Terms loaded Successfully"); } else { bgworker.ReportProgress(0, "Disconnected from Sharepoint"); } }