Archive

Posts Tagged ‘sharepoint 2013’

Traversing Taxonomy Terms from branch to leaf

29 January 2013 Leave a comment

I had a need to show the path of terms, starting from a specific term and then showing the path to the final children,

This would involve traversing the structure as the depth is unknown, so I wrote this piece of code to accomplish this using the Client Components.

Please feel free to steal and improve (Only if you give back the improved code though!)

private IEnumerable<Path> Paths(bool includeRoot, Guid termId, string siteUrl)
{
var paths = new List<Path>();
Action<ClientContext, Term, String> traverse = null;

traverse = (context, term, path) =>
{
context.Load(term, t => t.Id, t => t.Name, t => t.Terms);
context.ExecuteQuery();

if (!(term.Id == termId && !includeRoot))
path += path == string.Empty ? term.Name : ” > {0}”.ToFormat(term.Name);

if (term.Terms.Count == 0)
{
paths.Add(new Path
{
TermId = term.Id,
PathText = path
});
}
else
{
foreach (var st in term.Terms)
{
traverse(context, st, path);
}
}
};

using (var context = new ClientContext(siteUrl))
{
var rootTerm = TaxonomySession.GetTaxonomySession(context).GetTerm(termId);

traverse(context, rootTerm, string.Empty);
}

return paths;
}

public class Path
{
public Guid TermId { get; set; }
public string PathText { get; set; }
}

Advertisements

The tale of two ampersands in a Taxonomy term

14 January 2013 Leave a comment

There are two types of ampersands that you need to be aware of when playing with SharePoint Taxonomy

Our favorite and most loved

& ASCII Number: 38

And the impostor

& ASCII Number: 65286

After reading this article by Nick Hobbs, it became apparent that when you create a term it replaces the 38 ampersand with a 65286 ampersand.

This then becomes a problem if you want to do a comparison with your original source (spreadsheet, database, etc) as they are no longer the same.

As detailed in Nick’s article, you can use the TaxonomyItem.NormalizeName method to create a “Taxonomy” version of your string for comparison.

Below is the code I used in the SharePoint 2013 Client Component which is a little different from the server code.

string myString = “This contains &”;
using (var context = new ClientContext(http://myurl&#8221;))
{
var result = TaxonomyItem.NormalizeName(context, myString);
context.ExecuteQuery();

string normalisedString = result.Value;
}