Tuesday, October 30, 2012

How to Deploy ItemStyle.xsl at SharePoint site Creation

It is a known issue with SharePoint that ItemStyle.xsl doesn’t get provisioned. Styling for the Content Query Web Parts (CQWP) are done on ItemStyle.xsl file. In most of the SharePoint projects we add ItemStyle.xsl in to Branding feature, but even after the activation of the feature this file won’t get provisioned.

Most of the sites suggest to upload this file manually after creating the site. But ItemStyle.xsl can be uploaded in to the site at feature activation. Few lined of code will do this. Steps are given below.

  1. Add Event Receiver to the Branding feature (Or what ever the feature that Item.xsl File is included)

  2. Override ”FeatureActivated” Event and add below code.

 

 

1 public override void FeatureActivated(SPFeatureReceiverProperties properties)
2 {
3
4 SPSecurity.RunWithElevatedPrivileges(delegate()
5 {
6 bool IsXSLUpdated = false;
7 String fileToUpload = @"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\FirstPrincipal\XslStyleSheet\ItemStyle.xsl";
8 string libraryName = "Style Library";
9 string xslFolderName = "XSL Style Sheets";
10
11 if (IsXSLUpdated == false)
12 {
13 using (SPSite spSite = (SPSite)properties.Feature.Parent)
14 {
15
16 SPFolder xslStylefolder = null;
17 SPWeb web = spSite.OpenWeb();
18 if (System.IO.File.Exists(fileToUpload))
19 {
20 SPFolderCollection stylefolders = web.Folders[libraryName].SubFolders;
21
22 foreach (SPFolder folder in stylefolders)
23 {
24 if (folder.Name == xslFolderName)
25 {
26 //upload replacing the existing
27 xslStylefolder = folder;
28 String fileName = System.IO.Path.GetFileName(fileToUpload);
29 System.IO.FileStream fileStream = System.IO.File.OpenRead(fileToUpload);
30
31 SPFileCollection xslFileCollection = xslStylefolder.Files;
32
33 foreach (SPFile file in xslFileCollection)
34 {
35 if (file.Name == fileName)
36 {
37
38 file.CheckOut();
39 break;
40 }
41 }
42 SPFile spFile = xslStylefolder.Files.Add(fileName, fileStream, true);
43
44 spFile.CheckIn("Checking in item style xsl sheet", SPCheckinType.MajorCheckIn);
45 spFile.Publish("Publishing the item style xsl sheet");
46 xslStylefolder.Update();
47 IsXSLUpdated = true;
48 break;
49 }
50 }
51
52 }
53
54
55 }
56 }
57 });
58 }

No comments:

Post a Comment