Wednesday, 16 May 2012

SharePoint JavaScript Unit Testing with Jasmine


So recently while working on some code, I realized that I have not yet ventured into the field of Unit Tests and TDD. I had read about it plenty but never had got an opportunity to work on it. Test Driven Development (TDD) consists of writing the test cases before you write your code. It mainly consist of 3 factors: Red, Green and Refactor. Red indicates writing of a test case which will always fail, mainly because of the fact that the functionality for passing the test has not yet been written. Next, Green indicates the creation of the functionality which will pass the test. And finally, Refactor indicates the re-modelling of your code to make it more efficient and performance friendly.

Since I am writing a lot of JavaScript these days, I decided to go forward and introduce TDD into my JavaScript Projects. When I was looking for more information on JavaScript Unit Testing, the one framework which immediately grabbed my attention was Jasmine. It came with a terse and easy syntax and it clearly outmatched the other frameworks in functionality and ease of use. More over, it could be used completely client side in the browser as a standalone framework. So I decided to go forward and implement it. (You can try out Jasmine here without installing anything).

Now being a SharePoint developer, things are not always as easy as they seem. You will find a lot of tutorials on the web integrating Jasmine with various technologies but almost none when SharePoint comes into the picture. So like most of the times, it was on me to figure out how to integrate the Jasmine Unit Testing Framework with SharePoint JavaScript and create successful Unit Tests with it.

As I mentioned before, the good thing about Jasmine is that you can use it as standalone framework without making much configuration settings. It completely runs in the browser and presents a very rich and informative UI when it comes to indicating whether a test has passed or failed.

Integrating it with SharePoint:

Following is my SharePoint project structure. I have included all the files for the tests in the "Tests" module (As highlighted below)


Now, the Jasmine framework requires some basic JS and html files to run the tests and display the results. 

  1.  The jasmine.js file does all the heavy lifting.It contains the code of the testing framework.
  2.  The jasmine-html.js, jasmine.css and the SpecRunner.aspx page all work in the presentation layer and provide a nice rich UI to display the result of the tests. 
  3.  The maiFileSpec.js is the specrunner which will contain and run all the tests for the JavaScript functions.
  4.  The mainFile.js is a regular old JavaScript file which will  contain all of our code which has to be tested. This does not have to be a single file you can test functions in multiple JS files also.
Now lets get into some code. Here is the code for my mainFile.js which has the functions which we will be testing with the Jasmine Framework:

This file contains 3 functions. MakeInt converts a value to a integer with radix 10. Divide returns the first number divided by the second number. It throws an error is the second number is 0. CreateJQObject creates and returns a jQuery object with the the specified HTML tag, is and class.

Now lets have a loot at the mainFileSpec.js file, which we will be using to test the functions defined in the previous file.



Now lets aggregate all this code in one aspx page so that we can carry out the tests. Here is how my SpecRunner.aspx looks:



Now once we deploy this project to the SharePoint site, all we have to do is navigate to the SpecRunner.aspx page to where it is deployed and the tests will be automatically run:


Now lets, change some code so that the tests will fails and we will get to see how jasmine displays the failed tests UI. I am changing the following code in the Test for the CreateJQObject function:
expect(jqObject.length).toEqual(0);
This test will now fail because the length of the jQuery object will be 1 and the test expects it to be 0.

Also, lets change one more thing. The error thrown by the Divide function:
 expect(testErr).toThrow(new Error("Result will be Infinity because divisor is 0"));
This test will also fail because the test is expecting one error but the code will throw another kind of error.

Lets runs the tests and find out. After running the test, we are presented with the following UI:



So as you can see, if the test fails we are presented with the functions which are failing, their expected and actual values and the execution queue which caused the error.

So in conclusion, TDD can be very easily achieved in JavaScript with help of the Jasmine JavaScript Framework. Moreover, we can utilize the framework inside SharePoint as well!

Have fun coding!

Wednesday, 4 April 2012

SharePoint List Designer in Visual Studio 11

I have recorded a ScreenCast describing one of the new Features of Visual Studio 11 that is the SharePoint List Designer:


Tuesday, 3 April 2012

JavaScript XML Documentation in Visual Studio 2012

So I have been playing around with Visual Studio 2012 developer preview recently. From a SharePoint developers perspective, there are a lot of new features which will improve the productivity such as the List Designer, Remote Deployment of Solutions etc. Also, from a JavaScript developers perspective, there are a truck load of new features which make your life quite easy and productive. Visual Studio 2012 treats JavaScript as a first class citizen with functionality such as Intellisense and 'Go to function definition'.

One of the exciting features is the XML documentation comments functionality which allows the developer to provide XML comments to functions which the Intellisense picks up and displays accordingly. Also, more than one signature can be displayed for overloaded functions. Lets have a look at an example:



One quirky thing is that we have to put the documentation inside the function. The <signature> element describes the documentation for one implementation of the function. The <summaryelement describes the description of that implementation. The <param> element describes the details about one parameter of the function. The <returns> describes the type of the value which the function returns. And as you can see from the following image, the Intellisense does indeed pick it up and display the documentation accordingly.





Here is the complete list of elements supported by the  <signature> element:

Also, the XML documentation functionality goes beyond the signatures. Here is the complete documentation available right now:

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.