Search code examples
searchsharepoint-2010xsltfeature-activation

Change XSLT of the SearchResultWebPart during the FeatureActivated


I have a piece of code which changes XSLT of a SearchResultWebPart at Sharepoint 2010 Search Center result page (spFileItem - is SPFile of a search result page) :

SPLimitedWebPartManager wpManager = spFileItem.GetLimitedWebPartManager(PersonalizationScope.Shared);
foreach (WebPart wpItem in wpManager.WebParts)
{
    if (wpItem is CoreResultsWebPart)
    {
      ((CoreResultsWebPart)wpItem).UseLocationVisualization = false;
      ((CoreResultsWebPart)wpItem).Xsl = someXSL;
      wpManager.SaveChanges(wpItem);
}
spFileItem.Update();
spFileItem.CheckIn(Consts.CheckInComment, SPCheckinType.MajorCheckIn);

But, this code doesn't work if it is called on feature activated (gives InvalidOperationException - incorrect object state). However it perfectly works in Console application. After some reflecting, I found out that there is a piece of code inside the SearchResultWebPart, which checks if the webpart wasn't initialized - it throws the mentioned above exception on setting XSL property. Does anybody know how to work this problem out? For me it'd be quite convenient to do XSL change at FeatureActivated...


Solution

  • I found a solution to my problem, but it uses different way of setting xsl for SearchResultBaseWebPart.

    SPLimitedWebPartManager wpManager = spFileItem.GetLimitedWebPartManager(PersonalizationScope.Shared);
    foreach (WebPart wpItem in wpManager.WebParts)
    {
        if (wpItem is CoreResultsWebPart)
        {
          ((CoreResultsWebPart)wpItem).UseLocationVisualization = false;
          ((CoreResultsWebPart)wpItem).XslLink = spFileItem.Web.Url + @"/_layouts/XSL/MYXSL.xsl";
          wpManager.SaveChanges(wpItem);
        }
    }
    spFileItem.Update();
    spFileItem.CheckIn(Consts.CheckInComment, SPCheckinType.MajorCheckIn);