Display attachments using JSLink in SharePoint

Recently I had a requirement where the customer wanted to show the actual attachment’s URL in the list view instead of default Icon. Following JSLink code will help to do that.

(function () {
    var linkFiledContext = {};
    linkFiledContext.Templates = {};
    linkFiledContext.Templates.Fields = {
        "Attachments": { "View": OverrideAttachmentFieldRendering }
    };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(linkFiledContext);
})();

function OverrideAttachmentFieldRendering(ctx) {
    var itemId = ctx.CurrentItem.ID;
    var listName = ctx.ListTitle;
    return GetAttachments(listName, itemId);
}

function GetAttachments(listName, itemId) {
    var url = _spPageContextInfo.webAbsoluteUrl;
    var requestUri = url + "/_api/web/lists/getbytitle('" + listName + "')/items(" + itemId + ")/AttachmentFiles";
    var htmlString = "<span style='white-space: nowrap;'>No attachment(s)</span>";

    $.ajax({
        url: requestUri,
        type: "GET",
        headers: { "ACCEPT": "application/json;odata=verbose" },
        async: false,
        success: function (data) {
            for (var i = 0; i < data.d.results.length; i++) {
                htmlString += "<a style='white-space: nowrap;'  href='" + data.d.results[i].ServerRelativeUrl + "'>" + data.d.results[i].FileName + "</a>";
                if (i != data.d.results.length - 1) {
                    htmlString += "<br/>";
                }
            }
        },
        error: function (error) {
            console.log("An error occured while fetching attachment details. Details: " + JSON.stringify(error))
        }
    });

    return htmlString;
}

Source: https://social.msdn.microsoft.com/Forums/office/en-US/29f7998f-ffc5-4877-b975-a49631b53ba2/show-attachments-with-jslink?forum=sharepointdevelopment

Change SharePoint’s “there are no items to show in this view” message

When a list has not data to be shown in the view, we see the following message.

There are no items to show in this view of the “<ListName>” list.

The following JSLink script helps to change this message.

(function () {
    var overrideCurrentContext = {};
    overrideCurrentContext.Templates = {};
    overrideCurrentContext.Templates.OnPreRender = changeNoListItemMessage; //OR overrideCurrentContext.OnPreRender = changeNoListItemMessage;
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCurrentContext);
})();

function changeNoListItemMessage(ctx) {
    ctx.ListSchema.NoListItem = "No data";
}

Source: http://www.idubbs.com/blog/2015/jslink-csr-to-override-there-are-no-items-to-show-in-this-view/

Displaying SharePoint user presence indicator in CSR

The following are code snippets which can be used to show a user’s Lync/Skype for Business presence status in SharePoint Client Side Rendering (CSR).

Default Render

<span>
    <span class="ms-imnSpan">
        <a href="#" onclick="IMNImageOnClick(event);return false;" class="ms-imnlink ms-spimn-presenceLink">
            <span class="ms-spimn-presenceWrapper ms-imnImg ms-spimn-imgSize-10x10">
                <img name="imnmark" title="" ShowOfflinePawn="1" class="ms-spimn-img ms-spimn-presence-disconnected-10x10x32" src="/_layouts/15/images/spimn.png?rev=23" alt="User Presence" sip="user@domain.com" id="imn_1,type=sip"></img>
            </span>
        </a>
    </span>
    <span>
        <a href="#" onclick="IMNImageOnClick(event);return false;" class="ms-imnlink" tabIndex="-1">
            <img name="imnmark" title="" ShowOfflinePawn="1" class=" ms-hide" src="/_layouts/15/images/spimn.png?rev=23" alt="User Presence" sip="user@domain.com" id="imn_2,type=sip"></img>
        </a>
        <span>User</span>
    </span>
</span>

With Picture Detail View

<div>
    <div class="ms-tableRow">
        <div>
            <span class="ms-imnSpan">
                <a href="#" onclick="IMNImageOnClick(event);return false;" class="ms-imnlink ms-spimn-presenceLink">
                    <span class="ms-spimn-presenceWrapper ms-imnImg ms-spimn-imgSize-10x10">
                        <img name="imnmark" title="" ShowOfflinePawn="1" class="ms-spimn-img ms-spimn-presence-disconnected-10x10x32" src="/_layouts/15/images/spimn.png?rev=23" alt="User Presence" sip="user@domain.com" id="imn_661,type=sip"></img>
                    </span>
                </a>
            </span>
        </div>
        <div class="ms-tableCell ms-verticalAlignTop">
            <div class="ms-peopleux-userImgDiv">
                <span class="ms-imnSpan">
                    <a href="#" onclick="IMNImageOnClick(event);return false;" class="ms-imnlink" tabIndex="-1">
                        <img name="imnmark" title="" ShowOfflinePawn="1" class="ms-hide" src="/_layouts/15/images/spimn.png?rev=23" alt="User Presence" sip="user@domain.com" id="imn_3452,type=sip"></img>
                    </a>
                    <span>
                        <img style="width:62px; height:62px; border:none" src="http://userimageurl" alt="User"></img>
                    </span>
                </span>
            </div>
        </div>
        <div class="ms-tableCell ms-peopleux-userdetails ms-noList">
            <ul style="max-width:150px">
                <li>
                    <div class="ms-noWrap">
                        <span>
                            <a href="#" onclick="IMNImageOnClick(event);return false;" class="ms-imnlink" tabIndex="-1">
                                <img name="imnmark" title="" ShowOfflinePawn="1" class="ms-hide" src="/_layouts/15/images/spimn.png?rev=23" alt="User Presence" sip="user@domain.com" id="imn_34523,type=sip"></img>
                            </a>
                            <span>User</span>
                        </span>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</div>

With Picture

<div>
    <div>
        <span>
            <a href="#" onclick="IMNImageOnClick(event);return false;" class="ms-imnlink" tabIndex="-1">
                <img name="imnmark" title="" ShowOfflinePawn="1" class="ms-hide" src="/_layouts/15/images/spimn.png?rev=23" alt="User Presence" sip="user@domain.com" id="imn_1,type=sip"></img>
            </a>
            <span>
                <img style="width:62px; height:62px; border:none" src="http://userimageurl" alt="User"></img>
            </span>
        </span>
    </div>
    <div class="ms-floatLeft ms-descriptiontext">
        <span class="ms-verticalAlignTop ms-noWrap ms-displayInlineBlock">
            <span class="ms-imnSpan">
                <a href="#" onclick="IMNImageOnClick(event);return false;" class="ms-imnlink ms-spimn-presenceLink">
                    <span class="ms-spimn-presenceWrapper ms-imnImg ms-spimn-imgSize-10x10">
                        <img name="imnmark" title="" ShowOfflinePawn="1" class="ms-spimn-img ms-spimn-presence-disconnected-10x10x32" src="/_layouts/15/images/spimn.png?rev=23" alt="User Presence" sip="user@domain.com" id="imn_2,type=sip"></img>
                    </span>
                </a>
            </span>
            <span class="ms-noWrap ms-imnSpan">
                <a href="#" onclick="IMNImageOnClick(event);return false;" class="ms-imnlink" tabIndex="-1">
                    <img name="imnmark" title="" ShowOfflinePawn="1" class="ms-hide" src="/_layouts/15/images/spimn.png?rev=23" alt="User Presence" sip="user@domain.com" id="imn_3,type=sip"></img>
                </a>
                <span>User</span>
            </span>
        </span>
    </div>
</div>

Presence Only

<span class="ms-imnSpan">
    <a href="#" onclick="IMNImageOnClick(event);return false;" class="ms-imnlink ms-spimn-presenceLink">
        <span class="ms-spimn-presenceWrapper ms-imnImg ms-spimn-imgSize-10x10">
            <img name="imnmark" title="" ShowOfflinePawn="1" class="ms-spimn-img ms-spimn-presence-disconnected-10x10x32" src="/_layouts/15/images/spimn.png?rev=23" alt="User Presence" sip="user@domain.com" id="imn_1,type=sip"></img>
        </span>
    </a>
</span>

Picture Only

<div>
    <div>
        <div class="ms-tableCell">
            <span class="ms-imnSpan">
                <a href="#" onclick="IMNImageOnClick(event);return false;" class="ms-imnlink ms-spimn-presenceLink">
                    <span class="ms-spimn-presenceWrapper ms-spimn-imgSize-8x72">
                        <img name="imnmark" title="" ShowOfflinePawn="1" class="ms-spimn-img ms-spimn-presence-disconnected-8x72x32" src="/_layouts/15/images/spimn.png?rev=23" alt="User Presence" sip="user@domain.com" id="imn_1,type=sip"></img>
                    </span>
                </a>
            </span>
        </div>
        <div class="ms-tableCell ms-verticalAlignTop">
            <div class="ms-peopleux-userImgDiv">
                <span class="ms-imnSpan">
                    <a href="#" onclick="IMNImageOnClick(event);return false;" class="ms-imnlink" tabIndex="-1">
                        <img name="imnmark" title="" ShowOfflinePawn="1" class="ms-hide" src="/_layouts/15/images/spimn.png?rev=23" alt="User Presence" sip="user@domain.com" id="imn_2,type=sip"></img>
                    </a>
                    <span class="ms-peopleux-imgUserLink">
                        <span class="ms-peopleux-userImgWrapper" style="width:72px; height:72px">
                            <img style="min-width:72px; min-height:72px; clip:rect(0px, 72px, 72px, 0px); max-width:72px" src="http://userimageurl" alt="User"></img>
                        </span>
                    </span>
                </span>
            </div>
        </div>
    </div>
</div>

Source: http://www.sharepointcolumn.com/lync-presence-indicators-code-snippets-in-sharepoint-2013/

Remove duplicate list items from SharePoint REST call result using JavaScript

The following code snippet show how to remove duplicate list items in the JSON result of a SharePoint REST call using JavaScript.

Function Definition:

function RemoveDuplicateItems(items, propertyName) {
    var result = [];
    if (items.length > 0) {
        $.each(items, function (index, item) {
            if ($.inArray(item[propertyName], result) == -1) {
                result.push(item);
            }
        });
    }
    return result;
}

Function Usage:
In the below code, assumption is that, the REST call returns data.d.results and the column for which duplicate items need to be removed is Title

var items = data.d.results;
items = RemoveDuplicateItems(items, 'Title');

 

Pass multiple parameters in SetTimeout JavaScript Function

Following is a code snippet which show how to pass multiple parameters in JavaScript’s SetTimeout() function.

setTimeout(function () {
    CustomFunction(param1, param2, param3, param4, param5);
}, 1000);

JSLink URL Tokens in SharePoint

Following are some of the JSLink URL Tokens I have come across in SharePoint.

  • ~site – reference to the current SharePoint site (or “Web”)
  • ~sitecollection – reference to the current SharePoint site collection (or “Site”)
  • ~layouts – version specific reference to the web application Layouts folder (so it will automatically swap out /_layouts/14 or /_layouts/15 for you)
  • ~sitecollectionlayouts – reference to the layouts folder in the current site collection (e.g. /sites/team/_layouts/15)
  • ~sitelayouts – reference to the layouts folder in the current site (e.g. /sites/teams/subsite/_layouts/15)

Few Examples:

~sitecollection/_catalogs/masterpage/
~site/siteassets/
~layouts/reputation.js

Source: https://www.martinhatch.com/2013/08/jslink-and-display-templates-part-1.html

Load scripts in SharePoint within custom Javascript or Workflow

Following is the code which can be used to load JavaScript in sequence.

This code for example loads the reputation.js from SharePoint’s layouts folder & jQuery from site assets.

(function () {
    ExecuteOrDelayUntilScriptLoaded(function () {
        //sp.runtime.js has been loaded
        ExecuteOrDelayUntilScriptLoaded(function () {
            //sp.js has been loaded
            SP.SOD.registerSod('reputation.js', SP.Utilities.Utility.getLayoutsPageUrl('reputation.js'));
            SP.SOD.registerSod('jquery-3.2.1', '../SiteAssets/Scripts/jquery-3.2.1.min.js');
            SP.SOD.loadMultiple(['reputation.js', 'jquery-3.2.1'], function () {
                //reputation.js & jquery-3.2.1.min.js have been loaded.
                var context = SP.ClientContext.get_current();
                var web = context.get_web();
                //Check if jQuery has been loaded
                if (typeof jQuery != 'undefined') {
                    console.log("Jquery is loaded");
                }
                else {
                    console.log("Jquery is not loaded!");
                }
            });
        }, "sp.js");
    }, "sp.runtime.js");
})();

Source: https://sharepoint.stackexchange.com/questions/92082/uncaught-typeerror-cannot-read-property-get-current-of-undefined

Setting up Node.js & NPM on a machine without administrative privileges and behind a corporate proxy

Recently I was trying to setup a development machine at our office and realized few issues.

  1. The machine didn’t have administrative privileges
  2. It was located behind the corporate proxy
  3. It uses Windows 10 as primary OS

So how to proceed? Following is what I did.

[Update: Now node.js includes npm, so I would suggest to download only node.]

Downloading Node.js & NPM

  1. Download the Node.js binary instead of installer from the below URLs

Node.js binary (32bit or 64 bit): https://nodejs.org/en/download/

  1. Download NPM binary release from the url below

NPM Release: https://github.com/npm/npm/releases

  1. Extract Node.js to D:\Development\Node
  2. Extract NPM to D:\Development\NPM

Set up environment

Every time the development environment is booted do the following

  1. Start a command prompt and set the following path
set PATH=%PATH%;D:\Development\Node;D:\Development\Node\node_modules\npm\bin;
  1. Check the Node version by typing the following
node -v
  1. Check the NPM version by typing the following
npm -v

If you get version numbers for both then both are working.

  1. Now set proxy so that NPM can download modules by running the following
set http_proxy=http://replace-with-your-organization-proxy-url:optional-port-number
set https_proxy=https://replace-with-your-organization-proxy-url:optional-port-number
npm config set strict-ssl false
npm config set proxy http://replace-with-your-organization-proxy-url:optional-port-number
npm config set https-proxy https://replace-with-your-organization-proxy-url:optional-port-number

Now the environment is set up.
Do remember, once the console is closed, all the above settings are lost and needs to be run again, just follow the section “Set up environment” again or do the following.

You can set up the “path” variable without administrator privileges in Windows by doing the following.

  1. From Windows’s Start Menu, open Control Panel.
  2. In Control Panel open “User Accounts”.
  3. In ‘User Accounts” open “Change my environment variables”.
  4. This will open the user’s “Environment Variables” window.
  5. Select the row with entry “Path”.
  6. Click “Edit” button.
  7. In the “Variable value:” text box, append the path of your executable location, which in this case is “D:\Development\Node;D:\Development\Node\node_modules\npm\bin;
  8. Click OK
  9. Open a new terminal or console
  10. Type “node -v” to check if node is working fine.
  11. type “npm -v” to check if npm is working fine.

Source URLs:
http://abdelraoof.com/blog/2014/11/11/install-nodejs-without-admin-rights
http://www.kscodes.com/misc/how-to-set-path-in-windows-without-admin-rights/