private static IList<Term> GetTermsForLabelInternal(TermStore termStore, Group termStoreGroup, TermSet termSet, string termLabel)
        {
            if (termStore == null)
            {
                throw new ArgumentNullException("termStore");
            }

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

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

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

            TermCollection termCollection = termSet.GetAllTerms();
            return termCollection.Where((term) =>
            {
                return term.Labels.Any(label => label.Value == termLabel);
            }).ToList();
        }
Example #2
0
        /// <summary>
        /// This method will check if the term exists and if it exists, it will return the reference to that term
        /// </summary>
        /// <param name="termSet">The term set underwhich, the term exists check will happen</param>
        /// <param name="clientContext">The sharepoint client context object</param>
        /// <param name="path">The term path under which we need to check for a term existence</param>
        /// <param name="termNameToRetrieve">The term that needs to be retrieved from a given term</param>
        /// <param name="term">The term reference that will be returned back to the caller</param>
        /// <returns></returns>
        public static bool TermExists(this TermSet termSet, ClientContext clientContext, string termNameToRetrieve, ref Term term)
        {
            TermCollection termCollection = termSet.GetAllTerms();

            clientContext.Load(termCollection,
                               tc => tc.Include(
                                   t => t.Name,
                                   t => t.PathOfTerm,
                                   t => t.TermsCount,
                                   t => t.Parent.Name

                                   ));
            clientContext.ExecuteQuery();
            foreach (Term currentTerm in termCollection)
            {
                string pathOfTerm = currentTerm.PathOfTerm;
                //ClientResult<string> pathOfTerm = currentTerm.GetPath(1033);
                if (currentTerm.Name.ToLower() == termNameToRetrieve.ToLower())
                {
                    term = currentTerm;
                    return(true);
                }
            }
            return(false);
        }
Example #3
0
        /// <summary>
        /// This extension method will give all the terms for a give path mentioned
        /// </summary>
        /// <param name="termSet">From which term set, we need to find a given term path</param>
        /// <param name="path">The path name to search</param>
        /// <param name="clientContext">The sharepoint client context object</param>
        /// <returns></returns>
        public static TermCollection GetTermsByPath(this TermSet termSet, String path, ClientContext clientContext)
        {
            TermCollection termCollection         = termSet.GetAllTerms();
            TermCollection termCollectionToReturn = null;

            clientContext.Load(termCollection,
                               tc => tc.Include(
                                   t => t.Name,
                                   t => t.PathOfTerm,
                                   t => t.TermsCount
                                   ));
            clientContext.ExecuteQuery();
            foreach (Term term in termCollection)
            {
                if (term.PathOfTerm == path)
                {
                    //Get all the terms under that path
                    if (term.TermsCount > 0)
                    {
                        termCollectionToReturn = term.LoadTerms(clientContext);
                    }
                }
            }
            return(termCollectionToReturn);
        }
Example #4
0
        private static IList <Term> GetTermsForLabelInternal(TermStore termStore, Group termStoreGroup, TermSet termSet, string termLabel)
        {
            if (termStore == null)
            {
                throw new ArgumentNullException("termStore");
            }

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

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

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

            TermCollection termCollection = termSet.GetAllTerms();

            return(termCollection.Where((term) =>
            {
                return term.Labels.Any(label => label.Value == termLabel);
            }).ToList());
        }
Example #5
0
 public TermSetLookup(TermSet termSet)
 {
     foreach (Term term in termSet.GetAllTerms())
     {
         TermsByName.Add(term.Name, term.Id);
     }
 }
Example #6
0
        //GetItems
        //GetTaxanomy
        public List <SelectListItem> GetTaxanomy(ClientContext context)
        {
            List <SelectListItem> items    = new List <SelectListItem>();
            TermCollection        terms    = null;
            TaxonomySession       taxonomy = TaxonomySession.GetTaxonomySession(context);

            if (taxonomy != null)
            {
                TermStore termStore = taxonomy.GetDefaultKeywordsTermStore();
                if (termStore != null)
                {
                    TermGroup termGroup = termStore.Groups.GetByName(TERMGROUPNAME);
                    TermSet   termSet   = termGroup.TermSets.GetByName(TERMSETNAME);
                    terms = termSet.GetAllTerms();

                    context.Load(terms);
                    context.ExecuteQuery();

                    foreach (var term in terms)
                    {
                        items.Add(new SelectListItem {
                            Text = term.Name, Value = term.Id.ToString()
                        });
                    }
                }
            }
            return(items);
        }
Example #7
0
        public async Task <TermSetModel> GetTermSetAsync(ClientContext clientContext, string termSetId)
        {
            var termSetCacheKey = TermSetCacheKey(termSetId);

            if (await _cacheClient.ExistsAsync(termSetCacheKey))
            {
                return((await _cacheClient.GetAsync <TermSetModel>(termSetCacheKey)).Value);
            }

            var pickerTermSet = new TermSetModel();

            if (clientContext != null)
            {
                //Get terms from the 'Keywords' termset for autocomplete suggestions.
                // It might be a good idea to cache these values.

                var taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
                var termStore       = taxonomySession.GetDefaultSiteCollectionTermStore();

                TermSet termSet = termStore.GetTermSet(new Guid(termSetId));

                clientContext.Load(termSet, ts => ts.Id, ts => ts.IsOpenForTermCreation, ts => ts.CustomSortOrder, ts => ts.Name,
                                   ts => ts.Terms.Include(t => t.PathOfTerm,
                                                          t => t.Id,
                                                          t => t.Labels.Include(l => l.IsDefaultForLanguage, l => l.Value),
                                                          t => t.Name,
                                                          t => t.TermsCount));
                clientContext.ExecuteQuery();

                var allTerms = termSet.GetAllTerms();

                clientContext.Load(allTerms, terms => terms.Include(t => t.PathOfTerm,
                                                                    t => t.Id,
                                                                    t => t.Labels.Include(l => l.IsDefaultForLanguage, l => l.Value),
                                                                    t => t.Name,
                                                                    t => t.TermsCount));
                clientContext.ExecuteQuery();

                pickerTermSet.Id   = termSet.Id.ToString().Replace("{", string.Empty).Replace("}", string.Empty);
                pickerTermSet.Name = termSet.Name;
                pickerTermSet.IsOpenForTermCreation = termSet.IsOpenForTermCreation;
                pickerTermSet.CustomSortOrder       = termSet.CustomSortOrder;
                pickerTermSet.Terms     = new List <TermModel>();
                pickerTermSet.FlatTerms = new List <TermModel>();

                foreach (var term in termSet.Terms.ToList <Term>())
                {
                    pickerTermSet.Terms.Add(await GetTermAsync(term, termSetId));
                }

                foreach (var term in allTerms.ToList <Term>())
                {
                    pickerTermSet.FlatTerms.Add(await GetTermAsync(term, termSetId, false));
                }
            }

            await _cacheClient.SetAsync(termSetCacheKey, pickerTermSet, _cacheExpirationTimeSpan);

            return(pickerTermSet);
        }
Example #8
0
        public ActionResult BuyAuctions()
        {
            var model = new SearchAdvertisementViewModel();

            model.FilterList.Add(new SelectListItem {
                Value = "PriceAsc", Text = "Pris (Stigande)"
            });
            model.FilterList.Add(new SelectListItem {
                Value = "PriceDesc", Text = "Pris (Fallande)"
            });
            model.FilterList.Add(new SelectListItem {
                Value = "DateAsc", Text = "Datum (Stigande)"
            });
            model.FilterList.Add(new SelectListItem {
                Value = "DateDesc", Text = "Datum (Fallande)"
            });


            SharePointContext spContext = Session["SpContext"] as SharePointContext;

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);

                if (taxonomySession != null)
                {
                    TermStore           termStore    = taxonomySession.GetDefaultSiteCollectionTermStore();
                    TermGroupCollection termGroupCol = termStore.Groups;
                    clientContext.Load(termGroupCol, t => t.Where(y => y.Name == "Advertisements"));
                    clientContext.ExecuteQuery();

                    TermGroup termGroup = termGroupCol.FirstOrDefault();
                    if (termGroup != null)
                    {
                        TermSet        termSet = termGroup.TermSets.GetByName("Categories");
                        TermCollection terms   = termSet.GetAllTerms();
                        clientContext.Load(termSet);
                        clientContext.Load(terms);
                        clientContext.ExecuteQuery();

                        foreach (Term term in terms)
                        {
                            SelectListItem newItem = new SelectListItem {
                                Value = term.Name, Text = term.Name
                            };
                            model.CategoryList.Add(newItem);
                        }
                    }
                }
            }

            model.CategoryList.OrderBy(x => x.Text);
            model.CategoryList.Insert(0, new SelectListItem {
                Value = "Alla", Text = "Alla"
            });
            return(View(model));
        }
Example #9
0
        private IList <string> loadAllTermNamesInSet(TermSet set)
        {
            var terms = set.GetAllTerms();

            _ctx.Load(terms);
            _ctx.ExecuteQuery();

            return(terms.Select(x => x.Name.ToLower()).ToList());
        }
Example #10
0
        // Update the objects in the Taxonomy TermSet to match the objects specified
        // in the TermSetGoal object that was read from the XML file.
        static void SyncTermSet(TermSet termSet, TermSetGoal termSetGoal)
        {
            // Load the tree of terms as a flat list.
            Log("Loading terms...");
            TermCollection allTerms = termSet.GetAllTerms();

            Program.clientContext.Load(allTerms,
                                       allTermsArg => allTermsArg.Include(Program.termRetrievals)
                                       );

            Program.ExecuteQuery(); // WCF CALL #2

            Program.itemsById = new Dictionary <Guid, Wrapper>();
            Wrapper termSetWrapper = new Wrapper(termSet, termSet.Id, Guid.Empty, termSet.Name);

            Program.itemsById.Add(termSetWrapper.Id, termSetWrapper);

            foreach (Term term in allTerms)
            {
                Guid parentItemId = termSet.Id;
                if (!term.Parent.ServerObjectIsNull.Value)
                {
                    parentItemId = term.Parent.Id;
                }
                Program.itemsById.Add(term.Id, new Wrapper(term, term.Id, parentItemId, term.Name));
            }

            foreach (Wrapper wrapper in Program.itemsById.Values)
            {
                if (wrapper != termSetWrapper)
                {
                    Program.itemsById[wrapper.ParentId].ChildTerms.Add(wrapper);
                }
            }

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

            Log("Step 2: Deletes");
            ProcessDeletes(termSetWrapper, termSetGoal); // Step 2

            Log("Step 3: Property Updates");

            Log("Querying auxiliary data");
            foreach (Wrapper wrapper in Program.itemsById.Values)
            {
                if (wrapper != termSetWrapper)
                {
                    wrapper.TermDescription = ((Term)wrapper.Item).GetDescription(Program.lcid);
                }
            }
            Program.ExecuteQuery();                              // WCF CALL #3

            ProcessPropertyUpdates(termSetWrapper, termSetGoal); // Step 3
            Program.ExecuteQuery();                              // WCF CALL #4
        }
Example #11
0
        public ArrayInstance GetAllTerms()
        {
            var result = Engine.Array.Construct();

            foreach (var term in m_termSet.GetAllTerms())
            {
                ArrayInstance.Push(result, new TermInstance(Engine.Object.InstancePrototype, term));
            }
            return(result);
        }
Example #12
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();
        }
        public TermSetLookup(TaxonomyField taxonomyField, TermSet termSet)
        {
            this.taxonomyField = taxonomyField;
            this.terms         = termSet.GetAllTerms();

            Program.clientContext.Load(this.terms,
                                       termsArg => termsArg.Include(
                                           termArg => termArg.Id,
                                           termArg => termArg.Name
                                           )
                                       );
        }
Example #14
0
        public ActionResult CreateAuction()
        {
            var model     = new AdvertisementViewModel();
            var spContext = Session["SpContext"] as SharePointContext;

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);

                if (taxonomySession != null)
                {
                    TermStore           termStore    = taxonomySession.GetDefaultSiteCollectionTermStore();
                    TermGroupCollection termGroupCol = termStore.Groups;
                    clientContext.Load(termGroupCol, t => t.Where(y => y.Name == "Advertisements"));
                    clientContext.ExecuteQuery();

                    TermGroup termGroup = termGroupCol.FirstOrDefault();
                    if (termGroup != null)
                    {
                        TermSet        termSet = termGroup.TermSets.GetByName("Categories");
                        TermCollection terms   = termSet.GetAllTerms();
                        clientContext.Load(termSet);
                        clientContext.Load(terms);
                        clientContext.ExecuteQuery();

                        foreach (Term term in terms)
                        {
                            SelectListItem newItem = new SelectListItem {
                                Value = term.Id.ToString(), Text = term.Name
                            };
                            model.CategoryList.Add(newItem);
                        }
                    }
                }
            }
            ModelState.Clear();
            return(View(model));
        }
Example #15
0
        public static string GetTaxonomyPickerData(ClientContext clientContext, TermSetQueryModel model)
        {
            var pickerTermSet = new PickerTermSetModel();

            if (clientContext != null)
            {
                //Get terms from the 'Keywords' termset for autocomplete suggestions.
                // It might be a good idea to cache these values.

                var taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
                var termStore       = taxonomySession.GetDefaultSiteCollectionTermStore();

                TermSet termSet = null;

                if (!string.IsNullOrWhiteSpace(model.Id))
                {
                    termSet = termStore.GetTermSet(new Guid(model.Id));
                }
                else if (!string.IsNullOrWhiteSpace(model.Name))
                {
                    var rawTermSets = termStore.GetTermSetsByName(model.Name, model.LCID);
                    termSet = rawTermSets.GetByName(model.Name);
                }
                else if (model.UseHashtags)
                {
                    termSet = termStore.HashTagsTermSet;
                }
                else if (model.UseKeywords)
                {
                    termSet = termStore.KeywordsTermSet;
                }

                clientContext.Load(termSet, ts => ts.Id, ts => ts.IsOpenForTermCreation, ts => ts.CustomSortOrder, ts => ts.Name,
                                   ts => ts.Terms.Include(t => t.PathOfTerm,
                                                          t => t.Id,
                                                          t => t.Labels.Include(l => l.IsDefaultForLanguage, l => l.Value),
                                                          t => t.Name,
                                                          t => t.TermsCount));
                clientContext.ExecuteQuery();

                var allTerms = termSet.GetAllTerms();

                clientContext.Load(allTerms, terms => terms.Include(t => t.PathOfTerm,
                                                                    t => t.Id,
                                                                    t => t.Labels.Include(l => l.IsDefaultForLanguage, l => l.Value),
                                                                    t => t.Name,
                                                                    t => t.TermsCount));
                clientContext.ExecuteQuery();

                pickerTermSet.Id   = termSet.Id.ToString().Replace("{", string.Empty).Replace("}", string.Empty);
                pickerTermSet.Name = termSet.Name;
                pickerTermSet.IsOpenForTermCreation = termSet.IsOpenForTermCreation;
                pickerTermSet.CustomSortOrder       = termSet.CustomSortOrder;
                pickerTermSet.Terms     = new List <PickerTermModel>();
                pickerTermSet.FlatTerms = new List <PickerTermModel>();

                foreach (var term in termSet.Terms.ToList <Term>())
                {
                    pickerTermSet.Terms.Add(GetPickerTerm(term));
                }

                foreach (var term in allTerms.ToList <Term>())
                {
                    pickerTermSet.FlatTerms.Add(GetPickerTerm(term, false));
                }
            }
            return(JsonHelper.Serialize <PickerTermSetModel>(pickerTermSet));
        }
Example #16
0
        public ActionResult Index()
        {
            var model     = new IndexAdvertisementViewModel();
            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            if (spContext != null)
            {
                Session["SpContext"] = spContext;
                Session["SpHostUrl"] = spContext.SPHostUrl;
            }
            else
            {
                spContext = Session["SpContext"] as SharePointContext;
            }
            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                if (clientContext != null)
                {
                    ListCollection  listCol         = clientContext.Web.Lists;
                    TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
                    User            currentUser     = clientContext.Web.CurrentUser;
                    clientContext.Load(taxonomySession);
                    clientContext.Load(listCol, y => y.Where(x => x.Title == "Annonser"));
                    clientContext.Load(currentUser);
                    clientContext.ExecuteQuery();
                    //List list = clientContext.Web.Lists.GetByTitle("Annonser");     Fungerar utan lista??

                    if (taxonomySession != null)
                    {
                        #region Create Category Taxonomy
                        Session["TaxSession"] = taxonomySession;
                        TermStore           termStore    = taxonomySession.GetDefaultSiteCollectionTermStore();
                        TermGroupCollection termGroupCol = termStore.Groups;
                        clientContext.Load(termGroupCol, t => t.Where(y => y.Name == "Advertisements"));
                        clientContext.ExecuteQuery();

                        var termGroup = termGroupCol.FirstOrDefault();
                        if (termGroup == null)
                        {
                            TermGroup annonsKategorierGroup = termStore.CreateGroup("Advertisements", Guid.NewGuid());
                            clientContext.ExecuteQuery();
                            TermSet annonsKateGorierTermSet = annonsKategorierGroup.CreateTermSet("Categories", Guid.NewGuid(), 1033);
                            clientContext.ExecuteQuery();

                            annonsKateGorierTermSet.CreateTerm("Electronics", 1033, Guid.NewGuid());
                            annonsKateGorierTermSet.CreateTerm("Appliances", 1033, Guid.NewGuid());
                            annonsKateGorierTermSet.CreateTerm("Clothing", 1033, Guid.NewGuid());
                            annonsKateGorierTermSet.CreateTerm("Books", 1033, Guid.NewGuid());
                            annonsKateGorierTermSet.CreateTerm("Office", 1033, Guid.NewGuid());
                            annonsKateGorierTermSet.CreateTerm("Other", 1033, Guid.NewGuid());
                            clientContext.ExecuteQuery();
                            termGroup = annonsKategorierGroup;
                        }
                        #endregion

                        if (termGroup != null)
                        {
                            TermSet        termSet = termGroup.TermSets.GetByName("Categories");
                            TermCollection terms   = termSet.GetAllTerms();
                            clientContext.Load(termSet);
                            clientContext.Load(terms);
                            clientContext.ExecuteQuery();

                            foreach (Term term in terms)
                            {
                                SelectListItem newItem = new SelectListItem {
                                    Value = term.Id.ToString(), Text = term.Name
                                };
                                model.Categories.Add(newItem);
                            }
                        }
                    }

                    var list = listCol.FirstOrDefault();

                    if (list == null)
                    {
                        #region Create Advertisement List
                        ListCreationInformation listCreationInfo = new ListCreationInformation();
                        listCreationInfo.Title        = "Annonser";
                        listCreationInfo.TemplateType = (int)ListTemplateType.GenericList;

                        var             newList  = clientContext.Web.Lists.Add(listCreationInfo);
                        FieldCollection fieldCol = newList.Fields;


                        Field defaultTitleField = fieldCol.GetByTitle("Title");
                        clientContext.Load(fieldCol);
                        clientContext.Load(defaultTitleField);
                        clientContext.ExecuteQuery();
                        defaultTitleField.Hidden = true;
                        defaultTitleField.SetShowInDisplayForm(false);
                        defaultTitleField.SetShowInEditForm(false);
                        defaultTitleField.SetShowInNewForm(false);
                        defaultTitleField.Required = false;
                        defaultTitleField.Update();

                        Field rubrikField = newList.Fields.AddFieldAsXml("<Field DisplayName='Rubrik' Type='Text' Name='Rubrik' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView);
                        Field textField   = newList.Fields.AddFieldAsXml("<Field DisplayName='Text' Type='Text' Name='Text' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView);
                        Field prisField   = newList.Fields.AddFieldAsXml("<Field DisplayName='Pris' Type='Number' Name='Pris' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView);
                        Field datumField  = newList.Fields.AddFieldAsXml("<Field DisplayName='Datum' Type='DateTime' Name='Datum' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView);
                        //Field anvandareField = newList.Fields.AddFieldAsXml("<Field DisplayName='Användare' Type='User' Name='Anvandare' StaticName='Anvandare' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView);
                        Field kategoriField = newList.Fields.AddFieldAsXml("<Field DisplayName='Kategori' Type='TaxonomyFieldType' Name='Kategori' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView);

                        FieldNumber rubrikFieldNumber = clientContext.CastTo <FieldNumber>(rubrikField);
                        FieldNumber textFieldNumber   = clientContext.CastTo <FieldNumber>(textField);
                        FieldNumber prisFieldNumber   = clientContext.CastTo <FieldNumber>(prisField);
                        FieldNumber datumFieldNumber  = clientContext.CastTo <FieldNumber>(datumField);
                        //FieldNumber anvandareFieldNumber = clientContext.CastTo<FieldNumber>(anvandareField);
                        //FieldNumber kategoryFieldNumber = clientContext.CastTo<FieldNumber>(anvandareField);
                        Guid termStoreId = Guid.Empty;
                        Guid termSetId   = Guid.Empty;
                        GetTaxonomyFieldInfo(clientContext, out termStoreId, out termSetId, "Categories");
                        TaxonomyField kategoryFieldNumber = clientContext.CastTo <TaxonomyField>(kategoriField);
                        kategoryFieldNumber.SspId          = termStoreId;
                        kategoryFieldNumber.TermSetId      = termSetId;
                        kategoryFieldNumber.TargetTemplate = String.Empty;
                        kategoryFieldNumber.AnchorId       = Guid.Empty;

                        rubrikFieldNumber.Update();
                        textFieldNumber.Update();
                        prisFieldNumber.Update();
                        datumFieldNumber.Update();
                        //anvandareFieldNumber.Update();
                        kategoryFieldNumber.Update();

                        View view = newList.Views.GetByTitle("All Items");
                        clientContext.Load(view);
                        clientContext.ExecuteQuery();
                        ViewFieldCollection viewFields = view.ViewFields;
                        viewFields.Remove("LinkTitle");
                        view.Update();

                        clientContext.ExecuteQuery();

                        list = newList;
                        #endregion
                    }
                    CamlQuery cQuery = new CamlQuery();
                    cQuery.ViewXml = @"<View>
                                        <Query>
                                        <Where>
                                        <Eq>
                                        <FieldRef Name='Author' LookupId='True'/>
                                        <Value Type='Lookup'>" + currentUser.Id + @"</Value>
                                        </Eq>
                                        </Where>
                                        </Query>
                                        </View>";
                    var listItems = list.GetItems(cQuery);
                    clientContext.Load(listItems);
                    clientContext.ExecuteQuery();

                    foreach (ListItem listItem in listItems)
                    {
                        AdvertisementViewModel tempObj = new AdvertisementViewModel
                        {
                            Title      = listItem["Rubrik"].ToString(),
                            Text       = listItem["Text"].ToString(),
                            Price      = int.Parse(listItem["Pris"].ToString()),
                            Date       = DateTime.Parse(listItem["Datum"].ToString()),
                            User       = listItem["Author"] as FieldUserValue,
                            Category   = listItem["Kategori"] as TaxonomyFieldValue,
                            ListItemId = listItem["ID"].ToString()
                        };
                        model.Advertisements.Add(tempObj);
                    }
                }
                return(View(model));
            }
        }
        private void CreateStackOTerms(Stack<Tuple<string, Guid>> rowStack, TermCollection allTerms, TermSet termSet)
        {
            var arrayStack = rowStack.ToArray();
               for(int x = 0; x < arrayStack.Length; ++x)
            {
                var currentItem = arrayStack[x];
                if(currentItem.Item2 == Guid.Empty)
                {
                    var newGuid = Guid.NewGuid();
                    if (x != 0)
                    {
                        var previousTermId = arrayStack[x - 1].Item2;
                        var previousTerm = allTerms.FirstOrDefault(o=>o.Id == previousTermId);
                        //termSet.Context.Load(previousTerm);

                        if (previousTerm.IsReused && previousTerm.IsSourceTerm == false)
                        {
                            // get term
                            var sourceTerm = previousTerm.SourceTerm;
                            termSet.Context.Load(sourceTerm, sc=>sc.Id, sc => sc.Terms, sc => sc.Terms.Include(t => t.Name, t => t.Id));
                            termSet.Context.ExecuteQuery();

                            var sourceNewTerm = sourceTerm.Terms.FirstOrDefault(trm => trm.Name == currentItem.Item1);

                            // not in the original either
                            if (sourceNewTerm == null)
                            {
                                // add new term
                                var newTerm = sourceTerm.CreateTerm(currentItem.Item1, 1033, newGuid);
                                // reuse it in the term-set we are iterating
                                previousTerm.ReuseTerm(newTerm, false);
                            }
                            else{
                                previousTerm.ReuseTerm(sourceNewTerm, false);
                                newGuid = sourceNewTerm.Id;
                            }

                        }
                        else
                        {
                            previousTerm.CreateTerm(currentItem.Item1, 1033, newGuid);
                        }

                    }
                    else
                    {
                        // Create a new term at the root of the termset
                        termSet.CreateTerm(currentItem.Item1, 1033, newGuid);
                    }
                    arrayStack[x] = Tuple.Create(currentItem.Item1, newGuid);

                    allTerms = termSet.GetAllTerms();
                    termSet.Context.Load(allTerms, ax => ax.Include(t => t.Terms, t => t.PathOfTerm, t => t.IsReused, t => t.SourceTerm, t => t.IsSourceTerm, t => t.IsPinned, t => t.Name, t => t.Id, t => t.Parent, t => t.PathOfTerm, t => t.Parent.Name, t => t.Parent.Id));
                    termSet.Context.ExecuteQuery();

                }
            }
        }
Example #18
0
        public static Term LookupTerm(ClientContext clientContext, TermStore termStore,
                                      TermSet termSet,
                                      TaxonomyFieldDefinition termModel)
        {
            var context = clientContext;
            var site    = clientContext.Site;

            Term result = null;

            TermGroup currenGroup = null;

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

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

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

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

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

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

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

                        using (scope.StartCatch())
                        {
                        }
                    }

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

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

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

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

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

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

                        using (scope.StartCatch())
                        {
                        }
                    }

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

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

                    result = terms.FirstOrDefault();

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

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

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

                return(result);
            }

            return(null);
        }
        private void ProcessTermsetData(IEnumerable<string> pathData, TermSet termSet)
        {
            var allTerms = termSet.GetAllTerms();
            ts.Context.Load(allTerms, ax => ax.Include(t => t.Terms, t => t.PathOfTerm, t => t.Name, t => t.Id, t => t.Parent, t => t.PathOfTerm, t => t.Parent.Name, t => t.Parent.Id));
            ts.Context.ExecuteQuery();

            foreach (var row in pathData)
            {
                var rowCells = row.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);

                for (var cell = 0; cell < rowCells.Length; ++cell)
                {
                    // Can't find a particular term
                    var matchedTerm = allTerms.Where(o => o.Name == rowCells[cell]);
                    if (matchedTerm.Count() == 0)
                    {
                        // If we are on the first entry of arow
                        // create term at the root
                        if (cell == 0)
                        {
                            termSet.CreateTerm(rowCells[cell], 1033, Guid.NewGuid());
                            ts.Context.ExecuteQuery();
                            ts.Context.Load(allTerms);
                            ts.Context.ExecuteQuery();
                        }
                        else
                        {

                            // find the parent by the current row path.
                            // We do this because terms can appear twice if didn't areas eg Budget->2012->Docs vs Budget->2010->Docs
                            // Path is unique
                            var currentPath = String.Join(";", rowCells.Where((cel, idx) => idx < cell));
                            try
                            {

                                var parentTerm = allTerms.First(o => o.PathOfTerm == currentPath);
                                parentTerm.CreateTerm(rowCells[cell], 1033, Guid.NewGuid());
                                ts.Context.ExecuteQuery();
                                ts.Context.Load(allTerms);
                                ts.Context.ExecuteQuery();
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message + " \r\n" + ex.StackTrace);
                            }
                        }
                    }
                    termSet.TermStore.CommitAll();
                }
            }
        }
Example #20
0
 private static void ImportTermSetRemoveExtraTerms(TermSet termSet, IDictionary<Guid, object> importedTermIds)
 {
     Log.Debug(Constants.LOGGING_SOURCE, "Removing extra terms");
     var termsToDelete = new List<Term>();
     var allTerms = termSet.GetAllTerms();
     termSet.Context.Load(allTerms, at => at.Include(t => t.Id, t => t.Name));
     termSet.Context.ExecuteQueryRetry();
     foreach (var term in allTerms)
     {
         if (!importedTermIds.ContainsKey(term.Id))
         {
             termsToDelete.Add(term);
         }
     }
     foreach (var termToDelete in termsToDelete)
     {
         try
         {
             Log.Info(Constants.LOGGING_SOURCE, CoreResources.TaxonomyExtension_DeleteTerm01, termToDelete.Name, termToDelete.Id);
             termToDelete.DeleteObject();
             termSet.Context.ExecuteQueryRetry();
         }
         catch (ServerException ex)
         {
             if (ex.Message.StartsWith("Taxonomy item instantiation failed."))
             {
                 // This is a sucky way to check if the term was already deleted
                 Log.Debug(Constants.LOGGING_SOURCE, "Term id {0} already deleted.", termToDelete.Id);
             }
             else
             {
                 throw;
             }
         }
     }
 }
        private void ProcessTermsetDataA(IEnumerable<string> pathData, TermSet termSet)
        {
            foreach (var row in pathData)
            {
                var allTerms = termSet.GetAllTerms();
                ts.Context.Load(allTerms, ax => ax.Include(t => t.Terms, t => t.PathOfTerm, t=>t.IsReused, t=>t.SourceTerm, t => t.IsSourceTerm,  t =>t.IsPinned, t => t.Name, t => t.Id, t => t.Parent, t => t.PathOfTerm, t => t.Parent.Name, t => t.Parent.Id));
                ts.Context.ExecuteQuery();

                var rowCells = row.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);

                var rowStack = new Stack<Tuple<string, Guid>>();
                for(var cell = rowCells.Length-1; cell >=0 ;--cell)
                {
                    var currentCell = rowCells[cell];
                    // we check the paths and work backwards
                    // for each one we don't have put in LIFO stack
                   var term =  allTerms.FirstOrDefault(o => o.PathOfTerm == String.Join(";", rowCells.Where((cel, idx) => idx < cell+1)));

                   rowStack.Push(Tuple.Create(currentCell, (term!= null)?term.Id:Guid.Empty));
                }

                // We now create any of the missing terms
                CreateStackOTerms(rowStack, allTerms, termSet);
            }
        }
        public static Term LookupTerm(ClientContext clientContext, TermStore termStore,
            TermSet termSet,
            TaxonomyFieldDefinition termModel)
        {
            var context = clientContext;
            var site = clientContext.Site;

            Term result = null;

            TermGroup currenGroup = null;

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

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

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

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

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

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

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

                        using (scope.StartCatch())
                        {

                        }
                    }

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

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

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

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

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

            else
            {

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

                        using (scope.StartCatch())
                        {

                        }
                    }

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

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

                    result = terms.FirstOrDefault();

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

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

                    }

                }
                }

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

                return result;
            }

            return null;
        }
Example #23
0
        public TermSetLookup(TaxonomyField taxonomyField, TermSet termSet)
        {
            this.taxonomyField = taxonomyField;
            this.terms = termSet.GetAllTerms();

            Program.clientContext.Load(this.terms,
              termsArg => termsArg.Include(
                termArg => termArg.Id,
                termArg => termArg.Name
              )
            );
        }