Monday, February 5, 2007

How to add a BestBet in SharePoint 2007 programmatically

First of all: hi! I'm Tom, software engineer at Dolmen (you know, the company where the infamous jopx works, not by coïncidence the person who I report to...). It took me a while to start blogging, but when I was looking for information on adding BestBets and Keywords programmatically and I couldn't find a thing, it just felt like the right moment to start a blog and "share the wisdom" as they say. Adding Keywords and BestBets is actually not that difficult, you just have to know the right syntax to do so. That's where I come in: here's what I did to make it work:

bool found = false;

Keywords keys = new Keywords(SearchContext.GetContext(SPContext.Current.Site), new Uri(SPContext.Current.Site.Url));

foreach (Keyword key in keys.AllKeywords)
{
if (key.Term.ToLower() == textToCompareTo.ToLower())
{
found = true;
bool foundBet = false;

foreach (BestBet bet in key.BestBets)
{
if (bet.Url == urlToReferTo)
{
foundBet = true;
}
}

if (!foundBet)
{
key.BestBets.Create("Title", "BestBet description", urlToReferTo);
}

break;
}
}
if (!found)
{
keys.AllKeywords.Create(textToCompareTo.ToLower(), DateTime.Now);
}


Now let's explain what this code does...

To start off, we create a boolean that tells us whether the Keyword we want to add a BestBet for is already in the Keywordcollection or not. If it isn't, we'll add it at the end of our code.
The next step is to get all the Keywords of the current Sitecollection you are working on. To do so, we need to create a new Keywordcollection with the context of the current Sitecollection and the url of this Sitecollection.
Once we've found the Keywords, we're going to browse through all the Keywords of the current Sitecollection to check for a match with the Keyword you want to add a BestBet for (in the example I've just used "textToCompareTo" as the string we're looking for). If we find this Keyword in the Keywordcollection, we're going to browse through all the BestBets that have been assigned to this Keyword, to check whether the BestBet we want to add is already part of the BestBetcollection or not. If it is, then our job is done and we don't have to do a thing anymore. If it isn't, we'll add it by creating a new BestBet with a certain title, description and an url we want the BestBet to refer to.

So there you go, not that hard as I first thought it was going to be. If there's any questions or remarks, feel free to leave a comment.