-->
Showing posts with label Sharepoint. Show all posts
Showing posts with label Sharepoint. Show all posts

Tuesday, 15 September 2015

Get Data in JQuery DataTable from SharePoint List using $skip, $top, $inlinecount, $orderby parameters

In this article we will show how you can load the data from SharePoint List using REST API into JQuery DataTable using the Ajax Pagination.

In my previous article I showed you how to retrieve the data from the SharePoint list using REST API but it retrieves all the data from the list at once which is good for the list having less number of items/records but what if the list has large number of items as SharePoint client object model supports retrieval of 5000 items at once. 

In this case the SharePoint REST API provides the $TOP, $ORDERBY, $SKIP AND $INLINECOUNT parameters to retrieve only the records required to show on one page.

Parameter
Example
Description
$skip
$skip=n
Returns entries skipping the first n entries, according to the $orderby parameter
$top
$top=n
Returns only the top n entries, according to the $orderby and $skip parameters
$inlinecount
$inlinecount=allpages
It will add the  __count property to the results which indicates the total number of entries which match the $filter expression 
$orderby
$orderby = CustomerName
Returns the records ordered by the CustomerName field

Example: http://server/siteurl/_vti_bin/listdata.svc/Customers?$ $select=Id,CustomerName,Address,HomePhone,MobileNumber,Email,Organization,RolesValue &$inlinecount=allpages&skip=2&$top=2

We will use these parameters to retrieve the data required and bind it to our JSON

We will use the same customers list we used in my previous article series
I have created the CustomerJqueryDataTableAjax.js and CustomerJqueryDatatableAjax.txt for this article, which you can download it at the end of this post.

The rest query to get the top 10 items from the customers list would look like this,

../_vti_bin/listdata.svc/Customers?$select=Id,CustomerName,Address,HomePhone,MobileNumber,Email,Organization,RolesValue&$inlinecount=allpages&$top=10

Now in order to support pagination in DataTable the json results should have values of “sEcho”, “iTotalRecords”, “iTotalDisplayRecords in the json results which is not provided by the SharePoint by default so we will manipulate it in the fnServerData function of the JQuery DataTable.

Monday, 14 September 2015

Free Text Search on Column in JQuery Datatable


In my previous article I showed you how to retrieve the data from the SharePoint list using REST api and bind it to the JQuery Datatable. And In another article I showed how you can perform a column filter using the dropdown. Jquery DataTable provides a free text search but it is for the entire table this article will help you implement the free text search on the particular column.

Articles on the Jquery DataTable and SharePoint REST API

In this article we will show how you can perform a free text search on the custom column particularly on the JQuery DataTable which retrieved the data from the SharePoint List using the REST Api.

We will use the same customers list we used in my previous article and perform a free text search on the Address column.



Custom DropDown Column Filter in JQuery Datatable


In this article we will show how you can add the custom column filters on the JQuery DataTable which retrieved the data from the SharePoint List using the REST Api.

In my previous article I showed you how to retrieve the data from the SharePoint list using REST api and bind it to the JQuery Datatable.


Articles on the Jquery DataTable and SharePoint REST API 

We will use the same customers list we used in my previous article except that we will add two more columns to it viz, ‘Organization’ and ‘Role’. I have assigned some data to these columns for the existing records.



Make sure you add the organization and Role column in the js file to be retrieved from the SharePoint.
 tableContent += '<td>' + objArray[i].Organization + '</td>';  
 tableContent += '<td>' + objArray[i].RolesValue + '</td>';  
Let’s pick up our CustomerJqueryDatatable.txt and add the panel to hold our dropdowns for organization and roles column. You can place this code above our CustomerPanel div.
 <div id="filterPnl">  
   <table style="width:100%">  
     <tr>  
       <td style="width:50%;">Organization : <span id="orgDropDown"></span></td>  
       <td style="width:50%;">Roles : <span id="roleDropdown"></span></td>  
     </tr>  
   </table>  
 </div>  
 </br /><hr /> </br />  

CustomerJqueryDatatable.txt should look something like this now.
 <script type="text/javascript" src="../SiteAssets/js/jquery-1.11.0.min.js"></script>  
 <script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>  
 <link href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="Stylesheet" type="text/css" />  
 <script type="text/javascript" src="../SiteAssets/CustomerJqueryDatatable.js"></script>  
 <div id="filterPnl">  
   <table style="width:100%">  
     <tr>  
       <td style="width:50%;">Organization : <span id="orgDropDown"></span></td>  
       <td style="width:50%;">Roles : <span id="roleDropdown"></span></td>  
     </tr>  
   </table>  
 </div>  
 </br /><hr /> </br />  
 <div id="CustomerPanel">  
   <table style="width: 100%;">  
     <tr>  
       <td>  
         <div id="CustomerGrid" style="width: 100%"></div>  
       </td>  
     </tr>  
   </table>  
 </div>  

Open the CustomerJqueryDatatable.js file in SharePoint Designer. Now here we will use the initComplete function and this.api().columns(column index)of the JQuery DataTable to get the column values for the organization and roles to bind it to our dropdown.

Friday, 4 September 2015

Load the Data in JQuery DataTable from SharePoint List using REST API



In this article I will show how you can retrieve the data from the SharePoint List using the REST Api and bind it to the JQuery DataTable.

JQuery DataTable is an excellent plugin tool built on JQuery JavaScript library to build an HTML table with lot of advanced interaction controls like pagination, sorting, searching, etc. 

You can download the js file for the data table from here

Articles on the Jquery DataTable and SharePoint REST API 

For the purpose of the demo, I have created a customer list with the below columns and loaded it with some dummy data.

Customer SharePoint List

First of all we will create 2 files viz CustomerJqueryDatatable.js and CustomerJqueryDatatable.txt files and place it under the Site Assets Library. Also make sure you add the jquery js file in your SiteAssets/js folder.

Add the content editor web part on your page and give the path of the CustomerJqueryDatatable.txt file from the Site Assets Library and Save/Publish the Page.

Open the CustomerJqueryDatatable.txt file in SharePoint Designer and add the reference to the “jquery-1.11.0.min.js”, “jquery.dataTables.min.js” ,”jquery.dataTables.min.cs” and “CustomerJqueryDatatable.js” file in the CustomerJqueryDatatable.txt file.

 <script type="text/javascript" src="../SiteAssets/js/jquery-1.11.0.min.js"></script>  
 <script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>  
 <link href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="Stylesheet" type="text/css" />  
 <script type="text/javascript" src="../SiteAssets/CustomerJqueryDatatable.js"></script>  

Wednesday, 2 September 2015

Query User Profile Service for Multiple Users in SharePoint Using SPServices


Lot of people are using the SPServices these days. SPServices is a jQuery library which encapsulates SharePoint Web Services with jQuery to make it easy to call them.

In this post, I will show how to query the user profile service from the SharePoint (2010/2013/Office 365) using the SPServices. As it will retrieve the properties of multiple users and there is no batch query possible in SharePoint to retrieve the properties of all users in one shot, we will leverage the async and cache property of the SPServices to query properties of multiple users.

Before we begin let’s make sure that SPServices is loaded correctly and SPServices JS files are loaded.

Download the jquery.SPServices-0.6.2.min.js file from here and reference in the code as below. I will suggest to upload it in the Site Assets Library.

 <script type="text/javascript" language="javascript" src="../SiteAssets/jquery-1.6.1.min.js"></script>  
 <script type="text/javascript" language="javascript" src="../SiteAssets/jquery.SPServices-0.6.2.min.js"></script>  
 <script type="text/javascript" language="javascript">  
  $(document).ready(function() {  
   alert("jQuery Loaded");  
   alert($().SPServices.SPGetCurrentSite());  
  });  
 </script>  

If we get both the alerts that means our Jquery and SPservices javascript files are loaded and we can move further.
Now to begin with for the demo purpose we will retrieve the users stored in the SharePoint group and we will display the user profile properties from that user list.
We will store the usernames of all the users in the ‘usersList’ array and push their login name in it.
 var userDivPnl;  
 var usersList = [];  
 $().SPServices({  
   operation: "GetUserCollectionFromGroup",  
   groupName: 'Members Group',  
   async: false,  
   completefunc: function(xml, Status) {  
     $(xml.responseXML).SPFilterNode("User").each(function() {  
       var name = $(this).attr("Name").toUpperCase();  
       var accountname = $(this).attr("LoginName");  
       usersList.push(accountname);  
       //Replacing the special characters from the loginname  
       var login = accountname.split("|")[2].replace("@", "_").replaceAll(".", "");  
       //Generate the HTML Div structure to add users properties in each div  
       userDivPnl += '<div>' +  
         '<div > ' +  
         '<div class="profile_photo" style="width: 100px;"> ' +  
         '     <img height="96" width="96" id="profile_' + login + '" src="' + noProfileImg + '" style="border-radius: 100%;"/> ' +  
         '</div> ' +  
         '&nbsp;&nbsp; ' +  
         '<div > ' +  
         '<p id="dispname_' + login + '"></p> ' +  
         '<p id="jobtitle_' + login + '"></p> ' +  
         '<p id="country_' + login + '"></p> ' +  
         '<p id="contact_' + login + '"><a href="#"></a></p> ' +  
         '<p><a id="email_' + login + '"></a></p> ' +  
         '</div> ' +  
         '</div> ' +  
         '</div> ';  
     });  
     userDivPnl += '</div>';  
     $("#container").append(userDivPnl);  
   }  
 });  

Thursday, 28 November 2013

Target Audiences in SharePoint


Audiences are created as part of the User Profiles service in SharePoint, and a user’s inclusion in an audience is defined by a set of rules that can combine membership in groups or user profile property comparisons.
Audience targeting is use to personalize content display including list or library items, navigation links, or Web Parts. Audience targeting is commonly used to filter news items on Portals. As an example, the Content By Query Web Part (CQWP) supports audience targeting when doing content aggregation.

***Since the Target Audiences field is not defined as a Site Column, the column cannot be added to a Content Type through the SharePoint User Interface

It allows your page to configure itself depending on who is viewing it. For instance you could use Target Audiences to:
§  Show an English language test to one set of people and a Spanish language one to another
§  Show an assessment only to approved people
§  Show a different survey to people depending on their context
§  Show an observational assessment only to instructors or monitors, and not show it to ordinary participants
§  Give different assessments to people in different departments

What to choose for Target Audience?


It’s easiest to choose audiences as SharePoint groups, distribution lists or security groups used in authentication

You can also define rules-based groups of people called global audiences, which gives potential of more sophisticated filtering. 


Tuesday, 24 September 2013

Site Definition Versus Site Templates


Site Definition:

Site definitions consist primarily of multiple XML and ASPX files stored on a front-end web server in folders under the %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\SiteTemplates directory.
-          Old & Out of Date
-          Involves managing of lot of tedious onet.xml and schema.xml files.
-          A site definition is installed on file system of web front ends
-          A site definition Page and List definition are cached at IIS process startup
 

Custom Site Templates:

 Custom web templates are stored in the database—specifically, the sandbox solutions gallery—and are created by using an existing site, with or without its specific content, as a model. This provides a means for reusing sites that you have customized.

 ***The first option for getting the SharePoint Designer changes beyond the current site is to take the site you have modified with SharePoint designer and save it as a template. You can download the template and upload this to another site collection and can create a site based on this template. Whenever you need a new site you can create it from the site template you have created. This is a good approach if the design is finalized and you want to reuse the same template in different site collections. But keep in mind you can't go back and apply the changes after the site is created. If you make any changes to the work that you did on the original site then those changes won't be reflected across the other SharePoint sites that were created from the same template. This is because each page exists separately in the SharePoint database.
 

 Major differences:

  • To create or use a site definition you need server admin access, but site template can install from web UI by site owners.
  • Site definition supports feature stapling, but for site template additional features must be activated in gallery.
  • Site definitions are stored on hard disk, but site templates are stored in content DB.
  • Site definition can provision multiple webs, but site templates are for single web only.
  • Creating site definition is relatively more complex than site template creation.
  • Performance wise Site definitions are better than site templates as files are stored on harddisk

Happy Sharepointing !

Please do Share/Like/Comment if this article was helpful.

Monday, 2 September 2013

Controlling growth using quotas

Can we control the amount of content that can be stored within a Site Collection so that it doesn’t grow beyond acceptable boundaries?
Yes, Using Quotas

What is it?
A quota specifies storage limit values for the maximum amount of data that can be stored in a site collection. Quotas also specify the storage size that, when reached, triggers an e-mail alert to the site collection administrator. Quota templates apply these settings to any site collection in a SharePoint farm.

Resource Points
Resource points correspond to specific levels of resource usage that you can define for up to 15 system resources that you want to monitor. Each of these resource measures accumulates points based on a single sandboxed solution's use of that resource, and those points are aggregated toward a quota that has been set for the whole site collection
When sandboxed code executes, certain metrics are collected such as % processor time and # of unhandled exceptions.  Timer jobs compile the metrics and calculate resource points usage.  When the total resource points used exceeds the daily limit (300 points by default), the sandbox is turned off for the entire site collection.  The following table describes the metrics collected and how they are normalized to resource points: 
Resource
Description
Units
Resources per Point
Limit
AbnormalProcessTerminationCount
Abnormally terminated process
count
1
1
CPUExecutionTime
CPU Execution Time for site
seconds
3,600
60
CriticalExceptionCount
Critical Exception Events
Events
10
3
InvocationCount
Solution Invocation Events
Events
<TBD>
<TBD>
PercentProcessorTime
% CPU usage by solution
%
85
100
ProcessCPUCycles
Solution CPU cycles
cycles
1 x10^11
1 x10^11
ProcessHandleCount
Windows handles count
items
10,000
1,000
ProcessIOBytes
Windows handles count
items
0
1 x10^8
ProcessThreadCount
Thread count in overall process
Thread instances
10,000
200
ProcessVirtualBytes
Memory consumed
Bytes
0
1.0x10^9
SharePointDatabaseQueryCount
Number of SharePoint database queries
Query instances
20
100
SharePointDatabaseQueryTime
Elapsed time to execute query
seconds
120
60
UnhandledExceptionCount
Number of unhandled exceptions
Unhandled exception instances
50
3
UnresponsiveProcessCount
Number of unresponsive processes
Unresponsive process instances
2
1

For example, if you developed a sandboxed web part that displayed data from a list, it would perform a SharePoint database query each time it loads.  20 database queries = 1 resource point, so if the web part was displayed 20 times, the site collection would have used 1 resource point.  The default site collection maximum is 300 points, so the web part could be displayed 6,000 times in a 24 hour period; after that, the sandbox is turned off until a timer job resets it.  It's important to understand is that resource quotas can be exceeded through high usage and is not necessarily an indicator of poorly written code.

About planning quota management

The basic steps to plan quota management are the following:
  1. Determine quota template settings
    There is no default quota template for site collections in a SharePoint Server 2010 environment
  1. Determine recycle bin settings
    The recycle bin can help to prevent the permanent deletion of content. The recycle bin enables site owners to retrieve items that users have deleted, without requiring administrator intervention such as restoring files from backup tapes. Key planning considerations include whether to use the second-stage recycle bin and how much space to allocate.
    The recycle bin is turned on and off at the Web application level. By default, the recycle bin is turned on in all the site collections in a Web application.
  2. Delete unused Web sites
    You can delete a quota template if you change your quota structures. However deleting a quota template does not delete quota values from site collections to which a quota template has been applied. If you want to remove quotas from all site collections that use a specific quota template, you must use the object model or perform a SQL Server query.

Key Notes about Quota Management

  1. Quotas are only applied to Site Collections
  2. You can create a default quota template at the web application level, which will be used by new site collections created moving forward.
  3. Everything in a site encompasses the Quota space: files in document libraries, items in your lists, all web parts, all images, form templates, etc…

Create Quota using Powershell

Get-SPWebTemplate | Out-File C:\SharepointWebTemplates.txt

Retreive the Current Quota settings for the site collection
(Get-SPSite -Identity "<Site Collection>").Quota
Where:
  • <SiteCollection> is the URL of the site collection
Create New Quota Template
       $quota = New-Object Microsoft.SharePoint.Administration.SPQuotaTemplate
        $quota.Name = “Dhaval”
        $quota.StorageMaximumLevel = ((10 * 1024) * 1024)
        $quota.StorageWarningLevel = ((8 * 1024) * 1024)
        $quota.UserCodeMaximumLevel = 100
        $quota.UserCodeWarningLevel = 80

        $service = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
        $service.QuotaTemplates.Add($quota)

        $service.Update()

Delete Quota Template
$service =[Microsoft.SharePoint.Administration.SPWebService]::ContentService
                                $service.QuotaTemplates.Delete($QuotaTemplateName)
        $service.Update()

Configure Quota and Locks


Option 
Option Description
Unlock Not locked
NoAdditions
Unlocks the site collection and makes it available to users.
ReadOnly Adding content prevented
NoAccess
Prevents users from adding new content to the site collection. Updates and deletions are still allowed.


To lock or unlock a site collection by using Windows PowerShell
Set-SPSite -Identity "<SiteCollection>" -LockState "<State>" –QuotaTemplate “<Quota Template>”

Where:
  • <SiteCollection> is the URL of the site collection that you want to lock or unlock.
  • <Quota Template> is the name of the quota template
  • <State> is one of the following values:
    • Unlock to unlock the site collection and make it available to users.
    • NoAdditions to prevent users from adding new content to the site collection. Updates and deletions are still allowed.
    • ReadOnly to prevent users from adding, updating, or deleting content.
    • NoAccess to prevent users from accessing the site collection and its content. Users who attempt to access the site receive an error.

References: