Tuesday, August 8, 2017

How To CheckIn And CheckOut a SharePoint page using JavaScript(JSOM)

Hi Friends,

Recently I have come across a requirement where I need to update the properties of a Sharepoint page. In this post we are going to see how to checkin and checkout a page in sharepoint using JSOM.
Below are the code snippets.

CheckOut:
function checkOut(){
        var ctx = SP.ClientContext.get_current();
        var page = ctx.get_web().getFileByServerRelativeUrl(window.location.pathname);
        //you can use any path. Here I am using current page.
        page.checkOut();
        ctx.load(page);
        ctx.executeQueryAsync(Function.createDelegate(this, checkOut_Success),
                                            Function.createDelegate(this, checkOut_Fail));
}
function checkOut_Success(sender, args){
 alert("Checked Out");
//do your actions
}
function checkOut_Fail(sender, args){
   alert("Fail checkout");
}

CheckIn:
function checkIn(){
         var ctx = SP.ClientContext.get_current();
        var web = ctx.get_web();
        var page = web.getFileByServerRelativeUrl(window.location.pathname);   
        //you can use any path. Here I am using current page.  
        page.checkIn();
        page.publish();
        ctx.executeQueryAsync(Function.createDelegate(this, checkIn_Success),
                                            Function.createDelegate(this, checkIn_Fail));
}
function checkIn_Success(sender, args){       
    alert(" checked in "); 
}
function checkIn_Fail(sender, args){   
    alert("Fail  checked in "+args.message);
}

Hope this helps...

Monday, August 7, 2017

How to Copy/Move a SharePoint Page/File from one location to another using Javascript

Hi Friends,

In this blog we are going to see How to copy or move a sharepoint Page/File from one location to the other using Javascript.

By default SP.js in SharePoint provides the following functions through which we can perform this activity with the minimal coding effort.

SP.MoveCopyUtil.copyFile
SP.MoveCopyUtil.moveFile

Copy a Sharepoint File/Page:
In the below code snippet we are copying the home.aspx present in pages library to the Folder called "duplicate" under the same pages library.

In order to achieve it, we will be using the function SP.MoveCopyUtil.copyFile which expects the below parameters

1)Current context
2)Source url – Full url of the file/page.
3)Destination url – Full destination url of the file/Page.

Code snippet:
var current_context = SP.ClientContext.get_current();
SP.MoveCopyUtil.copyFile(current_context,"https://siteurl/pages/home.aspx","http://siteurl/Pages/duplicate/home.aspx");
current_context.executeQueryAsync(function(){ PageCopySuccess(); },function(){ PageCopyFailure(); });

function PageCopySuccess(){
alert('Success');
}

function PageCopyFailure(){
alert('Failed');
}


Move a Sharepoint File/Page:
In the below code snippet we are moving the home.aspx present in pages library to the sitepages page library.

In order to achieve it, we will be using the function SP.MoveCopyUtil.moveFile which expects the below parameters

1)Current context
2)Source url – Full url of the file/page.
3)Destination url – Full destination url of the file/Page.

Code snippet:
var current_context = SP.ClientContext.get_current();
SP.MoveCopyUtil.moveFile(current_context,"https://siteurl/pages/home.aspx","http://siteurl/sitepages/home.aspx");
current_context.executeQueryAsync(function(){ PageMoveSuccess(); },function(){ PageMoveFailure(); });

function PageMoveSuccess(){
alert('Success');
}

function PageMoveFailure(){
alert('Failed');
}

Hope this helps...


Thursday, March 23, 2017

Structural Navigation vs Managed Navigation in SharePoint

Hi Friends,

In this post we are going to learn about the navigation options present in SharePoint Online.

Below are the two main out of the box navigation options in SharePoint
1) Structured Navigation
2) Managed Navigation

What is Structured Navigation?
This is SharePoint out of the box navigation used by default and it is based on the site structure we define for our portal.

Below are some of the advantages and disadvantages using Structured Navigation.
PROS
CONS
  • Navigation will be updated automatically whenever Sites are added.
  • Easy to configure.
  • Pages are automatically added.
  • Security trimmed, so if a user doesn’t have access to a link it will not appear in the top navigation.

  • Slower performance with complex navigation structure having more than 10 levels.
  • URLs are not friendly and can be hard to memorize.
  • Homepages belonging to structured navigation links do not appear in search when you type a search term.
  • Cannot tag a structured navigation link to a document that it may relate to.


What is a Managed Metadata Navigation?
Managed Metadata is a hierarchical collection of centrally managed terms that we can define, and then use as attributes. It uses a dedicated term set for site navigation and the terms correspond to the friendly URL segment created.

Below are some of the advantages and disadvantages using Managed Navigation
PROS
CONS
  • Easy to maintain.
  • Significantly faster page loads.
  • Pages with term show up in search results.
  • Documents tagged with navigation term show up in search results along with homepage of term.
  • Friendly URLs that are easy to remember.
  • Easy to maintain with more options to target search.
  • Pages are automatically added.

  • Not security trimmed, so if a user doesn’t have access to a link in the top navigation they will still see it but can’t get to it.
  • Sites are not automatically added.
  • Cannot be used across site collections.


Hope this helps...

Tuesday, March 21, 2017

How to create thumbnail/preview of any document or Image or Video in SharePoint

Hi Friends,

In this post, we are going to learn how to generate a thumbnail/preview of any Document or Video or Image in SharePoint.

Recently I came across a requirement to show some document links on a page but the links should be the thumbnail of the document instead of a plain text(document title). Please find the below approach I followed to achieve this.

getpreview.ashx is a http handler used to generate thumbnail/preview of any document(word,pdf, ppt etc.,), Image and Video which resides in SharePoint.

If you observe in SharePoint search results, when we mouse over on the search results we get a preview of that item. This is actually happening through http handler getpreview.ashx

This handler expects a parameter called “path” which expects absolute path of the doc/image/video. Please find the below sample URLs to generate the thumbnail.

Image:

Document:

Video:

This handler has also expects a parameter called “resolution” which has a predefined values 1, 2, 3 etc., for different resolutions of previews/Thumbnails. Please find the below sample URLs with different resolutions



Hope this helps…

Wednesday, March 15, 2017

How to use Image Renditions in SharePoint

Hi Friends,
In this post we are going to learn What are the Image Renditions and how we can use it in SharePoint.

Image renditions helps to display a single image into various sizes based on our needs. Apart from choosing size, it also allows you to crop the image while adding it to the publishing page.

So based on our needs, we can display abcd.jpg as Logo, Banner and Thumbnail etc., This technique helps in reducing the size of the file that is downloaded to the client, which then improves site performance. You can find some of the ways to improve SharePoint site speed and performance here.

The other advantage if you notice, we need not to create different sized images i.e., one for logo, one for thumbnail etc.,. With Image renditions we can display a single image into multiple sizes.

Below are the prerequisites for using Image Renditions 
  •  Publishing Site
  • BLOB Caching enabled(Follow this link on how to configure BLOB cache and its uses)



Please find the below steps on how we can configure Image Renditions.

1.     Go to the top-level site of the publishing site collection.

2.    Choose the Settings icon. On the Site Settings page, in the Look and Feel section,  choose Image Renditions.

3.    This will show you list of available Image Renditions available on this site. We can  modify the existing one, Or we can even create our own based on required dimensions.



          4.       ID indicates the RenditionID. We will be using this RenditionID as a parameter to                       specify the dimensions of an image we need.

         5.       If we want to construct image URL directly from the RenditionID, we just need to                  add it as a  Query String.

Examples: If we want display abcd.jpg as 100*100 on a page, then my image source URL will be “abcd.jpg?RenditionID=1
If we want display abcd.jpg as 200*200 on a page, then my imgage source URL will be “abcd.jpg?RenditionID=2”

        6.       If we want to insert the image in the page content then follow the below steps. 
a)     Edit the page and place the cursor in the Page Content field.

b)    From the Ribbon Insert tab, choose Picture, and then choose From    SharePoint.

c)     Select the image that you want to add to the page and then choose Insert. The image will be displayed at full size.

d)    Next on the Design tab, in the Select group, choose Pick Rendition, and then select an  image rendition whichever required. That’s it, the image will display according to the size  specified for the image rendition.

Hope this helps... 

Tuesday, March 14, 2017

What is a BLOB cache in SharePoint and how to use it?

Hi Friends,

In this article, we are going to learn what is a BLOB cache and how to configure it.

The term BLOB means Binary Large Objects. BLOB cache is one of the disk-based caching techniques used in the SharePoint applications which has large amounts of Media content (Video, Audio and Images etc.,) and heavy user traffic.

So basically this method is used to improve the performance of a SharePoint Application. You can also find some of the other SharePoint performance improvement techniques here.

Disk-based caching techniques are extremely fast which eliminates the need for database round trips. BLOBs are retrieved from the database once and stored on the Web client(WFE server). Further requests are served from the cache and trimmed based on security.

Note: If you are using Image Renditions in the application, then BLOB Cache is the pre-requisite.

We can enable/disable the BLOB cache by modifying the web.config file of the SharePoint web application.
By Default, BLOB cache is disabled. Below is how it looks like.

<BlobCache location="C:\blobCache" path="\.(gif|jpg|png|css|js)$" maxSize="10" enabled="false" />

- Location is the directory where the cached files will be stored.
- Path specifies which files(Ex: mov|mp3|mp4|mpeg|mpg) are cached based on the file extension.
- maxSize is the maximum allowable size of the disk-based cache in gigabytes.

- enabled is a Boolean that disables or enables the cache.

To turn ON the BLOB, just make the property enabled as true as shown below.

<BlobCache location="C:\blobCache" path="\.(gif|jpg|png|css|js)$" maxSize="10" enabled="true" />

Note : change the location attribute to specify a directory that has enough space to accommodate the cache size.


Hope this helps...

Monday, March 13, 2017

What is the difference between Local Storage and Cookies

Hi Friends,

In this post we are going to talk about when to use Local storage and Cookies.

To begin with, this is an extremely broad scope question, and a lot of pros/cons will be contextual to the situation.

Please find the below differences.


Local Storage
Cookies
Good to store large amount of data, up to 4MB
Good for small amount of data.
Cookies give you a limit of 4096 bytes (4095, actually) per cookie
Local Storage allow you to store JavaScript primitives but not Objects or Arrays (it is possible to JSON serialize them to store them using the APIs)
Cookies only allow you to store strings
Local storage data is not sent to the server on every request (HTTP header) as it is purely at the client side
All data is transferred to and from server, so bandwidth is consumed on every request
It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data
Can specify timeout period so that cookies data are removed from browser
Local storage stores the data in the form of key and value

Not supported by anything before: IE 8, Firefox 3.5, Safari 4, Chrome 4, Opera 10.5, iOS 2.0, Android 2.0
local storage can only be read client-side



Hope this helps...

Friday, March 10, 2017

When to use ScriptLink in SharePoint 2013

Hi Folks,

Some times we will run into situations where our custom js file should load only after the page is ready.

In this kind of scenario's, best thing to use is ScriptLink.

ScriptLink have the ability to specify, when we want the script to load asynchronously after the page is ready. By Default, the ScriptLink will always look for the scripts present in /_LAYOUTS/1033 folder.

<SharePoint:ScriptLink language="javascript" name="MyCustomJS.js" Defer="true" runat="server"></SharePoint:ScriptLink>

MyCustom.js should be present in /_LAYOUTS/1033 folder, if not we will get a SharePoint Error screen.

If you set the "Localizable" property of the ScriptLink to false, you can also reference files outside of /_LAYOUTS/1033/ and just put your path to the "Name" property

<SharePoint:ScriptLink Language="javascript" Localizable="false" Name="/_layouts/JS/MyCustomJS.js" runat="server"></SharePoint:ScriptLink>

With the above approaches, we can load the page first and then load the script file.

Note: Using Defer="False" is basically the same as loading the script with the usual method as below.
<script type="text/javascript" src="/_layouts/1033/MyCustomJS.js"></script>


Hope this helps...

Wednesday, March 8, 2017

Why Javascript works only after launching developer tool bar in IE once

Hi Friends,

This post basically talks about the strange experience which I faced in one of the applications.

Problem Statement:
In Internet Explorer, the Javascript/jQuery is not working until I open the IE Tool bar once.


Solution:
After multiple trial and errors, what I observed is, it's because of the console.log present in my jQuery file.

The console object will only be activated when the IE Dev Toolbar is opened. Prior to that, calling the console object will result as undefined. After the toolbar has been opened, the console will exist (even if the toolbar is subsequently closed), so your console calls will then work.


Hence make sure to remove any Console entries from the JS file during the roll-out of the application.


Hope this helps...

Thursday, February 23, 2017

SharePoint 2010/2013 Display user information using ProfilePropertyLoader

Hi Folks,

This article talks about the best way to get the user profile properties on page.

Sometimes we come across the requirement asking to show the User related information on the page.
Generally we write code by accessing User Information list to get the User related data.

In such cases, rather than writing code SharePoint gives us the provision to read the User data.

SharePoint has something called "ProfilePropertyLoader" control which will be available in any SharePoint page which has the below register tag.

<%@ Register Tagprefix="SPSWC" Namespace="Microsoft.SharePoint.Portal.WebControls" Assembly="Microsoft.SharePoint.Portal, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

Follwing are the tags we need to add to the page inoder to read the current user Name and Email.

User Name
The first line below is needed to load and make the profile properties available.

<SPSWC:ProfilePropertyLoader runat="server"/>

<SPSWC:ProfilePropertyValue PropertyName="FirstName" ApplyFormatting="False" runat="server" ShowPrivate="True" PrefixBrIfNotEmpty="False"/>

<SPSWC:ProfilePropertyValue PropertyName="LastName" ApplyFormatting="False" runat="server" ShowPrivate="True" PrefixBrIfNotEmpty="False"/>

Email
<SPSWC:ProfilePropertyValue cssClass="loggedin" PropertyName="WorkEmail" ApplyFormatting="False" runat="server" ShowPrivate="True" PrefixBrIfNotEmpty="False"/>


Hope this helps...

RELATED POST: How to get current user info using jquery spservices



SharePoint site performance improvement techniques - SharePoint2010/2013 and SharePoint Online

Hi Friends,

In this article we will talk about the Steps to Optimize SharePoint Performance.

This article covers some of the factors which plays a vital role in the performance of the SharePoint site on a high level.

1)    Code optimization


  •  Server side code - Use optimized methods, SPDisposeCheck etc.,


Poor Performing Methods and Properties
Better Performing Alternatives
SPList.Items.Count
SPList.ItemCount
SPList.Items.XmlDataSchema
Create an SPQuery object to retrieve only the items you want.
SPList.Items.NumberOfFields
Create an SPQuery object (specifying the ViewFields) to retrieve only the items you want.
SPList.Items[System.Guid]
SPList.GetItemByUniqueId(System.Guid)
SPList.Items[System.Int32]
SPList.GetItemById(System.Int32)
SPList.Items.GetItemById(System.Int32)
SPList.GetItemById(System.Int32)
SPList.Items.ReorderItems(System.Boolean[],System.Int32[],System.Int32)
Perform a paged query by using SPQuery and reorder the items within each page.
SPFolder.Files.Count
SPFolder.ItemCount


  • CSOM - Keep ExecuteQuery function call as less as possible.
Also request properties whichever required. Ref below example

var userObj = clientContext.Web.CurrentUser;
clientContext.Load(userObj, user => user.Title, user => user.LoginName);




  • Use caching in Code (Both CSOM and Server Side). Use the cache duration depends on how often the block of code changes the data.

2)    Merge JS files to single wherever possible.

3)    Make JS files to minified (min) files.

4)    Reduce the usage of global variables in JS files.

5)    Merge CSS files to single wherever possible.

6)    Use CDN(Content Deployment Network) deployment of JS, CSS and Images.

Note: Using CDNs only makes sense in a SharePoint Online context and should be avoided with SharePoint Server.


Hope this helps...

Wednesday, February 22, 2017

Scroll to top of the page after Pagination or Refinement in SharePoint 2013 search results

Hi Friends,

In SharePoint out of the box search results, the paging control will be under the Search results. In this case, whenever there is paging happened the SharePoint will keep the page remained at the bottom though it moved to next set of results. This make users to scroll up the page in order to see the next set of results.


We can overcome this approach using "ScrollToTopOnRedraw” property in Search results webpart. This is a hidden property which will not be visible in Edit webpart properties UI. However this change can be done by modifying the  .webpart file.

"ScrollToTopOnRedraw" is a boolean property which is false by default and all we need to do is, setting this property true.

Please find the below steps

1) Export your current search results webpart to get .webpart file

2) Open it in a text editor or Notepad

3) Find the property “ScrollToTopOnRedraw” and change its value from False to True and Save the file.

4) Import the webpart and add it in your page.

Thats All. The page scrolls to top whenever there is pagination or refinement.

Hope this helps...

Open and Close a SharePoint modal dialog with HTML structure

HI Friends,

In this post we are going look at How to Open and Close a SharePoint Modal Dialog using HTML instead of webpage.

Generally we use SharePoint modal dialog in order to call a webpage as pop-in. But, in this post we are going to open a DIV as a pop-in using SharePoint modal dialogue SP.UI.ModalDialog.showModalDialog

Note: You can open any HTML structure as per your needs.

Please use the below code snippet which does this trick.

function OpenModaldialog() {
  SP.SOD.executeOrDelayUntilScriptLoaded(function () {
    var element = document.createElement('div');
    element.innerHTML = '<div id="modalcontent">This is modal dialogue cocntent</div>';

    SP.UI.ModalDialog.showModalDialog({
     html: element,
     title: 'Dialogue box',
     allowMaximize: false,
     showClose: true,
     dialogReturnValueCallback : Function.createDelegate(null, CloseCallback),
     autoSize: true
    });
   }, "SP.js");
}

function CloseCallback(result, target) {
   //custom action if any
}

That's it, you just need to call the function OpenModaldialog(); on the onclick event of the button through which you want to launch the modal dialogue.

Hope this helps...

RELATED POST: How to Show and Hide a Modal Pop up Dialog in a SharePoint
RELATED POST: How to Open and Close a jquery dialog popup

Popular Posts