If you are adding a (standard or custom) ContentByQueryWebPart through code and you want to add the link to your custom ItemStyle.xsl you will run into the following problem:
My scenario was adding the webparts to the pagelayout through code on site creation. I added a new Custom ItemStyle 'CustomItemStyle.xsl' next to the default xsl, however after site creation the webpart still referred to the default ItemStyle file. You will recieve no error messages.
Sharepoint requires knowing the current HttpContext before being able to set the link to the custom file in the webpart, if HttpContext is empty, fill it before setting the part and it will work.
// Add a list view to the bottom of the zone.
if (HttpContext.Current == null)
{
HttpRequest request = new HttpRequest("", newweb.Url, "");
HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));
HttpContext.Current.Items["HttpHandlerSPWeb"] = newweb;
}
ContentByQueryWebPart part = new ContentByQueryWebPart();
part.Title = title;
part.ItemStyle = itemstylename;
part.ListGuid = listguid;
part.ItemLimit = 5;
part.CommonViewFields = commonviewfields;
part.Xsl = "<xsl:stylesheet xmlns:x=\"http://www.w3.org/2001/XMLSchema\" version=\"1.0\"
xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:cmswrt=\"http://schemas.microsoft.
com/WebPart/v3/Publishing/runtime\" exclude-result-prefixes=\"xsl cmswrt x\" > <xsl:
import href=\"/Style Library/XSL Style Sheets/Header.xsl\" /> <xsl:import href=\"/Style
Library/XSL Style Sheets/CustomItemStyle.xsl\" /> <xsl:import href=\"/Style Library/XSL
Style Sheets/ContentQueryMain.xsl\" /> </xsl:stylesheet>";
part.ItemXslLink = "/Style Library/XSL Style Sheets/CustomItemStyle.xsl";
wpm.AddWebPart(part, zoneId, zoneIndex);
wpm.SaveChanges(part);