Tuesday, 22 March 2016

Add .js reference at run time to the existing page.




var jQueryScriptOutputted = false;
function initJQuery() {

    if (typeof(jQuery) == 'undefined') {  if (! jQueryScriptOutputted) {
jQueryScriptOutputted = true;        
       
var path   = "//ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
   var script   = document.createElement( 'script' );
   script.src   = path;
   document.getElementsByTagName( 'head' )[0].appendChild( script );
 }
        setTimeout("initJQuery()", 50); } else {
   $(function() {

// add your code here...............

         
        });  }}

initJQuery();


Sunday, 7 February 2016

Something went wrong. To try again, reload the page and then start the workflow, error on starting a workflow.


sharepoint designer workflow is howing above error message when tried to start worfklow manually on list item, and worflow is not triggered on item added or updaed event.

This was happening for only few lists. On other lists workflow is triggering with out any issue.

Reason for the issue: we modified the default display and edit forms of the list which are throwing issue. 

Removed the pages which are modified for customization and added new pages using designer making new pages as the default display and edit forms then designer workflow started working.



Tuesday, 22 December 2015

Delete data from large lists using powershell

Delete data from large lists using powershell

cls
$web = Get-Spweb "http://........:/";
$list =  $web.Lists["NintexWorkflowHistory"]
$query = New-Object Microsoft.SharePoint.SPQuery;
$query.ViewAttributes = "Scope='Recursive'";
$query.RowLimit = 2000;
$query.Query = '<Where><Lt><FieldRef Name="ID"/><Value Type="Counter">1000000</Value></Lt></Where>';
Write-Host $list.Title
$itemCount = 0;
$listId = $list.ID;
[System.Text.StringBuilder]$batchXml = New-Object "System.Text.StringBuilder";
$batchXml.Append("<?xml version=`"1.0`" encoding=`"UTF-8`"?><Batch>");
$command = [System.String]::Format( "<Method><SetList>{0}</SetList><SetVar Name=`"ID`">{1}</SetVar><SetVar Name=`"Cmd`">Delete</SetVar></Method>", $listId, "{0}" );

do
{
    $listItems = $list.GetItems($query)
    $query.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
    foreach ($item in $listItems)
    {
Write-Host $item.ID
        if($item -ne $null){$batchXml.Append([System.String]::Format($command, $item.ID.ToString())) | Out-Null;$itemCount++;}
    }
}
while($query.ListItemCollectionPosition -ne $null)

$batchXml.Append("</Batch>");
$itemCount;

$web.ProcessBatchData($batchXml.ToString()) | Out-Null;
#$web.RecycleBin.DeleteAll()
$web.Dispose()

Friday, 20 November 2015

Sharepoint 2013 visual studio workflow is not updated on subsequesnt deployments

tasklist /FI "IMAGENAME eq vssphost5.exe" 2>NUL | find /I /N "vssphost5.exe">NUL
if "%ERRORLEVEL%"=="0" taskkill /f /im vssphost5.exe
exit 0


http://stackoverflow.com/questions/19286924/sharepoint-2013-visual-studio-workflow-not-updating

Friday, 16 October 2015

SharePoint 2010 error while submitting nintex forms

An SPRequest object was not disposed before the end of this thread.  To avoid wasting system resources, dispose of this object or its parent (such as an SPSite or SPWeb) as soon as you are done using it.  This object will now be disposed.  Allocation Id: {}  To determine where this object was allocated, set Microsoft.SharePoint.Administration.SPWebService.ContentService.CollectSPRequestAllocationCallStacks = true.

System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80131904
 at Microsoft.SharePoint.Library.SPRequestInternalClass.AddOrUpdateItem(String bstrUrl, String bstrListName, Boolean bAdd, Boolean bSystemUpdate, Boolean bPreserveItemVersion, Boolean bPreserveItemUIVersion, Boolean bUpdateNoVersion, Int32& plID, String& pbstrGuid, Guid pbstrNewDocId, Boolean bHasNewDocId, String bstrVersion, Object& pvarAttachmentNames, Object& pvarAttachmentContents, Object& pvarProperties, Boolean bCheckOut, Boolean bCheckin, Boolean bMigration, Boolean bPublish, String bstrFileName, ISP2DSafeArrayWriter pListDataValidationCallback, ISP2DSafeArrayWriter pRestrictInsertCallback, ISP2DSafeArrayWriter pUniqueFieldCallback)  
 at Microsoft.SharePoint.Library.SPRequest.AddOrUpdateItem(String bstrUrl, String bstrListName, Boolean bAdd, Boolean bSystemUpdate, Boolean bPreserveItemVersion, Boolean bPreserveItemUIVersion, Boolean bUpdateNoVersion, Int32& plID, String& pbstrGuid, Guid pbstrNewDocId, Boolean bHasNewDocId, String bstrVersion, Object& pvarAttachmentNames, Object& pvarAttachmentContents, Object& pvarProperties, Boolean bCheckOut, Boolean bCheckin, Boolean bMigration, Boolean bPublish, String bstrFileName, ISP2DSafeArrayWriter pListDataValidationCallback, ISP2DSafeArrayWriter pRestrictInsertCallback, ISP2DSafeArrayWriter pUniqueFieldCallback)







Not allowing to edit list items wicth the above exception.

Fix: Removed indexed column in the list. started working.

Tuesday, 1 September 2015

 ##SharePoint Copy Users between Site Colletions to same Groups

$SourceUrl = "http://";
$DestinationUrl = "http://";
 ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  #
 ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  #
cls
if ((Get-PSSnapin -Name Microsft.SharePoint.PowerShell -ErrorAction SilentlyContinue)) {
    Add-PSSnapin Microsoft.SharePoint.Powershell
    Write-Host "Loaded Powershell" -ForegroundColor gray
}

function CopyUsersBetweenSiteColetions( $SourceUrl, $DestinationUrl){
$SourceWeb = Get-SPWeb $SourceUrl -ErrorAction SilentlyContinue
    $DestWeb = Get-SPWeb $DestinationUrl -ErrorAction SilentlyContinue
    if (!$SourceWeb) {
        Write-Host "Not able to get site with url : $SourceUrl" -ForegroundColor Red
        return
    }
    if (!$DestWeb) {
        Write-Host "Not able to get site with url : $DestinationUrl" -ForegroundColor Red
        return
    }


    if ($DestWeb) {
    $DestWeb.AllowUnsafeUpdates = $true
        Write-Host " Getting site groups from the Site : " $SourceWeb.Title -ForegroundColor Yellow
        foreach($SourceGrp in $SourceWeb.SiteGroups) {
            $desGrp = $DestWeb.SiteGroups[$SourceGrp.Name]
                if ($desGrp) {
                    Write-Host "Comparing Group Members of the Group:- " $desGrp.Name -ForegroundColor Cyan
                    foreach($SourceMembr in $SourceGrp.Users) {
                        $DesMember = $DestWeb.EnsureUser($SourceMembr)
                            if ($DesMember) {
                           $exist = $desGrp.Users | Where{ $_.LoginName -eq $DesMember.LoginName  }

                            if(!$exist)
                            {
                             Write-Host " Adding User" $DesMember.LoginName "to the destination web" -ForegroundColor Gray
                                $desGrp.AddUser($DesMember)                          
                                }
                             
                            } else {
                                Write-Host $SourceMembr.Email " User Not existing in destination web" -ForegroundColor Yellow
                            }
                    }
                } else {
                    Write-Host "Group not exists in Destination site : " $SourceGrp.Name -ForegroundColor Gray
                }
        }
        $DestWeb.AllowUnsafeUpdates = $false
        $SourceWeb.Dispose()
        $DestWeb.Dispose()
        Write-Host "Opeartion complted." -ForegroundColor DarkYellow
    }
 }
 CopyUsersBetweenSiteColetions $SourceUrl $DestinationUrl

Tuesday, 25 August 2015

SharePoint 2013 sort Left navigation using jquery

var $eleContainer = $("tr td:last-child.ms-tv-item").closest('div');
var $aryTblChl = $eleContainer.children('table');
$aryTblChl.sort(function (a, b) {
    a = $(a).find("tr td:last-child.ms-tv-item").text();
    b = $(b).find("tr td:last-child.ms-tv-item").text();
    return (a == b) ? 0 : ((a > b) ? 1 : -1);
}); $aryTblChl.detach().appendTo($eleContainer);

Friday, 17 July 2015

Error 545 Error occurred in deployment step 'Recycle IIS Application Pool': The local SharePoint server is not available. Check that the server is running and connected to the SharePoint farm.

while deploying sharepoint solution to the sharepoint environment.


Add user to the sqlserver admins group.
Limit the No of characters entry in textarea control.


function LimitTextAreaContent() {
    $(".clstxtSummary").keydown(function (event) {
        if ($(this).val().trim().length > 500) {
            $(this).val($(this).val().trim().substring(0, 500));
        }
    });
    $(".clstxtJustification").keydown(function (event) {
        if ($(this).val().trim().length > 1000) {
            $(this).val($(this).val().trim().substring(0, 1000));
        }
    });
    $(".clstxtSummary").keyup(function (event) {
        if ($(this).val().trim().length > 500) {
            $(this).val($(this).val().trim().substring(0, 500));
        }
    });
    $(".clstxtJustification").keyup(function (event) {
        if ($(this).val().trim().length > 1000) {
            $(this).val($(this).val().trim().substring(0, 1000));
        }
    });
    $(".clstxtSummary").on('paste', function (event) {
        setTimeout(function () {
            var text = event.currentTarget.value;
            if (event.currentTarget.value.length > 500) {
                event.currentTarget.value = text.substring(0, 500);
            }
        }, 0);
    });
    $(".clstxtJustification").on('paste', function (event) {
        setTimeout(function () {
            var text = event.currentTarget.value;
            if (event.currentTarget.value.length > 1000) {
                event.currentTarget.value = text.substring(0, 1000);
            }
        }, 0);
    });
    (function ($) {
        $("textarea[id$='txtDelegateComments'], textarea[id$='txtComments'] , textarea[id$='txtResubComments'], textarea[id$='txtDCCComments'] ").bind("change keyup input", function () {
            if ($(this).val().trim().length > 250) {
                $(this).val($(this).val().trim().substring(0, 250));
            }
        });

    })(jQuery);
}

$(document).ready(function () {
    LimitTextAreaContent();
});
sharepoint logout of page after every 20 mins using script

var idle = 0;
$(document).ready(function () {
    //Call timeOutCheck every 10 minutes.
    var idleInterval = setInterval(timeOutCheck, 600000); // 10 minute

    //set idlaTimer to true on mouse click/keypress/keydown
    $(this).mousedown(function (e) {
        idle = 1;
    });
    $(this).keypress(function (e) {
        idle = 1;
    });          
    $(this).keydown(function (e) {
        idle = 1;
    });
});

function timeOutCheck() {

   
    if (idle == 0) { // 20 minutes
        window.location.assign(_spPageContextInfo.webAbsoluteUrl+"/_layouts/15/signout.aspx")
        //alert("time out");
    }
    else
    {
        //reset the timer
        idle = 0;
    }
}


Monday, 6 July 2015

calculated column functions
http://blogs.technet.com/b/collaboration/archive/2008/03/28/functions-for-use-in-a-moss-2007-column-today-me-other.aspx

Wednesday, 22 April 2015

Run Javascript from code behid  C# code
 ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "alert", "alert('This Document already exists!');", true);

Tuesday, 23 September 2014

Sharepoint resize modal dialog window

 SP.SOD.executeOrDelayUntilScriptLoaded(resizeModalDialog, 'sp.js');
 function resizeModalDialog(){
 var dlg = typeof(SP.UI.ModalDialog.get_childDialog) == "function" ? SP.UI.ModalDialog.get_childDialog() : null;
    if (dlg != null) {
        dlg.autoSize();
}
 }



Modal dialog window

<div class="ms-dlgContent">
    <div class="ms-dlgBorder">
        <div class="ms-dlgTitle"></div>
        <div class="ms-dlgFrameContainer"></div>
    </div>
</div>
Sharepoint 2010 css refference chart

http://sharepointexperience.com/csschart/csschart.html

Thursday, 4 September 2014

GET All Sub Sites and Users Info and Lists Info Using Javascript with console window
tested in sharepoint 2007 , 2010 & 2013


console.clear();
var jQueryScriptOutputted = false;
function initJQuery() {
    if (typeof(jQuery) == 'undefined') {
if (! jQueryScriptOutputted) {
jQueryScriptOutputted = true;    
var path   = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js";
var sppath = "http://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/0.7.1a/jquery.SPServices-0.7.1a.min.js";
var script   = document.createElement( 'script' );
script.src   = path;
document.getElementsByTagName( 'head' )[0].appendChild( script );
            var spservice =   document.createElement('script');
            spservice.src= sppath;
            document.getElementsByTagName( 'head' )[0].appendChild( spservice );
        }
        setTimeout("initJQuery()", 100);
}
else {
$(function() { ExecuteRequiredScript(); });
}
}
initJQuery();
var AllLists = "";
function ExecuteRequiredScript(){
GetAllSubWebs();
}
function GetAllSubWebs(){
var count = 0;
console.clear();
$().SPServices({
         operation:"GetWebCollection",//GetWebCollection,GetAllSubWebCollection
         async: false,
         completefunc: function (xData, status) {
console.log(status);                      
$(xData.responseXML).find("Web").each(function() {        
count++;

var title = $(this).attr("Title");

var url = $(this).attr("Url");  
console.log(title +"\t" +url );

if(url.indexOf("current weburl") > -1){

getOwnersgrpNAme(title,url);
getUsers(title,url);
}
});
//console.log( AllLists);
console.log(" Sub Webs count \t"+count);
}
});
}
function getCurrentUserRoleforUser(username,url) {//alert(username);
var rolename="";
var counter=0;
    $().SPServices({
        operation: "GetRoleCollectionFromUser",
userLoginName:username,
webURL:url,
        async: false,
        completefunc: function (xData, Status) {
            if( Status == "success") {

                $(xData.responseXML).find("Role").each(function () {
                   if(counter==0)
{
                    rolename=$(this).attr("Name");
counter++;
}
else
{
rolename+=";"+$(this).attr("Name");
}
                });
            }
        }
    });
return rolename;
}
function getCurrentUserRole(group,url) {
var rolename="";
var counter=0;
    $().SPServices({
        operation: "GetRoleCollectionFromGroup",
groupName:group,
webURL:url,
        async: false,
        completefunc: function (xData, Status) {
            if( Status == "success") {
                $(xData.responseXML).find("Role").each(function () {
 if(counter==0)
{
                    rolename=$(this).attr("Name");
counter++;
}
else
{
rolename+=";"+$(this).attr("Name");
}
                });
            }
        }
    });
return rolename;
}
function getUsers(title,url)
{
var perms="";
   $().SPServices({
    operation: "GetUserCollectionFromWeb",
    webURL: url,
async: false,
    completefunc: function (xData, Status) {


    $(xData.responseXML).find("User").each(function() {
     
        var liHtml = $(this).attr("Name");
perms=getCurrentUserRoleforUser($(this).attr("LoginName"),url);

        AllLists +=  title+"\t"+url+"\t"+perms+"\t"+liHtml+"\t"+"\n";
     });
console.log( AllLists);
     }
});
}


function getOwnersgrpNAme(title,url){
console.log("Getting Owners");
var siteusers="",rolename="";
 $().SPServices({
  operation: "GetGroupCollectionFromWeb",
  webURL:url,
  async: false,
  completefunc: function(xData, Status) {
   //var AllLists = "";
  $(xData.responseXML).find("Group").each(function () {
        var name = $(this).attr("Name");
  rolename=getCurrentUserRole(name,url);
        siteusers=getGroupOwners(title,url,name);  
AllLists +=  title+"\t"+url+"\t"+rolename+"\t"+name+"\t"+siteusers+"\n";
      });
     console.log( "successuser1");
  }
 });
 //return siteowner;
}
function getGroupOwners(title,url,groupName) {
    var ownerdata = "";

    // Gets users within Owners group
    $().SPServices({
    operation: "GetUserCollectionFromGroup",
    groupName: groupName,
webURL:url,
    async: false,
    completefunc: function (xData, Status) {
//alert(groupName+" "+Status);
      $(xData.responseXML).find("User").each(function () {
        var displayName = $(this).attr("Name");
        if(ownerdata ==""){
     ownerdata =displayName ;
 }
 else{
  ownerdata =ownerdata +";"+displayName ;
 }
      });
    }
   });
   return ownerdata;
}
function GetAllListsIntheSite(wburl,title,siteOwners){
$().SPServices({
        operation: "GetListCollection",
        webURL:wburl,
        async: false,
        completefunc: function( xData, Status ) {      
var AllLists = "",AllLibraries = "",UngroupedLists = "";
            $( xData.responseXML ).find("Lists > List").each(function() {
                var $node = $(this);
var ListTitle = $node.attr("Title");
var ListDefaultviewUrl = $node.attr("DefaultViewUrl");
var modified = $node.attr("Modified");
var modifiedstr=modified.substr(4,2)+"/"+modified.substr(6,2)+"/"+modified.substr(0,4)+" "+modified.substr(9,2)+":"+modified.substr(12,2);
if(ListDefaultviewUrl.indexOf("/_catalogs/")== -1){
if(ListDefaultviewUrl.indexOf("/Lists/") > 0){
var itemCount=GetItemCount(ListTitle,wburl);
AllLists +=  ListTitle+"\t , \t"+"List"+"\t , \t"+ListDefaultviewUrl+"\t , \t"+title+"\t , \t"+wburl+"\t , \t"+siteOwners+"\t , \t"+modifiedstr+"\t , \t"+ itemCount +" Items"+"\n";
}
else if(ListDefaultviewUrl.indexOf("/Forms/") > 0){
AllLibraries +=ListTitle+"\t , \t"+"Document Library"+"\t , \t"+ListDefaultviewUrl+"\t , \t"+ title+"\t , \t"+wburl+"\t , \t"+siteOwners+"\t , \t"+modifiedstr+"\n";
}
else{
UngroupedLists +=ListTitle+"\t , \t"+" "+"\t , \t"+ListDefaultviewUrl+"\t , \t"+ title+"\t , \t"+wburl+"\t , \t"+siteOwners+"\t , \t"+modifiedstr+"\n";
}
}              
            });                                              
            //console.log( AllLists);
            console.log( AllLibraries);          
            console.log( UngroupedLists);
        }
});
}
function GetItemCount(ListTitle,wburl){
var count=0;
$().SPServices({
operation: "GetListItems",
listName: ListTitle,
async: false,
webURL: wburl,
completefunc: function (xData, status) {
count=  $(xData.responseXML).SPFilterNode("rs:data").attr("ItemCount") * 1;
}
});
return count;
}

Thursday, 7 August 2014

Global Navigation add class based on selected node sub node.

 $('.ms-core-listMenu-root > li > ul').find('li.dynamic >a[href^="/' + location.pathname.split("/")[1] + '"]').closest('li.dynamic-children').addClass('DefaultSelected');


Saturday, 2 August 2014

Sharepoint 2013 show PDF document in flyoutmenu
http://www.wictorwilen.se/sharepoint-2013-enabling-pdf-previews-with-office-web-apps-2013-march-2013-update



Monday, 7 July 2014

In IE add and select option dynamically is not working.

$(document).ready(function()
   {
   $("select[title='lookup Required Field']").prepend("<option value='' selected='selected'>-select-</option>");
setTimeout("SelectItem()", 100);
});

function SelectItem()
{
$("select[title=lookup Required Field'] option:eq(0)").attr('selected', 'selected');
}

Saturday, 28 June 2014

SharePoint external List data from BDC read using c#

string txt = "Fieldvalue";

                string url = SPContext.Current.Site.Url.ToString();
                SPUserToken token = SPUserToken.SystemAccount;
                using (SPSite osite = new SPSite(url, token))
                {
                    using (SPWeb oweb = osite.OpenWeb())
                    {
                        BdcServiceApplicationProxy proxy = (Microsoft.SharePoint.BusinessData.SharedService.BdcServiceApplicationProxy)SPServiceContext.Current.GetDefaultProxy(typeof(Microsoft.SharePoint.BusinessData.SharedService.BdcServiceApplicationProxy));
                        DatabaseBackedMetadataCatalog catalog = proxy.GetDatabaseBackedMetadataCatalog();
                        IEntity ectResource = catalog.GetEntity(url, Name);
                   
                        foreach (KeyValuePair<string, IMethod> method in ectResource.GetMethods())
                        {
                            IMethodInstance methodInstance = method.Value.GetMethodInstances()[method.Key];
                     
                       
                            if (methodInstance.MethodInstanceType == MethodInstanceType.SpecificFinder)
                            {
                                Identity identity = new Identity(txt);
                                IEntityInstance entInstance = ectResource.FindSpecific(identity, ectResource.GetLobSystem().GetLobSystemInstances()[0].Value);

                                if (entInstance[Const.ITEM_NO].ToString() == txt)
                                {
                                    if (ddlBrandName.Items.Count > 0)
                                    {
                                        ddlBrandName.Items.Clear();
                                    }
                                    ddlBrandName.Items.Add(new ListItem(entInstance[Const.BRAND_DESCRIPTION].ToString()));
                                    txtSameAsDesc.Text = entInstance[Const.ITEM_DESC].ToString();
                                    txtSize.Text = entInstance[Const.PACK_SIZE].ToString();
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }

Thursday, 29 May 2014

Office 365 Get User Photo using jsom error

try with src="/_layouts/15/userphoto.aspx?size=S&url="+imageurlfromuserProfile