Search This Blog

Thursday 27 February 2014

Dialog Modal in SharePoint 2013

function OpenPopUpPage(url, callback, width, height)
#
function OpenPopUpPageWithTitle(url, callback, width, height, title)
#
function OpenPopUpPageWithDialogOptions(dialogOptions)
E.g.,
 <a href="javascript:OpenPopUpPageWithTitle('http://example.com/Pages/another.aspx',null,null,null,'Advanced Search - Tips');">Advanced Search Tips</a>


Reference:
http://wp.ahcheng.com/2013/04/09/calling-dialog-modal-form-in-sharepoint-2013/

Thursday 13 February 2014

Open list item attachments with a click on the paperclip

All you have to do is uploading this script to the Style Library (or any other document libary, SVN or the Hive )  and putting the following snippet into a CEWP or Script Editor Web Part on the page where you want to to have this functionality.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="..location of the script here../ListAttachments.js" type="text/javascript"></script>
<script type="text/javascript">
var argObj = {hideIdColumn:true,
              clickToOpen:false,
              clickMouseover:'Click to open',
              oneClickOpenIfSingle:true};
</script>
Please note: To make this script work, your list view has to have the ID column as well as the attachment column visible.

The four options you can see in the snippet above are as follows:

1.hideIdColumn: Defines whether the ID column will be hidden or not
2.clickToOpen: Defines whether you have to click in the paperclip in order to see the list of attached files or not
3.clickMouseOver: Defines the text in the tooltip when you hover your mouse over the paperclip
4.oneClickOpenIfSingle: Defines if an attachment is directly opened or not if it is the only attachment of the list item

=================================================================
ListAttachments.js
=================================================================


/* List all attachments when clicking the paperclip
 * ---------------------------------------------
 * Created by Alexander Bautz
 * alexander.bautz@gmail.com
 * http://sharepointjavascript.wordpress.com
 * Copyright (c) 2010-2012 Alexander Bautz (Licensed under the MIT X11 License)
 * v1.7 for SharePoint 2010
 * LastMod: 05.06.2012
 * ---------------------------------------------
 * Include reference to:
 *  jquery - http://jquery.com
 * ---------------------------------------------
 * Place code in a CEWP below the list view
*/

/*
 * Edited by Daniel Stoelzner
 * daniel.stoelzner@gmail.com
 * http://spoodoo.com
 * LastMod: Febraury 12th 2014
 * Change: Added compatibility with SharePoint 2013
*/

var argPlaceholder;

jQuery(document).ready(function(){
   customListAttachments(argObj);
})

function customListAttachments(argObj){
 var thisWPContainer, isListView, intName, thisListCTX, thisRow, idColIndex, attcolIndex; 
 if(argPlaceholder===undefined){
  argPlaceholder = argObj;
 }else{
  argObj = argPlaceholder;
 }
 $("div[id^='WebPartWPQ']").each(function(){
  thisWPContainer = $(this);
  isListView = false;
  thisWPContainer.find(".ms-viewheadertr th").each(function(i){  
   intName = $(this).find('div:first').attr('name');
   if(intName=='ID'){
    thisWPContainer.data("idColIndex",this.cellIndex);
    thisWPContainer.data("ctxNum",$(this).find('div:first').attr('CtxNum'));
    // Hide ID column
    if(argObj.hideIdColumn){
     $(this).addClass('dummyHideClass');
    }
   }else if(intName=='Attachments'){
    isListView = true;
    thisWPContainer.data("attcolIndex",this.cellIndex);
   }
  });
  if(!isListView){
   return;
  }
  //if(thisWPContainer.data("idColIndex")==undefined && location.href.match(/ShowInGrid=True/)==null && isListView){
  // alert("The ID column must be in the view.\nYou may hide it in the script call by setting the argument \"hideIdColumn\" to true.");
  //}
  thisListCTX = thisWPContainer.data("ctxNum");
  if(thisListCTX!==undefined){
   thisListCTX = eval("ctx"+thisListCTX);
  } else {
   return;
  }
  
  
  thisWPContainer.find("table.ms-listviewtable tbody[beenthere!=1]").each(function(){  
   // Prevent processing of the same tbody multiple times   
   if($(this).attr('isloaded')!=='false'){
    $(this).attr('beenthere','1');   
    if(this.id.match('aggr')==null){
     $(this).find("tr:has(td.ms-vb2)").each(function(){     
      thisRow = $(this);         
      idColIndex = thisWPContainer.data("idColIndex");
      attcolIndex = thisWPContainer.data("attcolIndex");
      // Hide ID column
      if(argObj.hideIdColumn){
       thisRow.find(">td:eq("+idColIndex+")").addClass('dummyHideClass');
      }
      thisRow.data('itemID',thisRow.find(">td:eq("+idColIndex+")").text());
      thisRow.data('listGuid',thisListCTX.listName);
      if(argObj.clickToOpen){      
       thisRow.find(">td:eq("+attcolIndex+")").find('img').attr('title',argObj.clickMouseover).css('cursor','pointer').click(function(){
        showAtt(this,argObj);
       }); 
      }else{
       thisRow.find(">td:eq("+attcolIndex+")").find('img').attr('title','').css('cursor','wait').mouseover(function(){
        showAtt(this,argObj);
       });     
      }   
     });
    }else if(this.id.match('aggr')!=null && argObj.hideIdColumn){
     $(this).find("td[cellIndex="+thisWPContainer.data("idColIndex")+"]").addClass('dummyHideClass');
    }
   }
  });
 });
 // Hide ID column if specified
 if(argObj.hideIdColumn){
  $(".dummyHideClass").hide();
 }
}

function showAtt(elm,argObj){
 var elmOffset, pageOffset, pTop, pLeft, allAtt, wrapBuffer;
 elmOffset = $(elm).offset();
 pageOffset = $("#s4-workspace").offset();
  
 pTop  = $(elm).offset().top  + 5;
 pLeft = $(elm).offset().left - 60;
  
 allAtt = getAllAttachments($(elm).parents('tr:first').data('listGuid'),$(elm).parents('tr:first').data('itemID'));
 wrapBuffer = [];
 if(allAtt.count===1 && argObj.clickToOpen && argObj.oneClickOpenIfSingle){
  customViewDoc(allAtt.items[0].fullPath);
  return;
 }
 if(allAtt.count>0){       
  $.each(allAtt.items,function(i,item){
   wrapBuffer.push("<div id='customAttDiv_"+i+"' nowrap='nowrap' style='font-family:Arial;font-size:11px;padding:1px'>");
   wrapBuffer.push("<img id='customAtt_"+i+"_icon' style='vertical-align:middle' src='/_layouts/images/ic"+item.ext+".gif' border='0'>&nbsp;");
   wrapBuffer.push("<a href='"+item.fullPath+"' ");
   wrapBuffer.push("id='customAtt_"+i+"' target='_blank'>"); 
   wrapBuffer.push(item.name+"</a></div>");
  });      
 }  
 $("#customAttPreviewWrapper").html(wrapBuffer.join('')).css({top:pTop,left:pLeft}).fadeIn();
}

// Placeholder for the attachment links
$("div#contentBox").prepend("<div id='customAttPreviewWrapper' style='padding:6px;background-color:white;border-radius: 4px;border:1px gray solid;position:fixed;display:none;cursor:pointer;z-index:999' onmouseout='customMouseOutHideMenu(event)'></div>");

function customViewDoc(url){
 var openOk = ViewDoc(url,'SharePoint.OpenDocuments.3');
 if(!openOk){
  window.open(url,"_blank","status=0,toolbar=0,resizable=1");
 }
}

function getAllAttachments(listName,itemID){
 var returnHTMLBuffer, result, attObj, ext;
 returnHTMLBuffer = [];
 result = {count:0,items:[]};
 attObj = spjs_GetAttachmentCollection({'listName':listName,'listItemID':itemID});
 $.each(attObj,function(name,obj){
  ext = name.substring(name.lastIndexOf('.')+1);
  result.items.push({ext:ext,name:name,fullPath:obj.fullPath});
  result.count++;
 });
 return result;
}

// Overcome the missing onmouseleave event in Firefox
function customMouseOutHideMenu(e){
 var target, relTarg, relTargID, isInWrapper;
 if(!e){
  var e = window.event;
 }
 target = e.srcElement || e.target; 
 relTarg = e.relatedTarget || e.toElement;
 relTargID = $(relTarg).attr('id');
 relTargID = (relTargID===undefined)?'':relTargID;
 isInWrapper = ($(target).attr('id')=='customAttPreviewWrapper' || $(target).parents("div[id='customAttPreviewWrapper']").length>0);
 if(!isInWrapper || relTargID.match('customAtt')==null){
  customHideMenu(true);
 }
}

// Hide menu if user moves mouse outside the container
function customHideMenu(hide){
 if(hide){
  $("#customAttPreviewWrapper").fadeOut();
 }else{
  if(typeof(hideMenu)!='undefined'){
   clearTimeout(hideMenu);
  }
 }
}

/*************************************************************
    Web service interactions
*************************************************************/
/* spjs_GetAttachmentCollection
 Argument type: object
  Object properties: listName,listbaseUrl[optional],listItemID
 LastMod: 18.08.2010
 Used to get the collection of attachments from a list item
*/
function spjs_GetAttachmentCollection(argObj){
 var returnObj, content, fullPath, name;
 if(argObj.listBaseUrl==undefined){
  argObj.listBaseUrl=L_Menu_BaseUrl;
 }
 returnObj = {};
 content = [];
 content.push("<GetAttachmentCollection xmlns='http://schemas.microsoft.com/sharepoint/soap/'>");
 content.push("<listName>"+argObj.listName+"</listName>");
 content.push("<listItemID>"+argObj.listItemID+"</listItemID>");
 content.push("</GetAttachmentCollection>");
 spjs_wrapSoapRequest(argObj.listBaseUrl+"/_vti_bin/lists.asmx","http://schemas.microsoft.com/sharepoint/soap/GetAttachmentCollection",content,function(data){
  $(data).find('Attachment').each(function(i){  
   fullPath = $(this).text();
   name = fullPath.substring(fullPath.lastIndexOf('/')+1);
   returnObj[name]={'fullPath':fullPath,'index':i};   
  }); 
 });
 return returnObj;
}

/* spjs_wrapSoapRequest 
 - internal use
 LastMod: 07.07.2010
*/
function spjs_wrapSoapRequest(webserviceUrl,requestHeader,soapBody,successFunc){
 var xmlWrap = [];
  xmlWrap.push("<?xml version='1.0' encoding='utf-8'?>");
  xmlWrap.push("<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
  xmlWrap.push("<soap:Body>");
  xmlWrap.push(soapBody);
  xmlWrap.push("</soap:Body>");
  xmlWrap.push("</soap:Envelope>");
  xmlWrap = xmlWrap.join('');
 $.ajax({
  async:false,
  type:"POST",
  url:webserviceUrl,
  contentType:"text/xml; charset=utf-8",
  processData:false,
  data:xmlWrap,
  dataType:"xml",
  beforeSend:function(xhr){
   xhr.setRequestHeader('SOAPAction',requestHeader);
  },
  success:successFunc
 });
}

function customTimeoutLoop(id){
var obj = $("#"+id);
var isloaded = ($(obj).attr('isloaded')=='true')?true:false;
 if(!isloaded){
  $(obj).hide();
  setTimeout(function(){
   customTimeoutLoop(id);
  },10);
 }else{
  $(obj).show();
  customListAttachments(); 
 }
}

function ExpGroupRenderData(d, a, e) {
    ULSA13: {
    }
    var c = document.getElementById("tbod" + a + "_"), b = document.createElement("DIV"), f = a.split("-");
    b.innerHTML = "<TABLE><TBODY id=\"tbod" + a + "_\" isLoaded=\"" + e + "\">" + d + "</TBODY></TABLE>";
    c.parentNode.replaceChild(b.firstChild.firstChild, c); 
 customTimeoutLoop("tbod" + a + "_");   
}

Tuesday 4 February 2014

“This Page has been modified since you opened it. You must open the page again. Refresh page.” error message


open the page in SharePoint designer and add the below script “ MSO_PageHashCode clearing script” :

<script language=”javascript” type=”text/javascript”>
if(document.getElementById(“MSO_PageHashCode”))
{
document.getElementById(“MSO_PageHashCode”).value=”";
}
</script>

Sometimes , You may face this issue when using any button (like asp:linkbutton or asp:button) for navigating to different URL (i.e: using the postback property) because , it’ll submit page.form , So in order to avoid this you should use normal <a href=”"></a> or use asp:hyperlink control.

Thursday 30 January 2014

Remove duplicate entries from Quicklaunch and Top Navigation (zine fame)

change the web URL in the attached powershell script file and run the script on powershell prompt.



RemoveDuplicateLinks.ps1.txt
**********************************



#New version of the detect and removal script:
#  You put the affected site collections into a textfile -> sites.txt <- which is stored in the same path as the ps script 
#  It will check all sites of each site collection of the sites.txt file to see if there are duplicates in the QuickLaunch and/or TopNavigation (NEW!)
#  Logging to a logfile commented out as it was not efficient (filling up disk space) …   
#  Tool will still output everything to the cmd prompt.


# THIS CODE-SAMPLE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR 
# FITNESS FOR A PARTICULAR PURPOSE.
#
# This sample is not supported under any Microsoft standard support program or service. 
# The script is provided AS IS without warranty of any kind. Microsoft further disclaims all
# implied warranties including, without limitation, any implied warranties of merchantability
# or of fitness for a particular purpose. The entire risk arising out of the use or performance
# of the sample and documentation remains with you. In no event shall Microsoft, its authors,
# or anyone else involved in the creation, production, or delivery of the script be liable for 
# any damages whatsoever (including, without limitation, damages for loss of business profits, 
# business interruption, loss of business information, or other pecuniary loss) arising out of 
# the use of or inability to use the sample or documentation, even if Microsoft has been advised 
# of the possibility of such damages.
################################################################################################



Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

function tryDeleteNode
{
    param
    (
        $node,$dictionary,$nodeCollection
    )

    $title = $node.Title
    
               
                   if(!$dictionary.ContainsKey($title))
                   {
                       $dictionary.Add($node.Title,$node.Url)
                   }
                   else
                   {
                       if($dictionary[$title] -eq $node.Url)
                       {
                           if($node.Children.Count -eq 0)
                           {
                               echo "       -> Deleting Duplicate Node: $title" 
                               $nodeCollection.Delete($node)
                               $global:didDelete= $true
                                            $temp = (get-date).ToString() +";"+ ($site.Url) +";"+ ($title)
                                            echo "$temp"
                           }
                           else
                           {
                               echo "       -> Dupe Node $title has children, Skipping..."
                           }
                       }
                              else
                       {
                   echo "       -> Duplicate title $title found, but mismatched link, Skipping..."
                       }
                   }
               
}

function deleteNodesRecurse
{
    $nodes = @{}
    foreach($node in $quickLaunch)
    {
        $childNodes = @{}
        foreach($child in $node.Children)
        {
            tryDeleteNode -node $child -dictionary $childNodes -nodeCollection $node.Children
        }

        tryDeleteNode -node $node -dictionary $nodes -nodeCollection $quickLaunch
    }
}
function deleteGlobalNodesRecurse
{
    $nodes = @{}
    foreach($node in $gnavNodes)
    {
        $childNodes = @{}
        foreach($child in $node.Children)
        {
            tryDeleteNode -node $child -dictionary $childNodes -nodeCollection $node.Children
        }

        tryDeleteNode -node $node -dictionary $nodes -nodeCollection $gnavNodes
    }
}


#$affectedSiteCollections = get-content sites.txt
#foreach ($sitecoll in $affectedSiteCollections)
#{
#    $sitecoll = Get-SPSite "http://isgdev5:43007"
#    write-host "SiteCollection: " $sitecoll.URL 
#               write-host "SiteCollection: " $sitecoll.URL 
#               foreach ($site in $sitecoll.AllWebs) 
#               { 
$site = Get-SPWeb "http://portal.ibsplc.com/crgltr"
                       write-host " -> Site: " $site.URL 
                              do
                              {
                                            $quickLaunch = $site.Navigation.QuickLaunch
                                            $global:didDelete = $false
                                            deleteNodesRecurse
                                            $pub= [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($site)
                                            $gnavNodes = $pub.Navigation.GlobalNavigationNodes;
                                            deleteGlobalNodesRecurse
                              }
                              while($global:didDelete)
                              $site.Dispose()
#}
#               $sitecoll.Dispose()
#}

File Upload control in sharepoint designer

Normally SharePoint provides Document Attachment in the ribbon. But in my case ribbon was hide from the user. So I need to add Attachment Control on the form instead of ribbon. So I achieve it using Client Object Model. Insert the following code in your form to make attachment field available in the Form.

<tr>
     <td rowspan="2" width="190px" valign="top" height="50px">
        <H3>
             Upload Evidence
        </H3>
     </td>
     <td valign="bottom" height="15" id="attachmentsOnClient">
         <span dir="ltr">
             <input type="file" name="fileupload0" id="onetidIOFile" size="56" title="Name" /> 
         </span>
     </td>
</tr>
<tr>
      <td colspan="4">
           <input id="attachOKbutton" type="BUTTON" onclick='OkAttach()' value="Upload" style="width: 12.8em; height: 2em"/>
           <span id="idSpace"/>
        </td>
</tr>

Thursday 23 January 2014

Find error using Correlation ID from across sharepoint Log files

Merge-SPLogFile -Path C:\zinelog.txt -Correlation bdfe6c9c-72f4-4023-47d2-44b445f95d05

How to make people picker read only in Edit form using jquery

<script language="javascript" src="/JSLibrary/jquery-1.9.0.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var control = $("textarea[title='People Picker']")[0];
/* Detect browser*/
        if (navigator.appName == 'Microsoft Internet Explorer') {
        control.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.childNodes[1].style.display = "none";
        }
        else {
        control.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.childNodes[2].style.display = "none";
        }
var innerHtml = control.parentNode.parentNode.innerHTML;
control.parentNode.style.display = "none";
control.parentNode.parentNode.parentNode.parentNode.parentNode.innerHTML = control.parentNode.parentNode.parentNode.parentNode.parentNode.innerHTML + "<span class='fieldsTitle'>" + $('.ms-inputuserfield #content').text() + "</span>";
});
</script>

Thursday 9 January 2014

Sharepoint: could not save the list changes to the server

delete all the content of the folder "C:\Users\user1\AppData\Local\Microsoft\WebSiteCache" where User1 is the actual user.

This is a SPD problem.