Tuesday 30 July 2019

Rest API Services

REST – Representation State Transfer.


  1. SharePoint can be integrated using REST API
  2. OData query operators supported in the SharePoint REST service
  3. There are so many ways but the approach is almost same everywhere. 
  4. jQuery($.ajax) will be used to access all endpoints
  5. Returns JSON format collection of the results


Powerful solution is using the $filter key.
/_api/web/lists/getbytitle('listname')/Items?$select=Title&$filter=Title eq 'example 1'

Multiple $filter keys + values
/_api/web/lists/getbytitle('listname')/Items?$select=Title&$filter=((Title eq 'example 1') or (Title eq 'example 2'))

For Paging
/_api/web/lists/getbytitle('listname')/Items?$top='10'&$skip='20'


Get a single list item


Function getListItem(url, listname, id, complete, failure) {
 // Getting our list items

$.ajax({
  url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")",
  method: "GET",
  headers: { "Accept": "application/json; odata=verbose" },
  success: function (data) {
   // Returning the results
   complete(data);
  },
  error: function (data) {
   failure(data);
  }
  });
 }

}

Refer the link
link

How to get more than 5000 items by Rest API?

Here we are doing recursive call to the GetListItems() function. This will fetch data in the bunch of 1000 items and concat it to response variable.

var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('DocumentList')/items?$select=customerID&$top=1000";
    var response = response || [];  // this variable is used for storing list items
    function GetListItems(){
        return $.ajax({
            url: url,  
            method: "GET",  
            headers: {  
                "Accept": "application/json; odata=verbose"  
            },
            success: function(data){
                response = response.concat(data.d.results);
                if (data.d.__next) {
                    url = data.d.__next;
                    GetListItems();
                }
                $.each(response, function(index, item) {
                    arrayCustomerID[index] = item.customerID;
                });
            },
            error: function(error){
            }
        });
    }
if (data.d.__next) will enter loop only if item number is 1001.
data.d.__next contains the url to get the next items. In case we don't have more items left to fetch, it will not call GetListItems() function.


What is formDigest in REST API?

If you aren't using OAuth to authorize your requests and when creating, updating, and deleting SharePoint entities
these operations require the server's request form digest value as the value of the X-RequestDigest header

jQuery.ajax({
        url: "http://<site url>/_api/web/lists",
        type: "POST",
        data:  JSON.stringify({ '__metadata': { 'type': 'SP.List' }, 'AllowContentTypes': true,
 'BaseTemplate': 100, 'ContentTypesEnabled': true, 'Description': 'My list description', 'Title': 'Test' }
),
        headers: { 
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "content-length": <length of post body>,
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: doSuccess,
        error: doError
});

Rest API Filtering:
Filter by Title

 /_api/web/lists/getbytitle('infolist')/items?$filter= Employee eq ‘parth'

Filter by ID:  

/_api/web/lists/getbytitle('infolist')/items?$filter=ID eq 2

Filter by Date

  /_api/web/lists/getbytitle('infolist')/items?$filter=Start_x0020_Date le datetime'2016-03-26T09:59:32Z'

Multiple Filters

  /_api/web/lists/getbytitle('infolist')/items?$filter=( Modified le datetime'2016-03-26T09:59:32Z') and (ID eq 2)

Title name starts with the letter P

/_api/web/lists/getbytitle(‘'infolist')/items?$filter=startswith(Title,‘P’)

Return all items from the'infolist'list modified in May


/_api/web/lists/getbytitle(‘'infolist')/items? $filter=month(Modified) eq 5

Retrieve all sites and all subsites from the SharePoint REST API

var url = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/webs";

Retrieve current login user

Step-1

url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/currentUser",

Step-2

var userid = _spPageContextInfo.userId;

var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";


Difference between PUT, PATCH, MERGE?

1. PATCH and MERGE works same but the method PUT is different. 
2. If we need to update only one field in the list item, we will have to go for PATCH or MERGE 
3. because the PUT method will require all the fields in the data variable to update.



How to get More than 5000 items in sharepoint by Rest API ?


1. We can call  recursive call to the GetListItems() function
2. This will fetch data in the bunch of 1000 items and concat it to response variable.
3. call  data.d.__next;



var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('DocumentList')/items?$select=customerID&$top=1000";
    var response = response || [];  // this variable is used for storing list items
    function GetListItems(){
        return $.ajax({
            url: url,  
            method: "GET",  
            headers: {  
                "Accept": "application/json; odata=verbose"  
            },
            success: function(data){
                response = response.concat(data.d.results);
                if (data.d.__next) {
                    url = data.d.__next;
                    GetListItems();
                }
                $.each(response, function(index, item) {
                    arrayCustomerID[index] = item.customerID;
                });
            },
            error: function(error){
            }
        });
    }

Friday 26 July 2019

SharePoint Interview Questions - 3

What is Low Trust and High Trust?


Low trust --> uses access tokens from a provider (Azure for example).
High trust --> uses digital certificates to validate the endpoints.


  1. How to elevate permission in Provider Hosted app?
Ans: AllowAppOnlyPolicy is similar to RunWithElevatedPrivileges, but not exactly the same.

AllowAppOnlyPolicy executes code based on the permissions granted to the SharePoint Add-in, not on behalf of another user who has the appropriate permissions to perform an operation.

Options to elevate permissions

You have a couple of options to elevate permissions.
  • OAuth (AllowAppOnlyPolicy)
    • S2S (sub option)
    • ACS (sub option)
  • Service Account
    • Remotely hosted code (Example: Azure WebJob)

OAuth (AllowAppOnlyPolicy)

In this option the AllowAppOnlyPolicy is set to true in the AppPermissionRequests element and permissions are set in the SharePoint Add-in manifest. OAuth is used to return access tokens to allow the SharePoint Add-in to execute operations it has permissions to perform.
  1. Can we run  Run with elevated privileges works in provider hosted app?
  2. What is OAuth
  3. Can we add  Server side dll into Provider Hosted app?
  4. Can we add PowerApp into Classic page?
  5. What is logging mechanism in SPFx?
  6. How exception handling in SPFx
  7. Can we convert classic site into Modern site?
  8. Difference between site design and site script?
  9. What is retensal and archival in SharePoint online?
  10. What is Labling in SharePoint online?
  11. Search in SharePoint online?
  12. Difference between Graph API and REST API?


How to Connect to API secured with Azure Active Directory?

  • Secure an API with Azure AD
  • Secure the API using Azure App Service Authentication
  • Secure the API using ASP.NET authentication
  • Access an API secured with Azure AD from SharePoint Framework solutions
  • Azure AD authorization flows
  • Use the AadTokenProvider to retrieve access token
  • Request permissions to API secured with Azure AD
  • Acquire an access token
  • Use ADAL JS to handle authorization and retrieve access token






What is SharePoint modern site page?


  1. This is one of the new and coolest features in SharePoint online.
  2. Modern team site pages are fast, easy to author and support rich multimedia content. And pages look great on any device, in a browser or from within the SharePoint app.
  3. SPFX (SharePoint Client site Framework) web part can easily add in modern pages.
  4. These pages are built with the Web parts, which you can customise according to your requirements. We can add the things given below in SP modern site pages.

Videos
Documents
Yammer embed feeds
Images
Site Activities


Using pages is a great way to communicate and share your ideas such as status and trip reports, how-to write write-ups, know-before-you-go guides and frequently asked questions.

Modern SharePoint exists only in SharePoint Online. Currently "modern" experiences not available for SharePoint on-premises.

Modern page:


  • Modern List and Library
  • Modern sites, Team and communication site with a template.
  • Modern Site Pages.
  • Before you create modern page, you should activate the Site Pages feature on your SharePoint site.
  • We should Activate the site pages Feature in site settings ->site features.
Difference berween Classiv View and Modern View?



Difference between ContentPlaceHolder and PlaceHolder in masterpage?

ContentPlaceHolder:
We are adding in Masterpage.
ASP Content Place Holders are very simple to setup and use
And they can make a website much easier to build with the help of MasterPages.
Inside the MasterPage is where we create our Content PlaceHolders.
<asp:ContentPlaceHolder ID=“Section1” runat=“server”>
</asp:ContentPlaceHolder>
  4. You will notice that the placeholder has an ID tag.
  5. This is how we can identify it to fill it with data form the aspx page.
  6. ContentPlaceHolder we are linked to the MasterPage we can go to the “default.aspx” page 
  7. And fill the Content PlaceHolder with data.

PlaceHolder:
We are adding in Default.aspx.
Go into the default.aspx page and insert a content Tag like below.
Notice we specify a ContentPlaceHolderID, this is how it knows which Content PlaceHolder to fill.

<asp:Content runat=“server” ID=“content1” ContentPlaceHolderID=“Section1”>
    CONTENT!
</asp:Content>
What is SharePoint Design manager?

Master pages provides the same look and feel for all the pages in our site. It lets you create and update the header, navigation links and Site Actions menu elements in one place, rather than changing them on each Web page



  1. Design Manager is available on publishing the site template.
  2. Using Design Manager, the branding and customization can be done in SharePoint 2013
  3. Open CustomMaster folder and create map folder for our CSS, Scripts and Images.
  4. Add our static HTML file, CSS, JS and the images in the respective folders.
  5. Publish the NewHTMLPage as a major version.
  6. Convert an HTML file to a SharePoint master page.
  7. Publish the master page as a major version in Design Manager
Convert Html to masterpage click here

Refer link    link2

Device Channel
1. Device Channels are one of the new features in SharePoint 2013.
2. A mobile rendering can be formatted with a smaller width, have better navigation with wider touch targets,
 and show a reduced amount of information for better usability.
3. When a user browses to a SharePoint site from a mobile device such as a smartphone or tablet, the mobile browser submits to the site an HTTP GET request that includes a user agent string.
4. Using a “user agent string” we can create the device channel for various devices such as desktop, Smartphone and tablets and so on.

User agent string is
This string contains information about the type of device that is trying to access the site. Based on that device substring,
the device browser can be redirected to a specific master page view

What is Client side Rendering(CSR/JS Link)?

Client Side Rendering(CSR):
  1. CSR is the main rendering framework in SharePoint 2013.
  2. CSR is nothing but JS link.
  3. CSR is used for rendering list views, list forms and search results.
  4. SharePoint rendering systems (XSLT in 2010 and CAML in 2007), CSR is client-side.
Benefits:
  • Client side => less server load.
  • CSR is javascript-based. Javascript community is huge and the number of different new JS libraries is astonishing
  • Works with apps, including sharepoint-hosted.
  • Huge improvement over the XSLT in terms of readability
What is Item Template(Display Template)?


 Show the results of a query made to the search index.

 Based on query we can show the search results of items.
  1.  Item template is we can configure in cswp or Display template.
  2.  Its involved with display template.
What are Visual webpart properties?

 Looking for some way to create a property for that WebPart that you can easily Set and Get from your application.

If you notice, each property you create has attributes.

Category – This will group your property according to category. If not declared, “Miscellaneous” will be used as the default.
Personalizable – How the WebPart is configured, which can be per-user (PersonalizationScope.User), or for everyone (PersonalizationScope.Shared). For this example, we have chosen all users.
WebBrowsable – This will hide or show the property on the tool pane.
WebDisplayName – Label for the property.
WebDescription – Description for the property

Content Targeting/Audience Targeting?

We can target the following types of content Targeting
1. Navigation links
2. Webparts
3. List and library items
4. Any item in a SharePoint list or library can be targeted to specific audiences.

We can do to identify a target audience

1. SharePoint Groups
2. Distribution list / Security groups
3. Global Audiences

We can do Target content for webparts and Navigation links.


To audience targeting, you need to activate the publishing feature at site collection level 

Link

What is App principal SharePoint 2013?

App have two polices 
1.App Only policy
2.App Principals

App Principals:  We are using in Provider hosted app MVC web application.

  • App Principal is used to make app authenticate with App Only Policy instead of real user credential,
  • it won't ask user input user name and password, so will be more security.
  • App Principal is very much like a user principal which you can give permissions to in SharePoint
 App Principal mainly contain App Id and App Secret and it needs to be added in MVC web.config.

<add key="ClientId" value="d0ee6f6d-1c39-44b2-a284-f3143e820ec2"/>
<add key="ClientSecret" value="11Flt0LME9mnToNhRN5nmgeynAXW3nMBvJBrIBGlT/o="/>

What is Publishing Feature in SharePoint?



What is array concept in Javascript?

fruits.push('Mango');
// ["Strawberry", "Banana", "Mango"]

var pos = fruits.indexOf('Banana');

// 1

Method -1:

var cars = [
  "Saab",
  "Volvo",
  "BMW"
];

Method -2:


var cars = new Array("Saab", "Volvo", "BMW");


How to retrieve more than 5000 items from SharePoint list?

If your list or library is having more than 5000 items, then you need to perform a repeated ajax call function filtering 5000 items each time. But to know how many times to call the ajax function, we must do in Dynamic way.

First call a ajax function with parameters "/_api/Web/Lists/GetByTitle(ListName)/Items?$orderby=Id desc&$top=1". Now you will get the latest added "Id".
Now Divide the Id returned by the ajax by 5000. (Id/5000) So that you will get a result of how many times you need to perform the ajax.

1. Now you can perform the ajax function repeatedly be filtering every 5000 items, with filter like, $filter=Id ge 0 and Id le 5000, $filter=Id ge 5000 and Id le 10000, ........ , etc.
2. You can have a foreach loop to perform the ajax repeatedly with a dynamic filter, $filter=Id ge (5000*LoopValue) and Id le (5000*(LoopValue+1)).
3. Also make sure, the ajax to have async:true, to avoid performance issue.

You can store the returned data in array and perform further actions, so that you could store more than 5000 data to perform your functions.

Since, there is a threshold limit for there kinda issues, we could use this kind of alternatives to make it possible.

What is Delegate control in SharePoint master page?

Its a Pointer to Function / Method", in this case, Delegate Control is a pointer to a Control which can be replaced at runtime based on Feature Activation or Deactivation.

Suppose we need to show one image on top of home page. we need to create three modules in visual studio image module, Delegatecontrol module, Masterpage module. So in our solution
we need to create one ascx page and add one image.give scope site, deploy the solution. next activate the feature. once you activate the feature image will be show on home page. if deactivate feature image will off on home page.

<SharePoint:DelegateControl runat="server" ControlId="BlogLogoControl"/>

Refer this link

Central admin:



Site collection Site Settings:
























Site pages:

How to add Page Layout to Site Page?

Page Layout: Click here

  1. Go to site pages document library.
  2. Go to library settings.
  3. We can create Page Layout 
  4. Select the content type among the two: Page Layout content Types and Publishing Content Types from Content Type Group.


Page Layouts Content Types




Page fields in Page Layout

Add new fields, web parts, and make other configuration changes to your layout.
Select what you want from the ribbon and then copy the generated HTML block the page provides.

Paste that HTML into your page layout in the desired location.




Site definition:

Click here

Seattle MasterPage

Click here

Do While loop in Javacript, Jquery, Client object model, C#

Javascript:

var text = "";
var i = 0;
while (i < 10) {
  text += "<br>The number is " + i;
  i++;
}

Jquery : There is no difference between javascript and jquery in case of while loop

$(function () {
    var text = "";
    var i = 0;
    while (i < 10) {
        text += "<br>The number is " + i;
        i++;
    }
    $("#demo").html(text);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="demo"></div>

C#:

using System;

public class Program
{
public static void Main()
{
int i = 0;

do
{
Console.WriteLine("Value of i: {0}", i);

i++;

} while (i < 10);
}
}

For loop in Javacript:

<p id="demo"></p>

<script>
var text = "";
var i;
for (i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

Difference between Team site and Communication site?






Difference between Office 365 and SharePoint On-Premises?



Modern Search in SharePoint?

On the SharePoint start page, communication sites, modern team sites, and Office.com, search is personal, and the search results are even easier to explore. Another user will see different results than you, even when you both search for the same words.

You'll only see results that you already have access to, and other users can’t find your private documents.

Even before you start typing, you'll see results based on your previous activity in Office 365. The results update as you start typing.

                                                              While Typing text for find document

While typing text


Difference between Application pages and Site Pages?

Site Pages:

These Pages are stored in the Content Database and they are parsed when requested by user.
A typical web part page is an example of Site Pages. They can be edited, modified by the Power Users and customized according to their needs.

Application Pages:

They are same as ASP.net Pages and stored on the layouts folder of SharePoint front end web server.
When user requests , application pages are compiled and they are much faster than Site Pages.
Admin Pages like settings.aspx, accessdenied.aspx are an example of Application Pages. Thus we can say that Application pages are common to all SharePoint Users.