Wednesday, April 25, 2018

Get Users from AD Group added in SharePoint Group

Requirement - I want to get all members which are there in AD group (added in SP group).

In SharePoint If you add AD group then SharePoint will consider AD group as a single user instead of group. So you will not able to get users directly from AD group after adding in SharePoint groups.


Option 1: Use group membership visibility as a workaround
One potential work around is to exploit a combination of two properties that you can access on groups via the JavaScript client object model: OnlyAllowMembersViewMemberhip and CanCurrentUserViewMembership.
If the current user can view group membership for a group that is only set to allow group members to do so, we can assume the user is a group member.

var clientContext = new SP.ClientContext();
var groupId = 5; // the group membership ID for the group you want to check
var group = clientContext.get_web().get_siteGroups().getById(groupId);
clientContext.load(group,"CanCurrentUserViewMembership");
clientContext.load(group,"OnlyAllowMembersViewMembership");
clientContext.executeQueryAsync(
    function(sender,args){
        var isMemberOfGroup = group.get_canCurrentUserViewMembership() && group.get_onlyAllowMembersViewMembership();
        if(isMemberOfGroup){
            doSomething();
        }
    },
    function(sender,args){"Whoops! "+alert(args.get_message());}
);
This approach will only work if you've set the groups to only be visible to members, and it'll always return a false positive if you have elevated access, such as if you're a site collection administrator or the group owner.
Edit: How to Iterate Through All Site Groups
If you want to apply the same logic as above to check the current user's membership in all groups on the site (instead of specifying a group by its ID), you can use the modified JavaScript code below.
var clientContext = new SP.ClientContext();
var groups = clientContext.get_web().get_siteGroups()
clientContext.load(groups,"Include(CanCurrentUserViewMembership,OnlyAllowMembersViewMembership,Title)");
clientContext.executeQueryAsync(
function(sender,args){
    var groupIterator = groups.getEnumerator();
    var myGroups = [];
    while(groupIterator.moveNext()){
        var current = groupIterator.get_current();
        var isMemberOfGroup = current.get_canCurrentUserViewMembership() && current.get_onlyAllowMembersViewMembership();
        if(isMemberOfGroup){
            myGroups.push(current.get_title()); // this example adds group titles to an array
        }
    }
    alert(myGroups); // show the array
},function(sender,args){"Whoops! "+alert(args.get_message());});
Option 2: Use Audience Targeting as a workaround
Of course, as I mentioned in a comment, for your requirements you may not even need programmatic access to the group membership. You could just set audience targeting on the web parts that you want to be visible only to certain groups; audience targeting should respect AD group membership.

Option 3 : Using REST API 

function spjs_isCurrentUserInGroup(groupIdOrName){
var endpoint;
if(typeof groupIdOrName === "string"){
endpoint = _spPageContextInfo.webAbsoluteUrl+"/_api/web/sitegroups/getbyname('"+groupIdOrName+"')/CanCurrentUserViewMembership" 
 }else{
 endpoint = _spPageContextInfo.webAbsoluteUrl+"/_api/web/sitegroups("+groupIdOrName+")/CanCurrentUserViewMembership" 
 }
 return jQuery.ajax({ 
 "url":endpoint,
 "type":"GET", 
 "contentType":"application/json;odata=verbose",
 "headers":{ 
 "Accept": "application/json;odata=verbose"
 }
 });
}

function checkADGroupMembership(){
 spjs_isCurrentUserInGroup(18).success(
 function(data){
 if(data.d.CanCurrentUserViewMembership){
 setTimeout(function(){
 spjs.dffs.triggerRule(["isInADGroup"]);
 },10);
 }
 }
 );
}

Tuesday, January 2, 2018

Caching in jQuery getScript function

In SharePoint 2013, there is a jQuery.getScript method which is suggested for loading SP.Runtime.js and SP.js files on the page.

The implementation of jQuery.getScript looks like,

jQuery.getScript(_spPageContextInfo.webAbsoluteUrl+"_layouts/15/sp.runtime.js",function(){
   
      alert("SP.Runtime.js loaded");
});

jQuery.getScript(_spPageContextInfo.webAbsoluteUrl+"_layouts/15/sp.js",function(){
   
      alert("SP.js loaded");
});

Thus, this function came out as a good practice for loading such mandate files on the page but then there is a limitation to this,

1) jQuery.getScript  - fetches the fresh copy of the files every time the page is getting loaded with the current time stamp appended to the file path, because this method disables caching of the browser thus degrading the performance of the page load.

The browsers have a property to cache the file once it's fetched to improve page loads from the next time if the such files are requested.

How to overcome this limitation ?

According to further study on jQuery.getScript method on Microsoft,

I came to a conclusion that jQuery.getScript method calls an ajax function internally which has a "cache" parameter which we can set to "true" if we want the function to look into the browser cache for the requested file or "false" if we want the file to be loaded from the original location.

Now the function looks like,

jQuery.getCachedScript(url,callback){

        jQuery.ajax({
           
             datatype: 'script',
             cache: true,
             url: url,
             success: callback
        });

};

jQuery.getCachedScript(_spPageContextInfo.webAbsoluteUrl+"_layouts/15/sp.runtime.js",function(){
   alert("SP.Runtime got loaded");
});

So, now there is no time-stamp appended to the file path which is fetched on page load as caching is set to 'true'.


Tuesday, December 19, 2017

How to overcome SharePoint's 5000 item limit threshold?

The best answer to this question is given on this blog, with an awesome analogy -

Courtesy -

https://sharepointmaven.com/how-to-overcome-sharepoint-5000-item-limit-threshold/

There is no more explanation beyond this blog..!!

Monday, December 18, 2017

RequestDigest value in SharePoint and it's Importance

 RequestDigest as a key through which,
  • You can GET information without using it.
  • There is some information you cannot GET without using it.
  • You need the key to PUT (POST) information in SharePoint.
When executing non-GET REST requests to the SharePoint API, you must add a valid request digest to your request. This digest proves validity of your request to SharePoint. Because this token is valid only for a limited period of time, you have to ensure that the token you have is valid, before adding it to your request or the request will fail. 

SharePoint includes a request digest token on the page in a hidden field named __REQUESTDIGEST. 

One of the most common approaches to work with the request digest, is to obtain it from that field and add it to the request, for example

var digest = $('#__REQUESTDIGEST').val(); $.ajax({ url: '/_api/web/...' method: "POST", headers: { "Accept": "application/json; odata=nometadata", "X-RequestDigest": digest }, success: function (data) { // ... }, error: function (data, errorCode, errorMessage) { // ... } });

Such request would work initially, but if the user would have the page open for a longer period of time, the request digest on the page would expire and the request would fail with a 403 FORBIDDEN result. By default, a request digest token is valid for 30 minutes, so before using it, you have to ensure that it's still valid. In the past you had to do this manually, by comparing the timestamp from the request digest with the current time. SharePoint Framework simplifies this process by offering you two ways of ensuring that your request has a valid request digest token.

1) Use the SPHttpClient to communicate with the SharePoint REST API

2) Retrieve valid request digest using the DigestCache service
If you can't use the SPHttpClient for communicating with the SharePoint REST API, you can obtain a valid request digest token using the DigestCache service provided with the SharePoint Framework. The benefit of using the DigestCache service over manually obtaining a valid request digest token is, that the DigestCache automatically checks if the previously retrieved request digest is still valid or not. If it's expired, the DigestCache service will automatically request a new request digest token from SharePoint and store it from subsequent requests. Using the DigestCache simplifies your code and makes your solution more robust.
To use the DigestCache service in your code, first import the DigestCache and IDigestCache types from the @microsoft/sp-http package:
Next, whenever you need a valid request digest token, retrieve a reference to the DigestCache service and call its fetchDigest method:

JavaScript Display Templates

There are 2 ways to include "JavaScript files" in SharePoint forms, web parts, lists, views -

1) Inclcude .js files in "Site Assets Library" or "Script Library".
2) Upload .js file in Master Page Gallery under "JavaScript Display Template Content Type".

Discussing more about "Javascript Display Template" -

There are 2 ways to include "JavaScript files" in SharePoint forms, web parts, lists, views -

1) Inclcude .js files in "Site Assets Library" or "Script Library".
2) Upload .js file in Master Page Gallery under "JavaScript Display Template Content Type".



JavaScript Display Template Content Type has some special Site Columns added to it that will help specify the target element (view,web-part etc..) 

Lets Look at the Steps to upload a new Js file as a new Javascript Display Template and look at the description of Site Columns.

1. Navigate to the Master Page Gallery (Site Settings -> under Web Designer Galleries -> Master Pages).

2. Select Files tab and then Upload Document.

3. Browse to the new JavaScript file that you have created and select Ok.





4. Choose Content Type as "JavaScript Display Template",
Target Control Type – By description “Target Control Type is the Type of Control that you will be using in this Display Template or JavaScript File”. For example if your Display Template or JavaScript File will be controlling the rendering of a View in a List, then the Target Control Type value should be “View”.
There are three possible options
  • Form
  • View
  • Field
Standalone – Specifies if you need to include this JavaScript File Override during view selection.Default options are
  • Override
  • Standalone
Target Scope – URL of the website this override applies to. This can be a relative path to your Site Collection or subsite.
Target List Template ID – Specify the ID of the list Template type this Override or JavaScript render applies to.
Lastly, "Publish a major version" of the js file uploaded in the master page gallery. 
Template ID List :-
  • 100   Generic list
  • 101   Document library
  • 102   Survey
  • 103   Links list
  • 104   Announcements list
  • 105   Contacts list
  • 106   Events list
  • 107   Tasks list
  • 108   Discussion board
  • 109   Picture library
  • 110   Data sources
  • 111   Site template gallery
  • 112   User Information list
  • 113   Web Part gallery
  • 114   List template gallery
  • 115   XML Form library
  • 116   Master pages gallery
  • 117   No-Code Workflows
  • 118   Custom Workflow Process
  • 119   Wiki Page library
  • 120   Custom grid for a list
  • 130   Data Connection library
  • 140   Workflow History
  • 150   Gantt Tasks list
  • 200   Meeting Series list
  • 201   Meeting Agenda list
  • 202   Meeting Attendees list
  • 204   Meeting Decisions list
  • 207   Meeting Objectives list
  • 210   Meeting text box
  • 211   Meeting Things To Bring list
  • 212   Meeting Workspace Pages list
  • 301   Blog Posts list
  • 302   Blog Comments list
  • 303   Blog Categories list
  • 1100   Issue tracking
  • 1200   Administrator tasks list
5. Since the File was upload in Master Page Gallery and we are using it in the same Site collection (not Subsite) the JS Link reference will be
~site/_catalogs/masterpage/JSLink.js
If the file was to be used in a Subsite you can use ~sitecollection URL token Instead.

Wednesday, November 15, 2017

Attach-File-Modal-Dialog-Sharepoint-2013

HTML Uploader :

<div id="FileUploaded"></div><a href="javascript:openpageindialog();">Attach Supporting Documents</a>

Script :

It opens the Attach File.aspx page in modal pop up.

function openpageindialog() {
    console.log(itemId);
    var options = {
                url: _spPageContextInfo.webAbsoluteUrl + '/_layouts/15/AttachFile.aspx?ListId={GUID}&ItemId='+itemId,
                title: 'Add Attachment',
                width:700,
                height: 200,
                dialogReturnValueCallback: function(result, fileAdded){
console.log(result);
                if(result == SP.UI.DialogResult.OK){
                    alert("file added");
                }
            }            
            }; 
            SP.UI.ModalDialog.showModalDialog(options);
        }

Clearing Person/Group Values

To clear out or empty the values in person or group columns, how you do it depends on if the column is single-value or multi-value. For ...