When To Use Content Query Web Part (CQWP) and Content Search Web Part (CSWP)

Share Point 2013 has several out-of-the-box web parts and the most widely of these are Content Query Web Part (CQWP) and the Content Search Web Part (CSWP). These two web parts are used for querying and search crawl indexed data from a share point site.

ContentByQuryWebpat referred as Content Query Web Part (CQWP) is used to display content using query/filter from another site or sub site within the same site collection. With the CQWP, content display as per the requirement, branding and context can be controlled. CQWP results are pulled using query or search directly from the site.

Content Search Web Part (CSWP) is available with SharePoint On-Premise and in Office 365 tenants. CSWP uses search indexing to return faster results using less resources. CQWP and CSWP web parts require publishing feature to be activated.

Let us explore the best situations/scenarios for using each web part.

Content Search Web Part (CSWP)

  • When we need to display all items of a type with n a site collection or from a different site collection.
  • When we need to deal with a complicated query for instance a certain content type in a certain date range.
  • When we need to customize the display of the items.

Content Query Web Part (CQWP)

We can use Content Query Web Part (CQWP) when we want to display a finite list of properties like title, description and image.

Please see the below image for more details on the same.

Pros and Cons

Web Part Behavior Content Query Web Part (CQWP) Content Search Web Part (CSWP)
Query configuration Easy You will need to know about certain search features such as managed properties.
Query across large amounts of content Limited yes
Handle complex queries Limited yes
Scale to handle future content growth Limited yes
Display content from other site collections No yes
Design of query results can be customized Yes, by using XSLT. Yes, by using HTML.
Maintenance cost in a complex site architecture High Small
Narrow down the query results that are displayed in the Web Part No Yes, in combination with other search web parts.

SharePoint 2013 User Profile Synchronization with Active Directory

SharePoint active directory import allows you to import the active directory user information to SharePoint user profile service.

User profile service application stores the information about the user like first Name, last name, Phone Number, location etc. in central location. SharePoint will create three databases for storing the profile information and associated data.

  1. Profile Database – This particular DB stores the user profile information.
  2. Social tagging Database – This database stores social tags and notes created by users.
  3. Synchronization Database – This database stores configuration and staging information. This helps for synchronizing data from external sources such as the Active Directory Domain Services (ADDS).

Prerequisites to perform the import for Sharepoint synchronization:

  • To perform the synchronization, you must be a member of farm administrator group.
  • You must know the credentials of domain controller that has synchronization permission.

Before you begin with the synchronization note what AD import does not support.

  • Import operation is one way, changes made to the SharePoint user profiles wont reflect in AD.
  • The active directory import option lets you configure and use only a single farm wide property mapping.
  • Active directory import option does not support generic (non-AD) LDAP sources.
  • Active directory import option does not support BCS Import.

Importing the User profile information to active directory involves following four steps.

  • Enable Active directory import.
  • Configure synchronization connection.
  • Map active directory attributes with user profile properties in SharePoint.
  • After completion of above three start synchronization in SharePoint.

Enable Active directory import:

  • Open SharePoint Central Administration click on Manage service application under the Application Management section.
  • In Manage Service Applications page, click on User Profile Service Application.
  • In Manage Profile Service page click Configure Synchronization Settings in the Synchronization section.
  • On the Configure Synchronization Settings page select Use SharePoint Active Directory Import option, and click OK.

Configure synchronization connection:

  • On the Manage Profile Service page, click Configure Synchronization Connections.
  • Now click on Create New Connection button.
  • In new synchronization connection page, enter the connection name in the Connection Name text box.
  • From the Type list, select Active Directory Import.
  • In the Fully Qualified Domain Name box, enter the Fully Qualified Domain Name.
  • Select the authentication provider type in Authentication Provider Type box.
  • Select an Authentication provider from the Authentication Provider Instance box when you select Trusted Claims Provider Authentication or Forms Authentication. The Authentication Provider Instance box lists only the authentication providers that are currently used by a Web application.
  • In the Account name box, enter the synchronization account with domain and username. The synchronization account must have Replicate Directory permissions or higher in the root OU of Active Directory.
  • In the Password box, enter the password for the synchronization account.
  • Enter the password for the synchronization account again in the Confirm password box.
  • In the Port box, enter the connection port. (optional)
  • Select Use SSL-secured connection If a Secure Sockets Layer (SSL) connection is required to connect to the directory service. (optional)
  • You can also filter objects that are imported from the directory service, in the Filter in LDAP syntax for Active Directory Import box, enter a standard LDAP query expression to define the filter. (optional)
  • In the Containers section, click Populate Containers and then select the containers from the directory service which you want to synchronize. All OUs selected will be synchronized along with their child OUs.
  • Click OK and a newly created connection will be listed on the Synchronization Connections page.

Map AD attributes with user profile properties.

  • Click Manage service applications in the Application management section in the Central Administration.
  • Click User Profile Service Application in service application page.
  • Click Manage User Properties in the People section.
  • Right-click the name of the property that you want to map a directory service attribute, and then click Edit.
  • You can also remove an existing mapping by selecting the mapping that you want to remove, and then click Remove in the Property Mapping for Synchronization section.
  • To add a new mapping: In the Add New Mapping section, in the Source Data Connection list, select the data connection that represents the directory service to which you want to map the user profile property to.
  • In the Attribute box, enter the name of the directory service attribute to which you want to map the property.
  • Click Add.
  • Click OK.
  • Repeat steps 4 through 7 to map additional properties.

Start synchronization:

  • Click Manage service applications in the Application management section in the Central Administration.
  • Click on Start Profile Synchronization in the Synchronization section.
  • Select Start Full Synchronization in Start Profile Synchronization, if this is the first time you are synchronizing or if you have already added or modified any synchronization connections in the past.
  • Select Start Incremental Synchronization to synchronize only information that has changed in the last time synchronization.
  • Click OK. The Manage Profile page will display the status of profile synchronization in the right panel.

Need help with Sharepoint. Reach out to our experts to help you with a full range of well-structured services for planning, developing, and deploying SharePoint based solutions. 

Provision SharePoint in One Click


Provisioning SharePoint makes it easier for developers and the organization too, as it reduces time consuming manual effort and resource utilization. More importantly, it is a single-click, reusable component, suitable for anyone!

Here, we will see how to develop a reusable component – methods and functionalists.

SharePoint Web Application Creation

We will create a web application using server-side code. We can achieve the same using client-server object model and power-shell script too.

We will see important methods and the logic involved in creating a feature:

SPWebApplicationBuilder _webAppBuilder = new SPWebApplicationBuilder(SPFarm.Local);
 SPWebApplication _webApplication;
 _webAppBuilder.Port = 2255;
 Uri url = new Uri("http://spTestSite:2255/");
 string host = url.Host;
 int port = 2255;
 _webAppBuilder.HostHeader = host;
 _webAppBuilder.ApplicationPoolId = "Sharepoint - " + port.ToString();
 _webAppBuilder.IdentityType = IdentityType.SpecificUser;

SPFarmManagedAccountCollection manaccountcollection = new SPFarmManagedAccountCollection(SPFarm.Local);
SPManagedAccount maccount = manaccountcollection.FindOrCreateAccount(“DomainUserName”);

//use the SPManagedAccount to receive the username and password automatically
_webAppBuilder.ManagedAccount = maccount;
_webAppBuilder.RootDirectory = new System.IO.DirectoryInfo(“C:\Inetpub\wwwroot\wss\VirtualDirectories\” + host + port.ToString());
_webAppBuilder.CreateNewDatabase = true;

// Create new database name
_webAppBuilder.DatabaseName = “WSS_Content_” + host + port.ToString();

//Mention the database server name
_webAppBuilder.DatabaseServer = “SQL01”;
_webAppBuilder.UseNTLMExclusively = true;

// Create new web application
_webApplication = _webAppBuilder.Create();

// Pass the parameter as per your requirement
SPSite mySiteCollection = _webApplication.Sites.Add(“/”, “Test Site”, “Site Description”, 1033, “STS#0”, “PrimaryDomainme”, “PrimaryAdminUserName”, “PrimaryTest@mail.com”);

In this method, we are creating a SharePoint web application using server-side code SPWebApplicationBuilder Member. This initializes a new instance of the class using the default Web application settings and exposes further properties like ManagedAccount, RootDirectory, CreateNewDatabase, DatabaseName, DatabaseServer, UseNTLMExclusively, et.,

The next level code is SPWebApplication Class – It represents Internet Information Services (IIS) load-balanced Web application that is installed on a server farm and exposes the methods as Delete(), Update(), etc.,

SharePoint Top-level Site Collection Creation

In the following method we will see how to create site collection through code using SharePoint objects SPSite, SPWeb and SPSiteCollection as below.

//Code to create site collection programmatically
 string _url = "http://spTestSite:2255/";
 SPSite site = new SPSite(_url);
 SPWeb web = null;
 try {
 SPWebApplication webapp = site.WebApplication;
 web = site.OpenWeb();
 SPSiteCollection spSites = webapp.Sites;
 webapp.Sites.Add("sites/team1", "Title of the Site", "Description", 1033, "STS#0", "PrimaryDomainName", "PrimaryAdminUserName", "PrimaryTest@mail.com");

At this point we have created the web application and the top-level site collection as needed. Where, “sites/team1” is the top level site, “Title of the Site” is to mention the name/title of the top-level site, “Description” is to mention the description, “1033” is the English language code, “STS#0” is the sharepoint site template code, “PrimaryDomainName” is the required primary domain name, “PrimaryAdminUserName” is the first primary admin user and “PrimaryTest@mail.com” is the primary admin user email id.

Further, “Sites.Add()” method will create/add the site collection into the web application with the required parameter as we described in the code.

SharePoint Required Default Features Activation for the Team Site

Next, we need to move on- to activate the SharePoint required features ‘Activate SharePoint Server Publishing Infrastructure’ and ‘Activate the publishing feature’. These features will not get activated by default when the site been created as a “Team Site (STS#0)”. So, let’s activate the same features using code as below.

//Code to activate Sharepoint Features programmatically
 string _url = "http://spTestSite:2255/";
 SPSite site = new SPSite(_url);
 if (site != null) {
 // Activate SharePoint Server Publishing Infrastructure
 site.Features.Add(new Guid("f6924d36-2fa8-4f0b-b16d-06b7250180fa"), true);
 foreach(SPWeb web in site.AllWebs) {
 // Activate the publishing feature for all created webs.
 web.Features.Add(new Guid("94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb"), true);

Where, SPSite object used to get the current site, the Guid (“f6924d36-2fa8-4f0b-b16d-06b7250180fa”) is the “SharePoint Server Publishing Infrastructure” feature which activates the feature at site level.

Next, the Guid (“94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb”) is the “SharePoint Server Publishing” feature which activates the feature at web level.

SharePoint Group Creation and Role Assign

Now, we create the group using the object SPGroup. First, we check whether the group is created or not using the object SPGroupCollection. Once the group has been created, assign the role using the object ‘SPRoleDefinition’ and ‘SPRoleAssignment ’.

SPGroup groupMngr = null;
 //check group already exists or not
 if (!ContainsGroup(web.SiteGroups, web.Title + "_" + CustomTestGroup)) {
 web.SiteGroups.Add(web.Title + "_" + CustomTestGroup, web.Author, web.Author, "CustomTestGroup");
 groupMngr = web.SiteGroups[web.Title + "_" + CustomTestGroup];
 groupMngr.OnlyAllowMembersViewMembership = false;

// assign edit permissions to ‘CustomTestGroup’
SPRoleDefinition roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Editor);
SPRoleAssignment roleAssignment = new SPRoleAssignment(groupMngr);

private bool ContainsGroup(SPGroupCollection groupCollection, string index) {
try {
SPGroup testGroup = groupCollection[index];
return true;
} catch (SPException e) {
return false;

SharePoint List/Libraries Creation

We then create the document library using the object ‘SPList’, ‘SPDocumentLibrary’. Checking if the library does not exist, create the new list or library as per the requirement. Once the library is created, create the necessary fields with the type accordingly using the object ‘SPFieldType’. Enable the library versioning. Next, break the Inheritance permission of the library and assign custom group permission. Then, create the custom view using the object ‘SPView’ and mention which column should appear in the view state. Finally, update the library at the last to complete the process.

string CustomerLibraryName = “customLibrary”;
 SPList list = web.Lists.TryGetList(CustomerLibraryName);
 if (list == null) {
 Guid customerGUID = web.Lists.Add(CustomerLibraryName, "Custom Document Library", SPListTemplateType.DocumentLibrary);
 SPDocumentLibrary CustomerDocLibrary = web.Lists[customerGUID] as SPDocumentLibrary;

CustomerDocLibrary.Fields.Add(“columnDocName”, SPFieldType.Text, true);
CustomerDocLibrary.Fields.Add(“columnDocCreator”, SPFieldType.Text, true);
CustomerDocLibrary.Fields.Add(“columnDocContributors”, SPFieldType.Text, true);
CustomerDocLibrary.Fields.Add(“columnDocSubject “, SPFieldType.Text, true);
CustomerDocLibrary.Fields.Add(“columnDocDate”, SPFieldType.DateTime, true);

//enable versioning
CustomerDocLibrary.EnableVersioning = true;

//check Inheritance broken or not
if (!CustomerDocLibrary.HasUniqueRoleAssignments) {

CustomerDocLibrary.RoleAssignments.Add(roleAssignment); CustomerDocLibrary.Update();

SPView CustomerView = CustomerDocLibrary.DefaultView; CustomerView.ViewFields.DeleteAll(); CustomerView.ViewFields.Add(“columnDocTitle”); CustomerView.ViewFields.Add(“columnDocLinkFileName”); CustomerView.ViewFields.Add(“columnDocDate”); CustomerView.Update(); CustomerDocLibrary.Update(); web.Lists[customerGUID].Update();

Finally, place all implemented code in the SharePoint event receiver file and once the file gets deployed successfully into the SharePoint site, activate the event receiver then the required lists/library, fields and group creation with assigned role. This will create the same in SharePoint, avoids manual creation and helps to save time!

Apps in SharePoint

What are Apps?

Over the last few years, desktops became laptops.  Laptops gave way to Notebooks. Notebooks became Ultra Books and the trend is moving towards Tablets and Smartphones.

As a result of this, web applications are paving the way for Apps.

Reasons for “Apps” development

  • No custom code execution on server side. It avoids application / server outages.
  • Custom code will be executed in Client-Browser, or IIS or Windows Azure, which are completely out of SharePoint’s scope.
  • The Server Object Model (SOM) code is replaced by Rest Services Client Side Object Model (CSOM) using which apps can communicate with a server. Authentication is done by OAuth.
  • Installation/updation /uninstallation of apps can be done without affecting the SharePoint site.
  • Better usability in mobile and tablets devices.
  • Takes SharePoint to the next level in terms of usability, deployment, development and hosting (Cloud).
  • Finally, everything in SharePoint 2013 is an App.

Types of Apps for SharePoint


  • Complete client-side code
  • Deployed to SharePoint On-premises, SharePoint online or in Office 365


  • Deployed to a different on-premises server (not SharePoint) or the cloud


  • Automatically provisions resources to SQL Azure and Windows Azure

Diagram of a possible Hybrid approach with some components in SharePoint and others residing in the Cloud:

SharePoint-hosted Apps:

  • App components hosted in isolated app domain
  • No server-side code – can use HTML, JavaScript and CSS

Provider-hosted Apps:

  • App components can be hosted anywhere ( on-premises or Cloud )
  • Authorized using JavaScript cross-domain library or OAuth
  • IncludesWindows Azure Web Sites
  • Can use ANY implementation language (ASP.NET, PHP, etc.)

Auto-hosted Apps:

  • App components are hosted in SQL Azure and Windows Azure
  • Automatically provisioned when app is installed
  • Authorized using the JavaScript cross-domain library or OAuth
  • Only available in SharePoint Online
  • Infrastructure is in preview status
  • Production use not recommended
  • Office Store not yet accepted

Host Web and App/Remote Web:

  • Each app is deployed to a SharePoint site known as the host web
  • Each app installation has its own unique URL
  • App web provisioned with app installation
    • https://[app prefix][app hash].[app domain]/[relative site URL]/[app name]
    • Required for Share Point hosted apps, optional for cloud-hosted apps
  • Cloud-hosted apps have a remote web
    • In Office 365, the remote web for Auto hosted apps is under 365apps.net
    • Name reminds us that this web doesn’t live on the SharePoint server

App Development Tools:

  • Office development tools for Visual Studio 2012/2013
  • “Napa” Office 365 development tools
  • Browser-based development environment (SharePoint-hosted apps only)

Office Development Tools for Visual Studio:

  • NET web application projects include classes to handle app AuthZ and AuthN (using OAuth)
  • SharePointContext.cs
    • Functions to manage SharePoint context across page requests
    • Can create app contexts and/or user for app and/or host webs
  • TokenHelper.cs
    • Functions to create and obtain AccessToken and ContextToken objects
  • On other platforms, you have to do the OAuth implementation and manage tokens yourself
  • Convert existing web application project to an App for SharePoint project

Accessing SharePoint data remotely:

  • JavaScript client object model (JSOM)
  • .NET Managed client object model (CSOM)
  • REST endpoints with OData

App authentication/authorization:

  • We can’t interact with data stored in SharePoint unless we (our apps) are authenticated to SharePoint and authorized to access data
    • Authentication: Are you who you say you are?
    • Authorization: Do you have permission to do what you are trying to do?
  • How can cloud-hosted apps for Share Point securely access data from the remote web?
    • Firewalls could be between servers
    • Code and script could be running on different domains
    • The external web server might not even be running Windows!

App authorization policy types:

  • User-only
    • Only the user identity is considered (non-app interactions with Share Point)
  • App + User
    • “Access denied” if one and/or the other lacks permissions
    • Both the app identity and the user identity are considered
  • App-only
    • Only the app identity is considered
    • Only supported for server-side code in cloud-hosted apps
    • Can’t be used with certain APIs (e.g., Search, Project Server)
    • Allows for elevation above current user’s permissions (or when there is no current user)

App permissions:

  • Trust must be explicitly granted by the user installing the app (nothing or all)
  • User installing the app must also have all permissions the app is requesting

Deploying provider-hosted apps:

  • To use OAuth, you must register an app principal
    • Automatically handled for Auto-hosted apps and <F5> local host deployments
    • Requires a visit to /_layouts/15/AppRegNew.aspx for provider-hosted apps
  • Update <appSettings> values in web.config file
    <add key=”ClientId” value=”xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx” />
    <add key=”ClientSecret” value=”xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=” />
  • Deploy/publish your remote web project
  • Set full URL for Start page in AppManifest.xml
  • Right-click and “Publish…” the app project
  • Click Package the app to generate .app file
  • Deploy the .app file to your app catalog
  • Click the link to launch the app
  • Grant permissions the app requests

Customizing ‘Content Query Webpart ItemStyle’ using XSLT in SharePoint 2013

Share Point 2013 has many out-of-the-box web parts and one  of them, i.e. a widely used  web part is Content Query Web Part (CQWP). ContentByQuryWebpat referred to as Content Query Web Part (CQWP) is used to display content using query/filter from another site or sub-site within the same site collection. With the CQWP, content display as per the requirement, branding and context can be controlled. CQWP style sheets reside in a folder “XSL Style Sheets” in the Style Library. ItemStyle.xsl file named under “XSL Style Sheets” folder contains the style templates which can applied on-the-fly to the items returned by CQWP.

Create custom style by making a copy of ItemStyle.xsl file and make changes as required to it. Upload the customized xsl file to the style library and publish it.

Note :  The Content Query Web Part is only supported in publishing sites. So, you must have the publishing features enabled to make use of it.


  • Aggregate data only within a single site collection.
  • Aggregate only list information.

Imagine that we have a requirement to display list data across sub-sites in a site collection. For instance we need to make use of a list to retrieve respective employee biographies across sub-sites in a site collection. Let me explain the scenario:

For instance the below hierarchy of share point site collections:

The requirement is to display upcoming events from a calendar in all sub-sites under communities’ site collection. We have a column named community which is used to filter and type will be choice in the same calendar list which is created as “Upcoming events” at communities site collection level. Please see the below picture for reference:

I  used out-of-the-box content query web part to retrieve events from the calendar list and community column to filter the context events. I also thought of customizing itemstyle.xsl which resides in the Style Library of the site collection. To achieve this, the following steps need to be taken:

Customizing the ItemStyle XSLT file in Share Point 2013

  1. Open the site collection URL and Open the XSL Style Sheets folder to view the Itemstyle.xsl file.

  • Download the ItemStyle.xsl file to your computer. Edit that file using notepad or share point designer 2013
  • Copy the below code block and paste it above the closing </xsl:stylesheet> Here the first HTML Table row and the second HTML table row represents the column headings and the actual data respectively.

Make sure that you use this code block to output a header in XSLT:

  1. Save the file, upload the updated file to XSL Style Sheets folder in Style Library folder. Publish a Major Version to see the changes in the itemstyle.

Customizing the content query web part properties configuration in Share Point 2013

  • Open Share Point 2013 page, where you wanted to add web part and click Site Actions, and then click Edit Page. The page will displayed in edit mode as depicted in below screen.

In Editing Tools chose insert Web Part and click “Content Rollup” Category then select “Content Query” showing in parts and click Add button. Refer the below screen

  • Web part will be shown as below and customize the web part properties using “Edit Web Part” context option as directed in the below reference

  • Customize the web part properties under query section, select Show items from the following list radio button and click browse button. Select List or Library pop up will be displayed and select the “UpcomingEvents” list. Refer the below screen shot.

Now change the following additional settings in the web part, which are as per your requirement. Traverse to Styles section to view the properties which will look similar to the below screen shot. Make sure that you will take care of Fields to display as provided in the reference. Then click “OK” button to save the changes to the CQWP. Refer the below screen shot.

Customized content query web part in Share Point 2013



SharePoint Custom Code Analysis using MSOCAF

Code review, as we all know, plays a critical role in software development.  It helps in developing high quality, custom codes using industry best practices.

Code analyzing can be performed in two ways, i.e. by manual analysis or by using tools. The main benefits of using tools over manual process is the fact that it is faster and the results have a higher accuracy rate.

There are several tools available in the market that help to perform code analysis, such as, FXCop, NDepend, Eclipse, SourceMeter, JSLint, and so forth. In the context of SharePoint, the code analysis tool provided by Microsoft is MSOCAF (Microsoft SharePoint Online Code Analysis Framework). It is a free tool provided by Microsoft for analyzing SharePoint custom code.

It is really important to ensure that the custom code we write is healthy to ensure that it will not bring down the entire SharePoint server due to the malicious code we deployed to the server. In fact, this is one of the reasons why Microsoft introduced the new Add-in concept for developing custom code. Either the Provider hosted Add-in or the SharePoint hosted Add-in will not be executing the custom code in the SharePoint server. The below sections will explain how we can use MSOCAF for analyzing our custom code.

Install MSOCAF in the development server.

The first step is to install the tool in the development server. We can download the tool from this url. After successful installation we can launch the application by selecting the shortcut from the desktop as shown below:

This will launch the tool:

This tool is not only used for analysis but can also be we used for deployment to the test environment, roll back the custom solution which is already deployed and also submit the code to Microsoft.  In this document let us focus on the analysis part.

Preparations for performing analysis:

Before we start analyzing our custom solution (.wsp file) we need to create a folder structure and keep the required files in this folder. The below screen shot shows the folder structure that is required to perform the analysis.

The folders and content of each of these folders is mentioned below:

Caf Reports – empty folder.  (This folder is used to store the output of code analysis. The output contains the cab file and the analysis comments in xml format)

Release Documents –should contain the release document in MS word format.

Solution Artifacts – contains the wsp and the DeploymentManifest.xml file (DeploymentManifest file contains the details for deployment as shown in code snippet below)

Source Code – This folder should contain the complete solution in Zip format.

Test Documents – Any file format that contains the test results

Installation Scripts – PowerShell scripts that contains pre and post deployment activities to be performed.

 Code Snippet:

<DeploymentManifest xmlns_xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns_xsd="http://www.w3.org/2001/XMLSchema" >


<Solution Name=”<Name of the  Solution>” Version=”<deployment version>” Action=”Deploy”>

<SolutionDescription><One line description about the solution></SolutionDescription>

<SolutionFileName><Solution Name></SolutionFileName>




<WebApplication Type

=”<Type of the site>” Uri=”<url of site>”></WebApplication>





Once all the required folders and the respective files are created we can start the analysis.

In the tool window click on the Analyze icon as shown below:

On selecting `Analyze’ it will take us to the next screen that gives us the required folder structure:

Click on the `Next’ button which open a short description page that tells  us about the review rules:

Click the `Next’ button where we have the option to select the folder where the source code and other artifacts are stored:

Select the folder that we created during the preparations for performing the analysis step right in the beginning. And click the Analyze button. This will start analyzing our code.  Once the analysis is completed we will get the below shown screen:

Here the analysis is completed successfully and this code is safe to get deployed into the server. If you notice, there are two warning which are ignorable. We can click on the expand icon to further drill down and find out the details.

Let us see what those warnings are:

It says we need to apply ULS log in each catch block and

The hardcoded control template path needs to be removed.

We can ignore these two warnings and proceed with deployment or can fix these two warnings and do a re-analyze.

Now, let us take a situation where it fails the code review. Below is the screen shot of the analysis failure:

Here if we notice the code analysis failed due to ten errors.  Let us analyze those errors:

It says there is an issue with marshalling. Let us click in the Resolution link provided under the Resolution column to find out what is the recommended resolution.

It says we need to add Marshal Attribute to the code when we are using unmanaged components.

Now let us look at the code and fix these failures and re- run the analysis.

After fixing those issues we can now re-run the analysis and the same will be completed successfully and the code is safe to be deployed. We can further get this code deployed by clicking the Next button. The code will be deployed into the environment as mentioned in the manifest file.

Since the focus was on getting the code reviewed, I am not taking you to the next action – deployment – of the solution from the tool.

Reference: https://caf.sharepoint.microsoftonline.com/

Customizing Content Query Web Part and ItemStyle

Content Query Webpart in SharePoint is a feature of Enterprise Content Management functionality. The Web Part helps to aggregate and display list items within a site collection. Content Query Web Part also has caching and query optimization capability for SPSiteDataQuery. The Content Query Web Part can display items such as any ‘list’ or ‘document library’ within a root site or its sub-sites.

A Content Query Web Part can be used to query items based on three options:

  • Show items from all sites in the site collection
  • Show items from the following site and all sub-sites
  • Show items from the following list

In this blog, I will explain the process to save items within a SharePoint List, in the root site, and display them in sub-sites based on a column filter and customizing ItemStyle.

Create Calendar Events List

For my requirement, a Calendar list for Departments root site is used to save all events. I have chosen the root site to save the calendar in order to have a common design and storage. The sub-sites for each department holds its documents and manages permissions. A home page should display upcoming events of the current department.

I have added two additional columns to default calendar list in SharePoint site:

  1. Community – Choice field to select a department for the event
  2. EventStartTime – Calculated field to copy ‘Start Time’ value

Add Content Query Web Part

This is an out-of-the-box Web Part available to all SharePoint pages under category ‘Content Rollup’. Insert the Web Part into the department home page:

Select the option to display items from a specific list and browse to select the Calendar list:

Configure filter and sort order for the web part and save:

On the home page, the CQWP will display upcoming events of the current department.

Customize ItemStyle XSLT

Content Query Webpart uses ItemStyle.xsl file located in sitecollection Style Library. I have created a new template named “EventsDisplay” within ItemStyle.xsl file.

&lt;xsl:template name="EventsDisplay" match="Row[@Style='EventsDisplay']" mode="itemstyle"&gt; &lt;/xsl:template&gt;

Custom header text and formatting are added to xsl file:

<div class="events-header">
 <xsl:if test="count(preceding-sibling::*)=0">
 <h3> <span class="events-header-text">Upcoming Events</span> <a class="events-header-link" href="/departments/Lists/UpcomingEvents">Visit Calendar <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span></a> </h3>

To display fields in content query webpart add an xsl:value-of attribute:

<xsl:value-of select="ddwrt:FormatDate(string(@EventDate), 1033, 3)" />
 <xsl:value-of select="@Title" />

The webpart displays its content in table format:

<table class="table events-table" style="margin-bottom:0px;">
 <xsl:if test="count(preceding-sibling::*)=0">
 <td width="25%" class="calevent_date" valign="top" style="border-top:1px solid #ddd;border-left:1px solid #ddd; border-right:1px solid #ddd; background-color:#F5F5F5;padding:0px 8px;">
 <div class="item"><b>Date</b></div>
 <td width="75%" class="calevent_date" valign="top" style="border-top:1px solid #ddd; border-right:1px solid #ddd; background-color:#F5F5F5;padding:0px 8px;">
 <div class="item"><b>Event</b></div>
 <td class="calevent_td" width="25%" valign="top" style="padding:0px 8px;">
 <div class="item">
 <xsl:value-of select="ddwrt:FormatDate(string(@EventDate), 1033, 3)" />
 <td class="calevent_td" width="75%" valign="top" style="padding:0px 8px;">
 <div class="item">
 <xsl:value-of select="@Title" />


Content Query Webpart in SharePoint is a very handy out-of-the-box functionality to display list items within a site collection, by avoiding customization. This Web Part does not belong to search category hence does not require crawl to view results. The Web Part’s display can be customized extensively with the help of XSL files.

Search Architecture in SharePoint 2013

Search architecture in SharePoint 2013 has undergone massive changes in comparison to the earlier versions of SharePoint. A primary change is, SharePoint 2013, fast search has been embedded in the native search engine as compared to previous version of SharePoint 2010, where fast search was a separate installation.

  1. Search in SharePoint 2013 has been enhanced in several ways with enhancements for ‘types of users’. For example, for end-users, SharePoint 2013 search enables them find relevant information more quickly and easily. For developers and administrators, SharePoint 2013 search provides new APIs and customized search experience.
  2. Also, Search in SharePoint 2013 has been re-architected to a single search platform. Search architecture in SharePoint 2013 has the following components:
    1. Crawl and content processing
    2. Index component
    3. Query processing components
    4. Analytics components
    5. Search administration component

Below is the search architecture diagram, which has different components as indicated above.

Let us discuss each of the components of SharePoint 2013 search engine architecture in detail.

  1. Crawl Component: connects to different content sources using protocol handlers and crawls the content. Crawl engine crawls the contents and extracts the crawled properties and Metadata from the crawled content. Crawl component then passes it to the content processing component.
  2. Crawl Database: is one of the key sections of the crawl and content processing component. Crawler will crawl the content and the extracted information will be stored in the crawl database. Crawl database stores the information about the timestamp of the crawled items, last crawled time, last crawl ID and the type of update during the last crawl.
  3. Content Processing Component: Here, the information sent by the crawl component is processed and passed to the index component.
  4. Link Database: The crawled link information extracted from the crawl component and proceeding link information from the content processing component is stored in the link database.
  5. Index Component: gets the processed items from the content processing component and makes an entry about the processed items in the search index. Index component is also responsible for handling incoming queries form query processing component and gets the result form the search index and passes it to the query processing components.
  6. Query Processing Component: This component in the SharePoint 2013 search engine is responsible for analyzing and processing search query. Processed query is sent to the index component which in turn submits the query to the search index and search index returns the result set.
  7. Analytics Component: contains analytics processing component, link database, analytic reporting database and event store. Analytics processing component is responsible for usage analytics and search analytics. Link database in the analytics component stores search click information. Analytics database in this component stores the result of usage analytics. Event store captures the data for usage events that are captured at the front end.
  8. Search administration: This component in SharePoint 2013 search engine, helps running in system processes. Using search administration component you can add new instances of search components. Search administration database in search administration component stores search configuration data.

Search Service Application:

Search engine in SharePoint 2013 is exposed using a service application known as search service application. Search service application provides you an interface to configure different components of the search architecture discussed in the above segment.

To create a search application follow the steps and screenshots given below.

  1. Open the SharePoint Central Administration Site using an admin account.
  2. Under Application Management section click on manage service application as shown in the screenshot below.
  3. Click on new button on the service application page as shown in the screenshot below. Click on the search service application from the drop down.
  4. Click event would open a dialog page to capture the configuration properties information. The settings you specify here can be changed later using the properties button in the manage service application page, after selecting the appropriate service application.

Fill in the necessary settings details and click ok.

After few minutes the search service application will be created and a web page as shown in below screenshot will be displayed.

Using the above shown search administration page, you can configure the search in your form.

Managed Metadata in SharePoint 2013

Metadata is defined as ‘data about data’ or ‘metadata’.  It can also be defined as ‘information about information’. For example, a book can have Meta data such as, title and author. Metadata can be of many types and can be associated with any type of element.

In SharePoint this information can be centrally managed and this makes it ‘Managed Metadata’ in SharePoint. Managed Metadata in SharePoint can be defined as the hierarchical collection of centrally managed terms, term set and enterprise keywords.

Managed Metadata concept was introduced by Microsoft in SharePoint 2010 version.

In SharePoint Managed Metadata is exposed using a service application known as Managed Metadata service application.

Given below are a few steps to create a managed Metadata service application in SharePoint 2013.

  1. Open central admin site using an admin account.
  2. In the central admin site under application management section click on ‘Manage Service application’ as shown below.
  3. Manage service applications link will redirect the user to manage Service Applications page. In the manage service applications page under service applications tab click on new button. New button click will display a drop down menu as shown in the screenshot below.
  4. Click on the Managed Metadata service link, which will pop up a new window, where in you can specify the name of the service application, name of the database which will be created to store the created managed terms, application pool details and content settings, as shown in the screenshot below.
  5. After a few minutes the service application will be created and the managed metadata service application default page will be loaded as shown in the screenshot below.In the default service application page, on the right pane, the default settings will be displayed.
  6. In the left pane of the managed service application page, under the system folder which is nothing but the system group, there will be three different term sets created as shown in the screenshot below.
    The hashtags term set will store the data, which has been used for social collaboration tagging. For example, if you create a new entry in the news feed web part, with hash tag, the same will stored in the hashtag term set as shown in the screenshot below.

    Keywords term set would store the terms created in a managed metadata column in a SharePoint list and library. This allows multiple values and has set the allow submission policy set to true. Therefore, if any user adds a new value to the column, the same will be stored as the keyword under keywords ‘TermSet’. Orphaned TermSet would store any of the deleted term which are being used.

  7. There are some more groups created by default as shown in the screenshot below.

People group would contain three different TermSets as shown in the screenshot above. These TermSets are used in user profiles and properties to store the information about the user. Every new entry for a user profile property for these three TermSets will be stored here.

Search dictionaries group would contain different TermSets as shown in the screenshot above. Let’s discuss about each TermSet in detail.

You can manage company names in the company name inclusion and company name exclusion term set you can control which company names will be extracted and placed in a managed property field.

Search queries can be improved by managing “Did you mean” spelling suggestions in the Term Store using query spelling exclusion and inclusion.

Important terminology

  • Taxonomy: Taxonomy is the way to arrange the terms in a formal way.
  • Folksonomy: Folksonomy is free flow and informal way of classification of data.
  • Groups:  A group is a set of term sets that share common security requirements.
  • TermSets: TermSet can be defined as group of related terms. There are two types of TermSets. One is local TermSet which is created at site collection scope and one is global TermSet which is created in managed metadata service application.
  • Terms:  A term can be defined as specific word or phrase that ca n be associated with a SharePoint item.

Driving SharePoint User Adoption [Part 2]

We have looked at the challenges and few basic rules to enhance user adoption for SharePoint sites in the previous blog Driving SharePoint User Adoption [Part 1]  Now, let us look at methods to promote user adoption and how to get a few easy wins for adoption.

Promoting User Adoption

Below are a few tips on the methods to promote user adoption:

Launch a Great Campaign

  • Start the launch campaign and create a healthy curiosity within the user community. There is a reason why movie trailers are created months or years in advance. They create the much needed hype and excitement!
  • Conduct some pre-launch sessions/open forums where the users get answers to questions they may have on the new launching site
  • Plan the application launch day and make it creative with posting the screenshots of the application across the floor with some interesting facts about the application

Promote Your Site Actively

  • In the first week after launch, identify the team/department which uses the application the most and reward the team members
  • Send frequent remailers to end-users about the good statics of the application usage
  • Have the email id/phone number of the people/system administrators on each page for a few days, so that users know whom to contact in case of errors/issues

Eat Your Own Dog Food

  • Use SharePoint for your own document sharing and collaboration
  • Lead by example – employees model the behavior of the leader
  • Top management should be active in internal blogs
  • Leaders should refuse to accept emails with too many attachments, large attachments or messages copied to several people

Make Your Home Page Interesting

Announcements Weather
Employee Directory Employee of the month
  • Make sure your Home Page is extremely attractive/user friendly and useful
  • Few sample widgets that you can have on the homepage are – announcements, current weather, tip of the day etc. The application should create interest in the users to make them want to check it at least once a day
  • Love-at-first-sight will have a long lasting impact

Provide Training

  • Train SharePoint owners on their responsibilities and how to be webmasters of their respective sites
  • Get users involved early and explain how it will make their job easier
  • Train users!

Encourage and Incorporate User Feedback

  • Collect formal and informal user feedback. It is always good to work towards improvement and have a regular release plan. Always show some progress to the users and win their confidence.
  • Post positive feedback’s regularly via bulletin boards/emails
  • You can use the SharePoint out of the box survey tool itself to capture user feedback.

Easy wins for SharePoint adoption

Below are few out-of-the-box features of SharePoint which can be exploited to win good user adoption.

Search Experience

  • Exploit search capabilities of SharePoint
  • Configure search with the right refiners
  • Optimize search speed
  • Maintain consistent search experience


Today’s world is leaning towards automation. We all know time is money and if we can gain time by automating a few processes, that will not only add to our business value, but will also result in better user adoption. SharePoint offers out-of-the-box workflows which are simple enough to be configured.

Below are few points to be considered around automation:

  • Automate simple processes
  • Leverage out-of-the-box workflows
  • Have notifications at various steps
  • Enable reporting around the process
  • Make approval process easy with mobile enablement

Mobile Enablement

  • Have the application mobile enabled
  • Release Intranet apps
  • Notifications on mobile(Email/SMS)
  • One click approval


  • Adoption is not that difficult, provided it is part of the strategy right from the beginning of the project.
  • The right features of SharePoint should be leveraged based on business needs
  • An appealing application will always have a good user adoption.

New Features in SharePoint 2016

Office 365 Integration

Microsoft has enabled Office 365 integration in terms of hybrid scenario, which can be configured using SharePoint 2016 on-premises central administration site.

There are two ways, using which hybrid integration can be done.

  1. One Drive
  2. One Drive and sites

SMTP Connection Encryption

In SharePoint 2013 the SMTP was on port 25. However in SharePoint 2016 you can use the custom port for SMPT configuration and you can also enable SSL and encrypt the connection between SharePoint 2016 and SMTP.

System Settings

Using central administration site, you can manage services running on the server as well as those in the farm. You can even change the server role from central administration site for a particular server in the farm.

Enterprise Metadata and Keyword Settings

The Enterprise Keywords column allows users to enter one or more text values that will be shared with other users and applications, for ease of search and filtering, as well as metadata consistency and reuse. In SharePoint 2016 you can use metadata publishing in a document library or list, using which values added to managed metadata and enterprise keyword columns can be shared as social tags on My Sites to appear in news feed, profile pages, tag clouds and tag profile pages.

Project Server Inclusion

SharePoint 2016 server will by default be shipped with the project server. Microsoft is consolidating project server databases into the SharePoint content database. The project server engine is now embedded into SharePoint 2016 On-Premises version. However, this will not be available free of cost. A separate license will be required to use the Project server features. Project Server features will be available using project server service application.

New Improved Synchronization Settings

SharePoint 2016 will no longer support FIM (Forefront Identity Manager), which was used in the earlier SharePoint version, i.e. SharePoint 2013. All the profiles imported in SharePoint 2016 will be supported using active directory import. In order to overcome the active directory limitations, Microsoft has come up with MIM (Microsoft Identity Manager), which is actually the upgraded version of FIM (Forefront Identity Manager). MIM overcomes all the limitations within Active Directory Import. SharePoint 2016 would have improved bidirectional synchronization support.

New Site Template

SharePoint 2016 has a new site template known as “Compliance Policy Center”. It can be used as the Document Deletion Policy Center to manage policies that can delete documents after a specified period of time. These Policies can then be assigned to specific site collections or to site collections templates.

The other site template which has been introduced is ‘In-Place Hold Policy Center’. This site template can be used to create a site to manage policies to preserve content for a fixed period of time.

Role-based Server Farm Configuration

SharePoint 2016 is now shipped with a configuration wizard, which will help SharePoint administrator to configure SharePoint farm servers with specific roles right at the time of installation. This will help to maintain the best performance of the desired server role. The different roles available are as follows:

  • Front End
  • Application
  • Distributed Cache
  • Search
  • Custom
  • Single Server Farm

Role Conversion

In SharePoint 2016, you can change the role of a server in the farm at any time, using SharePoint Central Admin site interface under system settings, i.e. convert server roles in the Farm.

Enhanced Control for Document Library (Similar to SharePoint Online)

SharePoint 2016 document libraries would have the same features as you get in SharePoint online document library. This will allow users to execute commands on SharePoint online.

Five Key Boundaries and Limits – Improved

Content Database Size – has been increased from Gigabytes to Terabytes.

Site Collection per content Database – has been increased to 100,000.

List Threshold – is now greater than 5000 items

Maximum file Size upload – limit increased to 10GB from 2 GB and character restriction have been removed.

Indexed Items – have been doubled from the 500 million items for Search scaling.

Durable Links

When renaming and moving a document from one document library to another, even to a separate site collection, the links will not break.

SLAPI (SharePoint logging API)

A new API to read the logging data has been introduced. This API will give a better insight into, how users are using SharePoint.

Driving SharePoint User Adoption

Today, IT success is measured by long term user adoption and driving adoption is about understanding the business challenges that you will address with solutions. It is about ensuring that people across your organization understand the benefits of adoption and embrace the solutions you provide. However, the fact remains that driving adoption is difficult and it takes time. More importantly, it is not a one-time activity and could require multiple iterations.


Below are the top four challenges of user adoption:

  1. Define the need – The first challenge is making sure that the application is meeting user needs. One should try to understand what the end-users need rather than forcing users to use the features available with a tool/technology.
  2. Project scope – It is better to always start small and grow big!! If the initial project scope is enormous, it could lead to requirement leaks, vast timelines, too many features and by the time you achieve all this, the user’s need itself could have changed! Hence, one should always keep this in mind.
    The best thing to do under these circumstances is to get users to categorize user stories/or what we call as requirements to “Must”/”Should”/”Could” and “Won’t”. All features which are ‘must’ and ‘should’ can go in the first release and ‘could’ can follow. One always has to look for phased roll outs.
  1. User requirement – Once you define the need, confident that SharePoint can meet your needs and are clear on the scope, then user requirements comes into picture. Capturing the user requirement and making sure the end product is exactly the way user wanted is one of the biggest challenges of the software industry. Communication is a very important aspect during any phase of the project execution. In most of the cases, there will be unstated requirements and if one goes by developing only stated requirements, it could lead into project failure. Engineers are expected to capture/cover unstated requirements to certain extent and these should come out of the discovery/requirements phase for a successful project roll out/user adoption.
  2. User experience – I have to quote a line about user experience here – “User interface is like a joke. If you have to explain it, it’s not that good”. Few things like the page load time, the way users are notified about success/failure of a transaction in the site, the ease of data entry are all very important and will lead to a very good user experience.
  3. Previous bad experience – A bad user experience will hinder not only the adoption of the current site and technology but also will have a huge negative impact for future implementations.

Best example for user adoption

Now that we have talked about challenges of user adoption, let’s see an example for good user adoption in the market. As you all know, e-shopping has had one of the best adoptions in the market and all of us are truly amazed by the variety of the audience it has!! As technology keeps advancing, people are learning quickly and adopting themselves to new technologies and are open to the new and convenient option of online shopping. This indeed is a cultural difference where most of the people today prefer staying indoors and buying stuffs online than physically visiting shops. This wasn’t the case a couple of decades back. If technology can bring in such big difference which is welcomed by millions of users, why cannot SharePoint implement bring a positive difference? It definitely can, provided we follow a few guidelines in implementing a SharePoint application.

Three basic rules for user adoption

  1. Don’t make me think – User adoption should be taken care right from the beginning. An application’s success depends greatly on its user experience. We have to make sure the application requires minimal or no thinking for its usage. This should be a standard guideline to follow across the applications we develop.
  2. Five point rule – Count a point for every different font, font size and color. Redesign if it is more than 5 per screen.
    – Marisaa Mayer, CEO YahooThe application should not distract the users and should let them retain their focus on the application. This is the most important rule to achieve.
  3. 9x or better – A new product has to offer 9x improvement over the existing solution in order to be easily adopted. At each stage of designing/developing the application, keep this in mind.


  • It is all about user – understand their needs
  • Adoption is a process and not an event
  • Application success majorly depends on the user adoption
  • Adoption should be considered and budgeted as part of the project strategy

Blog on methods to promote user adoption and the easy wins for adoption coming up shortly.

Creating Open XML Documents using SharePoint Object Model


Open XML files are Zip files that contain XML, and it is very easy to generate or modify Open XML documents programmatically. Using the programmability features of Open XML and SharePoint, we can put together a small document-generation system.

Here we will see how to develop a document-generation system that uses SharePoint lists to populate tables in an Open XML word-processing document.

Sharepoint List

Two SharePoint list Policy and PerminsAndForms are created that contains data we want create the table in the Word document.

Template Document

We need to create a template document which defines format of the output document like Styles, Settings, Fonts, columns of the table etc. Below figure shows the template we created for this sample.

Programming for Open XML Using the .NET Framework

Here we need to use Open XML SDK (ver 2.5) and it is available for free download. We should refer documentformat.openxml.dll of the SDK in our project before get into coding.

We also need to refer Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll to access the SharePoint list and read data from the above two lists.

We have created two classes in this sample project, SPDocumentGenerator class contains the logic to create the word document and SPDataRepository class for communicating to Sharepoint and get the data.

We will see important methods of these classes and the logic involved in generating the final output.

CreatePackage method of the SPDocumentGenerator creates a blank document package in the specified path that is passed as parameter to this method. All parts of the document such as Body, Font, Style, Settings, and Themes are created in the CreateParts method. Each of these child parts are created in their respective methods like GenerateMainDocumentPart1Content creates Body of the document, GenerateFontTablePart1Content creates fonts, and GenerateStyleDefinitionsPart1Content creates Styles etc.

GenerateMainDocumentPart1Content is the important method for us now because it creates content of the document and in our case it will create some plain text and table of data from the Sharepoint list.

In this method, to begin with, we are creating the body object, and then the paragraph. The most basic unit of block-level content when creating word document from OpenXML is paragraph. A paragraph can contain optional paragraph properties, inline content (Run object that we see in the above code).

After the paragraph, the next level document hierarchy is Run which defines a region of text.  Run can also have properties (RunProperties object). Some examples of run properties are bold, border, character style, color, font, font size, italic, and underline.

The Text object is the container for the text that makes up the document content. We need to use Text object to place text in a Wordprocessing document.

In the above code text “Creating Open XML Documents using SharePoint Object Model” is added to the main document. A Run object contains a region of text within the paragraph and then a RunProperties object is used to apply bold formatting to the run.

Now we will see how to create table.

In the below code we can see that Table object is created and then style, width of the table is defined through TableProperties object.  Required columns and its width are created by using TableGrid object. Then we need start creating TableRow and Cell in the each row.  In our example we have table with four columns with static column header. This Column header is created by using Paragraph, Run and Text object as explained above and then Paragraph object will be added to Cell of the TableRow. “Sl No.” is the first column we created in this table.

Now we will see how to create data row in this table. In the below code snippet we have created instance of SPDataRepository class which has the logic to retrieve data from the Sharepoint using CSOM (Client Side Object Model). We will explore that code in next section.

We are using getListItems method of the SPDataRepository to get the required SharePoint list. First parameter in getListItems is the SharePoint list name, and other two parameters are useful if we want to fetch list items that match certain criteria. Second parameter is for criteria field name and third is for matching value.

Return values of getListItems method are stored in a collection (lstPolicies). Then we need to create TableRow for each item, and TableCell for each field in the list item. Then as we did for static text, we need to create Paragraph, Run, and Text object for assigning SharePoint List Item field value to the table cell.

The figure below displays getListItems method of the SPDataRepository. Firstly, we need to get access to SharePoint and this is done by creating ClientContext object with the URL of the SharePoint site. Then using GetByTitle method we are retrieving the specific List whose name is passed to this method.

The next part of the code defines a CAML (Collaborative Application Markup Language) query that specify which items of the List is to be returned. Created query string is to be assigned to Viewxml property of the CamlQuery object.

GetItems() method takes a CamlQuery input to return the items which meets the CamlQuery criteria.

One thing to note here is the client side object model (CSOM) uses the same pattern as SQL, i.e To start with, we need to Build a query, then execute and then Read the result. So here ClientContext object Load method builds the query and ExecuteQuery submits the prepared query to the SharePoint server and retrieves the data.

Finally returned result will be sent to the calling object, in our case it is SPDocumentGenerator

Output document which is generated from our application looks like below.


One of the important features of Open XML is Programmability. In this blog, we explored a very simple solution to study how we can use the Open XML to create Office documents by referring SharePoint as the data source. This also demonstrates how to reuse information between the applications and the information system.

Introduction to REST API with OData Operators in SharePoint 2013

What is REST API?

REpresentational State Transfer Application Program Interface (REST API)  is an architectural style which consists of a set of constraints applied to components, connectors and data elements within a system. REST-based systems typically communicate over HTTP, using  verbs such as GET, POST, PUT and DELETE.

SharePoint 2013 supports REST service which helps in executions similar to Client Object Model scripts. Using REST API we can interact remotely with SharePoint by using any technology of our choice that supports REST web service requests. This empowers developers to perform Create, Read, Update and Delete (CRUD) operations from their solutions, client applications or SharePoint apps using REST and Open Data Protocol (OData).

How REST API works in SharePoint 2013

SharePoint 2013 uses two different approaches to authorize user access to the site with REST. Firstly, when you use a remotely hosted application, an OAuth token with Microsoft Access Control Service is used as secure token server. Another alternative approach is used while accessing from client side scripting where the logged-in user’s permission is sufficient for authentication. SharePoint REST helps authenticated users to directly interact with SharePoint objects.

SharePoint resources are accessed using a RESTful HTTP request using Open Data Protocol (OData) which resulta from client-object model API. Consider the below example:


The client.svc web service in SharePoint handles this HTTP request and returns the response in JSON format. A client application handling this request can parse the response.

How to Construct RESTful URLs to access SharePoint resources

REST service always uses the main entry point to SharePoint as the site collection and the site of the specified context. The site collection is accessed using the below url:


And, to access a sub-site you can generate url as:


where <server> represents SharePoint server name and site represents path of the site

One can access the SharePoint data with below REST endpoints; prefix the endpoint with url http://<server>/site/_api/ to construct a fully qualified REST url.

URL endpoint HTTP method Result
web/title GET Get the list title
lists GET Get all lists from a site
lists/getbytitle(‘listname’) GET Get a specified list’s metadata
lists/getbytitle(‘listname’)/items GET Get items from a specified list
lists/getbytitle(‘listname’)?select=Title GET Get a specific property of an item
lists POST Creates a list
lists/getbytitle(‘listname’)/items POST Add an item to a specific list

Open Data (OData) Standard Protocol

OData is a Standard protocol or a set of rules for creating RESTful calls. You can use OData system query options to control the result.

Criteria Result
$select Sets the field names for returned result
$filter Sets the members of a collection
$top Sets the number of items to return
$skip Let you skip first n items from the result
$orderby Let you sort result by a specific field

Some examples on how to use OData operators in RESTful calls:


This REST endpoint URL will return top 10 employees from the list ‘Employee’


This url will have a response of top 5 employees from the list and the result will consists of only three fields from the list namely; FirstName, LastName and Email.

OData Operators

The query section of OData URI can be used to filter data in SharePoint REST service.

Operator Description
Logical Operators
Eq Equal
Ne Not equal
Gt Greater than
Ge Greater than or equal
Lt Less than
Le Less than or equal
And Logical and
Or Logical or
Not Logical negation
String comparison
startsWith Starts with a specified text
endsWith Ends with a specified text
replace Replace a string
tolower Convert to lower case
toupper Convert to upper case
trim Removes white spaces

Few examples of getting SharePoint data using OData operators

http://<server>/site/_api/web/lists/getbytitle(‘Employee’)/items$select=FirstName,LastName,Email&$orderby=EmpID asc

http://<server>/site/_api/web/lists/getbytitle(‘Employee’)/items$orderby=EmpID asc&$filter=FirstName eq ‘John’


SharePoint 2013 with REST interface is extensive and powerful enough to execute most of the operations for web and app developers. We have looked at the key ways to integrate SharePoint to other applications using REST API interface, but there are several other possibilities. The SharePoint 2013 SDK consists of a huge collection of resources for REST based development, which can be a reference.

SharePoint 2016 Beta 2 – Closing the loop with enhanced usability

Just a few months after Microsoft released its SharePoint server 2016 Beta 1 i.e. IT Preview, it launched the last public beta releases – SharePoint Server 2016 Beta 2 and Project Server 2016 Beta 2, on 18th November just one week before the Thanksgiving.

In the OfficeBlogs, SharePoint team stated that the latest four enhancements are primarily focused on updating existing features, and incorporating feedback and improvement received the from IT preview, released in August 2015. Most of these improvements have also been made focusing on hybrid scenarios.

SharePoint 2016 Beta 2 can be downloaded from Microsoft Download Center.

Four Last-mile improvements ahead of the grand release

  • Profile Synchronization with Microsoft Identity manager
    Microsoft Identity Manager 2016 makes it easy to manage identity lifecycle by allowing easy integration with heterogeneous platforms, automated workflows and business rules. The new improvements in Beta 2 allow bi-directional synchronization and common identity scenarios.
  • Data Loss Prevention
    Augmented support for Data loss Prevention capabilities.
  • Extensible Hybrid App Launcher
    Supports App Launcher tool to other tools delivering common access experience across applications and solutions in cloud.
  • Profile Redirection
    Enables easy profile management by extending to other suites like Delve, About me and Office 365, apart from on premise version.

Along with the focus on improving scale and performance, SharePoint 2016 Beta 2 has introduced CSOM (Client Side Object Model) reducing the gap between Object Model and PSI.

Have something to share? Do write to me at himanshu_s@trigent.com

Exit mobile version