Archive

Posts Tagged ‘SharePoint 2013’

SharePoint online / SharePoint 2013: Sharing variable values between search control and display templates

November 29, 2017 Leave a comment

Recently I came across to a scenario where I need to set the variable in control template and the value of the variable should be accessible in item template and vice versa.
I was showing some data in item templates and using third party pagination for displaying the search result, needed the value of pagination size which is available in control template.
I tried with normal JavaScript variable but due to the scoping in display template it was not available for me inside the item template.
Solution 1:
We can use Windows.variable which is nothing but global variable creation on the scope of the window object and hence will be accessible throughout the scope of windows object.
Control Template:

<!--#_ window.PageSize = "30"; _#-->

Item Template:

<!--#_ alert(window.PageSize); _#-->

Solution 2:
Another better alternative is to use the built-in ctx object which is already shared between the control and item display template.
Control Template:

<!--#_ ctx.PageSize = "30"; _#-->

Item Template:

<!--#_ alert(ctx.PageSize); _#-->

Happy learning.

SharePoint 2013: Creating and calling custom JavaScript function in search display template

October 23, 2017 Leave a comment

Hi Friends,

Recently I came across a requirement where I need to create a custom JavaScript function which will change the date formatting on the provided string date parameter.

I tried creating normal JavaScript function in display template and tried calling it from other part of template but the function was undefined and not found inside the display template, I got little bit confused as I have created the JavaScript function in same display template but still not able to find it in same display template while calling. We can have couple of ways to resolve the issue.

Solution 1:

After some googling I found the cause of the issue and the solution as well, as follows.

The possible reason is scoping of the display template not allowing to consider external JavaScript function as a part of the scope to call inside display template.

The solution is to create new function on window scope and the call it in the desired place inside display template.

window.MyTestFunction = function(myParam)
{
// your own logic to work on the param 'myParam'
}

Calling the function:

<a style="cursor:pointer" onclick='window.MyTestFunction(3)'>Call My custom JS function</a>

Solution 2:

  1. Create a JavaScript file (MySampleJS.js) in the Display Templates/Search folder.
  2. Add the custom JS function in to the MySampleJS.js file.
  3. Add the following code into thetag below to include the JS file in display template
<script>
$includeScript(this.url, "~sitecollection/_catalogs/masterpage/Display Templates/Search/ MySampleJS.js");
</script>

Happy learning.

SharePoint 2013: Converting GMT/UTC time to local time in XSLT for rendering RSS feed

September 28, 2017 Leave a comment

Hi Friends,

Recently I came across the requirement where the date coming from RSS feed which is in GMT format needed to be converted to local time and display in required format.

As RSSAggregatorWebPart webparts executes on server side and renders the output html in browser, we cannot utilize the rss date to convert to local date.

I tried multiple solution with default XSLT for calling JavaScript function, like CDATA, xsl:comment and try adding script tag but none worked for me.

Finally after struggling I found a way to achieve desired result using onerror handler with img tag.

Solution as fallows –

XSLT changes

Add following section in XSLT, which actually uses the img tag to call the JavaScript function using on error event.

Rss1

JavaScript changes

Following function we needed to add a separate JS file which will be referred in the master page or add in master page itself and make sure it that JS method gets loaded before the method call in XSLT.

function ConverDateToLocal(pDate, sender) {
    try {
        var today = new Date(pDate);
        var dd = today.getDate();
        var mm = today.getMonth() + 1; //January is 0!
        var yyyy = today.getFullYear();
        var hh = today.getHours();
        var mmm = today.getMinutes();
        /*if(dd<10) {
            dd='0'+dd
        } 

        if(mm<10) {
            mm='0'+mm
        } */
        var restStr = dd + '.' + mm + '.' + yyyy + " " + hh + ":" + mmm;
        if (sender != null) {
        var senderid = sender.id;
        if (senderid) {
        var senderidsplit = senderid.split('_');
        if (senderidsplit.length > 0) {
                    var datedivid = "datediv_" + senderidsplit[1];
                    if (datedivid) {
                        var datediv = document.getElementById(datedivid);
                        if (datediv != null) {
                            datediv.innerHTML += " :: " + "New ::" + restStr;
			                // After testing folling code should be execuated
			                //datediv.innerHTML = restStr;
                        }
                    }
                }
            }
        }
    }
    catch(err) {}
}

After applying the XSLT we can see the output like following where first date is GST date and next date is converted local date.

RSS3

Happy coding.

SharePoint: How to check if page is in edit mode or not in JavaScript

August 28, 2017 Leave a comment

As SharePoint evolved and other client technologies started to become popular and independent we are achieving most of the solution with client side technologies like JavaScript, jQuery and other similar.

I came across one requirement while working on a JavaScript based component, where I need a conditional code to run only when my page is in edit mode. I found multiple solutions which I summaries below.

Option 1:

var inDesignMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;
if (inDesignMode == "1")
{
// page is in edit mode
}
else
{
// page is in browse mode
}

For Wiki pages

var wikiInEditMode = document.forms[MSOWebPartPageFormName]._wikiPageMode.value;
if (wikiInEditMode == "Edit")
{
// wiki page is in edit mode
}
else
{
// wiki page is not in edit mode
}

Option 2: Using SP.Ribbon.PageState.Handlers.isInEditMode()

ExecuteOrDelayUntilScriptLoaded(function(){
var InEditMode = SP.Ribbon.PageState.Handlers.isInEditMode();
if(InEditMode){
// page is in edit mode
}
}, 'SP.Ribbon.js');

Option 3: While checking the value in SharePoint search display template we need to use Srch.U.isPageInEditMode Method

var isRollupPageInDisplayMode = Srch.ContentBySearch.isRollupPage(ctx.ClientControl) && !Srch.U.isPageInEditMode();

Happy Learning!

SharePoint 2013: Newly created rendition not working

Recently I was facing an issue with newly created rendition, I created new rendition but the images are not showing the newly created rendition on my development server, also in image picker we not able to see the newly created rendition.

After waiting for some time as well my newly created rendition not worked. After some investigation we figured out that as renditions was previously working fine means blob cache working as expected but after adding new rendition we found that it was not working.

Solution:

We need to flush the blob cache using PowerShell.

$webApplication = Get-SPWebApplication "http://mytestdomain.com";
[Microsoft.SharePoint.Publishing.PublishingCache]::FlushBlobCache($webApplication);

After flushing the blob cache we are now able to see newly added rendition. For more details please check https://technet.microsoft.com/en-us/library/gg277249.aspx

Flush action will not be immediate, it will be queued.

Hope this will help, happy learning.

SharePoint 2013: Identifying the variation source and target with PowerShell

While working with one reporting requirement I needed to eliminate the variation targets and only need to consider variation sources. I struggled to find out the property which will help me to identify the page is variation source or target.

Solution:

Publishing web and Publishing page have the property called as ‘PublishingPage.Label.IsSource’ which we can use to identify the source page and source web. The same way we can use the publishing web level property as well.

if ([Microsoft.SharePoint.Publishing.PublishingWeb]::IsPublishingWeb($childWeb)){
 $spPubWeb =
 [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($childWeb);

 $item = $spPubWeb.PagesList.GetItemById($row.ID);
 $pubPage =
 [Microsoft.SharePoint.Publishing.PublishingPage]::GetPublishingPage($item);

 if($pubPage.VariationPageUrls.Count -eq 0)
 {
     #Page directly created in language sites and not Variated from source
 }
 else #Page Variated
 {
   if($pubPage.Label.IsSource) # then check if the web is Label IsSource
   {
     #this page is variation source
   }
 }
}

Hope this will help, happy learning.

SharePoint 2013: Make list tools appear again when added multiple web parts on allitems.aspx page

Recently while working with one of the requirement, I needed to add a content editor web part on Allitems.aspx page, I completed the requirement with adding the CE web part on the page but later testing team reported that the top level ‘list tools’ section is not appearing.

ListTools1

After some analysis I found the issue is nothing but default behavior, while allitems.aspx page is unmodified SharePoint knows that list tools section should be shown always and for the same list or library, when we add some other web part like content editor web part the SharePoint actually not able to understand where the focus currently on i.e. on Allitems web part or on the new web part we added.

Solution:

If customer is fine we can ask customer to click on the List Views web part, then customer will be able to see the list tools directly.

Other solution is to keep the focus on the List Views web part using JavaScript.

<script type="text/javascript">

ExecuteOrDelayUntilScriptLoaded(init_defaultWP, "sp.ribbon.js");

function init_defaultWP() {

setTimeout(function () {

var defaultWP = document.getElementById("MSOZoneCell_WebPartWPQ2");

WpClick({ target: defaultWP, srcElement: defaultWP });

SP.Ribbon.WebPartComponent.$3.deselectWebPartAndZone = function () { };

}, 100);

}

</script>

Happy learning.

SharePoint: Access denied error while calling web service from JavaScript

March 6, 2017 3 comments

Hi Friends,

I would like to share one very specific while calling web service from JavaScript, we were getting exception. Important point to note here is the code is working very fine if we access the page on server. But we are getting JavaScript ‘Error: Access is denied.’ Error while accessing the web page from client machine through browser.

error1

We are getting exception where we are calling the web service.

After some analysis the error came out as HTTP and HTTPS mixed content issue.

In our case HTTPS is configured on load balancer level and on ISS 7 level we have HTTP only hence web service call is working fine.

While accessing from outside URL is getting accessed only with HTTPS and non-secured request is also redirected with secured.

Problem fund that we have used ‘_spPageContextInfo.webAbsoluteUrl’ variable which is providing the HTTP path as SharePoint is unaware with existence of HTTPS as it is configured on load balancer level.

‘_spPageContextInfo.webAbsoluteUrl’ is supposed to give HTTPS path if HTTPS configured on ISS 7 level but as in our case SSL is configured on load balancer hence SharePoint is unaware about SSL.

Solution:

We have checked the protocol of the browser request using ‘document.location.protocol’ and if it is HTTPS then we replaced HTTP with HTTPS from the output of ‘_spPageContextInfo.webAbsoluteUrl’

change

This solution is working fine both in the case of HTTPS and HTTP.

Though this scenario is very specific but still this may help someone to understand the issue better.

SharePoint 2013: Modal Dialog position and scrolling issue with lengthy page

We have come across an issue with SharePoint modal dialog, while working with a lengthy page where due to some lengthy content vertical scroll bar were coming. We developed one web part form, which we have added at the center of the vertical screen. From that web part we can open a SharePoint Asset picker to select the image which opens a model dialog. The functionality was working as expected but we found an UI level issues.

Problem: When we try to launch SharePoint ‘Modal Dialog’ from the bottom of the huge scrolled page, we are not able to see the dialog and only see the bluer screen (overlay). The actual model dialog is getting opened at the top of the page and because of the current scroll position which is somewhere in between the screen or at the bottom, we are not able to see the popup.

Solution: The model dialog location is set by CSS class on the top of the screen, we need to override the css class to change the property. The name of the class is ms-dlgContent. We can add following css class in either master page or respective CSS.

.ms-dlgContent
{
position:fixed! important;
}