コード例 #1
0
        // Create the goal objects in the specified term store
        static void ImportTermSet(TermStore termStore, TermSetGoal termSetGoal)
        {
            Log("Setting up term set \"" + termSetGoal.Name + "\"");
            Group group = termStore.Groups.FirstOrDefault(g => g.Name == termSetGoal.GroupName);

            if (group == null)
            {
                Log("Creating missing group \"" + termSetGoal.GroupName + "\"");
                group = termStore.CreateGroup(termSetGoal.GroupName);
            }

            TermSet termSet = termStore.GetTermSet(termSetGoal.Id);

            if (termSet != null)
            {
                Log("Deleting existing term set \"" + termSetGoal.Name + "\"");
                termSet.Delete();
                termStore.CommitAll();
            }

            Log("Creating new term set \"" + termSetGoal.Name + "\"");
            termSet = group.CreateTermSet(termSetGoal.Name, termSetGoal.Id);
            termStore.CommitAll();

            ImportTerms(termSet, termSetGoal);

            termStore.CommitAll();
        }
コード例 #2
0
        public SPOTermGroup CreateGroup(string name, Guid id, string description)
        {
            var       ctx   = _termStore.Context;
            TermGroup group = null;
            ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    group = _termStore.Groups.GetByName(name);
                    ctx.Load(group);
                }
                using (scope.StartCatch())
                {
                }
            }
            ctx.ExecuteQuery();

            if (group == null || group.ServerObjectIsNull == null || group.ServerObjectIsNull.Value)
            {
                group             = _termStore.CreateGroup(name, id);
                group.Description = description;
                ctx.ExecuteQuery();
                ctx.Load(group);
                ctx.ExecuteQuery();
                return(new SPOTermGroup(group));
            }
            else
            {
                throw new Exception("The specified term group already exists.");
            }
        }
コード例 #3
0
        //ModifyItem
        //CreateTermSet
        public void CreateTermSet(ClientContext context)
        {
            //English(Default English Locale ID)
            int lcid = 1033;
            //Get termSession
            TaxonomySession taxonomy = TaxonomySession.GetTaxonomySession(context);

            if (taxonomy != null)
            {
                //Get TermStore
                TermStore termStore = taxonomy.GetDefaultKeywordsTermStore();
                if (termStore != null)
                {
                    //Set TermGroup
                    TermGroup termGroup = termStore.CreateGroup(TERMGROUPNAME, Guid.NewGuid());
                    //Set TermSet
                    TermSet termSetCollection = termGroup.CreateTermSet(TERMSETNAME, Guid.NewGuid(), lcid);
                    //Set Terms
                    termSetCollection.CreateTerm(TERM_ELEKTRONIK, lcid, Guid.NewGuid());
                    termSetCollection.CreateTerm(TERM_FORDON, lcid, Guid.NewGuid());
                    termSetCollection.CreateTerm(TERM_FRITIDOCHHOBBY, lcid, Guid.NewGuid());
                    termSetCollection.CreateTerm(TERM_HYGIENARTIKLAR, lcid, Guid.NewGuid());
                    termSetCollection.CreateTerm(TERM_MÖBLER, lcid, Guid.NewGuid());

                    context.ExecuteQuery();
                }
            }
        }
コード例 #4
0
        private static void ProcessGroup(XmlNode termGroup)
        {
            if (termGroup != null)
            {
                string strGroupName = termGroup.Attributes["Name"].Value;

                //Get TermStore Groups
                GroupCollection groups = termStore.Groups;

                //Find group that we want to Import to
                Group thisGroup = groups.Where(g => g.Name == strGroupName).SingleOrDefault();

                //Check that group exist
                if (thisGroup != null)
                {
                    //Get Current group
                    group = termStore.GetGroup(thisGroup.Id);
                }
                else //If group doesn't exist, create it
                {
                    group = termStore.CreateGroup(strGroupName);
                    termStore.CommitAll();
                }
                Console.WriteLine(strGroupName);

                ProcessTermSet(termGroup);
            }
        }
コード例 #5
0
        private Group GetGroup(bool ignoreExistingGroup)
        {
            //Get TermStore Groups
            GroupCollection groups = _termStore.Groups;
            //Find group that we want to Import to
            Group thisGroup = groups.GetByName(_groupName);

            //Check that group exist
            if (thisGroup != null)
            {
                if (!ignoreExistingGroup)
                {
                    //Get all termset from that group
                    TermSetCollection termSets = thisGroup.TermSets;
                    //For each termset, delete it
                    foreach (TermSet termSet in termSets)
                    {
                        termSet.Delete();
                    }

                    //save all changes to TermStore
                    _termStore.CommitAll();
                }
            }
            //If group doesn't exist, create it
            else
            {
                thisGroup = _termStore.CreateGroup(_groupName);
            }

            return(thisGroup);
        }
コード例 #6
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();
                }
            }
        }
コード例 #7
0
        public static TermGroup GenerateGroup(this TermStore ts, string name, Guid guid)
        {
            var group = ts.Groups.FirstOrDefault(g => g.Name == name);

            if (group == null)
            {
                group = ts.CreateGroup(name, guid);
            }
            return(group);
        }
コード例 #8
0
        // Create the TermSetGoal objects in the specified TermStore object.
        static void SyncTermSet(TermStore termStore, TermSetGoal termSetGoal)
        {
            Group group = termStore.Groups.FirstOrDefault(g => g.Name == termSetGoal.GroupName);

            if (group == null)
            {
                Log("* Creating missing group \"" + termSetGoal.GroupName + "\"");
                group = termStore.CreateGroup(termSetGoal.GroupName);
            }

            TermSet termSet = termStore.GetTermSet(termSetGoal.Id);

            if (termSet == null)
            {
                Log("* Creating missing term set \"" + termSetGoal.Name + "\"");
                termSet = group.CreateTermSet(termSetGoal.Name, termSetGoal.Id, lcid);
            }
            else
            {
                if (termSet.Group.Id != group.Id)
                {
                    Log("* Moving term set to group \"" + group.Name + "\"");
                    termSet.Move(group);
                }

                if (termSet.Name != termSetGoal.Name)
                {
                    termSet.Name = termSetGoal.Name;
                }
            }

            termStore.CommitAll();

            // Load the tree of terms as a flat list.
            Dictionary <Guid, Term> termsById = new Dictionary <Guid, Term>();

            foreach (Term term in termSet.GetAllTerms())
            {
                termsById.Add(term.Id, term);
            }

            Log("Step 1: Adds and Moves");
            ProcessAddsAndMoves(termSet, termSetGoal, termsById);

            Log("Step 2: Deletes");
            // Requery the TermSet object to reflect changes to the topology.
            termSet = termStore.GetTermSet(termSetGoal.Id);
            ProcessDeletes(termSet, termSetGoal); // Step 2

            Log("Step 3: Property Updates");
            termSet = termStore.GetTermSet(termSetGoal.Id);
            ProcessPropertyUpdates(termSet, termSetGoal); // Step 3

            termStore.CommitAll();
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: booko365dev/BookExamples
        //gavdcodeend 01

        //gavdcodebegin 02
        static void SpCsCsomCreateTermGroup(ClientContext spCtx)
        {
            string termStoreName = "Taxonomy_hVIOdhme2obc+5zqZXqqUQ==";

            TaxonomySession myTaxSession = TaxonomySession.GetTaxonomySession(spCtx);
            TermStore       myTermStore  = myTaxSession.TermStores.GetByName(termStoreName);

            TermGroup myTermGroup = myTermStore.CreateGroup(
                "CsCsomTermGroup", Guid.NewGuid());

            spCtx.ExecuteQuery();
        }
コード例 #10
0
        public TermGroup CreateGroup(TermStore termStore, string groupname)
        {
            TermGroup group = termStore.Groups.FirstOrDefault(x => x.Name == groupname);

            if (group == null)
            {
                group = termStore.CreateGroup(groupname, Guid.NewGuid());
            }
            Ctx.Load(group);
            Ctx.ExecuteQuery();
            return(group);
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            TaxonomySession session      = new TaxonomySession(SPContext.Current.Site);
            TermStore       termStore    = session.TermStores[0];
            Group           myGroup      = termStore.CreateGroup("Training");
            TermSet         topicTermSet = myGroup.CreateTermSet("Topics");

            string[] topics = new string[] { "CRM", "SharePoint", "End User", "Developer", "IT Administrator", "Introduction", "Advanced" };
            foreach (string topic in topics)
            {
                Term newTerm = topicTermSet.CreateTerm(topic, 1033);
            }
            termStore.CommitAll();
        }
コード例 #12
0
        protected void btnCreateGroup_Click(object sender, EventArgs e)
        {
            // Update Term set drop down for the taxonomy field creation.
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var ctx = spContext.CreateUserClientContextForSPHost())
            {
                TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(ctx);
                TermStore       termStore       = taxonomySession.GetDefaultSiteCollectionTermStore();
                termStore.CreateGroup("Samples", SampleGroupId);
                ctx.ExecuteQuery();
            }
            // Update drop downs
            GenerateTaxonomyDropDowns();
        }
コード例 #13
0
        private static Group CreateGroup()
        {
            Group group = null;

            group = TermStore.CreateGroup(TaxonomyGroup.Name, TaxonomyGroup.Id);

            if (group != null)
            {
                return(group);
            }
            else
            {
                throw new Exception(String.Format("Group {0} could not be created!", TaxonomyGroup.Name));
            }
        }
コード例 #14
0
        private void CreatePlantTaxonomy(string contextToken, string hostWeb)
        {
            using (var clientContext
                       = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority))
            {
                //Create Taxonomy
                //To manage terms, we must create a new Taxonomy Session object
                TaxonomySession session = TaxonomySession.GetTaxonomySession(clientContext);

                //Get the termstore
                //TermStore termstore = session.TermStores["Managed Metadata Service"];
                TermStore termStore = session.GetDefaultSiteCollectionTermStore();

                //Create a term group
                //Group plantsGroup = termstore.CreateGroup("Plants", Guid.NewGuid());
                TermGroup plantsGroup = termStore.CreateGroup("Plants", Guid.NewGuid());

                //Create a term set
                TermSet flowersTermSet = plantsGroup.CreateTermSet("Flowers", Guid.NewGuid(), 1033);

                //Create some terms
                Term tulipsTerm    = flowersTermSet.CreateTerm("Tulips", 1033, Guid.NewGuid());
                Term orchidsTerm   = flowersTermSet.CreateTerm("Orchids", 1033, Guid.NewGuid());
                Term daffodilsTerm = flowersTermSet.CreateTerm("Daffodils", 1033, Guid.NewGuid());

                //Create a child term within the Orchids term
                Term vanillaTerm = orchidsTerm.CreateTerm("Vanilla", 1033, Guid.NewGuid());

                //You should set properties for every term. In this example, we'll
                //do just one for brevity
                vanillaTerm.SetDescription("A common orchid whose pods are used in desserts", 1033);
                //Use CreateLabel to add synomyns and alternates
                vanillaTerm.CreateLabel("Vanilla planifolia", 1033, false);
                vanillaTerm.CreateLabel("Flat-leaved vanilla", 1033, false);

                //When we are finished making changes, we must commit them
                try
                {
                    //termstore.CommitAll();
                    clientContext.ExecuteQuery();
                    resultsLabel.Text = "Taxonomy created successfully";
                }
                catch (Exception ex)
                {
                    resultsLabel.Text = "There was an error: " + ex.Message;
                }
            }
        }
コード例 #15
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;
        }
コード例 #16
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);
        }
コード例 #17
0
        // 5.	Crear una función para definir los grupos
        static Group CreateGroup(TermStore termStore, string name)
        {
            Group g = null;

            try
            {
                g = termStore.Groups[name];
            }
            catch (Exception ex) { }

            if (g == null)
            {
                g = termStore.CreateGroup(name);
                termStore.CommitAll();
            }

            return(g);
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: kirankakanur/SPOUtilities
        // NOTE: The user account referenced in the SPOUserName setting in App.Config file must be a Term Store Administrator
        // in order to to create Terms in Term Store
        // This is granted in the SharePoint Admin site (for example:https://<yourtenant>-admin.sharepoint.com/_layouts/15/termstoremanager.aspx)
        static void CreateTermsInTermStore(string siteUrl, string userName, string userPassword)
        {
            try
            {
                //get client context
                ClientContext context = GetUserContext(siteUrl, userName, userPassword);

                TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(context);
                context.Load(taxSession);
                context.ExecuteQuery();


                if (taxSession != null)
                {
                    TermStore termStore = taxSession.GetDefaultSiteCollectionTermStore();
                    if (termStore != null)
                    {
                        //
                        // Create group, termset, and terms.
                        //
                        TermGroup myGroup   = termStore.CreateGroup("Custom", Guid.NewGuid());
                        TermSet   myTermSet = myGroup.CreateTermSet("Countries", Guid.NewGuid(), 1033);
                        myTermSet.CreateTerm("United States of America", 1033, Guid.NewGuid());
                        myTermSet.CreateTerm("Canada", 1033, Guid.NewGuid());
                        myTermSet.CreateTerm("Mexico", 1033, Guid.NewGuid());
                        myTermSet.CreateTerm("India", 1033, Guid.NewGuid());
                        myTermSet.CreateTerm("Thailand", 1033, Guid.NewGuid());
                        myTermSet.CreateTerm("Australia", 1033, Guid.NewGuid());

                        context.ExecuteQuery();
                    }
                }
            }
            catch (ClientRequestException clientEx)
            {
                Console.WriteLine("Client side error occurred: {0} \n{1} " + clientEx.Message + clientEx.InnerException);
                throw clientEx;
            }
            catch (ServerException serverEx)
            {
                Console.WriteLine("Server side error occurred: {0} \n{1} " + serverEx.Message + serverEx.InnerException);
                throw serverEx;
            }
        }
コード例 #19
0
        /// <summary>
        /// Since the administrator members like TermStore.DoesUserHavePermissions aren't available in the client API, this is currently how we check if user has permissions
        /// </summary>
        /// <param name="context"></param>
        /// <param name="termStore"></param>
        /// <returns></returns>
        private bool IsCurrentUserTermStoreAdministrator(ClientContext context, TermStore termStore)
        {
            const string testGroupName = "SherpaTemporaryTestGroup";
            var          testGroupGuid = new Guid("0972a735-b89a-400f-a858-b80e29492b62");

            try
            {
                var termGroup = termStore.CreateGroup(testGroupName, testGroupGuid);
                context.ExecuteQuery();

                termGroup.DeleteObject();
                context.ExecuteQuery();
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
コード例 #20
0
        public static bool MakeTermstoreGroup(TermStore termstore, string _group)
        {
            LogHelper logger = LogHelper.Instance;

            bool _result = false;
            try
            {
                Group group = termstore.CreateGroup(_group);
                termstore.CommitAll();
                _result = true;
                logger.Log(string.Format("Gruppo {0} creato nel termstore {1}", _group, termstore.Name.ToString(), LogSeverity.Debug));
            }
            catch (Exception ex)
            {
                _result = false;
                logger.Log(string.Format("Gruppo {0} non creato nel termstore {1}", _group, termstore.Name.ToString() + "  :  " + ex.Message, LogSeverity.Error));
            }
            return _result;
        }
コード例 #21
0
        public void WriteTaxonomyToTermStore(ClientContext context)
        {
            Log.Info("Taxonomy import started");
            ValidateConfiguration(_termGroup);
            TermStore termStore = GetTermStore(context);

            if (!IsCurrentUserTermStoreAdministrator(context, termStore))
            {
                Log.Warn("Couldn't verify admin access. You must be a term store administrator to perform this operation. Trying to continue...");
            }

            var termGroup = termStore.Groups.ToList().FirstOrDefault(g => g.Id == _termGroup.Id) ??
                            termStore.CreateGroup(_termGroup.Title, _termGroup.Id);

            context.Load(termGroup, x => x.TermSets);
            context.ExecuteQuery();

            foreach (var termSet in _termGroup.TermSets)
            {
                var spTermSet = termStore.GetTermSet(termSet.Id);
                context.Load(spTermSet, x => x.Terms);
                context.ExecuteQuery();
                if (spTermSet.ServerObjectIsNull != null && spTermSet.ServerObjectIsNull.Value)
                {
                    spTermSet = termGroup.CreateTermSet(termSet.Title, termSet.Id, termStore.DefaultLanguage);
                    if (!string.IsNullOrEmpty(termSet.CustomSortOrder))
                    {
                        spTermSet.CustomSortOrder = termSet.CustomSortOrder;
                    }
                    foreach (var prop in termSet.CustomProperties)
                    {
                        spTermSet.SetCustomProperty(prop.Key, prop.Value);
                    }
                    context.Load(spTermSet, x => x.Terms);
                    context.ExecuteQuery();
                }

                foreach (var term in termSet.Terms)
                {
                    CreateTerm(context, termStore, term, spTermSet);
                }
            }
        }
コード例 #22
0
        private void Import(XmlElement groupElement, TermStore parentTermStore)
        {
            string groupName = groupElement.GetAttribute("Name");
            Guid   groupId   = new Guid(groupElement.GetAttribute("Id"));

            LoadWorkingLanguage(parentTermStore);

            TermGroup group = null;
            ExceptionHandlingScope scope = new ExceptionHandlingScope(_ctx);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    group = parentTermStore.Groups.GetByName(groupName);
                    _ctx.Load(group);
                }
                using (scope.StartCatch())
                {
                }
            }
            _ctx.ExecuteQuery();

            if (group == null || group.ServerObjectIsNull == null || group.ServerObjectIsNull.Value)
            {
                _cmdlet.WriteVerbose(string.Format("Creating Group: {0}", groupName));

                group             = parentTermStore.CreateGroup(groupName, groupId);
                group.Description = groupElement.GetAttribute("Description");
                group.Context.ExecuteQuery();
                parentTermStore.CommitAll();
                parentTermStore.Context.ExecuteQuery();
            }
            XmlNodeList termSetNodes = groupElement.SelectNodes("./TermSets/TermSet");

            if (termSetNodes != null && termSetNodes.Count > 0)
            {
                foreach (XmlElement termSetElement in termSetNodes)
                {
                    Import(termSetElement, group);
                }
            }
        }
コード例 #23
0
ファイル: TermStore.cs プロジェクト: ronaldmavarez/Scripts
        public static void ImportCSV(string csvPath, string SiteURL)
        {
            SPSite oSite = new SPSite(SiteURL);
            SPWeb  oWeb  = oSite.OpenWeb();

            string groupName = "TermSetGroupImport";

            try
            {
                StreamReader    reader  = File.OpenText(csvPath);
                TaxonomySession session = new TaxonomySession(oSite);

                TermStore store = session.TermStores[0];
                var       exist = from t in store.Groups where t.Name == groupName select t;

                Group group;

                if (exist == null)
                {
                    group = store.CreateGroup(groupName);
                }
                else
                {
                    group = exist.FirstOrDefault();
                }

                ImportManager manager = store.GetImportManager();

                bool   allTermsAdded = false;
                string errorMsg      = string.Empty;

                manager.ImportTermSet(group, reader, out allTermsAdded, out errorMsg);

                if (errorMsg.Length > 0)
                {
                    throw new Exception(errorMsg);
                }
            }
            catch (Exception ex) {
                Console.WriteLine(ex);
            }
        }
コード例 #24
0
        protected void createTaxonomyButton_Click(object sender, EventArgs e)
        {
            SPSite currentSite = SPContext.Current.Site;
            //To manage terms, we must create a new Taxonomy Session object
            TaxonomySession session = new TaxonomySession(currentSite);
            //Get the termstore
            TermStore termstore = session.TermStores["Managed Metadata Service"];

            //Create a term group
            Group plantsGroup = termstore.CreateGroup("Plants");

            //Create a term set
            TermSet flowersTermSet = plantsGroup.CreateTermSet("Flowers");

            //Create some terms
            Term tulipsTerm    = flowersTermSet.CreateTerm("Tulips", 1033);
            Term orchidsTerm   = flowersTermSet.CreateTerm("Orchids", 1033);
            Term daffodilsTerm = flowersTermSet.CreateTerm("Daffodils", 1033);

            //Create a child term within the Orchids term
            Term vanillaTerm = orchidsTerm.CreateTerm("Vanilla", 1033);

            //You should set properties for every term. In this example, we'll
            //do just one for brevity
            vanillaTerm.SetDescription("A common orchid whose pods are used in desserts", 1033);
            //Use CreateLabel to add synomyns and alternates
            vanillaTerm.CreateLabel("Vanilla planifolia", 1033, false);
            vanillaTerm.CreateLabel("Flat-leaved vanilla", 1033, false);

            //When we are finished making changes, we must commit them
            try
            {
                termstore.CommitAll();
                resultsLabel.Text = "Taxonomy created successfully";
            }
            catch (Exception ex)
            {
                resultsLabel.Text = "There was an error: " + ex.Message;
            }
        }
コード例 #25
0
        public static void CriarItemNaTermStore(string url)
        {
            using (SPSite site = new SPSite(url))
            {
                TaxonomySession session = new TaxonomySession(site);

                TermStore termStore = session.TermStores["MMS"];


                Group group1 = termStore.CreateGroup("Links1");

                TermSet termSet1 = group1.CreateTermSet("TermSet1");

                Term term1 = termSet1.CreateTerm("Term1", 1033);

                Term term2 = termSet1.CreateTerm("Term2", 1033);

                Term term3 = termSet1.CreateTerm("Term3", 1033);

                Term term1a = term1.CreateTerm("Term1a", 1033);

                Term term1b = term1.CreateTerm("Term1b", 1033);

                termStore.CommitAll();

                term1.SetDescription("This is term1", 1033);

                term1.CreateLabel("TermOne", 1033, false);

                term1.CreateLabel("FirstTerm", 1033, false);

                termStore.CommitAll();


                term3.Delete();

                termStore.CommitAll();
            }
        }
コード例 #26
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);
                }
            }
        }
コード例 #27
0
ファイル: Program.cs プロジェクト: SyAbou/sharpointonline
        private static void CreateTaxonomyNavigation(ClientContext clientContext, TaxonomySession taxonomySession)
        {
            string taxonomyInputFileName = "mms.xml";
            string applicationPath       = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, taxonomyInputFileName);

            XDocument termsXML = XDocument.Load(applicationPath);

            #region for each taxonomy sessions, repeat for each term store, term group
            foreach (XElement termStoreElement in termsXML.Elements())
            {
                TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
                clientContext.Load(termStore.Groups);
                clientContext.ExecuteQuery();
                if (termStore != null)
                {
                    foreach (XElement termGroupElement in termStoreElement.Elements())
                    {
                        string    termgroupElementName = termGroupElement.Attribute("Name").Value;
                        string    termgroupElementGuid = termGroupElement.Attribute("ID").Value;
                        TermGroup termGroup            = termStore.Groups.FirstOrDefault(e => e.Name.Equals(termgroupElementName) == true);
                        if (termGroup == null)
                        {
                            termGroup = termStore.CreateGroup(termgroupElementName, new Guid(termgroupElementGuid));
                        }
                        clientContext.Load(termGroup);
                        clientContext.ExecuteQuery();
                        foreach (XElement termSetElement in termGroupElement.Elements())
                        {
                            CreateTermSetAndTerms(clientContext, termSetElement, termGroup);
                        }
                    }
                }
                termStore.CommitAll();
            }
            #endregion
        }
コード例 #28
0
        public void CreateDepartmentTermSet()
        {
            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);

            clientContext.Load(taxonomySession,
                               ts => ts.TermStores.Include(
                                   store => store.Name,
                                   store => store.Groups.Include(
                                       group => group.Name
                                       )
                                   )
                               );
            clientContext.ExecuteQuery();

            if (taxonomySession != null)
            {
                TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
                if (termStore != null)
                {
                    //
                    //  Create group, termset, and terms.
                    //
                    TermGroup myGroup   = termStore.CreateGroup("DemoDepartment", Guid.NewGuid());
                    TermSet   myTermSet = myGroup.CreateTermSet("DepartmentSet", Guid.NewGuid(), 1033);
                    myTermSet.CreateTerm("HR", 1033, Guid.NewGuid());
                    myTermSet.CreateTerm("Finance", 1033, Guid.NewGuid());
                    myTermSet.CreateTerm("Commercial", 1033, Guid.NewGuid());
                    myTermSet.CreateTerm("Food and Drink", 1033, Guid.NewGuid());
                    myTermSet.CreateTerm("Support", 1033, Guid.NewGuid());
                    var parentIt = myTermSet.CreateTerm("IT", 1033, Guid.NewGuid());
                    parentIt.CreateTerm("IT Test 1", 1033, Guid.NewGuid());
                    parentIt.CreateTerm("IT Test 2", 1033, Guid.NewGuid());
                    clientContext.ExecuteQuery();
                }
            }
        }
コード例 #29
0
ファイル: MMSSyncManager.cs プロジェクト: ADefWebserver/PnP
        private void CreateTargetNewTermGroup(ClientContext sourceClientContext, ClientContext targetClientContext, TermGroup sourceTermGroup, TermStore targetTermStore)
        {
            try
            {
                this._destinationTermGroup = targetTermStore.CreateGroup(sourceTermGroup.Name, sourceTermGroup.Id);
                if(!string.IsNullOrEmpty(sourceTermGroup.Description))
                {
                    this._destinationTermGroup.Description = sourceTermGroup.Description;
                }
                TermOperation _op = new TermOperation();
                _op.Term = sourceTermGroup.Name;
                _op.Id = sourceTermGroup.Id.ToString();
                _op.Operation = "Add";
                _op.Type = "TermGroup";
                this._termStoreOperations.Add(_op);
     
                TermSetCollection _sourceTermSetCollection = sourceTermGroup.TermSets;
                if (_sourceTermSetCollection.Count > 0)
                {
                    foreach (TermSet _sourceTermSet in _sourceTermSetCollection)
                    {
                        sourceClientContext.Load(_sourceTermSet,
                                                  set => set.Name,
                                                  set => set.Description,
                                                  set => set.Id,
                                                  set => set.Terms.Include(
                                                            term => term.Name,
                                                            term => term.Id),
                                                            term => term.Description,
                                                            term => term.Contact);
                                                   

                        sourceClientContext.ExecuteQuery();
                        
                        TermSet _targetTermSet = _destinationTermGroup.CreateTermSet(_sourceTermSet.Name, _sourceTermSet.Id, targetTermStore.DefaultLanguage);
                        if(!string.IsNullOrEmpty(_sourceTermSet.Description))
                        {
                             _targetTermSet.Description = _sourceTermSet.Description;
                        }
                        foreach(Term _sourceTerm in _sourceTermSet.Terms)
                        {
                             Term _targetTerm = _targetTermSet.CreateTerm(_sourceTerm.Name, targetTermStore.DefaultLanguage, _sourceTerm.Id);
                             _op = new TermOperation();
                             _op.Term = _sourceTerm.Name;
                             _op.Id = _sourceTerm.Id.ToString();
                             _op.Operation = "Add";
                             _op.Type = "Term";
                             this._termStoreOperations.Add(_op);
                        }
                    }

                }
                try
                {
                    targetClientContext.ExecuteQuery();
                    targetTermStore.CommitAll();
                }
                catch
                {
                    throw;
                }
               
            }
            catch
            {
                throw;
            }
        }
コード例 #30
0
        public TermGroupInstance CreateGroup(string name)
        {
            var newGroup = m_termStore.CreateGroup(name);

            return(new TermGroupInstance(Engine.Object.InstancePrototype, newGroup));
        }
コード例 #31
0
        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);
                }
            }
        }
コード例 #32
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);
        }
コード例 #33
0
        internal static List <ReusedTerm> ProcessGroup(ClientContext context, TaxonomySession session, TermStore termStore, Model.TermGroup modelTermGroup, TermGroup siteCollectionTermGroup, TokenParser parser, PnPMonitoredScope scope)
        {
            List <ReusedTerm> reusedTerms = new List <ReusedTerm>();

            SiteCollectionTermGroupNameToken siteCollectionTermGroupNameToken =
                new SiteCollectionTermGroupNameToken(context.Web);

            #region Group

            var newGroup = false;

            var modelGroupName = parser.ParseString(modelTermGroup.Name);

            var normalizedGroupName = TaxonomyItem.NormalizeName(context, modelGroupName);
            context.ExecuteQueryRetry();

            TermGroup group = termStore.Groups.FirstOrDefault(
                g => g.Id == modelTermGroup.Id || g.Name == normalizedGroupName.Value);
            if (group == null)
            {
                var parsedDescription = parser.ParseString(modelTermGroup.Description);

                if (modelTermGroup.Name == "Site Collection" ||
                    modelGroupName == siteCollectionTermGroupNameToken.GetReplaceValue() ||
                    modelTermGroup.SiteCollectionTermGroup)
                {
                    var site = (context as ClientContext).Site;
                    group = termStore.GetSiteCollectionGroup(site, true);
                    context.Load(group, g => g.Name, g => g.Id, g => g.TermSets.Include(
                                     tset => tset.Name,
                                     tset => tset.Id));
                    context.ExecuteQueryRetry();
                }
                else
                {
                    group = termStore.Groups.FirstOrDefault(g => g.Name == normalizedGroupName.Value);

                    if (group == null)
                    {
                        if (modelTermGroup.Id == Guid.Empty)
                        {
                            modelTermGroup.Id = Guid.NewGuid();
                        }
                        group = termStore.CreateGroup(modelGroupName, modelTermGroup.Id);

                        group.Description = parsedDescription;

                        // Handle TermGroup Contributors, if any
                        if (modelTermGroup.Contributors != null && modelTermGroup.Contributors.Count > 0)
                        {
                            foreach (var c in modelTermGroup.Contributors)
                            {
                                group.AddContributor(c.Name);
                            }
                        }

                        // Handle TermGroup Managers, if any
                        if (modelTermGroup.Managers != null && modelTermGroup.Managers.Count > 0)
                        {
                            foreach (var m in modelTermGroup.Managers)
                            {
                                group.AddGroupManager(m.Name);
                            }
                        }

                        termStore.CommitAll();
                        context.Load(group);
                        context.Load(termStore);
                        context.ExecuteQueryRetry();

                        newGroup = true;
                    }
                }
            }
            #endregion

            session.UpdateCache();
            session.Context.ExecuteQueryRetry();
            #region TermSets

            foreach (var modelTermSet in modelTermGroup.TermSets)
            {
                TermSet set        = null;
                var     newTermSet = false;

                var normalizedTermSetName = TaxonomyItem.NormalizeName(context, parser.ParseString(modelTermSet.Name));
                context.ExecuteQueryRetry();
                if (!newGroup)
                {
                    set =
                        group.TermSets.FirstOrDefault(
                            ts => ts.Id == modelTermSet.Id || ts.Name == normalizedTermSetName.Value);
                }
                if (set == null)
                {
                    if (modelTermSet.Id == Guid.Empty)
                    {
                        modelTermSet.Id = Guid.NewGuid();
                    }
                    else
                    {
                        if (CheckIfTermSetIdIsUnique(termStore, modelTermSet.Id) == false)
                        {
                            throw new Exception($"Termset ID {modelTermSet.Id} is already present in termstore");
                        }
                    }
                    var termSetLanguage = modelTermSet.Language.HasValue ? modelTermSet.Language.Value : termStore.DefaultLanguage;
                    set = group.CreateTermSet(normalizedTermSetName.Value, modelTermSet.Id, termSetLanguage);
                    parser.AddToken(new TermSetIdToken(context.Web, group.Name, normalizedTermSetName.Value, modelTermSet.Id));
                    if (siteCollectionTermGroup != null && !siteCollectionTermGroup.ServerObjectIsNull.Value)
                    {
                        if (group.Name == siteCollectionTermGroup.Name)
                        {
                            parser.AddToken((new SiteCollectionTermSetIdToken(context.Web, normalizedTermSetName.Value, modelTermSet.Id)));
                        }
                    }
                    newTermSet = true;
                    if (!string.IsNullOrEmpty(modelTermSet.Description))
                    {
                        set.Description = parser.ParseString(modelTermSet.Description);
                    }
                    set.IsOpenForTermCreation = modelTermSet.IsOpenForTermCreation;
                    set.IsAvailableForTagging = modelTermSet.IsAvailableForTagging;
                    foreach (var property in modelTermSet.Properties)
                    {
                        set.SetCustomProperty(property.Key, parser.ParseString(property.Value));
                    }
                    if (modelTermSet.Owner != null)
                    {
                        set.Owner = parser.ParseString(modelTermSet.Owner);
                    }
                    termStore.CommitAll();
                    context.Load(set);
                    context.ExecuteQueryRetry();
                }

                context.Load(set, s => s.Terms.Include(t => t.Id, t => t.Name));
                context.ExecuteQueryRetry();
                var terms = set.Terms;

                foreach (var modelTerm in modelTermSet.Terms)
                {
                    if (!newTermSet)
                    {
                        if (terms.Any())
                        {
                            var term = terms.FirstOrDefault(t => t.Id == modelTerm.Id);
                            if (term == null)
                            {
                                var normalizedTermName = TaxonomyItem.NormalizeName(context, parser.ParseString(modelTerm.Name));
                                context.ExecuteQueryRetry();

                                term = terms.FirstOrDefault(t => t.Name == normalizedTermName.Value);
                                if (term == null)
                                {
                                    var returnTuple = CreateTerm(context, modelTerm, set, termStore, parser, scope);
                                    if (returnTuple != null)
                                    {
                                        modelTerm.Id = returnTuple.Item1;
                                        parser       = returnTuple.Item2;
                                    }
                                    reusedTerms.AddRange(returnTuple.Item3);
                                }
                                else
                                {
                                    // todo: add handling for reused term?
                                    modelTerm.Id = term.Id;
                                }
                            }
                            else
                            {
                                // todo: add handling for reused term?
                                modelTerm.Id = term.Id;
                            }

                            if (term != null)
                            {
                                CheckChildTerms(context, modelTerm, term, termStore, parser, scope);
                            }
                        }
                        else
                        {
                            var returnTuple = CreateTerm(context, modelTerm, set, termStore, parser, scope);
                            if (returnTuple != null)
                            {
                                modelTerm.Id = returnTuple.Item1;
                                parser       = returnTuple.Item2;
                            }
                            reusedTerms.AddRange(returnTuple.Item3);
                        }
                    }
                    else
                    {
                        var returnTuple = CreateTerm(context, modelTerm, set, termStore, parser, scope);
                        if (returnTuple != null)
                        {
                            modelTerm.Id = returnTuple.Item1;
                            parser       = returnTuple.Item2;
                        }
                        reusedTerms.AddRange(returnTuple.Item3);
                    }
                }

                // do we need custom sorting?
                if (modelTermSet.Terms.Any(t => t.CustomSortOrder > 0))
                {
                    var sortedTerms = modelTermSet.Terms.OrderBy(t => t.CustomSortOrder);

                    var customSortString = sortedTerms.Aggregate(string.Empty,
                                                                 (a, i) => a + i.Id.ToString() + ":");
                    customSortString = customSortString.TrimEnd(new[] { ':' });

                    set.CustomSortOrder = customSortString;
                    termStore.CommitAll();
                    context.ExecuteQueryRetry();
                }
            }

            #endregion

            return(reusedTerms);
        }
コード例 #34
0
        public static void ImportTerms(this Site site, string[] termLines, int lcid, string delimiter)
        {
            var             clientContext   = site.Context;
            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
            TermStore       termStore       = taxonomySession.GetDefaultSiteCollectionTermStore();

            clientContext.Load(termStore);
            clientContext.ExecuteQuery();
            foreach (string line in termLines)
            {
                // split up
                string[] items = line.Split(new string[] { delimiter }, StringSplitOptions.None);
                if (items.Count() > 0)
                {
                    string groupItem = items[0];
                    string groupName = groupItem;
                    Guid   groupId   = Guid.Empty;
                    if (groupItem.IndexOf(";#") > -1)
                    {
                        groupName = groupItem.Split(new string[] { ";#" }, StringSplitOptions.None)[0];
                        groupId   = new Guid(groupItem.Split(new string[] { ";#" }, StringSplitOptions.None)[1]);
                    }
                    TermGroup termGroup = null;
                    if (groupId != Guid.Empty)
                    {
                        termGroup = termStore.GetGroup(groupId);
                    }
                    else
                    {
                        termGroup = termStore.Groups.GetByName(NormalizeName(groupName));
                    }
                    try
                    {
                        clientContext.Load(termGroup);
                        clientContext.ExecuteQuery();
                    }
                    catch
                    {
                    }
                    if (termGroup.ServerObjectIsNull == null)
                    {
                        groupId   = Guid.NewGuid();
                        termGroup = termStore.CreateGroup(NormalizeName(groupName), groupId);
                        clientContext.Load(termGroup);
                        clientContext.ExecuteQuery();
                    }
                    if (items.Count() > 1)
                    {
                        // TermSet
                        if (termGroup.ServerObjectIsNull == false)
                        {
                            string termsetItem = items[1];
                            string termsetName = termsetItem;
                            Guid   termsetId   = Guid.Empty;
                            if (termsetItem.IndexOf(";#") > -1)
                            {
                                termsetName = termsetItem.Split(new string[] { ";#" }, StringSplitOptions.None)[0];
                                termsetId   = new Guid(termsetItem.Split(new string[] { ";#" }, StringSplitOptions.None)[1]);
                            }
                            TermSet termSet = null;
                            if (termsetId != Guid.Empty)
                            {
                                termSet = termGroup.TermSets.GetById(termsetId);
                            }
                            else
                            {
                                termSet = termGroup.TermSets.GetByName(NormalizeName(termsetName));
                            }
                            clientContext.Load(termSet);
                            try
                            {
                                clientContext.ExecuteQuery();
                            }
                            catch { }
                            if (termSet.ServerObjectIsNull == null)
                            {
                                termsetId = Guid.NewGuid();
                                termSet   = termGroup.CreateTermSet(NormalizeName(termsetName), termsetId, lcid);
                                clientContext.Load(termSet);
                                clientContext.ExecuteQuery();
                            }
                            if (items.Count() > 2)
                            {
                                // Term(s)

                                if (termSet.ServerObjectIsNull == false)
                                {
                                    string termItem = items[2];
                                    string termName = termItem;
                                    Guid   termId   = Guid.Empty;
                                    if (termItem.IndexOf(";#") > -1)
                                    {
                                        termName = termItem.Split(new string[] { ";#" }, StringSplitOptions.None)[0];
                                        termId   = new Guid(termItem.Split(new string[] { ";#" }, StringSplitOptions.None)[1]);
                                    }
                                    Term term = null;
                                    if (termId != Guid.Empty)
                                    {
                                        term = termSet.Terms.GetById(termId);
                                    }
                                    else
                                    {
                                        term = termSet.Terms.GetByName(NormalizeName(termName));
                                    }
                                    clientContext.Load(term);
                                    try
                                    {
                                        clientContext.ExecuteQuery();
                                    }
                                    catch { }
                                    if (term.ServerObjectIsNull == null)
                                    {
                                        termId = Guid.NewGuid();
                                        term   = termSet.CreateTerm(NormalizeName(termName), lcid, termId);
                                        clientContext.ExecuteQuery();
                                    }

                                    if (items.Count() > 3)
                                    {
                                        clientContext.Load(term);
                                        clientContext.ExecuteQuery();
                                        if (term.ServerObjectIsNull == false)
                                        {
                                            for (int q = 3; q < items.Count(); q++)
                                            {
                                                termName = items[q];
                                                termId   = Guid.Empty;
                                                if (termItem.IndexOf(";#") > -1)
                                                {
                                                    termName = termItem.Split(new string[] { ";#" }, StringSplitOptions.None)[0];
                                                    termId   = new Guid(termItem.Split(new string[] { ";#" }, StringSplitOptions.None)[1]);
                                                }
                                                term = term.AddTermToTerm(lcid, termName, termId);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #35
0
        /// <summary>
        ///  Imports an array of | delimited strings into the deafult site collection termstore. Specify strings in this format:
        ///  TermGroup|TermSet|Term
        ///  
        ///  E.g. "Locations|Nordics|Sweden"
        ///  
        /// </summary>
        /// <param name="site"></param>
        /// <param name="termLines"></param>
        /// <param name="lcid"></param>
        /// <param name="termStore">The termstore to import the terms into</param>
        /// <param name="delimiter"></param>
        public static void ImportTerms(this Site site, string[] termLines, int lcid, TermStore termStore, string delimiter = "|")
        {
            termLines.ValidateNotNullOrEmpty("termLines");
            termStore.ValidateNotNullOrEmpty("termStore");

            var clientContext = site.Context;
            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
            if (termStore.ServerObjectIsNull == true)
            {
                clientContext.Load(termStore);
                clientContext.ExecuteQuery();
            }
            clientContext.Load(termStore);
            clientContext.ExecuteQuery();
            foreach (string line in termLines)
            {
                // split up
                string[] items = line.Split(new string[] { delimiter }, StringSplitOptions.None);
                if (items.Count() > 0)
                {
                    string groupItem = items[0];
                    string groupName = groupItem;
                    Guid groupId = Guid.Empty;
                    if (groupItem.IndexOf(";#") > -1)
                    {
                        groupName = groupItem.Split(new string[] { ";#" }, StringSplitOptions.None)[0];
                        groupId = new Guid(groupItem.Split(new string[] { ";#" }, StringSplitOptions.None)[1]);
                    }
                    TermGroup termGroup = null;
                    if (groupId != Guid.Empty)
                    {
                        termGroup = termStore.Groups.GetById(groupId);
                    }
                    else
                    {
                        termGroup = termStore.Groups.GetByName(NormalizeName(groupName));
                    }
                    try
                    {
                        clientContext.Load(termGroup);
                        clientContext.ExecuteQuery();
                    }
                    catch
                    {

                    }
                    if (termGroup.ServerObjectIsNull == null)
                    {
                        groupId = Guid.NewGuid();
                        termGroup = termStore.CreateGroup(NormalizeName(groupName), groupId);
                        clientContext.Load(termGroup);
                        clientContext.ExecuteQuery();
                    }
                    if (items.Count() > 1)
                    {
                        // TermSet
                        if (termGroup.ServerObjectIsNull == false)
                        {
                            string termsetItem = items[1];
                            string termsetName = termsetItem;
                            Guid termsetId = Guid.Empty;
                            if (termsetItem.IndexOf(";#") > -1)
                            {
                                termsetName = termsetItem.Split(new string[] { ";#" }, StringSplitOptions.None)[0];
                                termsetId = new Guid(termsetItem.Split(new string[] { ";#" }, StringSplitOptions.None)[1]);
                            }
                            TermSet termSet = null;
                            if (termsetId != Guid.Empty)
                            {
                                termSet = termGroup.TermSets.GetById(termsetId);
                            }
                            else
                            {
                                termSet = termGroup.TermSets.GetByName(NormalizeName(termsetName));
                            }
                            clientContext.Load(termSet);
                            try
                            {
                                clientContext.ExecuteQuery();
                            }
                            catch { }
                            if (termSet.ServerObjectIsNull == null)
                            {
                                termsetId = Guid.NewGuid();
                                termSet = termGroup.CreateTermSet(NormalizeName(termsetName), termsetId, lcid);
                                clientContext.Load(termSet);
                                clientContext.ExecuteQuery();
                            }
                            if (items.Count() > 2)
                            {
                                // Term(s)

                                if (termSet.ServerObjectIsNull == false)
                                {
                                    string termItem = items[2];
                                    string termName = termItem;
                                    Guid termId = Guid.Empty;
                                    if (termItem.IndexOf(";#") > -1)
                                    {
                                        termName = termItem.Split(new string[] { ";#" }, StringSplitOptions.None)[0];
                                        termId = new Guid(termItem.Split(new string[] { ";#" }, StringSplitOptions.None)[1]);
                                    }
                                    Term term = null;
                                    if (termId != Guid.Empty)
                                    {
                                        term = termSet.Terms.GetById(termId);
                                    }
                                    else
                                    {
                                        term = termSet.Terms.GetByName(NormalizeName(termName));
                                    }
                                    clientContext.Load(term);
                                    try
                                    {
                                        clientContext.ExecuteQuery();
                                    }
                                    catch { }
                                    if (term.ServerObjectIsNull == null)
                                    {
                                        termId = Guid.NewGuid();
                                        term = termSet.CreateTerm(NormalizeName(termName), lcid, termId);
                                        clientContext.ExecuteQuery();
                                    }

                                    if (items.Count() > 3)
                                    {
                                        clientContext.Load(term);
                                        clientContext.ExecuteQuery();
                                        if (term.ServerObjectIsNull == false)
                                        {
                                            for (int q = 3; q < items.Count(); q++)
                                            {
                                                termName = items[q];
                                                termId = Guid.Empty;
                                                if (termItem.IndexOf(";#") > -1)
                                                {
                                                    termName = termItem.Split(new string[] { ";#" }, StringSplitOptions.None)[0];
                                                    termId = new Guid(termItem.Split(new string[] { ";#" }, StringSplitOptions.None)[1]);
                                                }
                                                term = term.AddTermToTerm(lcid, termName, termId);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #36
0
ファイル: TaxonomyExtensions.cs プロジェクト: ipbhattarai/PnP
        /// <summary>
        ///  Imports an array of | delimited strings into the deafult site collection termstore. Specify strings in this format:
        ///  TermGroup|TermSet|Term
        ///  
        ///  E.g. "Locations|Nordics|Sweden"
        ///  
        /// </summary>
        /// <param name="site"></param>
        /// <param name="termLines"></param>
        /// <param name="lcid"></param>
        /// <param name="termStore">The termstore to import the terms into</param>
        /// <param name="delimiter"></param>
        /// <param name="synchronizeDeletions">Remove tags that are not present in the import</param>
        public static void ImportTerms(this Site site, string[] termLines, int lcid, TermStore termStore, string delimiter = "|", bool synchronizeDeletions = false)
        {
            var groupDict = new Dictionary<TermGroup, List<string>>();

            var clientContext = site.Context;
            if (termStore.ServerObjectIsNull == true)
            {
                clientContext.Load(termStore);
                clientContext.ExecuteQueryRetry();
            }
            clientContext.Load(termStore);
            clientContext.ExecuteQueryRetry();

            foreach (var line in termLines)
            {
                // Find termgroup
                var items = line.Split(new[] { delimiter }, StringSplitOptions.None);
                if (items.Any())
                {


                    List<string> terms = null;

                    var groupItem = items[0];
                    var groupName = groupItem;
                    var groupId = Guid.Empty;
                    if (groupItem.IndexOf(";#", StringComparison.Ordinal) > -1)
                    {
                        groupName = groupItem.Split(new[] { ";#" }, StringSplitOptions.None)[0];
                        groupId = new Guid(groupItem.Split(new[] { ";#" }, StringSplitOptions.None)[1]);
                    }
                    TermGroup termGroup = null;
                    // Cached?
                    if (groupDict.Any())
                    {
                        KeyValuePair<TermGroup, List<string>> groupDictItem;
                        if (groupId != Guid.Empty)
                        {
                            groupDictItem = groupDict.FirstOrDefault(tg => tg.Key.Id == groupId);

                            termGroup = groupDictItem.Key;
                            terms = groupDictItem.Value;

                        }
                        else
                        {
                            groupDictItem = groupDict.FirstOrDefault(tg => tg.Key.Name == groupName);

                            termGroup = groupDictItem.Key;
                            terms = groupDictItem.Value;
                        }
                    }
                    if (termGroup == null)
                    {
                        if (groupId != Guid.Empty)
                        {

                            termGroup = termStore.Groups.GetById(groupId);
                        }
                        else
                        {
                            termGroup = termStore.Groups.GetByName(NormalizeName(groupName));
                        }
                        try
                        {
                            clientContext.Load(termGroup);
                            clientContext.ExecuteQueryRetry();
                            groupDict.Add(termGroup, new List<string>());
                            terms = new List<string>();
                        }
                        catch
                        {

                        }
                    }
                    if (termGroup.ServerObjectIsNull == null)
                    {
                        if (groupId == Guid.Empty)
                        {
                            groupId = Guid.NewGuid();
                        }
                        termGroup = termStore.CreateGroup(NormalizeName(groupName), groupId);
                        terms = new List<string>();
                        clientContext.Load(termGroup);
                        clientContext.ExecuteQueryRetry();

                        groupDict.Add(termGroup, new List<string>());

                    }
                    var sb = new StringBuilder();
                    if (items.Length > 1)
                    {
                        var termSetName = items[1];
                        termSetName = termSetName.Replace(";#", "|");
                        sb.AppendFormat("{0},,{1},True,,", termSetName, lcid);

                        // Termset = position 1
                        for (var q = 0; q < 7; q++)
                        {
                            var item = "";
                            if (items.Length > q + 2)
                            {
                                item = items[q + 2];
                                item = item.Replace(";#", "|");
                            }
                            sb.AppendFormat("{0},", item);
                        }
                        if (terms != null)
                        {
                            terms.Add(sb.ToString());

                            groupDict[termGroup] = terms;
                        }
                    }
                }
            }
            foreach (var groupDictItem in groupDict)
            {
                var memoryStream = new MemoryStream();

                var termGroup = groupDictItem.Key as TermGroup;
                using (var streamWriter = new StreamWriter(memoryStream))
                {
                    // Header
                    streamWriter.WriteLine(@"""Term Set Name"",""Term Set Description"",""LCID"",""Available for Tagging"",""Term Description"",""Level 1 Term"",""Level 2 Term"",""Level 3 Term"",""Level 4 Term"",""Level 5 Term"",""Level 6 Term"",""Level 7 Term""");

                    // Items
                    foreach (var termLine in groupDictItem.Value)
                    {
                        streamWriter.WriteLine(termLine);
                    }
                    streamWriter.Flush();
                    memoryStream.Position = 0;
                    termGroup.ImportTermSet(memoryStream, synchroniseDeletions: synchronizeDeletions);
                }

            }
        }
コード例 #37
0
        private void Import(XmlElement groupElement, TermStore parentTermStore)
        {
            string groupName = groupElement.GetAttribute("Name");
            Guid groupId = new Guid(groupElement.GetAttribute("Id"));
            LoadWorkingLanguage(parentTermStore);

            TermGroup group = null;
            ExceptionHandlingScope scope = new ExceptionHandlingScope(_ctx);
            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    group = parentTermStore.Groups.GetByName(groupName);
                    _ctx.Load(group);
                }
                using (scope.StartCatch())
                {
                }
            }
            _ctx.ExecuteQuery();

            if (group == null || group.ServerObjectIsNull == null || group.ServerObjectIsNull.Value)
            {
                _cmdlet.WriteVerbose(string.Format("Creating Group: {0}", groupName));

                group = parentTermStore.CreateGroup(groupName, groupId);
                group.Description = groupElement.GetAttribute("Description");
                group.Context.ExecuteQuery();
                parentTermStore.CommitAll();
                parentTermStore.Context.ExecuteQuery();
            }
            XmlNodeList termSetNodes = groupElement.SelectNodes("./TermSets/TermSet");
            if (termSetNodes != null && termSetNodes.Count > 0)
            {
                foreach (XmlElement termSetElement in termSetNodes)
                {
                    Import(termSetElement, group);
                }
            }
        }
コード例 #38
0
ファイル: TaxonomyManager.cs プロジェクト: olemp/sherpa
        /// <summary>
        /// Since the administrator members like TermStore.DoesUserHavePermissions aren't available in the client API, this is currently how we check if user has permissions
        /// </summary>
        /// <param name="context"></param>
        /// <param name="termStore"></param>
        /// <returns></returns>
        private bool IsCurrentUserTermStoreAdministrator(ClientContext context, TermStore termStore)
        {
            const string testGroupName = "SherpaTemporaryTestGroup";
            var testGroupGuid = new Guid("0972a735-b89a-400f-a858-b80e29492b62");
            try
            {
                var termGroup = termStore.CreateGroup(testGroupName, testGroupGuid);
                context.ExecuteQuery();

                termGroup.DeleteObject();
                context.ExecuteQuery();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
コード例 #39
0
ファイル: MMSSyncManager.cs プロジェクト: AaronSaikovski/PnP
        private void CreateNewTargetTermGroup(ClientContext sourceClientContext, ClientContext targetClientContext, TermGroup sourceTermGroup, TermStore targetTermStore, List<int> languagesToProcess)
        {
            TermGroup destinationTermGroup = targetTermStore.CreateGroup(sourceTermGroup.Name, sourceTermGroup.Id);
            if (!string.IsNullOrEmpty(sourceTermGroup.Description))
            {
                destinationTermGroup.Description = sourceTermGroup.Description;
            }

            TermSetCollection sourceTermSetCollection = sourceTermGroup.TermSets;
            if (sourceTermSetCollection.Count > 0)
            {
                foreach (TermSet sourceTermSet in sourceTermSetCollection)
                {
                    sourceClientContext.Load(sourceTermSet,
                                              set => set.Name,
                                              set => set.Description,
                                              set => set.Id,
                                              set => set.Contact,
                                              set => set.CustomProperties,
                                              set => set.IsAvailableForTagging,
                                              set => set.IsOpenForTermCreation,
                                              set => set.CustomProperties,
                                              set => set.Terms.Include(
                                                        term => term.Name,
                                                        term => term.Description,
                                                        term => term.Id,
                                                        term => term.IsAvailableForTagging,
                                                        term => term.LocalCustomProperties,
                                                        term => term.CustomProperties,
                                                        term => term.IsDeprecated,
                                                        term => term.Labels.Include(label => label.Value, label => label.Language, label => label.IsDefaultForLanguage)));

                    sourceClientContext.ExecuteQuery();

                    TermSet targetTermSet = destinationTermGroup.CreateTermSet(sourceTermSet.Name, sourceTermSet.Id, targetTermStore.DefaultLanguage);
                    targetClientContext.Load(targetTermSet, set => set.CustomProperties);
                    targetClientContext.ExecuteQuery();
                    UpdateTermSet(sourceClientContext, targetClientContext, sourceTermSet, targetTermSet);

                    foreach (Term sourceTerm in sourceTermSet.Terms)
                    {
                        Term reusedTerm = targetTermStore.GetTerm(sourceTerm.Id);
                        targetClientContext.Load(reusedTerm);
                        targetClientContext.ExecuteQuery();

                        Term targetTerm;
                        if (reusedTerm.ServerObjectIsNull.Value)
                        {
                            try
                            {
                                targetTerm = targetTermSet.CreateTerm(sourceTerm.Name, targetTermStore.DefaultLanguage, sourceTerm.Id);
                                targetClientContext.Load(targetTerm, term => term.IsDeprecated,
                                                                     term => term.CustomProperties,
                                                                     term => term.LocalCustomProperties);
                                targetClientContext.ExecuteQuery();
                                UpdateTerm(sourceClientContext, targetClientContext, sourceTerm, targetTerm, languagesToProcess);
                            }
                            catch (ServerException ex)
                            {
                                if (ex.Message.IndexOf("Failed to read from or write to database. Refresh and try again.") > -1)
                                {
                                    // This exception was due to caching issues and generally is thrown when there's term reuse accross groups
                                    targetTerm = targetTermSet.ReuseTerm(reusedTerm, false);
                                }
                                else
                                {
                                    throw ex;
                                }
                            }
                        }
                        else
                        {
                            targetTerm = targetTermSet.ReuseTerm(reusedTerm, false);
                        }

                        targetClientContext.Load(targetTerm);
                        targetClientContext.ExecuteQuery();

                        targetTermStore.UpdateCache();

                        //Refresh session and termstore references to force reload of the term just added. This is 
                        //needed cause there can be a update change event following next and without this trick
                        //the newly created termset cannot be obtained from the server
                        targetTermStore = GetTermStoreObject(targetClientContext);

                        //recursively add the other terms
                        ProcessSubTerms(sourceClientContext, targetClientContext, targetTermSet, targetTerm, sourceTerm, languagesToProcess, targetTermStore.DefaultLanguage);
                    }
                }
            }
            targetClientContext.ExecuteQuery();
        }
コード例 #40
0
        public TermGroup CreateGroup(TermStore termStore, string groupname)
        {
            TermGroup group = termStore.Groups.FirstOrDefault(x => x.Name == groupname);
            if (group == null)
            {
                group = termStore.CreateGroup(groupname, Guid.NewGuid());

            }
            Ctx.Load(group);
            Ctx.ExecuteQuery();
            return group;
        }