Saturday 21 January 2012

Reference CSS files in Sandbox Solution for SharePoint Foundation 2010


Recently I had a requirement where I had to push some custom css files to the page when my SharePoint solution package was deployed. This being a sandbox solution, I could not simply put the files in the /_layouts/ folder and reference it from there.
Also, since the solutions was targeted at a SharePoint 2010 Foundation environment, that meant that I could not use the <% $SPUrl:~sitecollection/Style Library/mystyles.css %> tag because that’s part of the publishing infrastructure which is unfortunately not allowed. If you are developing for the SharePoint Server, then you can use these tokens in sandbox solutions with help of a "hack" mentioned here:
http://msdn.microsoft.com/en-us/library/ee231594.aspx

Now, since I wanted to deploy my CSS file with the solution, I could not just go to the current MasterPage and edit it using SharePoint designer. Also, I figured that there might be times when you don’t have the access to the MasterPage and cannot edit it. So directly editing the current MasterPage was quickly ruled out.
After some thought and some digging around I found out 2 promising methods to include CSS to your Sandbox solution targeted at SharePoint foundation:
1)      Using CustomActions:
Now here is the weird thing about SharePoint 2010: They have provided a separate custom action for pushing the JavaScript to the masterpage  but they have not provided a similar method for the CSS files. So I had to improvise a little in this case. I created an empty elements file and included the following custom action inside it.


The Location=”ScriptLink” attribute tells the custom actions to include it in the ScriptLink section on the masterpage. And the ScriptBlock attribute defines what JavaScript code to be included in it. What I did is simply create a HTML link control and gave the appropriate path to of my CSS file in the href attribute.
2)      Using Feature Receiver:
Another way is by using a feature receiver which executes the defined code when a Feature is activated. Here we can use the SPWeb.AlternateCSSUrl property which can be used to give path of a CSS file which will be included in the current Web.

No comments: