Tagging

Enterprise Keywords TaxKeyword Tag Cloud

Posted on Updated on

In this post, i will help you to generate a Tag Cloud based on the TaxKeyword, the default enterprise TAG for SharePoint. This sample is for OOTB or not. I’m using SharePoint Search.

Let’s roll to the search method:

Now that we have the DataTable let´s get the Tags from the TAGS Field

/// <summary>
/// Executes the key word search.
/// </summary>
/// <param name="queryText">The query text.</param>
/// <param name="siteUrl"></param>
/// <param name="queryLimit"></param>
/// <returns></returns>
public DataTable ExecuteKeyWordSearch(string queryText, string siteUrl, int queryLimit)
{
    var retResults = new DataTable(); 
    using (var site = new SPSite(siteUrl))
    {
        using (var query = new KeywordQuery(site))
        {
            query.QueryText = queryText;
            query.KeywordInclusion = KeywordInclusion.AllKeywords;
            query.RowLimit = queryLimit;

            query.SelectProperties.Add("Tags");

            var se = new SearchExecutor();
            var rtc = se.ExecuteQuery(query);
            if (rtc.Count <= 0) return null;
            var results = rtc.Filter("TableType", KnownTableTypes.RelevantResults);
            var resultTables = results as IList<ResultTable> ?? results.ToList();
            if (results != null && resultTables.Count() == 1)
                retResults.Load(resultTables.First(), LoadOption.OverwriteChanges);
            return retResults;
        }
    }
}

Let’s replace all “L0|#” and remove all Guid’s

public List<string> GetSafeTagName(string tag)
{
    tag = tag
        .Replace("L0|#", "");
    tag = Regex.Replace(tag, @"([a-z0-9]{8}[-][a-z0-9]{4}[-][a-z0-9]{4}[-][a-z0-9]{4}[-][a-z0-9]{12})", ""); 
    char[] delimiter = { ';' };
    var parts = tag.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
    return parts.ToList();
} 

 
var list = new List<string>(); 
foreach (var refiners in from dr in _dt.AsEnumerable()
                         where dr["Tags"].ToString() != string.Empty
                         select GetSafeTagName(dr["Tags"].ToString()))
{
    list.AddRange(refiners);
}
 

After having our tags, let’s take a count for each TAG, I’m taking 11 for my render

var q = (from x in list
 group x by x
     into g
     let count = g.Count()
     orderby count descending
     select new { Value = g.Key, Count = count }).Take(11); 
 

So? Let´s render. I’m having a bug :), but let´s remove the first 2 characters

foreach (var x in q)
{
    x.Value.Substring(2)
    x.Count
} 
 

THE TAG CLOUD

This is an example, but you can refine it. I’m taking the total, that is 11, and passing the xCount

private static string TagLogic(double xCount, double xTotal)
    {
        string ret;
        var count = xCount;
        var percent = (count / xTotal) * 100; 
        if (percent < 20)
        {
            ret = "10";
        }
        else if (percent < 50)
        {
            ret = "20";
        }
        else if (percent < 70)
        {
            ret = "50";
        }

        else
        {
            ret = "70";
        }
        return ret;
    }
} 
Advertisements

Create Terms in Metadata Service Programmatically

Posted on Updated on

Working with Taxonomy Fields that created in Visual Studio without OOTB, it’s not a peace of cake. You have to follow some rules:

  1. In a Feature Receiver, Scoped SITE use the bellow Override
  2. Then you have to activate your field  (Bind) to a specific GUID, if you not it become disabled “Grayed”
    1. Use class bellow “Taxonomy”
  3. For XML Declarative find here you may find other options also
using UTIL = ChangeYourNameSpace.Utils; 
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    try
    {
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            var site = properties.Feature.Parent as SPSite;
            var session = new TaxonomySession(site);

            if (session.TermStores.Count == 0) return;
            var termStore = session.TermStores["Managed Metadata Service"];

            if (termStore.Groups.All(x => x.Name != "MY TAGs"))
            {
                //TAGS
                var group = termStore.CreateGroup("MY TAGA");
                var termSetTag = group.CreateTermSet("TAGs");
                termSetTag.CreateTerm("Tag 1", 1033);
                termSetTag.CreateTerm("Tag 2", 1033);
                termSetTag.CreateTerm("Tag 3", 1033);                
                termSetTag.IsAvailableForTagging = true;
                termSetTag.IsOpenForTermCreation = true;
                termSetTag.Contact = "intranet@yourcorp.pt";
            }

            if (termStore.Groups.All(x => x.Name != "MY Documentos"))
            {
                //Tech Documents
                var groupDoc = termStore.CreateGroup("MY Documentos");

                var termSetDocTec = groupDoc.CreateTermSet("My Docs 1");
                termSetDocTec.CreateTerm("Tag 1", 1033);
                termSetDocTec.CreateTerm("Tag 2", 1033);
                termSetDocTec.CreateTerm("Tag 3", 1033);
                termSetDocTec.IsAvailableForTagging = true;
                termSetDocTec.IsOpenForTermCreation = true;
                termSetDocTec.Contact = "intranet@yourcorp.pt";

                var termSetDocCorp = groupDoc.CreateTermSet("My Docks 2");
                termSetDocCorp.CreateTerm("Tag 1", 1033);
                termSetDocCorp.CreateTerm("Tag 2", 1033);
                termSetDocCorp.CreateTerm("Tag 3", 1033);               
                termSetDocCorp.IsAvailableForTagging = true;
                termSetDocCorp.IsOpenForTermCreation = true;
                termSetDocCorp.Contact = "intranet@yourcorp.pt";
            }

            termStore.CommitAll();

            //TAGGING
            UTIL.Taxonomy.ActivateTaxField(site, "{9358ED54-0957-4A56-8047-F940C60D2024}", "TAG's", "TAGs");

            //Documents
            UTIL.Taxonomy.ActivateTaxField(site, "{ECA6E20C-20E0-433C-8D3C-667AD9C25E99}", "Documents", "My Documents");
        });
    }
    catch (Exception ex)
    {
        //Log
    }
}

public static class Taxonomy
{
    public static void ActivateTaxField(SPSite site, string taxonomyGuid,
        string taxonomyGroup, string taxonomyTerm)
    {
        try
        {
            var fieldId = new Guid(taxonomyGuid);
            if (!site.RootWeb.Fields.Contains(fieldId)) return;

            var session = new TaxonomySession(site);

            if (session.TermStores.Count == 0) return;
            var termStore = session.TermStores["Managed Metadata Service"];
            var group = termStore.Groups[taxonomyGroup];
            var termSet = @group.TermSets[taxonomyTerm];

            var field = site.RootWeb.Fields[fieldId] as TaxonomyField;

            if (field == null) return;
            field.SspId = termSet.TermStore.Id;
            field.TermSetId = termSet.Id;
            field.TargetTemplate = string.Empty;
            field.AnchorId = Guid.Empty;
            field.Update();
        }
        catch (Exception ex)
        {
            //Log
        }

    }
} 

Good Luck 😉

Add Enterprise Keywords to List with Receiver

Posted on Updated on

Let’s see, a easy tag field is the “TaxKeyword”, the default for “Enterprise Keywords”. The advantage is that he is already at the Search Schema an Indexed, so you can use in all objects that you want, Page Layouts for Publishing Pages, Lists, whatever.

How to do it in a SharePoint Feature Receiver?

SCOPE: Web

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    var web = properties.Feature.Parent as SPWeb;
    AddDocs(web);
}

private void AddDocs(SPWeb web)
{
    if (web == null) return;
    var list = web.Lists.TryGetList("Documents");
    if (list != null)
    {
        var field = list.ParentWeb.AvailableFields["Enterprise Keywords"];
        if (!list.Fields.ContainsField("Enterprise Keywords"))
        {
            list.Fields.Add(field);
            list.EnableModeration = true;
            list.EnableVersioning = true;

            var view = list.Views[0];
            view.ViewFields.Add(field);
            view.Update();

            list.Update();
            web.Dispose();
        }
        else
        {
            //Log
        }
    }
    else
    {
        //Log
    }
} 

 

How to add it to a Page Layout?

<%@ Register TagPrefix="Taxonomy" Namespace="Microsoft.SharePoint.Taxonomy" Assembly="Microsoft.SharePoint.Taxonomy, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>


 <Taxonomy:TaxonomyFieldControl FieldName="TaxKeyword" InputFieldLabel="My Custom Tags" runat="server"></Taxonomy:TaxonomyFieldControl>