Tagging content in SharePoint 2010 using SocialTagManager

 In my last article I described how you can enumerate tagged items in your entire site collection ; in this article we’ll take a look at the trivial yet important part of actually tagging your content. Sure you can use existing Tags & Notes feature on the ribbon – but in case you need to perform tagging programatically here is how you go about it.

In my example I’m using simple visual webpart from Visual Studio 2010 Beta SharePoint 2010 projects.

I create a button that will call the handler code below; note, I do some extra processing to make sure that I apply only one of two tags (promote/demote). I have an enum that defines Promote/Demote as a TagType. When the handler is called it checks to make sure Promote/Demote are keywoprds within your term store. I also assume you have Metadata Service running otherwise none of the below will work:

private static void TagResource(TagType tag)
        {
            SPSite siteColl = SPContext.Current.Site;
            SPServiceContext serviceContext = SPServiceContext.GetContext(siteColl);
            SocialTagManager mySocialTagManager = new SocialTagManager(serviceContext);
            SocialTerm[] socTerms = mySocialTagManager.GetAllTerms();

            IEnumerable<SocialTerm> termQuery = socTerms.Where(socTerm =>
                (
                socTerm.Term.Name.Equals(TagType.Promote.ToString()) ||
                socTerm.Term.Name.Equals(TagType.Demote.ToString())
                ));

            foreach (SocialTerm aTerm in termQuery)
            {
                string termName = aTerm.Term.Name;
                if (termName.Equals(tag.ToString()))
                {
                    mySocialTagManager.AddTag(HttpContext.Current.Request.Url, aTerm.Term,
                        aTerm.Term.Name);
                    break;
                }
            }
        }

This is it, above code will tag the current URL of where your webpart is with one of the tags you passed into your handler. If you used the code above with the code described in my last article you will be able to see the results of your tagging in a webpart as well.

Enjoy!

This entry was posted in sharepoint and tagged , , , . Bookmark the permalink.

Comments are closed.