Saturday, 28 January 2012

Working with CoffeeScript on SharePoint : Interacting through jQuery

Now in this next part, lets see how CoffeeScript can be used with jQuery on SharePoint:
Lets start with the most nifty feature first:
$(document).ready(function () { 
    //Code here.
});
is now:
$ ->
    //Code here.  

CoffeeScript makes it extremely easy to iterate over jQuery collections using the for loop:


Simple demo using CoffeeScript with jQuery to create a button, append it after the SP ribbon and assign a click function to it.
I hope you have enjoyed the series as much as me. Please feel free to leave me any feedback through comments or email. Happy Exploring!

GitHub Link to the project: https://github.com/vman/SPCoffeeScript

Friday, 27 January 2012

Working with CoffeeScript on SharePoint : ECMAScript Client Object Model

Now, the most interesting part of the series. We will be working with the ECMAScript Client Object Model through CoffeeScript.  The basic Create, Read, Update and Delete operations are done by using the ECOM with CoffeeScript:

Load the Client Object Model:


Get the Title of the Current Web:


Add Item to a List:

Update Item from List:

Delete Item from List:

Get All Items from List: In this last piece of code, notice how the while loop in CoffeeScript makes it extremely easy to iterate over a ListItemCollection.

Next:Working with CoffeeScript on SharePoint : Interacting through jQuery
GitHub Link to the project: https://github.com/vman/SPCoffeeScript

Working with CoffeeScript on SharePoint : Setup and Basics

So this new language called CoffeeScript was released recently and the only thing I could read everywhere was how its just JavaScript but only cleaner and more developer friendly. After digging a bit into it, I discovered that indeed the syntax is more friendlier and could boost productivity among JavaScript developers.

Also, being a SharePointer, whenever any new technology comes along, I always think about how it can be used in conjunction with SharePoint. How the technology can be leveraged to make SharePoint a better environment for developers as well as end-users.

So my natural instinct was to go ahead and see how CoffeeScript can be introduced in a SharePoint environment and how it can make life easier for the many SP developers out there. Lets get started then:

Project Setup:
For writing CoffeeScript, I have used the Mindscape Web WorkBench which is a very useful Visual Studio Extension. It lets you write code in CoffeeScript and then automatically produces a JavaScript file which contains the compiled code. This way you get to see your CoffeeScript code as well as the corresponding JavaScript code.

My SharePoint solution for working with CoffeeScript is very simple. I have created a Sandbox solution which contains a script module. Inside the script module, I deploy the MyScript.coffee, MyScript.js and the jQuery 1.7.1 files. I have included the script files on my pages with help of Custom Actions:
<CustomAction Location="ScriptLink" ScriptSrc="~Site/Scripts/jquery-1.7.1.min.js" Sequence="5000"/>
<CustomAction Location="ScriptLink" ScriptSrc="~Site/Scripts/MyScript.coffee" Sequence="5010" />
<CustomAction Location="ScriptLink" ScriptSrc="~Site/Scripts/MyScript.js" Sequence="5020" />

And lastly, I have included all the above elements in a Web Scoped Feature. Here is how my Solution Explorer Looks:
                                  (The GitHub link to my project is at the end of this blog post)

Now lets dive into the actual CoffeeScript code and see what exactly is up. Here are some interesting features of CoffeeScript that I felt are really nifty:

Here, I check the relative url of the current web and the use CoffeeScript's if else statement to modify it if necessary.
Optional parameters can be included in functions. Also, with the #{ } wildcard, parameters can be directly accessed from within a string.
Next: Working with CoffeeScript on SharePoint : ECMAScript Client Object Model
GitHub link to the project: https://github.com/vman/SPCoffeeScript

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.

Monday, 26 September 2011

Change Feature Image in Sandbox Solutions.


So recently, I had created a sandbox solution which deployed a Web Part when the feature associated with my solution was activated. So I thought when the user navigated to the Manage Features page, it should be easier for him/her to recognize which feature has to be activated and decided to assign an custom image to it.

Now my first thought was to deploy an image from the solution and assign its relative URL to the ImageUrl property of the feature. So, I deployed my custom image to the path /myFolder/awesome_img.png and assigned the same relative URL to my feature’s ImageUrl property.

And when I navigated to the Manage Features page, I was greeted with the following:


It turned out that SharePoint by default looks for the assigned image in the /_layouts/images/ folder. So whichever URL I provided to the ImageUrl property, SharePoint appended the /_layouts/images in front of it and assigned it to my feature.

Now since we are in the Sandbox, we do not have access to the _layouts folder. So we cannot deploy our custom Image to the folder and assign it to the feature.

But there is a workaround...and JavaScript has the answer!

So what I did was:
1) Deployed my custom Image to one of my SharePoint libraries.

2) Assigned place holder text to the ImageUrl property of the feature.


3) Wrote this little jQuery script which checked for the place holder text and replaced it with the path to my custom image.


jQuery(document).ready(function () {

      //Check if the current page is the Manage Features page.
     if (location.href.indexOf("ManageFeatures.aspx") != -1) {
           
          //Fetch each image with the place holder as the src.
         jQuery("img[src*='myFeatureImagePlaceHolder']").each(function () {
           
            //Replace the src of the image.
            this.src = this.src.replace("/_layouts/images/myFeatureImagePlaceHolder", _spPageContextInfo.siteServerRelativeUrl + "/myFolder/awesome_img.png");
          
        });
    }
});


4) Using Script delegates, Embedded the jQuery library and my custom JavaScript file into the masterpage, So that they will be available on the Manage Features page.


xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

<CustomAction Location="ScriptLink" ScriptSrc="~SiteCollection/Scripts/jquery-1.6.min.js" Sequence="1004" />

<CustomAction Location="ScriptLink" ScriptSrc="~SiteCollection/Scripts/ReplaceFeatureIcon.js" Sequence="1005"/>
<Elements>


After deploying the solution, I navigated to the Manage Features page and Voila! The feature image had changed:

Sunday, 25 September 2011

View & Edit InfoPath Forms in the SharePoint 2010 Modal Dialog

Recently, there was a requirement in my project that, an InfoPath form (which was stored in a Forms Library on SharePoint) had to be displayed as a pop-up when the user clicked on a particular HTML page element. The user also had to have the functionality to save the changes he/she made to the displyed form.

So naturally, my first thought was to use the JavaScript Modal Dialog which SharePoint provides out of the box. Now, My challenge was to provide it with a relevant URL which pointed to my desired InfoPath form.

I navigated to my InfoPath form stored in the Forms Library and observed the URL which showed in the browser. It was similar to the following:

 [SiteCollection]/_layouts/FormServer.aspx?XmlLocation=[RelativeURLofFormXML]&Source=[FormsLibraryAbsolutePath]&DefaultItemOpen=1

Where:
SiteCollection: URL of the Site Collection
RelativeURLofFormXML: relative path of the XML file of the InfoPath form I wanted to display.
FormsLibraryAbsolutePath: The absolute path of the Forms Library which contained my InfoPath form.


Now, the only thing remaining to do was to take the JavaScript modal dialog and push the form url into it, which i did with the following code:


After that, I assigned the OpenForm( ) function to an anchor tag and when i clicked on it:


I was even able to save the form after filling it! :)

Friday, 26 August 2011

JavaScript "L_Menu_BaseUrl" variable for SharePoint

When working with Sandbox Solutions, there are a lot of times when you have to determine the URL or the serverRelativeUrl of the current site. This is especially needed on Office 365.
With the ECMAScript Client Object Model, there are multiple ways to access the current site URL or the serverRelativeUrl like the SP.Site.get_url() for the Root site URL or SP.Web.get_serverRelativeUrl() for the relative url of the current site.

But there is an easier way get the URL  by using the OOB Javascript variable L_Menu_BaseUrl which stores the URL of the current Web or the Subsite.

For example, this was extremely helpful to me for calling the EditDialog on any list item. It worked great with Office 365 top level sites as well as sub-sites:

function OpenEditDialog(itemid)
{
   var options = {

    url: L_Menu_BaseUrl + "/Lists/Claims/EditForm.aspx?ID=" + itemid + "&IsDlg=1",
     width: 700,
     height: 700,
     dialogReturnValueCallback: DialogCallback 
};
     SP.UI.ModalDialog.showModalDialog(options);
}

Here are some more OOB Javascript variables which can be useful: 

L_Menu_LCID : This contains the LCID setting of the current site.
L_Menu_SiteTheme : This contains the theme name of the current site.
_spUserId : This contains the id of the current user.