Sunday, 28 September 2014

SharePoint 2013 - Retrieve all items from a SharePoint list using JavaScript Object Model (JSOM)

In the previous post we discussed the basics of JavaScript Object Model (JSOM). In this post, we will implement JSOM inside a Content editor webpart. As per your requirement you can implement JSOM inside a Site page, Application page or a Master page directly.

Create a custom list for retrieving data from client side
Create a custom list named "Products" with three columns Title, Description and Price.


Code for retrieving all items from a SharePoint list
In the previous post we have already discussed about the objects and methods used in JSOM. Following is complete code for implementing JSOM for retrieving all items from a SharePoint list.
Code Snippet
  1. <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
  2. <script type="text/javascript" src="_layouts/15/sp.runtime.js"></script>
  3. <script type="text/javascript" src="_layouts/15/sp.js"></script>
  4.  
  5. <script type="text/javascript">
  6.     function GetProducts() {
  7.         var clientContext = new SP.ClientContext.get_current();
  8.         var oList = clientContext.get_web().get_lists().getByTitle('Products');
  9.         this.collListItem = oList.getItems("");
  10.  
  11.         clientContext.load(collListItem);
  12.         clientContext.executeQueryAsync(
  13.             Function.createDelegate(this, this.onQuerySucceeded),
  14.             Function.createDelegate(this, this.onQueryFailed)
  15.         );
  16.     }
  17.  
  18.     function onQuerySucceeded(sender, args) {
  19.         var ProductInfo = '';
  20.         var listItemEnum = collListItem.getEnumerator();
  21.  
  22.         while (listItemEnum.moveNext()) {
  23.             var oListItem = listItemEnum.get_current();
  24.             ProductInfo += '\n\nID: ' + oListItem.get_id() +
  25.                 '\nTitle: ' + oListItem.get_item('Title') +
  26.                 '\nDesc: ' + oListItem.get_item('Description') +
  27.                 '\nPrice: ' + oListItem.get_item('Price');
  28.         }
  29.  
  30.         alert(ProductInfo.toString());
  31.     }
  32.  
  33.     function onQueryFailed(sender, args) {
  34.         alert('Request failed. ' + args.get_message() +
  35.             '\n' + args.get_stackTrace());
  36.     }
  37. </script>​
  38.  
  39. <input type="button" value="Get Products" onclick="GetProducts()"/>

Copy the above code in a Content editor web part
Go to the SharePoint site and add a content editor web part.

Choose the Edit Source option and the HTML source window will pop up.

Copy the code mentioned in the previous step and paste it inside the HTML source window as follows. Click OK button and save the page.

Displaying the data
Click on the "Get Products" button and all the list items in the Products list will be displayed as an alert.



SharePoint 2013 - The JavaScript Object Model (JSOM)

In this post we shall look a little deep into the JavaScript Object Model in SharePoint 2013. In the next post we will see a demo for retrieving list items from a SharePoint list using JSOM.

JSOM Objects
Objects in JSOM are pretty much similar to the classes in SharePoint server object model. Following are some of the commonly used JSOM counter parts.
.NET Server type
JSOM object
SPSite
SP.Site object (sp.js)
SPWeb
SP.Web object (sp.js)
SPWebCollection
SP.WebCollection object (sp.js)
SPList
SP.List object (sp.js)
SPListItem
SP.ListItem object (sp.js)
SPListItemCollection
SP.ListItemCollection object (sp.js)
Client context not available
SP.ClientContext object (sp.js)
SPContentType
SP.ContentType object (sp.js)
SPContext
SP.RequestContext object (sp.js)

JSOM Implementation
Following are the main steps for implementing JSOM.
1) Add reference to the JavaScript libraries that support JSOM.
2) Get an instance of Client Context and load the JSOM objects
3) Specify Callback functions and Execute the query.

Now lets see each of the above mentioned steps in detail. After that we will see a demo for getting the items from a SharePoint list using JSOM.

1) Adding reference to the JS libraries for supporting JSOM
For implementing JSOM, a reference to the following JS files should added inside the page.
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script type="text/javascript" src="_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="_layouts/15/sp.js"></script>

Note:- In case we have customized or utilized a new master page for our sites, we should ensure that JSOM is loaded before we start accessing it. There are 2 methods for doing in it.
(i) ScriptLink : Use the server side ScriptLink class to declaratively register a script. The class provides properties and methods for registering scripts so that they can be requested when the page is being rendered.
<SharePoint:ScriptLink ID="registerSP" runat="server" OnDemand="true" LoadAfterUI="true" Name="SP.js">
(ii) ExecuteOrDelayUntilScriptLoaded : The SOD framework provides methods to ensure that the client scripts are loaded before any execution takes place on the dependent methods. Calling the following method before the executing method ensures that the function provided in the first parameter is not executed until the script file name mentioned is not loaded or has not been loaded.
ExecuteOrDelayUntilScriptLoaded(GetProducts, "sp.js");

2) Get an instance of client context and load the JSOM objects
First of all, an instance of the client context must be created to access the objects in the JSOM. The current context can be get by using the get_current() method in SP.ClientContext as shown below.
var clientContext = new SP.ClientContext.get_current();

Using the Client Context object all the other SharePoint objects should be loaded as follows. In the following example we are loading all the items from the list named "Products".
var oList = clientContext.get_web().get_lists().getByTitle('Products');
this.collListItem = oList.getItems("");
clientContext.load(collListItem);

Note: You can further add a CAML query to the above code as follows 
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +'<Value  type=\'Number\'>1</Value></Geq></Where></Query>' + '<RowLimit>10</RowLimit></View>');
this.collListItem = oList.getItems(camlQuery);


3) Specify the callback functions and execute the query
Once all the necessary objects are loaded, we must specify the callback functions and execute the query as follows.
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed));

Specify the Callback function if query execution succeeded

function onQuerySucceeded(sender, args) {
alert("Success");
}
Specify the Callback function if query execution failed
function onQueryFailed(sender, args) {
alert("Failure");
}
Hope this post helps you to get a basic idea about the JavaScript object model in SharePoint 2013. In the next post we will see a demo for retrieving list items from a SharePoint list using JSOM.

SharePoint 2010 - Features Stapling

Feature stapling allows a Feature to be stapled to any new sites created from any site definition or from specific site definitions based on the template name identified in the appropriate WEBTEMP.xml file. The stapled feature will be automatically activated each time a new site or sub-site is created using the associated site definition.

Warning: You can not use feature stapling on a site created using a site template (.stp) file.  If you try to staple feature on a site which was created using site template (.stp) file, the feature will not get activated automatically when the new site is created.

You can staple a feature to a site created using any of the in-built site definition templates or your own custom site definitions. For instance, following are some of the main site definitions available in SharePoint.
Template Name
Template Title
STS#0       
Team Site
STS#1      
Blank Site
STS#2      
Document Workspace
MPS#0      
Basic Meeting Workspace
MPS#1      
Blank Meeting Workspace
MPS#2      
Decision Meeting Workspace
MPS#3      
Social Meeting Workspace
MPS#4      
Multipage Meeting Workspace
WIKI#0     
Wiki Site
BLOG#0     
Blog Site
Feature stapling Components
Feature stapling consists of 3 main components:
1) Stapler Feature: The parent feature which has a higher scope than the Staplee or Child feature.
2) Staplee Feature: The Child feature which gets activated when the Stapler feature gets activated.
3) Stapler Feature's Element.xml: Consist the association between the Staplee feature's Id and the Site definition template name (eg: STS#0) on which it will get activated.
<FeatureSiteTemplateAssociation Id="b94f446e-0989-4d90-8abb-7aa0704f4506" TemplateName="STS#0">

Feature stapling Scenario
We need to create multiple sub sites inside a site collection with template as team site. Each time a new sub-site is created, it must have a list named Team Docs which is automatically created at the time of creation.

Feature stapling Implementation
We can use Feature Stapling in this scenario as follows:
1) Create a Stapler feature scoped to Site level.
2) Create a Staplee feature scoped to the Web level. Also add a feature reciever and write the code for creating a new list named "Team Docs" at the time of activation.
3) Associate the Staplee feature with the Team Site template Name ("STS#0") in the Elements.xml file.
4) Deploy the solution and Install both the features.
5) Activate the Site collection level Stapler feature. The Web level Staplee feature will be automatically stapled.
6) Whenever a new sub-site based on Team Site template is created, a list named Team Docs will be automatically created.

Feature stapling Demo
Following are the steps:-

Create an empty SharePoint 2010 project
Enter your site collection url and select "Deploy as a farm solution" option.

Add a new feature named "FeatureStaplingDemo Stapler" with scope as Site.

Add another new feature named "FeatureStaplingDemo Staplee" with scope as Web.
Now, right click on project and add an Empty Element to the project.

Go to web scoped Staplee feature and copy the feature id from the feature manifest.

Add the following code in the FeatureSiteTemplateAssociation tag in Elements.xml where
id is the feature id of the staplee and
TemplateName is the name of Site template on which we are stapling this feature.

Code for Elements.xml
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <FeatureSiteTemplateAssociation Id="b94f446e-0989-4d90-8abb-7aa0704f4506" TemplateName="STS#0"></FeatureSiteTemplateAssociation>
</Elements>
Now, add a feature receiver to the web scoped Staplee feature.

In the feature activated event, add the code for adding a new list named "Team Docs" whenever a new sub-site is created.

Code for Feature Activated and Deactivating
public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
                SPWeb web = properties.Feature.Parent as SPWeb;
                try
                {
                    SPList targetList = web.Lists["Sales"];
                }
                catch (ArgumentException)
                {
                    Guid listId = web.Lists.Add("Team Docs", "Team Documents", SPListTemplateType.GenericList);
                    SPList list = web.Lists[listId];
                    list.OnQuickLaunch = true;
                    list.Update();
                }                
        }       
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWeb web = properties.Feature.Parent as SPWeb;
            try
            {
                SPList list = web.Lists["Team Docs"];
                list.Delete();
            }
            catch (ArgumentException)
            {
            }    

        }

Deploy the solution

In the site collection, go to Site Setting->Site Collection Features. You can see that the Stapler feature has been activated.

Now, create a new sub-site with template as Team Site.

You will notice that the List named "Team Docs" has been automatically created.

Go back to Site Setting->Site Collection Features in the site collection and deactivate the Stapler feature.

Create another sub-site with the template as Team Site.

This time the list named "Team Docs" is not created since the Stapler feature is deactivated.

Hope this post helps!