Пример #1
0
 private void SetTaxonomyField(TaxonomySession metadataService, SPListItem item, Guid fieldId, string fieldValue)
 {
     TaxonomyField taxField = item.Fields[fieldId] as TaxonomyField;
     TermStore termStore = metadataService.TermStores[taxField.SspId];
     TermSet termSet = termStore.GetTermSet(taxField.TermSetId);
     SetTaxonomyFieldValue(termSet, taxField, item, fieldValue);
 }
Пример #2
0
        public void MoveTermGroup(ClientContext sourceCtx, ClientContext targetCtx, string termGroup)
        {
          
            this._termStoreOperations = new List<TermOperation>();

            this.sourceTermStore = this.GetTermStoreObject(sourceCtx);
            this.targetTermStore = this.GetTermStoreObject(targetCtx);

            this.sourceTermGroup = this.GetTermGroup(sourceCtx, sourceTermStore, termGroup);
            this.targetTermGroup = this.GetTermGroup(targetCtx, targetTermStore, termGroup);

            if (sourceTermGroup == null)
            {
                return;
            }
            if (targetTermGroup != null)
            {
                if (sourceTermGroup.Id != targetTermGroup.Id)
                {
                    throw new Exception("The Term groups have different ID's. I don't know how to work it.");
                }
            }
            else
            {
                this.CreateTargetNewTermGroup(sourceCtx, targetCtx, sourceTermGroup, targetTermStore);
            }
        }
Пример #3
0
        /// <summary>
        /// Returns the default term store for the site collection.
        /// </summary>
        /// <param name="session">The taxonomy session.</param>
        /// <returns>The default term store or null if none is found.</returns>
        public TermStore GetDefaultSiteCollectionTermStore(TaxonomySession session)
        {
            TermStore store = null;

            if (session.DefaultSiteCollectionTermStore == null)
            {
                if (session.DefaultKeywordsTermStore == null)
                {
                    if (session.TermStores != null && session.TermStores.Count > 0)
                    {
                        store = session.TermStores[0];
                    }
                }
                else
                {
                    store = session.DefaultKeywordsTermStore;
                }
            }
            else
            {
                store = session.DefaultSiteCollectionTermStore;
            }

            return(store);
        }
Пример #4
0
        private static void AssignTermSetToAllListUsagesOfSiteColumn(SPSite site, TermStore termStore, Guid fieldId, string termStoreGroupName, string termSetName, string termSubsetName)
        {
            var listFieldsToUpdate = new List <TaxonomyField>();

            foreach (SPWeb oneWeb in site.AllWebs)
            {
                foreach (SPList oneList in oneWeb.Lists)
                {
                    foreach (SPField oneField in oneList.Fields)
                    {
                        if (oneField.Id == fieldId)
                        {
                            var oneTaxoField = oneField as TaxonomyField;
                            if (oneTaxoField != null)
                            {
                                listFieldsToUpdate.Add(oneTaxoField);
                            }
                        }
                    }
                }
            }

            // Can't update the fields while iterating over their parent collection, so gotta do it after
            foreach (TaxonomyField taxFieldToReconnect in listFieldsToUpdate)
            {
                InternalAssignTermSetToTaxonomyField(termStore, taxFieldToReconnect, termStoreGroupName, termSetName, termSubsetName);
            }
        }
Пример #5
0
        /// <summary>
        /// Updates a single-value managed metatada column
        /// </summary>
        /// <param name="taxonomyTerm"></param>
        /// <param name="item"></param>
        /// <param name="fieldToUpdate"></param>
        public static void UpdateMMField(string taxonomyTerm, SPListItem item, string fieldToUpdate)
        {
            //Get the metadata taxonomy field, a taxonomy session, the term store, and a collection of term sets in the store
            TaxonomyField   managedMetadataField = item.ParentList.Fields[fieldToUpdate] as TaxonomyField;
            Guid            tsId        = managedMetadataField.TermSetId;
            Guid            termStoreId = managedMetadataField.SspId;
            TaxonomySession tSession    = new TaxonomySession(item.ParentList.ParentWeb.Site);
            TermStore       tStore      = tSession.TermStores[termStoreId];
            TermSet         tSet        = tStore.GetTermSet(tsId);
            TermCollection  terms       = tSet.GetTerms(taxonomyTerm, false);
            Term            term        = null;

            //If term doesn't exist, create it in the term store
            if (terms.Count == 0)
            {
                Console.WriteLine("Creating term in managed metadata, {0}", taxonomyTerm);
                term = tSet.CreateTerm(taxonomyTerm, tStore.Languages[0]);
                tStore.CommitAll();
            }
            else
            {
                term = terms[0];
            }

            //Set the managed metadata field to the term retrieved from the term store
            managedMetadataField.SetFieldValue(item, term);
            item.Update();
        }
Пример #6
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);
 }
Пример #7
0
        public void Import(TermStore parentTermStore)
        {
            if (parentTermStore == null)
            {
                throw new ArgumentNullException("parentTermStore", "The parent TermStore object is null.");
            }

            if (_xml.DocumentElement.Name == "Groups")
            {
                XmlNodeList groupNodes = _xml.SelectNodes("./Groups/Group");
                if (groupNodes == null || groupNodes.Count == 0)
                {
                    return;
                }

                foreach (XmlElement groupElement in groupNodes)
                {
                    Import(groupElement, parentTermStore);
                }
            }
            else if (_xml.DocumentElement.Name == "Group")
            {
                Import(_xml.DocumentElement, parentTermStore);
            }
            parentTermStore.CommitAll();
        }
Пример #8
0
        static void Main(string[] args)
        {
            Log("\r\nTermSetSync (Server OM): Starting...\r\n");

            // Uncomment this section to create a sample input file.
#if false
            GenerateExampleXmlFile();
#else
            TermSetGoal termSetGoal = LoadTermSetGoal();

            using (SPSite site = new SPSite(siteUrl))
            {
                TaxonomySession taxonomySession = new TaxonomySession(site, updateCache: true);
                TermStore       termStore       = taxonomySession.DefaultSiteCollectionTermStore;

                Program.lcid = termStore.WorkingLanguage;

                SyncTermSet(termStore, termSetGoal);
            }
#endif

            Log("\r\nThe operation completed successfully.");

            if (Debugger.IsAttached)
            {
                Debugger.Break();
            }
        }
Пример #9
0
        private Term GetTermForLabelInternal(TermStore termStore, string termStoreGroupName, string termSetName, string termLabel)
        {
            Group   termStoreGroup = GetGroupFromTermStore(termStore, termStoreGroupName);
            TermSet termSet        = this.GetTermSetFromGroup(termStore, termStoreGroup, termSetName);

            return(GetTermForLabelInternal(termStore, termStoreGroup, termSet, termLabel));
        }
Пример #10
0
        public TermStore FetchClientTermStore(Guid termStoreId)
        {
            TaxonomySession taxonomySession = this.GetTaxonomySession();

            TermStore clientTermStore    = null;
            ExceptionHandlingScope scope = new ExceptionHandlingScope(this.ClientContext);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    clientTermStore = taxonomySession.TermStores.GetById(termStoreId);
                }
                using (scope.StartCatch())
                {
                }
            }

            this.ExecuteQuery();

            if (scope.HasException || clientTermStore.ServerObjectIsNull.Value)
            {
                throw new InvalidOperationException(string.Format("The term store was not found with ID={0}",
                                                                  termStoreId));
            }
            return(clientTermStore);
        }
Пример #11
0
        /// <summary>
        /// Retrieves a TaxonomyValue corresponding to a term label within the default term store
        /// </summary>
        /// <param name="site">The current site</param>
        /// <param name="termStoreGroupName">The group name</param>
        /// <param name="termSetName">The term set name</param>
        /// <param name="termLabel">The default label of the term</param>
        /// <returns>The taxonomy value or null if not found</returns>
        public TaxonomyValue GetTaxonomyValueForLabel(SPSite site, string termStoreGroupName, string termSetName, string termLabel)
        {
            TaxonomySession session   = this.taxonomyCacheManager.GetSiteTaxonomyCache(site, null, this.taxonomyHelper).TaxonomySession;
            TermStore       termStore = this.taxonomyHelper.GetDefaultSiteCollectionTermStore(session);

            return(GetTaxonomyValueForLabelInternal(termStore, termStoreGroupName, termSetName, termLabel));
        }
Пример #12
0
        private static IList <Term> GetTermsForLabelInternal(TermStore termStore, Group termStoreGroup, TermSet termSet, string termLabel)
        {
            if (termStore == null)
            {
                throw new ArgumentNullException("termStore");
            }

            if (termStoreGroup == null)
            {
                throw new ArgumentNullException("termStoreGroup");
            }

            if (termSet == null)
            {
                throw new ArgumentNullException("termSet");
            }

            if (string.IsNullOrEmpty(termLabel))
            {
                throw new ArgumentNullException("termLabel");
            }

            TermCollection termCollection = termSet.GetAllTerms();

            return(termCollection.Where((term) =>
            {
                return term.Labels.Any(label => label.Value == termLabel);
            }).ToList());
        }
 /// <summary>
 /// Gets the term set group from the term store.
 /// </summary>
 /// <param name="termStore">The term store.</param>
 /// <param name="groupName">The term set group name, in the term store's default working language.</param>
 /// <returns>The term set group</returns>
 public Group GetTermGroupFromStore(TermStore termStore, string groupName)
 {
     using (var timeTracker = this.timeTracker.BeginTimeTrackerScope(TimeTrackerKey))
     {
         return(this.decorated.GetTermGroupFromStore(termStore, groupName));
     }
 }
Пример #14
0
 public static TermSet LookupTermSet(
     ClientContext clientContext,
     TermStore termStore,
     TaxonomyFieldDefinition taxFieldModel)
 {
     return(LookupTermSet(clientContext, clientContext.Site, termStore, taxFieldModel));
 }
Пример #15
0
 public static TermSet LookupTermSet(ClientRuntimeContext context, Site site,
                                     TermStore termStore, TaxonomyFieldDefinition taxFieldModel)
 {
     return(LookupTermSet(context, termStore, site,
                          taxFieldModel.TermGroupName, taxFieldModel.TermGroupId, taxFieldModel.IsSiteCollectionGroup,
                          taxFieldModel.TermSetName, taxFieldModel.TermSetId, taxFieldModel.TermSetLCID));
 }
 /// <summary>
 /// Gets the term set from group.
 /// </summary>
 /// <param name="termStore">The term store.</param>
 /// <param name="group">The group.</param>
 /// <param name="termSetName">Name of the term set.</param>
 /// <returns>The term set for the specified store, group and term set name.</returns>
 public TermSet GetTermSetFromGroup(TermStore termStore, Group group, string termSetName)
 {
     using (var timeTracker = this.timeTracker.BeginTimeTrackerScope(TimeTrackerKey))
     {
         return(this.decorated.GetTermSetFromGroup(termStore, group, termSetName));
     }
 }
Пример #17
0
        private IList <TaxonomyValue> GetTaxonomyValuesForTermSetInternal(TermStore termStore, string termStoreGroupName, string termSetName)
        {
            Group   termStoreGroup = GetGroupFromTermStore(termStore, termStoreGroupName);
            TermSet termSet        = this.GetTermSetFromGroup(termStore, termStoreGroup, termSetName);

            return(GetTaxonomyValuesForTermSetInternal(termStore, termStoreGroup, termSet));
        }
Пример #18
0
        protected override void ExecuteCmdlet()
        {
            DefaultRetrievalExpressions = new Expression <Func <TermSet, object> >[] { g => g.Name, g => g.Id };
            var taxonomySession = TaxonomySession.GetTaxonomySession(ClientContext);
            // Get Term Store
            TermStore termStore = null;

            if (TermStore == null)
            {
                termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
            }
            else
            {
                termStore = TermStore.GetTermStore(taxonomySession);
            }

            var termGroup = TermGroup.GetGroup(termStore);

            if (Identity != null)
            {
                var termSet = Identity.GetTermSet(termGroup);

                ClientContext.Load(termSet, RetrievalExpressions);
                ClientContext.ExecuteQueryRetry();
                WriteObject(termSet);
            }
            else
            {
                var query    = termGroup.TermSets.IncludeWithDefaultProperties(RetrievalExpressions);
                var termSets = ClientContext.LoadQuery(query);
                ClientContext.ExecuteQueryRetry();
                WriteObject(termSets, true);
            }
        }
Пример #19
0
        private IList <Term> GetTermsForLabelInternal(TermStore termStore, string termStoreGroupName, string termSetName, string termLabel)
        {
            if (termStore == null)
            {
                throw new ArgumentNullException("termStore");
            }

            if (string.IsNullOrEmpty(termStoreGroupName))
            {
                throw new ArgumentNullException("termStoreGroupName");
            }

            if (string.IsNullOrEmpty(termSetName))
            {
                throw new ArgumentNullException("termSetName");
            }

            if (string.IsNullOrEmpty(termLabel))
            {
                throw new ArgumentNullException("termLabel");
            }

            Group   group   = GetGroupFromTermStore(termStore, termStoreGroupName);
            TermSet termSet = this.GetTermSetFromGroup(termStore, group, termSetName);

            return(GetTermsForLabelInternal(termStore, group, termSet, termLabel));
        }
 public ListItemCreatorBuilder(ClientContext ctx, Web web, List list, TaxonomySession taxonomySession, TermStore termStore)
 {
     ClientContext   = ctx;
     Web             = web;
     TaxonomySession = taxonomySession;
     TermStore       = termStore;
 }
        public void Import(TermStore parentTermStore)
        {
            if (parentTermStore == null || parentTermStore.ServerObjectIsNull.Value)
            {
                throw new ArgumentNullException("parentTermStore", "The parent TermStore object is null.");
            }

            LoadWorkingLanguage(parentTermStore);
            if (_xml.DocumentElement.Name == "Groups")
            {
                XmlNodeList groupNodes = _xml.SelectNodes("./Groups/Group");
                if (groupNodes == null || groupNodes.Count == 0)
                {
                    return;
                }

                foreach (XmlElement groupElement in groupNodes)
                {
                    Import(groupElement, parentTermStore);
                }
            }
            else if (_xml.DocumentElement.Name == "Group")
            {
                Import(_xml.DocumentElement, parentTermStore);
            }
            parentTermStore.CommitAll();
            parentTermStore.Context.ExecuteQuery();
        }
Пример #22
0
        /// <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();
                }
            }
        }
Пример #23
0
        /// <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());
        }
Пример #24
0
        private void MatchTaxonomyField(SPListItem targetSPListItem, SPField targetSPField, string sourceValue)
        {
            // this is a managed metadata field
            TaxonomyField   managedField = targetSPField as TaxonomyField;
            TaxonomySession session      = new TaxonomySession(targetSPListItem.Web.Site);
            TermStore       termStore    = session.TermStores[managedField.SspId];
            TermSet         termSet      = termStore.GetTermSet(managedField.TermSetId);
            int             lcid         = CultureInfo.CurrentCulture.LCID;

            // TODO: this is Classification code; to be replaced with the one below!
            Term myTerm = termSet.GetTerms(this.SubstringBefore(sourceValue, "|"), false).FirstOrDefault();

            if (myTerm != null)
            {
                string termString =
                    string.Concat(myTerm.GetDefaultLabel(lcid), TaxonomyField.TaxonomyGuidLabelDelimiter, myTerm.Id);
                int[] ids =
                    TaxonomyField.GetWssIdsOfTerm(targetSPListItem.Web.Site, termStore.Id, termSet.Id, myTerm.Id, true, 1);

                // set the WssId (TaxonomyHiddenList ID) to -1 so that it is added to the TaxonomyHiddenList
                if (ids.Length == 0)
                {
                    termString = "-1;#" + termString;
                }
                else
                {
                    termString = ids[0] + ";#" + termString;
                }

                targetSPListItem[targetSPField.Id] = termString;
            }
        }
Пример #25
0
        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();
                }
            }
        }
Пример #26
0
        public static bool sp_NOR(TermStore termstore, string _group, string _termset, string _nor, string _p, string _v)
        {
            LogHelper logger = LogHelper.Instance;
            
            bool _result = false;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    Guid uidStore = new Guid(idStore);
                    TermSet termset = termstore.GetTermSet(GetIdTermSet(termstore, _group, _termset));
                    Term term = termset.Terms[_nor];
                    term.SetCustomProperty(_p, _v);
                    termset.TermStore.CommitAll();
                });

                _result = true;
                logger.Log(string.Format("Proprietà {0} aggiunta nella Normativa {1} ", _p, _nor, LogSeverity.Debug));
            }
            catch (Exception ex)
            {
                _result = false;
                logger.Log(ex.Message + " : " + string.Format("Proprietà {0} non aggiunta nella Normativa {1} ", _p, _nor, LogSeverity.Error));
            }
            return _result;
        }
Пример #27
0
        /// <summary>
        /// Wires up MMS field to the specified term set.
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="field">Field to be wired up</param>
        /// <param name="mmsGroupName">Taxonomy group</param>
        /// <param name="mmsTermSetName">Term set name</param>
        public static void WireUpTaxonomyField(this Web web, Field field, string mmsGroupName, string mmsTermSetName)
        {
            TermStore termStore = GetDefaultTermStore(web);

            if (termStore == null)
            {
                throw new NullReferenceException("The default term store is not available.");
            }

            if (string.IsNullOrEmpty(mmsTermSetName))
            {
                throw new ArgumentNullException("mmsTermSetName", "The MMS term set is not specified.");
            }

            // get the term group and term set
            TermGroup termGroup = termStore.Groups.GetByName(mmsGroupName);
            TermSet   termSet   = termGroup.TermSets.GetByName(mmsTermSetName);

            web.Context.Load(termStore);
            web.Context.Load(termSet);
            web.Context.ExecuteQuery();

            // set the SSP ID and Term Set ID on the taxonomy field
            var taxField = web.Context.CastTo <TaxonomyField>(field);

            taxField.SspId     = termStore.Id;
            taxField.TermSetId = termSet.Id;
            taxField.Update();
            web.Context.ExecuteQuery();
        }
Пример #28
0
        private TermGroup GetTermGroup(ClientContext ctx, TermStore termStore, string groupName)
        {
            TermGroup _termGroup = termStore.Groups.GetByName(groupName);

            ctx.Load(_termGroup, group => group.Name, group => group.Id, group => group.Description,
                group => group.TermSets.Include(
                        termSet => termSet.Name,
                        termSet => termSet.Id));

            try
            {
                ctx.ExecuteQuery();
                if(!_termGroup.ServerObjectIsNull.Value)
                {
                    return _termGroup;
                }
                else
                {
                    return null;
                }

            }
            catch(Exception _ex)
            {
                return null;
            }
        }
Пример #29
0
        public static bool mk_NOR(TermStore termstore, string _group, string _termset, string _nor)
        {
            LogHelper logger = LogHelper.Instance;
            
            bool _result = false;
            try
            {
                TermSet termset = termstore.GetTermSet(GetIdTermSet(termstore, _group, _termset));

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    Term term = termset.CreateTerm(_nor, termstore.DefaultLanguage);
                    termset.TermStore.CommitAll();
                });

                _result = true;
                logger.Log(string.Format("Normativa {0} creata nel Set {1}", _nor, _termset, LogSeverity.Debug));
            }
            catch (Exception ex)
            {
                _result = false;
                logger.Log(ex.Message + " : " + string.Format("Normativa {0} non creata nel Set {1}", _nor, _termset, LogSeverity.Error));
            }
            return _result;
        }
Пример #30
0
        public static bool mk_At(TermStore termstore, string _group, string _termset, string _am, string _pr, string _at)
        {
            LogHelper logger = LogHelper.Instance;
            
            bool _result = false;
            try
            {
                TermSet termset = termstore.GetTermSet(GetIdTermSet(termstore, _group, _termset));
                Term term = termset.Terms[_am].Terms[_pr];

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    term.CreateTerm(_at, termstore.DefaultLanguage);
                    termset.TermStore.CommitAll();
                });

                _result = true;
                logger.Log(string.Format("Attivita {0} creata nel processo {1} dell'ambito {2} nel set {3}", _pr, _am, _termset, LogSeverity.Debug));
            }
            catch (Exception ex)
            {
                _result = false;
                logger.Log(ex.Message + " : " + string.Format("Attivita {0} creata nel processo {1} dell'ambito {2} nel set {3}", _at, _pr, _am, _termset, LogSeverity.Debug));
            }
            return _result;
        }
Пример #31
0
        public static bool MakeTermSet(TermStore termstore, string _group, string _termset)
        {
            LogHelper logger = LogHelper.Instance;

            bool _result = false;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    Guid termSetId = Guid.NewGuid();
                    Guid uidStore = GetIdTermStoreGroup(termstore, _group);
                    termstore.GetGroup(uidStore).CreateTermSet(_termset, termSetId, termstore.DefaultLanguage);
                    termstore.CommitAll();
                });

                _result = true;
                logger.Log(string.Format("Set Termini {0} creato nel Gruppo {1}", _termset, _group, LogSeverity.Debug));
            }
            catch (Exception ex)
            {
                _result = false;
                logger.Log(ex.Message + " : " + string.Format("Set Termini {0} non creato nel Gruppo {1}", _termset, _group, LogSeverity.Error));
            }
            return _result;            
        }
        internal static TermStore FindTermStore(SPSite site,
                                                string termStorename, Guid?termStoreId, bool?useDefaultSiteCollectionTermStore)
        {
            var       session   = new TaxonomySession(site);
            TermStore termStore = null;

            if (useDefaultSiteCollectionTermStore.HasValue && useDefaultSiteCollectionTermStore.Value == true)
            {
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Resolving Term Store as useDefaultSiteCollectionTermStore");
                termStore = session.DefaultSiteCollectionTermStore;
            }
            else if (termStoreId.HasGuidValue())
            {
                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving Term Store by ID: [{0}]", termStoreId.Value);
                termStore = session.TermStores[termStoreId.Value];
            }
            else if (!string.IsNullOrEmpty(termStorename))
            {
                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving Term Store by Name: [{0}]", termStorename);
                termStore = session.TermStores[termStorename];
            }


            return(termStore);
        }
Пример #33
0
 public static TermSet LookupTermSet(TermStore tesmStore, TaxonomyFieldDefinition taxFieldModel)
 {
     return LookupTermSet(tesmStore,
         taxFieldModel.TermSetName,
         taxFieldModel.TermSetId,
         taxFieldModel.TermSetLCID
         );
 }
		internal static void GenODA1Terms(TermStore defaultTermStore) {
			var ProductTS = defaultTermStore.GenerateGroup("ODA1", ConstGUIDs.GUID_G_ODA1)
				.GenerateTermSet("Product", ConstGUIDs.GUID_TS_PRODUCT);

			ProductTS.AddTerm("Virus Protection", ConstGUIDs.GUID_T_VP);
			ProductTS.AddTerm("Spam Protection", ConstGUIDs.GUID_T_SP);
			ProductTS.AddTerm("Internet Filtering", ConstGUIDs.GUID_T_IF).Context.ExecuteQuery(); 
		}
Пример #35
0
        public static Term LookupTerm(TermStore tesmStore, TaxonomyFieldDefinition taxFieldModel)
        {
            if (taxFieldModel.TermId.HasValue)
                return tesmStore.GetTerm(taxFieldModel.TermId.Value);

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

            return null;
        }
        public ManagedMetadataManager(TermStore termStore, string groupName)
        {
            if (termStore == null) throw new ArgumentNullException("termStore");

            Delimiter = ",";
            UseDefaultImporter = false;
            Encoding = Encoding.UTF8;
            _termStore = termStore;
            _groupName = groupName;
        }
Пример #37
0
        private static void ExportTerms(string directoryPath, string groupName, string termsetName, string urlSPSite)
        {
            strExportXml = new StringBuilder();

            using (SPSite site = new SPSite(urlSPSite))
            {
                String fileName = groupName + "-" + termsetName + ".xml";
                fileName = fileName.Replace("/", "").Replace("\\", "").Replace(" ", "");

                // function that return termstore from site.
                termStore = termstorefromWebApp(site);

                Group group = termStore.Groups[groupName];
                TermSet termSet = group.TermSets[termsetName];

                String termsetNameFr = String.Empty;
                try
                {
                    PropertyInfo namesProperty = termSet.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Instance).Single(pi => pi.Name == "Names");
                    System.Collections.Generic.Dictionary<int, string> names = (System.Collections.Generic.Dictionary<int, string>)namesProperty.GetValue(termSet, null);

                    if (names[1036] != null)
                    {
                        termsetNameFr = names[1036];
                    }
                }
                catch (System.Collections.Generic.KeyNotFoundException)
                {

                }

                strExportXml.Append("<?xml version=\"1.0\" encoding=\"utf-16\" ?>");
                strExportXml.Append("<Groups>");
                strExportXml.Append("<Group Name=\"" + groupName + "\">");
                strExportXml.Append("<TermSet Name=\"" + termsetName + "\" " + "NameFr=\"" + termsetNameFr + "\">");
                strExportXml.Append("<Terms>");

                foreach (Term trm in termSet.Terms)
                {
                    GetTerm(trm);
                }
                strExportXml.Append("</Terms>");
                strExportXml.Append("</TermSet>");
                strExportXml.Append("</Group>");
                strExportXml.Append("</Groups>");
                System.Console.WriteLine("Export Terms");
                FinalExport(directoryPath, fileName);
            }
        }
Пример #38
0
        private static void AddLanguages(ClientContext clientContext, TermStore termStore)
        {
            clientContext.Load(clientContext.Web, w => w.ServerRelativeUrl);
            clientContext.Load(termStore, ts => ts.Languages);
            clientContext.ExecuteQuery();

            var languages = new int[] { 1031, 1033, 1036, 1053 };
            Array.ForEach(languages, l => { 
                if (!termStore.Languages.Contains(l)) 
                    termStore.AddLanguage(l); 
            });

            termStore.CommitAll();
            clientContext.ExecuteQuery();
        }
Пример #39
0
        public static TermSet LookupTermSet(SPSite site, TermStore tesmStore, TaxonomyFieldDefinition taxFieldModel)
        {
            return LookupTermSet(tesmStore,

                taxFieldModel.TermGroupName,
                taxFieldModel.TermGroupId,
                taxFieldModel.IsSiteCollectionGroup,

                site,

                taxFieldModel.TermSetName,
                taxFieldModel.TermSetId,
                taxFieldModel.TermSetLCID
                );
        }
Пример #40
0
        public static TermStore termstorefromWebApp(SPSite site)
        {
            TaxonomySession session = new TaxonomySession(site);

            //ThroubleShooting problem during get termstore
            // http://sharepoint.stackexchange.com/questions/4097/why-are-taxonomy-term-stores-always-empty
            //http://blog.henryong.com/2012/03/20/sharepoint-dev-getting-null-taxonomysession-and-argumentoutofrangeexception-errors-on-termstore-objects/

            // 1st way;
            termStore = session.TermStores["Managed Metadata Service"];

            // 2nd way;
            // termStore = session.DefaultKeywordsTermStore;//Try  session.DefaultSiteCollectionTermStore

            return termStore;
        }
Пример #41
0
        private static TermGroup AddGroup(ClientContext clientContext, TermStore termStore)
        {
            var groupId = new Guid("8de44223-5a8f-41cd-b0e2-5634b0bb953b");
            var termGroup = termStore.GetGroup(groupId);
            clientContext.Load(termGroup);
            clientContext.ExecuteQuery();

            if (termGroup.ServerObjectIsNull.Value)
            {
                termGroup = termStore.CreateGroup("Taxonomy Navigation", groupId);
                clientContext.Load(termGroup);
                clientContext.ExecuteQuery();
            }

            return termGroup;
        }
Пример #42
0
        public SPOTermStore(TermStore termStore)
        {
            _termStore = termStore;

            if (_termStore.ServerObjectIsNull == null)
            {
                _termStore.Context.Load(_termStore);
                _termStore.Context.Load(_termStore, ts => ts.ContentTypePublishingHub);
                _termStore.Context.ExecuteQuery();
            }

            if (_termStore.IsPropertyAvailable("DefaultLanguage"))
                SetProp("DefaultLanguage", _termStore.DefaultLanguage, false);
            if (_termStore.IsPropertyAvailable("WorkingLanguage"))
                SetProp("WorkingLanguage", _termStore.WorkingLanguage, false);
        }
Пример #43
0
        private static TermSet AddTermSet(ClientContext clientContext, TermStore termStore, TermGroup termGroup)
        {
            var termSetId = new Guid("56ca0eea-635e-4cc1-ac35-fc2040f4cfe5");
            var termSet = termStore.GetTermSet(termSetId);
            clientContext.Load(termSet, ts => ts.Terms);
            clientContext.ExecuteQuery();

            if (termSet.ServerObjectIsNull.Value)
            {
                termSet = termGroup.CreateTermSet("Taxonomy Navigation", termSetId, 1033);
                termSet.SetCustomProperty("_Sys_Nav_IsNavigationTermSet", "True");
                clientContext.Load(termSet, ts => ts.Terms);
                clientContext.ExecuteQuery();
            }

            return termSet;
        }
Пример #44
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;
        }
        public XmlDocument Export(TermStore termStore)
        {
            if (termStore == null)
                throw new ArgumentNullException("termStore", "The TermStore object is null.");

            LoadLanguages(termStore);
            XmlElement termStoreElement = AddTermStoreElement(null, termStore);
            var groups = termStore.Groups;
            if (!termStore.IsObjectPropertyInstantiated("Groups") || !termStore.Groups.AreItemsAvailable)
            {
                _ctx.Load(groups);
                _ctx.ExecuteQuery();
            }
            foreach (TermGroup group in groups)
            {
                Export(termStoreElement, group);
            }
            return _xml;
        }
        public void Import(TermStore parentTermStore)
        {
            if (parentTermStore == null)
                throw new ArgumentNullException("parentTermStore", "The parent TermStore object is null.");

            if (_xml.DocumentElement.Name == "Groups")
            {
                XmlNodeList groupNodes = _xml.SelectNodes("./Groups/Group");
                if (groupNodes == null || groupNodes.Count == 0)
                    return;

                foreach (XmlElement groupElement in groupNodes)
                {
                    Import(groupElement, parentTermStore);
                }
            }
            else if (_xml.DocumentElement.Name == "Group")
            {
                Import(_xml.DocumentElement, parentTermStore);
            }
            parentTermStore.CommitAll();
        }
Пример #47
0
        public static void ConnectTaxonomyField(TaxonomyField field, TaxonomySession session, TermStore termStore, string termGroup, string termSetName, bool isOpen = false, bool createValuesInEditForm = false)
        {
            if (field == null || session == null || termStore == null) { return; }

            Group group = termStore.Groups.GetByName(termGroup);

            if (group != null)
            {
                TermSet termSet = group.TermSets.GetByName(termSetName);
                // connect the field to the specified term
                if (termSet != null)
                {
                    field.SspId = termSet.TermStore.Id;
                    field.TermSetId = termSet.Id;
                    field.Open = isOpen && termSet.IsOpenForTermCreation;
                    field.CreateValuesInEditForm = field.Open && createValuesInEditForm;
                }
            }

            field.TargetTemplate = string.Empty;
            field.AnchorId = Guid.Empty;
            field.Update();
        }
Пример #48
0
        public void ImportGroup(TermStore termStore, XElement groupElement, bool recurse = true)
        {
            //Get the group name
            string groupName = (string)groupElement.Attribute("Name");

            //Check if the group exists
            Group group = (from termgroup in termStore.Groups where termgroup.Name == groupName select termgroup).SingleOrDefault();

            //If it doesn't exist, create it
            if (group == null)
            {
                group = termStore.CreateGroup(groupName);
            }

            //Create all child term sets in the group
            if (recurse)
            {
                foreach (XElement childElement in groupElement.Elements())
                {
                    ImportTermSet(group, childElement, recurse);
                }
            }
        }
Пример #49
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;
        }
Пример #50
0
 public static TermSet LookupTermSet(ClientRuntimeContext context, Site site,
     TermStore termStore, TaxonomyFieldDefinition taxFieldModel)
 {
     return LookupTermSet(context, termStore, site,
         taxFieldModel.TermGroupName, taxFieldModel.TermGroupId, taxFieldModel.IsSiteCollectionGroup,
         taxFieldModel.TermSetName, taxFieldModel.TermSetId, taxFieldModel.TermSetLCID);
 }
Пример #51
0
        public static TermSet LookupTermSet(
            SiteModelHost currentSiteModelHost,
            TermStore termStore,
            TaxonomyFieldDefinition taxFieldModel)
        {
            var storeContext = currentSiteModelHost.HostClientContext;

            return LookupTermSet(storeContext, currentSiteModelHost.HostSite, termStore, taxFieldModel);
        }
Пример #52
0
        public static TermSet LookupTermSet(
          ClientContext clientContext,
          TermStore termStore,
          TaxonomyFieldDefinition taxFieldModel)
        {

            return LookupTermSet(clientContext, clientContext.Site, termStore, taxFieldModel);
        }
Пример #53
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;
        }
Пример #54
0
 public static TermSet LookupTermSet(TermStore tesmStore,
    string termSetName, Guid? termSetId, int termSetLCID)
 {
     return LookupTermSet(tesmStore, null, null, null, null, termSetName, termSetId, termSetLCID);
 }
Пример #55
0
 /// <summary>
 /// Gets the term set from group.
 /// </summary>
 /// <param name="termStore">The term store.</param>
 /// <param name="group">The group.</param>
 /// <param name="termSetName">Name of the term set.</param>
 /// <returns>The term set for the specified store, group and term set name.</returns>
 public TermSet GetTermSetFromGroup(TermStore termStore, Group group, string termSetName)
 {
     using (var timeTracker = this.timeTracker.BeginTimeTrackerScope(TimeTrackerKey))
     {
         return this.decorated.GetTermSetFromGroup(termStore, group, termSetName);
     }
 }
Пример #56
0
 public static Term LookupTerm(SiteModelHost currentSiteModelHost, TermStore termStore,
     TermSet termSet,
     TaxonomyFieldDefinition termModel)
 {
     return LookupTerm(currentSiteModelHost.HostClientContext, termStore, termSet, termModel);
 }
Пример #57
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 Term GetTermForLabelInternal(TermStore termStore, string termStoreGroupName, string termSetName, string termLabel)
        {
            Group termStoreGroup = GetGroupFromTermStore(termStore, termStoreGroupName);
            TermSet termSet = this.GetTermSetFromGroup(termStore, termStoreGroup, termSetName);

            return GetTermForLabelInternal(termStore, termStoreGroup, termSet, termLabel);
        }
Пример #59
0
 /// <summary>
 /// Gets the term set group from the term store.
 /// </summary>
 /// <param name="termStore">The term store.</param>
 /// <param name="groupName">The term set group name, in the term store's default working language.</param>
 /// <returns>The term set group</returns>
 public Group GetTermGroupFromStore(TermStore termStore, string groupName)
 {
     using (var timeTracker = this.timeTracker.BeginTimeTrackerScope(TimeTrackerKey))
     {
         return this.decorated.GetTermGroupFromStore(termStore, groupName);
     }
 }
        private IList<Term> GetTermsForTermSetInternal(TermStore termStore, string termStoreGroupName, string termSetName)
        {
            if (termStore == null)
            {
                throw new ArgumentNullException("termStore");
            }

            if (string.IsNullOrEmpty(termStoreGroupName))
            {
                throw new ArgumentNullException("termStoreGroupName");
            }

            if (string.IsNullOrEmpty(termSetName))
            {
                throw new ArgumentNullException("termSetName");
            }

            IList<Term> termsList = new List<Term>();

            Group group = GetGroupFromTermStore(termStore, termStoreGroupName);
            TermSet termSet = this.GetTermSetFromGroup(termStore, group, termSetName);

            return GetTermsForTermSetInternal(termStore, group, termSet);
        }