Wednesday, 9 September 2009

Problem adding Keywords and Best Bets programmatically in MOSS 2007

I was writing a small Windows application for a customer to create keywords and best bets using a CSV file and experienced a weird problem. I used the code published here by Stefan Go├čner as a starting point, which successfully added the keywords to the Manage Keywords UI in Site Collection Administration, but when I tried to search on one of the keywords, no best bets were shown in the search results.

The format of the CSV file was, as follows:

Keyword name, Synonyms (semi-colon delimited), Best bet URL

For example: Acme Primary School, Acme;Acme School;Acme Primary, http://www.acme.com

The code I used to create the keywords was:

keywords.AllKeywords.Create(keywordTerm, DateTime.Today.AddHours(-1));
keywords.AllKeywords[keywordTerm].Synonyms.Create(objSynonyms);
keywords.AllKeywords[keywordTerm].BestBets.Create(objBestBet.ToString() + " Profile", "Full school profile for " + objBestBet.ToString(), new Uri(objUrl.ToString()));
keywords.AllKeywords[keywordTerm].Update();

I then found that if I clicked on one of these keywords in the Manage Keywords UI and clicked OK without changing anything, the search for that keyword worked. I eventually discovered that SharePoint didn’t like adding the semi-colon delimited synonyms as a single string and that they needed to be created separately. Therefore, I changed the code to below, using the semi-colons to split the string up into an array of separate synonyms, which worked:

keywords.AllKeywords.Create(keywordTerm, DateTime.Today.AddHours(-1));
//Create synonyms from semi-colon separated array
string[] synonymArray = objSynonyms.ToString().Split(new char[] { ';' });
foreach (string synonym in synonymArray)
{
     keywords.AllKeywords[keywordTerm].Synonyms.Create(synonym);
}
keywords.AllKeywords[keywordTerm].BestBets.Create(objBestBet.ToString() + " Profile", "Full school profile for " + objBestBet.ToString(), new Uri(objUrl.ToString()));
keywords.AllKeywords[keywordTerm].Update();