Change XSLT of the SearchResultWebPart during the FeatureActivated

1.4k views Asked by At

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...

2

There are 2 answers

0
MaksymD On BEST ANSWER

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);
1
pholpar On

I feel you mix up a few things in the question. You would like to set the Xsl property of the CoreResultsWebPart. This class has no direct implementation of the Xsl method, so it inherits the implementation of its parent class (SearchResultBaseWebPart). The Xsl property setter try to set the XslHash property (but only if we are after the OnInit that sets _BeforeOnInit = false;), and the setter method of the XslHash property throws an InvalidOperationException, but this exception should be catched by the try/catch block in Xsl property setter anyway. I don't see any other potential source of InvalidOperationException in the code.

You should check the patch level of your SP2010 (is it SP1/some of the cummulative updates/original version?) and try to activate the feature from different contexts (from web site / STSADM or PowerShell).

But first I suggest you to add a try / catch block to your feature receiver code and trace out the error details (like stack trace) and monitor the results using DebugView.