Wednesday, 26 April 2017

Query List/Document Library in Specific Folder

To query SharePoint List or Document Library in specific Folder “FolderServerRelativeUrl” as part of the CAML Query

Code Snippet

using (ClientContext clientContext = new ClientContext(siteURL))
List customList = clientContext.Web.Lists.GetByTitle("CustomListName");
CamlQuery camlQueryCustomList = new CamlQuery();
camlQueryCustomList.ViewXml = "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='CustomField'/>" +
"<Value Type='Boolean'>1</Value></Eq></Where></Query></View>";
camlQueryCustom.FolderServerRelativeUrl = "/Lists/CustomListName/FolderName";
ListItemCollection items = customList.GetItems(camlQueryCustomList);

Friday, 21 April 2017

How to Expose Sharepoint Rating Feature as Service

Problem Statement:

Recently, I came across a situation where SharePoint List was used as the repository and application was built in other technologies. We wanted to expose SharePoint Rating feature as service and we encountered that rating was done in the context of the service account/App pool account contrary to it should be in current user’s context.


We exposed the Web API service as Provider hosted App and consumed Token Helper’s  GetS2SClientContextWithWindowsIdentity  method to create client context.

Code Snippet:

        public string SetRating([FromBody]RatingDetails folderDetails)
               //Site Collection/Web URL
                Uri hostWeb = new Uri(“”);

                //Item Id for which user want’s to rate     
                int itemID = Convert.ToInt32(folderDetails.ItemId);
                int rating = Convert.ToInt32(folderDetails.Rating);

  using (var clientContext =   TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb,   HttpContext.Current.Request.LogonUserIdentity))
                    clientContext.Load(clientContext.Web, web => web.Title);
                    Web w = clientContext.Web;
                    clientContext.Load(w, cw => cw.CurrentUser);
                    List curentList = w.Lists.GetByTitle("MyListName");
                    clientContext.Load(curentList, cl => cl.Id);
                    string ListID = curentList.Id.ToString();
                    Reputation.SetRating(clientContext, ListID, itemID, rating);

                    ListItem ratedItem = curentList.GetItemById(itemID);
                    clientContext.Load(ratedItem, item => item.Id, item =>                                       item["AverageRating"], item => item["RatingCount"], item =>                                   item["Ratings"]);
                    return Convert.ToString(ratedItem["AverageRating"]);

            catch (Exception ex)
                return ex.Message;

Web Config Changes:

key="ClientId" value="689c2335-715b-4c50-969b-2d19f520adf7"
key="ClientSigningCertificatePath" value="D:\Cert\HighTrustCertOS.pfx"
key="ClientSigningCertificatePassword" value="Password123"

key="IssuerId" value="b7e4be28-8baa-4c18-83c9-73130305cb7a"

Note: You have to give permission on the SharePoint Site Collection for this App


Tuesday, 18 April 2017

Retrieve All the Files From Specific Folder Along with properties like ID, File Size,Editor etc

Below Code will fetch all the files under MyFolder in Documents library along with extended metadata like document id, modified by, document size and document url etc. ListItemAllFields will do the trick to get all the extended properties of the document.

var folderUrl  = "sites/sc1/Documents/MyFolder"
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/GetFolderByServerRelativeUrl('" + folderUrl + "')/Files?$expand=ModifiedBy,ListItemAllFields",
    type: "Get",
    cache: false,
    async: true,
    crossDomain: true,
    beforeSend: function(xhr, settings) {
        // To do any operation before sending the request              
    xhrFields: {
        withCredentials: true
    dataType: "json",
    contentType: "application/json",

    success: function(data) {
        $.each(data.value, function(index, item) {
            var obj = {};
            obj["ID"] = item.ListItemAllFields.ID;
            obj["Name"] = itemN.ame;
            obj["LastUpdatedBy"] = item.ModifiedBy.Title;
            obj["LastUpdatedOn"] = item.TimeLastModified;
            var fileSize = item.Length / 1024;
            obj["Size"] = fileSize.toFixed() + "KB";
    error: function(err) {
       console.log("Error Occurred. : " + err);

Tuesday, 4 April 2017

Getting the current item's icon path in Search Display Template Code

To show the file icon for the results in search display template, below code can be used.

// Get the current path of the file
var currentItem = ctx.CurrentItem.Path;
// Get the file extension from path 
Var ext = currentItem.split(",")[0].split(".").pop().split('?')[0];
// Add this extension in an object
Var  extObject = new Object();
extObject["FileExtension"] = ext;
// Get the icon url using below getIconUrlByFileExtension method
var iconUrl = SP.Utilities.HttpUtility.htmlEncode(Srch.U.ensureAllowedProtocol(Srch.U.getIconUrlByFileExtension(extObject, null)));

Monday, 3 April 2017

SharePoint Online/ SharePoint 2013 - Calling Sync Function Through Javascript

Sharepoint enables users to take the document library offline and sync the documents on personal devices leveraging OneDrive for Business feature

  1. Sync option is available in Sharepoint Online as well Sharepoint 2013 on premise (Provided we have Onedrive installed on our local machine
  2. In case we have customized our masterpage and we are not using  OOB document library views we can’t use sync feature
  3. In this scenario we need to hook some client script to call the sync functionality on custom event.
  4. To call the sync functionality on click of control/using javascript below method can be used 

EnsureScriptFunc('offline.js', 'TakeOfflineToClientReal', function() { TakeOfflineToClientReal(2, 1, '', 1, 101,'989F78C3-FB40-46DE-ABF5-60380B44D201', '');});

989F78C3-FB40-46DE-ABF5-60380B44D201 – Is the GUID of the document library

Tuesday, 5 March 2013

Using Modules to Include Files in the Solution

I have seen lots of people struggle with Modules. Sometimes modules are getting deployed successfully but files are not reflecting in Document library.

First of all the Element.xml file should have below structure.

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="">

  <Module Name="MyCustomModule" Url="SitePages" Path="MyCustomModule">
    <File Url="Sample.aspx" Type="GhostableInLibrary"/>

In above XML few things need to be taken care.

Url ( In Module element): Url in module element indicates the URL of the library where files need be created.

Url (In File element) : The location where the file will be deployed on the SharePoint server

Type: It indicates that whether file is available in Document library as a Item. If this attribute is missing, file would be available under list/libraries but it won’t show up in any of the Views.

Tuesday, 26 February 2013

Populating current logged in user in people picker

Sometimes there are requirement to populate the current logged in user in People picker field.
I had tried to populate using PickerEntity class, but it use to fail on click of "Check Names" button. So changed the approch to se the comma seprated names and it worked.

1. Take the curent Logged user

loginName = SPContext.Current.Web.CurrentUser.LoginName

2. Assign the login to picker control. 
pkrControlName.CommaSeparatedAccounts =loginName

Note: You can have multiple comma serpated login names to populate multiple users in people picker field.

Query List/Document Library in Specific Folder

To query SharePoint List or Document Library in specific Folder “ FolderServerRelativeUrl ” as part of the CAML Query Code Snippet ...