Responsive Ads Here

Tuesday, July 17, 2012

Insert terms to term store using SharePoint object model


SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(siteUrl))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            oWeb.AllowUnsafeUpdates = true;
                            TaxonomySession _TaxonomySession = newTaxonomySession(oSite);


                            //Get instance of the Term Store
                            TermStore _TermStore = _TaxonomySession.TermStores[Constants.ManagedMetaDataServiceAppName];
                            //Get instance of Group
                            Group group = _TermStore.Groups.FirstOrDefault(e => e.Name == Constants.AIPTermsGroup);


                            //Get the termset of projectType
                            TermSet termset_ProjectTerms = group.TermSets.FirstOrDefault(e => e.Name ==Constants.ProjectTermsTermSet);

                            #region BU
                            //Get the term --BU
                            Term term_BU = termset_ProjectTerms.Terms.FirstOrDefault(e => e.Name ==Constants.TermBU);
                            //Check for BU not emptty
                            if (!string.IsNullOrEmpty(BUTerm))
                            {
                                //Check whether the current projects BU exists in BU term
                                if (term_BU.Terms.Where(t => t.Name == BUTerm).Count() == 0)
                                {
                                    //Add the term if it doesnt exists
                                    term_BU.CreateTerm(BUTerm, lcid);
                                }
                            }

                            #endregion BU


                            //commit the changes to SharePoint
                            _TermStore.CommitAll();


                            oWeb.AllowUnsafeUpdates = false;
                        }
                    }
                });

No comments:

Post a Comment