Exemplo n.º 1
0
 /// <summary>
 /// Iterates through the taxonomy hierarchy for the specified term set group.
 /// </summary>
 /// <param name="clientContext">Client content for specified site</param>
 /// <param name="termStore">Term Store object</param>
 /// <param name="termStoreDetails">Term Store object containing Term store data</param>
 /// <returns>Fetch Group Terms Status</returns>
 private TaxonomyResponseVM GetTaxonomyHierarchy(TermStore termStore, TermStoreDetails termStoreDetails)
 {
     try {
         if (generalSettings.IsTenantDeployment)
         {
             foreach (TermGroup termGroup in termStore.Groups)
             {
                 if (termGroup.Name == termStoreDetails.TermGroup)
                 {
                     taxonomyResponseVM = FetchGroupTerms(termGroup, termStoreDetails);
                     break;
                 }
             }
         }
         else
         {
             TermGroup termGroup = termStore.GetSiteCollectionGroup(clientContext.Site, false);
             taxonomyResponseVM = FetchGroupTerms(termGroup, termStoreDetails);
         }
     }
     catch (Exception ex)
     {
         customLogger.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable);
         throw;
     }
     return(taxonomyResponseVM);
 }
 /// <summary>
 /// An item is being deleted.
 /// </summary>
 public override void ItemDeleting(SPItemEventProperties properties)
 {
     try
     {
         SPSecurity.RunWithElevatedPrivileges(delegate()
         {
             TaxonomySession session       = new TaxonomySession(properties.Web.Site);
             TermStore mainTermStore       = session.TermStores[0];
             Group siteGroup               = mainTermStore.GetSiteCollectionGroup(properties.Web.Site);
             TermSet issuingCompanyTermSet = GetTermSetByName("Issuing Company", siteGroup);
             if (issuingCompanyTermSet != null)
             {
                 string newTerm    = properties.ListItem["Title"].ToString();
                 Term matchingTerm = GetTermByName(newTerm, issuingCompanyTermSet);
                 if (matchingTerm != null)
                 {
                     if (!matchingTerm.IsDeprecated)
                     {
                         matchingTerm.Deprecate(true);
                         mainTermStore.CommitAll();
                     }
                 }
             }
             else
             {
                 throw new Exception("There was an error connecting to the SharePoint Managed Metadata Service");
             }
         });
     }
     catch (Exception taxonomyException)
     {
         properties.ErrorMessage = taxonomyException.Message;
         properties.Status       = SPEventReceiverStatus.CancelWithError;
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SiteTaxonomyCache"/> class.
        /// </summary>
        /// <param name="site">
        /// The site.
        /// </param>
        /// <param name="termStoreName">
        /// The term store name.
        /// </param>
        /// <param name="taxonomyHelper">The taxonomy helper.</param>
        public SiteTaxonomyCache(SPSite site, string termStoreName, ITaxonomyHelper taxonomyHelper)
        {
            SPMonitoredScope monitor = null;

            this.taxonomyHelper = taxonomyHelper;

            try
            {
                monitor = new SPMonitoredScope("GSoft.Dynamite - Site taxonomy cache initialization");
            }
            catch (TypeInitializationException)
            {
                // Failed to initialize local diagnostics service. Fail to log monitor trace.
            }
            catch (ArgumentNullException)
            {
                // Failed to initialize local diagnostics service. Fail to log monitor trace.
            }

            if (site == null)
            {
                throw new ArgumentNullException("site", "SPSite is currently null, please pass a valid site as argument.");
            }

            this.SiteId = site.ID;

            // Don't send in the updateCache=true setting - let the SharePoint inner Taxonomy cache refresh itself normally (every 10 seconds or so)
            this.TaxonomySession = new TaxonomySession(site);

            if (!string.IsNullOrEmpty(termStoreName))
            {
                this.SiteCollectionGroup = this.TaxonomySession.TermStores[termStoreName].GetSiteCollectionGroup(site);
            }
            else
            {
                // Use default term store
                TermStore termStore = null;

                if (taxonomyHelper != null)
                {
                    termStore = this.taxonomyHelper.GetDefaultSiteCollectionTermStore(this.TaxonomySession);
                }
                else
                {
                    termStore = this.TaxonomySession.DefaultSiteCollectionTermStore;
                }

                if (termStore != null)
                {
                    this.SiteCollectionGroup = termStore.GetSiteCollectionGroup(site);
                }
            }

            if (monitor != null)
            {
                monitor.Dispose();
            }
        }
Exemplo n.º 4
0
        public static NavigationTermSet CriarItemNaTermStore(string url, string urlweb, Guid NavTermSetId, Guid TaggingTermSetId)
        {
            SPSite site = new SPSite(url);

            SPWeb web = site.AllWebs[urlweb];

            TaxonomySession taxonomySession = new TaxonomySession(site);

            if (taxonomySession.TermStores.Count == 0)
            {
                throw new InvalidOperationException("O Serviço de taxonomia não existe");
            }

            TermStore termStore = taxonomySession.TermStores[0];

            TermSet existingTermSet = termStore.GetTermSet(NavTermSetId);

            if (existingTermSet != null)
            {
                existingTermSet.Delete();
                termStore.CommitAll();
            }


            Group   siteCollectionGroup = termStore.GetSiteCollectionGroup(web.Site);
            TermSet termSet             = siteCollectionGroup.CreateTermSet("Teste01", NavTermSetId);

            termStore.CommitAll();

            NavigationTermSet navTermSet = NavigationTermSet.GetAsResolvedByWeb(termSet, web,
                                                                                StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider);

            termStore.CommitAll();

            navTermSet.IsNavigationTermSet = true;

            navTermSet.TargetUrlForChildTerms.Value = "/en/Pages/default.aspx";

            NavigationTerm term1 = navTermSet.CreateTerm("Term 1", NavigationLinkType.SimpleLink);

            term1.SimpleLinkUrl = "http://h9j/pt/Paginas/default.aspx";
            termStore.CommitAll();

            /*
             * NavigationTerm term2 = navTermSet.CreateTerm("Term 2", NavigationLinkType.FriendlyUrl, Guid.NewGuid());
             *
             * term2.FriendlyUrlSegment.Value = "PAgInicial";
             *
             * term2.TargetUrl.Value = "/en/Pages/default.aspx";
             */


            termStore.CommitAll();

            return(navTermSet);
        }
Exemplo n.º 5
0
    public static SiteCollectionModel GetSiteCollectionModel(string url)
    {
        SiteCollectionModel model = new SiteCollectionModel();

        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();
                model.Url = siteCollection.Url;

                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, false);
                clientContext.ExecuteQuery();
                bool siteCollectionHasPrivateGroup = CSOMObjectExists(group);
                model.hasPrivateGroup = siteCollectionHasPrivateGroup;
                model.Termsets        = new Dictionary <Guid, TermsetModel>();
                if (siteCollectionHasPrivateGroup)
                {
                    clientContext.Load(group, g => g.Id, g => g.Name, g => g.TermSets);
                    clientContext.ExecuteQuery();
                    model.GroupId   = group.Id;
                    model.GroupName = group.Name;
                    foreach (var ts in group.TermSets)
                    {
                        TermsetModel termset = new TermsetModel {
                            TermsetId = ts.Id, DisplayName = ts.Name
                        };
                        clientContext.Load(ts.Terms);
                        clientContext.ExecuteQuery();
                        List <TermModel> terms = new List <TermModel>();
                        foreach (Term term in ts.Terms)
                        {
                            TermModel newTerm = new TermModel {
                                TermName = term.Name, TermId = term.Id
                            };
                            LoadChildTerms(term, newTerm, clientContext);
                            terms.Add(newTerm);
                        }
                        termset.TopLevelTerms = terms;
                        model.Termsets.Add(ts.Id, termset);
                    }
                }
            }
            return(model);
        }
    }
Exemplo n.º 6
0
    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();
            }
        }
    }
Exemplo n.º 7
0
 public void AssignTermSetToListColumn(SPList list, Guid fieldId, string termSetName, string termSubsetName)
 {
     if (list.Fields.Contains(fieldId))
     {
         TaxonomySession session             = new TaxonomySession(list.ParentWeb.Site);
         TermStore       termStore           = session.DefaultSiteCollectionTermStore;
         TaxonomyField   field               = (TaxonomyField)list.Fields[fieldId];
         Group           siteCollectionGroup = termStore.GetSiteCollectionGroup(list.ParentWeb.Site);
         InternalAssignTermSetToTaxonomyField(termStore, field, siteCollectionGroup.Name, termSetName, termSubsetName);
     }
 }
Exemplo n.º 8
0
 public void AssignTermSetToSiteColumn(SPWeb web, Guid fieldId, string termSetName, string termSubsetName)
 {
     if (web.Fields.Contains(fieldId))
     {
         TaxonomySession session             = new TaxonomySession(web.Site);
         TermStore       termStore           = session.DefaultSiteCollectionTermStore;
         Group           siteCollectionGroup = termStore.GetSiteCollectionGroup(web.Site);
         TaxonomyField   field = (TaxonomyField)web.Site.RootWeb.Fields[fieldId];
         InternalAssignTermSetToTaxonomyField(termStore, field, siteCollectionGroup.Name, termSetName, termSubsetName);
         AssignTermSetToAllListUsagesOfSiteColumn(web.Site, termStore, fieldId, siteCollectionGroup.Name, termSetName, termSubsetName);
     }
 }
Exemplo n.º 9
0
        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;
            }
        }
Exemplo n.º 10
0
        public static Term LookupTerm(SPSite site, TermStore tesmStore, TaxonomyFieldDefinition taxFieldModel)
        {
            Group currentGroup = null;

            var termGroupName         = taxFieldModel.TermGroupName;
            var groupId               = taxFieldModel.TermGroupId;
            var isSiteCollectionGroup = taxFieldModel.IsSiteCollectionGroup;

            if (!string.IsNullOrEmpty(termGroupName))
            {
                currentGroup = tesmStore.Groups.FirstOrDefault(g => g.Name.ToUpper() == termGroupName.ToUpper());
            }
            else if (groupId != null && groupId.HasGuidValue())
            {
                currentGroup = tesmStore.GetGroup(groupId.Value);
            }
            else if (isSiteCollectionGroup.HasValue && isSiteCollectionGroup.Value)
            {
                currentGroup = tesmStore.GetSiteCollectionGroup(site);
            }

            // TODO
            // that should also check if the TermSet is there, so to scope the term

            if (currentGroup != null)
            {
                if (taxFieldModel.TermId.HasValue)
                {
                    return(tesmStore.GetTerm(taxFieldModel.TermId.Value));
                }

                if (!string.IsNullOrEmpty(taxFieldModel.TermName))
                {
                    return(tesmStore.GetTerms(taxFieldModel.TermName, taxFieldModel.TermLCID, false)
                           .FirstOrDefault(t => t.TermSet.Group.Name == currentGroup.Name));
                }
            }
            else
            {
                if (taxFieldModel.TermId.HasValue)
                {
                    return(tesmStore.GetTerm(taxFieldModel.TermId.Value));
                }

                if (!string.IsNullOrEmpty(taxFieldModel.TermName))
                {
                    return(tesmStore.GetTerms(taxFieldModel.TermName, taxFieldModel.TermLCID, false).FirstOrDefault());
                }
            }

            return(null);
        }
Exemplo n.º 11
0
        // 4.	En el evento, en la activación de la feature, activar las etiquetas SEO.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = (SPSite)properties.Feature.Parent;

            using (SPWeb web = site.RootWeb)
            {
                // configure SEO properties for the home page (does not use Navigation Term SEO properites)
                SPListItem welcomePage = web.GetListItem(web.RootFolder.WelcomePage);
                // Aqui hay 3 Resources descritos en Resources.resx
                welcomePage["SeoBrowserTitle"]    = Resources.SeoBrowserTitle;
                welcomePage["SeoMetaDescription"] = Resources.SeoDescription;
                welcomePage["SeoKeywords"]        = Resources.SeoKeywords;
                welcomePage["SeoRobotsNoIndex"]   = false.ToString();
                welcomePage.SystemUpdate();

                // configure SEO propertie on all navigation terms associated with Welcome Pages

                TaxonomySession taxSession = new TaxonomySession(site, updateCache: true);
                TermStore       termStore  = taxSession.DefaultSiteCollectionTermStore;
                Group           termGroup  = termStore.GetSiteCollectionGroup(site, true);

                // locate the navigation term set for the site collection (there can be only one)
                foreach (TermSet termSet in termGroup.TermSets)
                {
                    NavigationTermSet navTermSet = NavigationTermSet.GetAsResolvedByWeb(termSet, site.RootWeb, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider);
                    if (navTermSet.IsNavigationTermSet)
                    {
                        // determine which navigation nodes are associated with Welcome Page content types
                        foreach (NavigationTerm navTerm in navTermSet.Terms)
                        {
                            string     pageUrl  = SPUtility.GetServerRelativeUrlFromPrefixedUrl(navTerm.TargetUrl.Value);
                            SPListItem pageItem = web.GetListItem(pageUrl);
                            if (pageItem.ContentType.Name == "Welcome Page")
                            {
                                // set the SEO properties on the Navigation Term (all will have same SEO tags)
                                Term term = termSet.GetTerm(navTerm.Id);
                                term.SetLocalCustomProperty("_Sys_Seo_PropBrowserTitle", Resources.SeoBrowserTitle);
                                term.SetLocalCustomProperty("_Sys_Seo_PropDescription", Resources.SeoDescription);
                                term.SetLocalCustomProperty("_Sys_Seo_PropKeywords", Resources.SeoKeywords);
                                term.SetLocalCustomProperty("_Sys_Seo_PropSiteNoIndex", false.ToString());
                            }
                        }

                        break;
                    }
                }

                termStore.CommitAll();
                web.Update();
            }
        }
Exemplo n.º 12
0
        public static NavigationTermSet RecreateSampleNavTermSet(TestContext testContext,
                                                                 TaxonomySession taxonomySession, SPWeb web)
        {
            Console.WriteLine(testContext, "RecreateSampleNavTermSet(): START");

            // Use the first TermStore object in the list.
            if (taxonomySession.TermStores.Count == 0)
            {
                throw new InvalidOperationException("The Taxonomy Service is offline or missing.");
            }

            TermStore termStore = taxonomySession.TermStores[0];

            // Does the TermSet object already exist?
            TermSet existingTermSet = termStore.GetTermSet(TestConfig.NavTermSetId);

            if (existingTermSet != null)
            {
                Console.WriteLine(testContext, "RecreateSampleNavTermSet(): Deleting old TermSet");
                existingTermSet.Delete();
                termStore.CommitAll();
            }

            Console.WriteLine(testContext, "RecreateSampleNavTermSet(): Creating new TermSet");

            // Create a new TermSet object.
            Group   siteCollectionGroup = termStore.GetSiteCollectionGroup(web.Site);
            TermSet termSet             = siteCollectionGroup.CreateTermSet("Navigation Demo", TestConfig.NavTermSetId);

            NavigationTermSet navTermSet = NavigationTermSet.GetAsResolvedByWeb(termSet, web,
                                                                                StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider);

            navTermSet.IsNavigationTermSet          = true;
            navTermSet.TargetUrlForChildTerms.Value = "~site/Pages/Topics/Topic.aspx";

            NavigationTerm term1 = navTermSet.CreateTerm("Term 1", NavigationLinkType.SimpleLink);

            term1.SimpleLinkUrl = "http://www.bing.com/";

            NavigationTerm term2  = navTermSet.CreateTerm("Term 2", NavigationLinkType.FriendlyUrl);
            NavigationTerm term2a = term2.CreateTerm("Term 2 A", NavigationLinkType.FriendlyUrl);
            NavigationTerm term2b = term2.CreateTerm("Term 2 B", NavigationLinkType.FriendlyUrl);

            NavigationTerm term3 = navTermSet.CreateTerm("Term 3", NavigationLinkType.FriendlyUrl);

            termStore.CommitAll();

            Console.WriteLine(testContext, "RecreateSampleNavTermSet(): FINISH");

            return(navTermSet);
        }
Exemplo n.º 13
0
        public override TokenParser ProvisionObjects(Web web, Model.ProvisioningTemplate template, TokenParser parser,
                                                     ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                this.reusedTerms = new List <TermGroupHelper.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)
                {
                    this.reusedTerms.AddRange(TermGroupHelper.ProcessGroup(web.Context as ClientContext, taxSession, termStore, modelTermGroup, siteCollectionTermGroup, parser, scope));
                }

                foreach (var reusedTerm in this.reusedTerms)
                {
                    TermGroupHelper.TryReuseTerm(web.Context as ClientContext, reusedTerm.ModelTerm, reusedTerm.Parent, reusedTerm.TermStore, parser, scope);
                }
            }
            return(parser);
        }
Exemplo n.º 14
0
        public static NavigationTermSet CriarItemNaTermStore(string url, string urlweb, Guid NavTermSetId, Guid TaggingTermSetId)
        {
            SPSite site = new SPSite(url);

            SPWeb web = site.AllWebs[url];

            TaxonomySession taxonomySession = new TaxonomySession(site);

            if (taxonomySession.TermStores.Count == 0)
            {
                throw new InvalidOperationException("O Serviço de taxonomia não existe");
            }

            TermStore termStore = taxonomySession.TermStores[0];

            TermSet existingTermSet = termStore.GetTermSet(NavTermSetId);

            if (existingTermSet != null)
            {
                existingTermSet.Delete();
                termStore.CommitAll();
            }


            Group             siteCollectionGroup = termStore.GetSiteCollectionGroup(web.Site);
            TermSet           termSet             = siteCollectionGroup.CreateTermSet("Teste01", NavTermSetId);
            NavigationTermSet navTermSet          = NavigationTermSet.GetAsResolvedByWeb(termSet, web,
                                                                                         StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider);

            navTermSet.IsNavigationTermSet = true;

            navTermSet.TargetUrlForChildTerms.Value = "~site/Pages/Topics/Topic.aspx";

            NavigationTerm term1 = navTermSet.CreateTerm("Term 1", NavigationLinkType.SimpleLink);

            term1.SimpleLinkUrl = "https://ekisiot.sharepoint.com/";

            NavigationTerm term2 = navTermSet.CreateTerm("Term 2", NavigationLinkType.FriendlyUrl);

            NavigationTerm term2a = term2.CreateTerm("Term 2 A", NavigationLinkType.FriendlyUrl);

            NavigationTerm term2b = term2.CreateTerm("Term 2 B", NavigationLinkType.FriendlyUrl);

            NavigationTerm term3 = navTermSet.CreateTerm("Term 3", NavigationLinkType.FriendlyUrl);

            termStore.CommitAll();

            return(navTermSet);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Given a site collection and a taxonomy session, fetches the parent term group
        /// for the current term set.
        /// </summary>
        /// <param name="currentSession">The current taxonomy session</param>
        /// <param name="currentSite">
        /// The current site collection - used to resolve the site-collection-specific term group whenever the parent TermGroupInfo on the current TermSetInfo is null.
        /// </param>
        /// <returns>The SharePoint taxonomy term group</returns>
        public Group ResolveParentGroup(TaxonomySession currentSession, SPSite currentSite)
        {
            TermStore currentStore = this.ResolveParentTermStore(currentSession);

            if (this.Group == null && currentSite == null)
            {
                string missingSiteErrorMsg = string.Format(
                    CultureInfo.InvariantCulture,
                    "Error while resolving parent term store group of term set ID={0} Name=. Both the TermGroupInfo and currentSite specified were null. Either initialize your TermSetInfo object with a valid TermGroupInfo or specify a currentSite SPSite instance so the SiteCollectionGroup can be resolved.",
                    this.Id,
                    this.Label);

                throw new NotSupportedException(missingSiteErrorMsg);
            }

            if (this.Group == null)
            {
                // Whenever the parent TermGroupInfo is null, by convention, we assume we're dealing with
                // the default site collection term store.
                if (currentStore == null)
                {
                    // If the TermGroupInfo is null, then ResolveParentTermStore should have returned us the DefaultSiteCollectionTermStore.
                    string missingGroupErrorMsg = string.Format(
                        CultureInfo.InvariantCulture,
                        "Error while resolving parent term store group of term set ID={0} Name=. Since the parent TermGroupInfo is null, we assume we're dealing with the DefaultSiteCollectionTermStore. However this default term store appears to not be configured. Please configure your managed metadata service as the 'Default location for site columns' or specify a parent TermGroupInfo on your TermSetInfo.",
                        this.Id,
                        this.Label);

                    throw new NotSupportedException(missingGroupErrorMsg);
                }

                return(currentStore.GetSiteCollectionGroup(currentSite));
            }
            else if (currentStore != null)
            {
                return(currentStore.Groups[this.Group.Name]);
            }
            else
            {
                string missingStoreErrorMsg = string.Format(
                    CultureInfo.InvariantCulture,
                    "Error while resolving parent term store of term set ID={0} Name=. Please configure your managed metadata service as the 'Default location for site columns' or specify a parent TermGroupInfo and a grandparent TermStoreInfo on your TermSetInfo.",
                    this.Id,
                    this.Label);

                throw new NotSupportedException(missingStoreErrorMsg);
            }
        }
Exemplo n.º 16
0
        public static Term LookupTerm(SPSite site, TermStore tesmStore, TaxonomyFieldDefinition taxFieldModel)
        {
            Group currentGroup = null;

            var termGroupName = taxFieldModel.TermGroupName;
            var groupId = taxFieldModel.TermGroupId;
            var isSiteCollectionGroup = taxFieldModel.IsSiteCollectionGroup;

            if (!string.IsNullOrEmpty(termGroupName))
            {
                currentGroup = tesmStore.Groups.FirstOrDefault(g => g.Name.ToUpper() == termGroupName.ToUpper());
            }
            else if (groupId != null && groupId.HasGuidValue())
            {
                currentGroup = tesmStore.GetGroup(groupId.Value);
            }
            else if (isSiteCollectionGroup.HasValue && isSiteCollectionGroup.Value)
            {
                currentGroup = tesmStore.GetSiteCollectionGroup(site);
            }

            // TODO
            // that should also check if the TermSet is there, so to scope the term

            if (currentGroup != null)
            {
                if (taxFieldModel.TermId.HasValue)
                    return tesmStore.GetTerm(taxFieldModel.TermId.Value);

                if (!string.IsNullOrEmpty(taxFieldModel.TermName))
                {
                    return tesmStore.GetTerms(taxFieldModel.TermName, taxFieldModel.TermLCID, false)
                                    .FirstOrDefault(t => t.TermSet.Group.Name == currentGroup.Name);
                }
            }
            else
            {
                if (taxFieldModel.TermId.HasValue)
                    return tesmStore.GetTerm(taxFieldModel.TermId.Value);

                if (!string.IsNullOrEmpty(taxFieldModel.TermName))
                    return tesmStore.GetTerms(taxFieldModel.TermName, taxFieldModel.TermLCID, false).FirstOrDefault();
            }

            return null;
        }
Exemplo n.º 17
0
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = (SPSite)properties.Feature.Parent;

            using (SPWeb web = site.RootWeb)
            {
                SPListItem welcomePage = web.GetListItem(web.RootFolder.WelcomePage);
                welcomePage["SeoBrowserTitle"]    = Resources.SeoBrowserTitle;
                welcomePage["SeoMetaDescription"] = Resources.SeoDescription;
                welcomePage["SeoKeywords"]        = Resources.SeoKeywords;
                welcomePage["SeoRobotsNoIndex"]   = false.ToString();
                welcomePage.SystemUpdate();

                TaxonomySession taxSession = new TaxonomySession(site, updateCache: true);

                TermStore termStore = taxSession.DefaultSiteCollectionTermStore;

                Group termGroup = termStore.GetSiteCollectionGroup(site, true);

                foreach (TermSet termSet in termGroup.TermSets)
                {
                    NavigationTermSet navigationTermSet = NavigationTermSet.GetAsResolvedByWeb(termSet, site.RootWeb, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider);

                    if (navigationTermSet.IsNavigationTermSet)
                    {
                        foreach (NavigationTerm navTerm in navigationTermSet.Terms)
                        {
                            string     pageUrl  = SPUtility.GetServerRelativeUrlFromPrefixedUrl(navTerm.TargetUrl.Value);
                            SPListItem pageItem = web.GetListItem(pageUrl);
                            if (pageItem.ContentType.Name == "Welcome page") // si no funciona verificar
                            {
                                Term term = termSet.GetTerm(navTerm.Id);
                                term.SetLocalCustomProperty("_Sys_Seo_PropBrowserTitle", Resources.SeoBrowserTitle);
                                term.SetLocalCustomProperty("_Sys_Seo_PropDescription", Resources.SeoDescription);
                                term.SetLocalCustomProperty("_Sys_Seo_PropKeywords", Resources.SeoKeywords);
                                term.SetLocalCustomProperty("_Sys_Seo_PropSiteNoIndex", false.ToString());
                            }
                        }
                        break;
                    }
                }

                termStore.CommitAll();
                web.Update();
            }
        }
Exemplo n.º 18
0
        static TermGroup GetSiteCollectionTermGroup(ClientContext clientContext, Site siteCollection)
        {
            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 termGroup        = termStore.GetSiteCollectionGroup(siteCollection, true);

            clientContext.Load(termGroup);
            clientContext.Load(termGroup.TermSets);
            clientContext.ExecuteQuery();
            return(termGroup);
        }
Exemplo n.º 19
0
    public static void CreatePrivateGroup()
    {
        var aspnetHttpContext = System.Web.HttpContext.Current;
        var spContext         = SharePointContextProvider.Current.GetSharePointContext(aspnetHttpContext);

        using (var clientContext = spContext.CreateUserClientContextForSPHost()) {
            if (clientContext != null)
            {
                Site            siteCollection  = clientContext.Site;
                TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
                taxonomySession.UpdateCache();
                clientContext.Load(taxonomySession, ts => ts.TermStores);
                clientContext.ExecuteQuery();
                TermStore termStore = taxonomySession.TermStores.FirstOrDefault <TermStore>();
                TermGroup group     = termStore.GetSiteCollectionGroup(siteCollection, true);
                clientContext.ExecuteQuery();
            }
        }
    }
Exemplo n.º 20
0
        public static TermSet LookupTermSet(
            TermStore tesmStore,
            string termGroupName, Guid?groupId, bool?isSiteCollectionGroup, SPSite site,
            string termSetName, Guid?termSetId, int termSetLCID)
        {
            Group currentGroup = null;

            if (!string.IsNullOrEmpty(termGroupName))
            {
                currentGroup = tesmStore.Groups.FirstOrDefault(g => g.Name.ToUpper() == termGroupName.ToUpper());
            }
            else if (groupId != null && groupId.HasGuidValue())
            {
                currentGroup = tesmStore.GetGroup(groupId.Value);
            }
            else if (isSiteCollectionGroup.HasValue && isSiteCollectionGroup.Value)
            {
                currentGroup = tesmStore.GetSiteCollectionGroup(site);
            }

            if (termSetId.HasGuidValue())
            {
                if (currentGroup != null)
                {
                    return(currentGroup.TermSets.FirstOrDefault(t => t.Id == termSetId.Value));
                }

                return(tesmStore.GetTermSet(termSetId.Value));
            }

            if (!string.IsNullOrEmpty(termSetName))
            {
                if (currentGroup != null)
                {
                    return(currentGroup.TermSets.FirstOrDefault(t => t.Name.ToUpper() == termSetName.ToUpper()));
                }

                return(tesmStore.GetTermSets(termSetName, termSetLCID).FirstOrDefault());
            }

            return(null);
        }
Exemplo n.º 21
0
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPWeb myWeb = properties.Web;

                    if (properties.ListTitle == "SectionDetails")
                    {
                        #region "Create Termstore Set For Friendly URL"

                        TaxonomySession taxonomySession = new TaxonomySession(myWeb.Site);
                        taxonomySession.UpdateCache();
                        TermStore termStore       = taxonomySession.DefaultSiteCollectionTermStore;
                        Group siteCollectionGroup = termStore.GetSiteCollectionGroup(myWeb.Site, createIfMissing: true);
                        TermSet ts = siteCollectionGroup.TermSets.Where(p => p.Name.ToLower() == "lappia education").FirstOrDefault();
                        if (ts != null)//check term set is exist or not
                        {
                            NavigationTermSet navigationTermSet   = NavigationTermSet.GetAsResolvedByWeb(ts, myWeb, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider);
                            navigationTermSet.IsNavigationTermSet = true;

                            NavigationTerm subterm = navigationTermSet.CreateTerm(Convert.ToString(properties.ListItem["Title"].ToString()) + ".aspx", NavigationLinkType.FriendlyUrl, Guid.NewGuid());
                            if ((uint)System.Globalization.CultureInfo.CurrentUICulture.LCID == 1033)
                            {
                                subterm.TargetUrl.Value = SPContext.Current.Web.Url + "/Pages/" + Convert.ToString(properties.ListItem["Title"].ToString()) + ".aspx";
                            }
                            else if ((uint)System.Globalization.CultureInfo.CurrentUICulture.LCID == 1035)
                            {
                                subterm.TargetUrl.Value = SPContext.Current.Web.Url + "/Pages/" + Convert.ToString(properties.ListItem["Title"].ToString()) + ".aspx";
                            }
                        }
                        termStore.CommitAll();
                        #endregion
                    }
                });
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 22
0
        private void DeleteTermGroupsImplementation(ClientContext cc, TermStore termStore)
        {
            cc.Load(termStore.Groups, p => p.Include(t => t.Name, t => t.TermSets.Include(s => s.Name, s => s.Terms.Include(q => q.IsDeprecated, q => q.ReusedTerms))));
            cc.ExecuteQueryRetry();

            foreach (var termGroup in termStore.Groups.ToList())
            {
                DeleteTermGroupImplementation(cc, termGroup);
            }

            var siteCollectionGroup = termStore.GetSiteCollectionGroup(cc.Site, true);

            cc.Load(siteCollectionGroup, t => t.Name, t => t.TermSets.Include(s => s.Name, s => s.Terms.Include(q => q.IsDeprecated, q => q.ReusedTerms)));
            cc.ExecuteQueryRetry();
            DeleteTermGroupImplementation(cc, siteCollectionGroup, true);

            termStore.CommitAll();
            termStore.UpdateCache();
            cc.ExecuteQueryRetry();
        }
Exemplo n.º 23
0
        private List <Project_Pagemap> GetFriendlyURLSFromTaxonomy()
        {
            List <Project_Pagemap> objtest = new List <Project_Pagemap>();

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite mySite = new SPSite(SPContext.Current.Site.Url))
                    {
                        using (SPWeb myWeb = mySite.OpenWeb())
                        {
                            TaxonomySession taxonomySession = new TaxonomySession(myWeb.Site);
                            TermStore termStore             = taxonomySession.DefaultSiteCollectionTermStore;
                            Group siteCollectionGroup       = termStore.GetSiteCollectionGroup(myWeb.Site, createIfMissing: false);
                            TermSet termSet          = siteCollectionGroup.TermSets["Lappia Education"];
                            NavigationTermSet tsList = NavigationTermSet.GetAsResolvedByWeb(termSet, myWeb, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider);

                            string url = (uint)System.Globalization.CultureInfo.CurrentUICulture.LCID == 1033 ? "/sites/en-us" : "/sites/fi-fi";
                            for (int i = 0; i < tsList.Terms.Count; i++)
                            {
                                if (!string.IsNullOrEmpty(tsList.Terms[i].Title.Value.ToLower()))
                                {
                                    Project_Pagemap ptest = new Project_Pagemap();
                                    ptest.Name            = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(tsList.Terms[i].Title.Value);
                                    ptest.Subsection      = "Root";
                                    ptest.Url             = url + "/" + tsList.Terms[i].FriendlyUrlSegment.Value;
                                    ptest.TermId          = tsList.Terms[i].Id;
                                    objtest.Add(ptest);
                                    Bind(objtest, tsList.Terms[i], tsList.Terms[i].Title.Value, i, 1, tsList.Terms[i].FriendlyUrlSegment.Value, url);
                                }
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
            }
            return(objtest);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Iterates through the taxonomy hierarchy for the specified term set group.
        /// </summary>
        /// <param name="clientContext">Client content for specified site</param>
        /// <param name="termStore">Term Store object</param>
        /// <param name="termStoreDetails">Term Store object containing Term store data</param>
        /// <returns>Fetch Group Terms Status</returns>
        internal static string GetReturnFlag(ClientContext clientContext, TermStore termStore, TermStoreDetails termStoreDetails)
        {
            string returnFlagStatus = ConstantStrings.FALSE;

            if (ServiceConstantStrings.IsTenantDeployment)
            {
                foreach (TermGroup termGroup in termStore.Groups)
                {
                    if (termGroup.Name == termStoreDetails.TermGroup)
                    {
                        returnFlagStatus = FetchGroupTerms(clientContext, termGroup, termStoreDetails, returnFlagStatus);
                    }
                }
            }
            else
            {
                TermGroup termGroup = termStore.GetSiteCollectionGroup(clientContext.Site, false);
                returnFlagStatus = FetchGroupTerms(clientContext, termGroup, termStoreDetails, returnFlagStatus);
            }

            // Returns the taxonomy hierarchy for the specified term set group
            return(returnFlagStatus);
        }
 /// <summary>
 /// An item is being updated.
 /// </summary>
 public override void ItemUpdating(SPItemEventProperties properties)
 {
     try
     {
         SPSecurity.RunWithElevatedPrivileges(delegate()
         {
             TaxonomySession session       = new TaxonomySession(properties.Web.Site);
             TermStore mainTermStore       = session.TermStores[0];
             Group siteGroup               = mainTermStore.GetSiteCollectionGroup(properties.Web.Site);
             TermSet issuingCompanyTermSet = GetTermSetByName("Issuing Company", siteGroup);
             if (issuingCompanyTermSet != null)
             {
                 string currentTerm = properties.ListItem["Title"].ToString();
                 string newTerm     = properties.AfterProperties["Title"].ToString();
                 Term matchingTerm  = GetTermByName(currentTerm, issuingCompanyTermSet);
                 if (matchingTerm != null)
                 {
                     matchingTerm.Name = newTerm;
                     mainTermStore.CommitAll();
                 }
                 else
                 {
                     throw new Exception(string.Format("Could not find an Issuing Company with name {0} to update! Please contact your system administrator!", currentTerm));
                 }
             }
             else
             {
                 throw new Exception("There was an error connecting to the SharePoint Managed Metadata Service");
             }
         });
     }
     catch (Exception taxonomyException)
     {
         properties.ErrorMessage = taxonomyException.Message;
         properties.Status       = SPEventReceiverStatus.CancelWithError;
     }
 }
Exemplo n.º 26
0
        /// <summary>
        /// Applies a term store mapping to a SharePoint field
        /// </summary>
        /// <param name="site">The current site collection</param>
        /// <param name="field">The site or list column to map to the term store</param>
        /// <param name="columnTermStoreMapping">
        /// The term set or sub-term-specific anchor which will determine what's available in the field's taxonomy picker
        /// </param>
        public void AssignTermStoreMappingToField(SPSite site, SPField field, TaxonomyContext columnTermStoreMapping)
        {
            TaxonomySession session = new TaxonomySession(site);

            TermStore store = null;

            if (columnTermStoreMapping.TermStore == null)
            {
                store = session.DefaultSiteCollectionTermStore;
            }
            else
            {
                store = session.TermStores[columnTermStoreMapping.TermStore.Name];
            }

            Group termStoreGroup = null;

            if (columnTermStoreMapping.Group == null)
            {
                termStoreGroup = store.GetSiteCollectionGroup(site);
            }
            else
            {
                termStoreGroup = store.Groups[columnTermStoreMapping.Group.Name];
            }

            TaxonomyField taxoField = (TaxonomyField)field;

            if (columnTermStoreMapping.TermSubset != null)
            {
                InternalAssignTermSetToTaxonomyField(store, taxoField, termStoreGroup.Id, columnTermStoreMapping.TermSet.Id, columnTermStoreMapping.TermSubset.Id);
            }
            else
            {
                InternalAssignTermSetToTaxonomyField(store, taxoField, termStoreGroup.Id, columnTermStoreMapping.TermSet.Id, Guid.Empty);
            }
        }
Exemplo n.º 27
0
        public static TermSet LookupTermSet(
            TermStore tesmStore,
            string termGroupName, Guid? groupId, bool? isSiteCollectionGroup, SPSite site,
            string termSetName, Guid? termSetId, int termSetLCID)
        {
            Group currentGroup = null;

            if (!string.IsNullOrEmpty(termGroupName))
            {
                currentGroup = tesmStore.Groups.FirstOrDefault(g => g.Name.ToUpper() == termGroupName.ToUpper());
            }
            else if (groupId != null && groupId.HasGuidValue())
            {
                currentGroup = tesmStore.GetGroup(groupId.Value);
            }
            else if (isSiteCollectionGroup.HasValue && isSiteCollectionGroup.Value)
            {
                currentGroup = tesmStore.GetSiteCollectionGroup(site);
            }

            if (termSetId.HasGuidValue())
            {
                if (currentGroup != null)
                    return currentGroup.TermSets.FirstOrDefault(t => t.Id == termSetId.Value);

                return tesmStore.GetTermSet(termSetId.Value);
            }

            if (!string.IsNullOrEmpty(termSetName))
            {
                if (currentGroup != null)
                    return currentGroup.TermSets.FirstOrDefault(t => t.Name.ToUpper() == termSetName.ToUpper());

                return tesmStore.GetTermSets(termSetName, termSetLCID).FirstOrDefault();
            }

            return null;
        }
Exemplo n.º 28
0
        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);
        }
        private void Import(XmlElement groupElement, TermStore parentTermStore)
        {
            string groupName = groupElement.GetAttribute("Name");
            Group group = null;
            if (bool.Parse(groupElement.GetAttribute("IsSiteCollectionGroup")))
            {
                XmlNodeList siteCollectionIdNodes = groupElement.SelectNodes("./SiteCollectionAccessIds/SiteCollectionAccessId");
                if (siteCollectionIdNodes != null)
                {
                    foreach (XmlElement siteCollectionIdElement in siteCollectionIdNodes)
                    {
                        SPSite site = null;
                        if (!string.IsNullOrEmpty(siteCollectionIdElement.GetAttribute("Url")))
                        {
                            try
                            {
                                site = new SPSite(siteCollectionIdElement.GetAttribute("Url"));
                            }
                            catch
                            {
                                Logger.WriteWarning("Unable to locate a Site Collection at {0}", siteCollectionIdElement.GetAttribute("Url"));
                            }
                        }
                        else
                        {
                            try
                            {
                                site = new SPSite(new Guid(siteCollectionIdElement.GetAttribute("Id")));
                            }
                            catch
                            {
                                Logger.WriteWarning("Unable to locate a Site Collection with ID {0}", siteCollectionIdElement.GetAttribute("Id"));
                            }
                        }
                        if (site != null)
                        {
                            try
                            {
                                if (group == null)
                                {
                                    group = parentTermStore.GetSiteCollectionGroup(site);
                                }
                                if (group != null && group.IsSiteCollectionGroup)
                                {
                                    group.AddSiteCollectionAccess(site.ID);
                                }
                            }
                            catch (MissingMethodException)
                            {
                                Logger.WriteWarning("Unable to retrieve or add Site Collection group. SharePoint 2010 Service Pack 1 or greater is required. ID={0}, Url={1}", siteCollectionIdElement.GetAttribute("Id"), siteCollectionIdElement.GetAttribute("Url"));
                            }
                            finally
                            {
                                site.Dispose();
                            }
                        }
                    }
                }
            }
            try
            {
                if (group == null)
                    group = parentTermStore.Groups[groupName];
            }
            catch (ArgumentException) {}

            if (group == null)
            {
                Logger.Write("Creating Group: {0}", groupName);
            #if SP2010
                group = parentTermStore.CreateGroup(groupName);
            #else
                // Updated provided by John Calvert
                if (!string.IsNullOrEmpty(groupElement.GetAttribute("Id")))
                {
                    Guid id = new Guid(groupElement.GetAttribute("Id"));
                    group = parentTermStore.CreateGroup(groupName, id);
                }
                else
                    group = parentTermStore.CreateGroup(groupName);
                // End update
            #endif
                group.Description = groupElement.GetAttribute("Description");
            }
            parentTermStore.CommitAll();//TEST

            XmlNodeList termSetNodes = groupElement.SelectNodes("./TermSets/TermSet");
            if (termSetNodes != null && termSetNodes.Count > 0)
            {
                foreach (XmlElement termSetElement in termSetNodes)
                {
                    Import(termSetElement, group);
                }
            }
        }
Exemplo n.º 30
0
 /// <summary>
 /// Iterates through the taxonomy hierarchy for the specified term set group.
 /// </summary>
 /// <param name="clientContext">Client content for specified site</param>
 /// <param name="termStore">Term Store object</param>
 /// <param name="termStoreDetails">Term Store object containing Term store data</param>
 /// <returns>Fetch Group Terms Status</returns>
 private TaxonomyResponseVM GetTaxonomyHierarchy (TermStore termStore, TermStoreDetails termStoreDetails)
 {
     try {
         if (generalSettings.IsTenantDeployment)
         {
             foreach (TermGroup termGroup in termStore.Groups)
             {
                 if (termGroup.Name == termStoreDetails.TermGroup)
                 {
                     taxonomyResponseVM = FetchGroupTerms(termGroup, termStoreDetails);
                     break;
                 }
             }
         }
         else
         {
             TermGroup termGroup = termStore.GetSiteCollectionGroup(clientContext.Site, false);
             taxonomyResponseVM = FetchGroupTerms(termGroup, termStoreDetails);
         }
     }
     catch(Exception ex)
     {
         customLogger.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable);
         throw;
     }           
     return taxonomyResponseVM;
 }
        /// <summary>
        /// Iterates through the taxonomy hierarchy for the specified term set group.
        /// </summary>
        /// <param name="clientContext">Client content for specified site</param>
        /// <param name="termStore">Term Store object</param>
        /// <param name="termStoreDetails">Term Store object containing Term store data</param>
        /// <returns>Fetch Group Terms Status</returns>
        internal static string GetReturnFlag(ClientContext clientContext, TermStore termStore, TermStoreDetails termStoreDetails)
        {
            string returnFlagStatus = ConstantStrings.FALSE;

            if (ServiceConstantStrings.IsTenantDeployment)
            {
                foreach (TermGroup termGroup in termStore.Groups)
                {
                    if (termGroup.Name == termStoreDetails.TermGroup)
                    {
                        returnFlagStatus = FetchGroupTerms(clientContext, termGroup, termStoreDetails, returnFlagStatus);
                    }
                }
            }
            else
            {
                TermGroup termGroup = termStore.GetSiteCollectionGroup(clientContext.Site, false);
                returnFlagStatus = FetchGroupTerms(clientContext, termGroup, termStoreDetails, returnFlagStatus);
            }

            // Returns the taxonomy hierarchy for the specified term set group
            return returnFlagStatus;
        }
Exemplo n.º 32
0
        private void DeleteTermGroupsImplementation(ClientContext cc, TermStore termStore)
        {
            cc.Load(termStore.Groups, p => p.Include(t => t.Name, t => t.TermSets.Include(s => s.Name, s => s.Terms.Include(q => q.IsDeprecated, q => q.ReusedTerms))));
            cc.ExecuteQueryRetry();

            foreach (var termGroup in termStore.Groups.ToList())
            {
                DeleteTermGroupImplementation(cc, termGroup);
            }

            var siteCollectionGroup = termStore.GetSiteCollectionGroup(cc.Site, true);
            cc.Load(siteCollectionGroup, t => t.Name, t => t.TermSets.Include(s => s.Name, s => s.Terms.Include(q => q.IsDeprecated, q => q.ReusedTerms)));
            cc.ExecuteQueryRetry();
            DeleteTermGroupImplementation(cc, siteCollectionGroup, true);

            termStore.CommitAll();
            termStore.UpdateCache();
            cc.ExecuteQueryRetry();
        }
Exemplo n.º 33
0
        public static TermSet LookupTermSet(ClientRuntimeContext context, TermStore termStore,
            Site site,
            string termGroupName, Guid? termGroupId, bool? isSiteCollectionGroup,
            string termSetName, Guid? termSetId, int termSetLCID)
        {
            var storeContext = context;

            TermGroup currenGroup = null;

            if (!string.IsNullOrEmpty(termGroupName))
            {
                currenGroup = termStore.Groups.GetByName(termGroupName);

                storeContext.Load(currenGroup);
                storeContext.ExecuteQueryWithTrace();
            }
            else if (termGroupId != null && termGroupId.HasGuidValue())
            {
                currenGroup = termStore.Groups.GetById(termGroupId.Value);

                storeContext.Load(currenGroup);
                storeContext.ExecuteQueryWithTrace();
            }
            else if (isSiteCollectionGroup == true)
            {
                currenGroup = termStore.GetSiteCollectionGroup(site, false);

                storeContext.Load(currenGroup);
                storeContext.ExecuteQueryWithTrace();
            }

            if (!string.IsNullOrEmpty(termSetName))
            {
                if (currenGroup != null && (currenGroup.ServerObjectIsNull == false))
                {
                    TermSet termSet = null;

                    var scope = new ExceptionHandlingScope(storeContext);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            termSet = currenGroup.TermSets.GetByName(termSetName);
                            storeContext.Load(termSet);
                        }

                        using (scope.StartCatch())
                        {

                        }
                    }

                    storeContext.ExecuteQueryWithTrace();

                    if (termSet != null && termSet.ServerObjectIsNull == false)
                    {
                        storeContext.Load(termSet, g => g.Id);
                        storeContext.ExecuteQueryWithTrace();

                        return termSet;
                    }
                }
                else
                {
                    var termSets = termStore.GetTermSetsByName(termSetName, termSetLCID);

                    storeContext.Load(termSets);
                    storeContext.ExecuteQueryWithTrace();

                    return termSets.FirstOrDefault();
                }
            }

            if (termSetId.HasGuidValue())
            {
                if (currenGroup != null && (currenGroup.ServerObjectIsNull == false))
                {
                    TermSet termSet = null;

                    var scope = new ExceptionHandlingScope(storeContext);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            termSet = currenGroup.TermSets.GetById(termSetId.Value);
                            storeContext.Load(termSet);
                        }

                        using (scope.StartCatch())
                        {

                        }
                    }

                    storeContext.ExecuteQueryWithTrace();

                    if (termSet != null && termSet.ServerObjectIsNull == false)
                    {
                        storeContext.Load(termSet, g => g.Id);
                        storeContext.ExecuteQueryWithTrace();

                        return termSet;
                    }
                }
                else
                {
                    TermSet termSet = null;

                    var scope = new ExceptionHandlingScope(storeContext);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            termSet = termStore.GetTermSet(termSetId.Value);
                            storeContext.Load(termSet);
                        }

                        using (scope.StartCatch())
                        {

                        }
                    }

                    storeContext.ExecuteQueryWithTrace();

                    if (termSet != null && termSet.ServerObjectIsNull == false)
                    {
                        storeContext.Load(termSet, g => g.Id);
                        storeContext.ExecuteQueryWithTrace();

                        return termSet;
                    }
                }
            }

            return null;
        }
Exemplo n.º 34
0
        public static Term LookupTerm(ClientContext clientContext, TermStore termStore,
            TermSet termSet,
            TaxonomyFieldDefinition termModel)
        {
            var context = clientContext;
            var site = clientContext.Site;

            Term result = null;

            TermGroup currenGroup = null;

            var termGroupName = termModel.TermGroupName;
            var termGroupId = termModel.TermGroupId;
            var isSiteCollectionGroup = termModel.IsSiteCollectionGroup;

            if (!string.IsNullOrEmpty(termGroupName))
            {
                currenGroup = termStore.Groups.GetByName(termGroupName);

                context.Load(currenGroup);
                context.ExecuteQueryWithTrace();
            }
            else if (termGroupId != null && termGroupId.HasGuidValue())
            {
                currenGroup = termStore.Groups.GetById(termGroupId.Value);

                context.Load(currenGroup);
                context.ExecuteQueryWithTrace();
            }
            else if (isSiteCollectionGroup == true)
            {
                currenGroup = termStore.GetSiteCollectionGroup(site, false);

                context.Load(currenGroup);
                context.ExecuteQueryWithTrace();
            }

            if (currenGroup != null)
            {
                if (termModel.TermId.HasValue)
                {
                    // by ID, the only one match

                    var scope = new ExceptionHandlingScope(context);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            result = termStore.GetTerm(termModel.TermId.Value);
                            context.Load(result);
                        }

                        using (scope.StartCatch())
                        {

                        }
                    }

                    context.ExecuteQueryWithTrace();
                }
                else if (!string.IsNullOrEmpty(termModel.TermName))
                {
                    var terms = termStore.GetTerms(new LabelMatchInformation(context)
                    {
                        Lcid = termModel.TermLCID,
                        TermLabel = termModel.TermName,
                        TrimUnavailable = false
                    });

                    context.Load(terms, t => t.Include(
                                                i => i.Id,
                                                i => i.Name,
                                                i => i.TermSet,
                                                i => i.TermSet.Group,
                                                i => i.TermSet.Group.Name
                                                ));
                    context.ExecuteQueryWithTrace();

                    result = terms.FirstOrDefault(t => t.TermSet.Group.Name == currenGroup.Name);

                    if ( (result == null) && (termSet != null ))
                        // sometimes label match information does not return the term 
                    {
                        var allTerms = termSet.GetAllTerms();
                        context.Load(allTerms, t => t.Include(
                                                    i => i.Id,
                                                    i => i.Name,
                                                    i => i.TermSet,
                                                    i => i.TermSet.Group,
                                                    i => i.TermSet.Group.Name,
                                                    i => i.Labels
                                                    ));
                        context.ExecuteQueryWithTrace();

                        result = allTerms.FirstOrDefault(t => (t.TermSet.Group.Name == currenGroup.Name) && (t.Labels.Any(l=>l.Value == termModel.TermName && l.Language == termModel.TermLCID)));
                    }
                }
            }

            else
            {

                if (termModel.TermId.HasValue)
                {
                    var scope = new ExceptionHandlingScope(context);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            result = termStore.GetTerm(termModel.TermId.Value);
                            context.Load(result);
                        }

                        using (scope.StartCatch())
                        {

                        }
                    }

                    context.ExecuteQueryWithTrace();
                }
                else if (!string.IsNullOrEmpty(termModel.TermName))
                {
                    var terms = termStore.GetTerms(new LabelMatchInformation(context)
                    {
                        Lcid = termModel.TermLCID,
                        TermLabel = termModel.TermName,
                        TrimUnavailable = false
                    });

                    context.Load(terms);
                    context.ExecuteQueryWithTrace();

                    result = terms.FirstOrDefault();

                    if ((result == null) && (termSet != null))
                        // sometimes label match information does not return the termset 
                    {
                        var allTerms = termSet.GetAllTerms();
                        context.Load(allTerms, t => t.Include(
                            i => i.Id,
                            i => i.Name,
                            i => i.TermSet,
                            i => i.TermSet.Group,
                            i => i.TermSet.Group.Name,
                            i => i.Labels
                            ));
                        context.ExecuteQueryWithTrace();

                        result =
                            allTerms.FirstOrDefault(
                                t => (t.Labels.Any(l=>l.Value == termModel.TermName && l.Language == termModel.TermLCID)));

                    }

                }
                }

            if (result != null && result.ServerObjectIsNull == false)
            {
                context.Load(result);
                context.ExecuteQueryWithTrace();

                return result;
            }

            return null;
        }
        private TermSet CreateTermSet(TermStore termStore, Guid termSetID, SPWeb currentWeb, TermStoreType tsType)
        {
            //termSet is null. Create new termSet, and set the property in the property bag.
            Group siteCollectionGroup = termStore.GetSiteCollectionGroup(currentWeb.Site);
            //Group navTermsGroup = termStore.Groups["Navigation"]; //TODO: Get this from configuration or passed in.

            string termStoreName = (tsType == TermStoreType.Global) ? string.Format("Global_Nav_For{0}", termSetID) : string.Format("Local_Nav_For{0}", termSetID);
            TermSet newTermSet = siteCollectionGroup.CreateTermSet(termStoreName, termSetID);

            NavigationTermSet navTermSet = NavigationTermSet.GetAsResolvedByWeb(newTermSet, currentWeb, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider);

            navTermSet.IsNavigationTermSet = true;
            navTermSet.TargetUrlForChildTerms.Value = "~site/SitePages/Home.aspx";

            uint langID = (uint) currentWeb.Locale.LCID;

            string webTemplateID = Convert.ToString(currentWeb.Site.RootWeb.AllProperties["MARTA.WebTemplateID"]);
            string termStoreType = (tsType == TermStoreType.Global) ? "Global" : "Local";
            string termMap = SPUtility.GetLocalizedString(string.Format("$Resources:MARTANavigation,{0}_{1}", webTemplateID, termStoreType) , "MARTANavigation", langID);
            string relativeURL = currentWeb.Site.ServerRelativeUrl;

            BuildNavTerms(navTermSet, termMap, relativeURL);

            termStore.CommitAll();

            return newTermSet;
            //Add this to the property bag of the web as well.
        }