Wednesday, 23 July 2014

Read list data using Client Object model (ECMA Script)

Read list data using Client Object model (ECMA Script) :-

Pre-requisite:-
1.Create list named "Announcements" using "Announcements" list template.
2.Make some announcement entries inside that list.
3.Create a js file named "AnnouncementData.js" and copy paste the code given below, then upload the same in to "Site Assets" library.
4.Create an application page and add "Content Editor" webpart, edit the webpart and in properties section under "links" add the link of "AnnouncementData.js" and save page.

Output:-
An alert message will appear with list of all entries in "Announcements" list.

Note: The announcement list and webpart should exists in same site.

Source Code :-

<SharePoint:ScriptLink Name="SP.js" runat="server" OnDemand="true"
    Localizable="false" />
<SharePoint:FormDigest runat="server" />

<script type="text/javascript">

ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");


function retrieveListItems() {

    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
     
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
        '<Value Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>');
    this.collListItem = oList.getItems(camlQuery);
     
    clientContext.load(collListItem);
     
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));      
     
}

function onQuerySucceeded(sender, args) {

    var listItemInfo = '';

    var listItemEnumerator = collListItem.getEnumerator();
     
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        listItemInfo += '\nID: ' + oListItem.get_id() +
            '\nTitle: ' + oListItem.get_item('Title') +
            '\nBody: ' + oListItem.get_item('Body');
    }

    alert(listItemInfo.toString());
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

Friday, 4 July 2014

PowerShell - List out all checked out documents in library

PowerShell - List out all checked out documents in library:-
Note:-
Library names needs to be hard coded inside code, at present dummy entries are made, replace it with actual library name before script execution.

Input:-
1. Enter web app url
2. Create a csv file with all site collection url and pass the path of the same.
Code:-
$UrlDochubWebApp = Read-Host "Enter destination web app url"
$SiteCollFilePath = Read-Host "Enter SIte collection csv details Path(folder path)"
#Loading Snap in for Microsoft.Sharepoint.Powershell
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null)
{

Write-Host "Loading SharePoint Powershell Snapin" -ForegroundColor Green
$snapin = Add-PSSnapin "Microsoft.Sharepoint.Powershell"

Write-Host $snapin
}


$Webapplication =GEt-SPWebAPplication $UrlDochubWebApp
$SiteCollFilePath = "$SiteCollFilePath\ItemsCheckedOut_$(get-date -format MMddyyHHmmss).csv";

$AllLibraryNames = New-Object "System.Collections.Specialized.StringCollection"
$AllLibraryNames.Add("<LibraryName-1>") | Out-Null;
$AllLibraryNames.Add("<LibraryName-2>") | Out-Null ;
$AllLibraryNames.Add("<LibraryName-3>") | Out-Null ;

$strToBeInserted = "Site URL,Web Url,FileName,FileUrl,Created By,Created";

function LogData()
{
 Param ([string]$logstring)
Add-content $SiteCollFilePath -value $logstring
}

LogData $strToBeInserted;
if($Webapplication -ne $null)
{
$Allsites = $Webapplication.Sites
foreach($Site in $Allsites)
{
$siteUrl = $Site.Url;
$siteTitle = $site.Title;
foreach($web in $site.AllWebs)
{
try
{
$WebURl = $web.Url;
if(-not($web.Url.toLOwer() -match ("/scrapsite")))
{
foreach($list in $web.Lists)
{
$ListTitle = $list.Title
$LIstITemCount = $list.ItemCount;
if(($list.BaseType -eq "DocumentLibrary") -and ($AllLibraryNames.Contains("$ListTitle") ) -and ($LIstITemCount -gt 0))
{
$files = $list.CheckedOutFiles;
foreach($file in $files)
{
$filename = $file.LeafName;
#$fileURl = $file.URl;
$fileDIr = $file.DirName ;
$fileURl="$fileDIr/$filename";
$itemCreated = $file.TimeLastModified;
$itemCreatedBY = $file.CheckedOutByName;
$strToBeInserted = "$siteUrl,$WebURl,$filename,$fileURl,$itemCreatedBY,$itemCreated";
LogData $strToBeInserted;
}
}
}
}
}
finally
{
$web.Dispose();
}
}
}
}




PowerShell : List all site level users with User Groups name

PowerShell : List all site level users with User Groups name:-
Input:-
1. Pass site URL as input
2. Pass output file path with file name and extension as "CSV"

Code:-
$destWebappUrl= Read-Host "Enter site URL (Eg: http://<HostName>:8080/ )"
$LogFilePath =  Read-Host "Enter Log file path (C:\.....\Log.csv)"

# =========================== LOADING SHAREPOITN POWERSHELL SNAPIN FILE DETAILS =====================================
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null)
{
                Write-Host "Loading SharePoint Powershell Snapin" -ForegroundColor Green
                $snapin = Add-PSSnapin "Microsoft.Sharepoint.Powershell"
                Write-Host $snapin
}

$site = Get-SPSite $destWebappUrl

Function GetUsersFromUserGroups
{
    $groups = $site.RootWeb.sitegroups
    foreach ($grp in $groups)
    {
        $groupName= $grp.name;
        foreach ($user in $grp.users)
        {
            $userName= $user.name
            $msg = "$groupName,$userName"  |  Out-File $LogFilePath -append
        }
    }
    $site.Dispose()
}

[Microsoft.SharePoint.SPSecurity]::RunWithElevatedPrivileges(
{
    Write-Host "Process Started...Time - $(get-date -format HH:mm:ss)" -Foregroundcolor Yellow
 
    $StartTime=Get-Date
    $msg = "User Group Name, User Name"  |  Out-File $LogFilePath -append          
    Write-Host "Processing..."
    GetUsersFromUserGroups
 
    $StartTime=(Get-Date) - $StartTime
    write-host "Total execution time- " $StartTime
    Write-Host "Process Completed...Time - $(get-date -format HH:mm:ss)" -Foregroundcolor Yellow

})

PowerShell - Script used to get list of files with same name in document library

PowerShell - Script used to get list of files with same name in document library:-
Input:-
1. Pass site URL and List name as input to the function to generate log with list of files with same name in that library.

Code:-
$LogFilePath =  Read-Host "Enter Log file path (C:/...../Log.txt)"

# =========================== LOADING SHAREPOITN POWERSHELL SNAPIN FILE DETAILS =====================================
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null)
{
                Write-Host "Loading SharePoint Powershell Snapin" -ForegroundColor Green
                $snapin = Add-PSSnapin "Microsoft.Sharepoint.Powershell"
 
                Write-Host $snapin

}

function Get-SPFilesInList
{
    param ($Url, $ListName)
 
    $web = Get-SPWeb -Identity $Url
    $list = $web.Lists.TryGetList($ListName)
    $folderExists=$false;  

    if ($list -ne $null)
    {
        #write-host $ListName $list.Items.count;
        $ItemsColl = $list.Items
        foreach ($item in $ItemsColl)
        {
            $documentType='';
    $docTypeWIthValues= $item["Debt Document Type"]
    if($docTypeWIthValues -ne $null)
    {
    $doctypeParts=$docTypeWIthValues.toString().split('|');
    $documentType= $doctypeParts[0];
    }
            #write-host $documentType
          [string]$fileNameWithExt=$item.File.Name;
          [string]$fileName = [System.IO.Path]::GetFileNameWithoutExtension($item.File.Name);
          #[string]$fileName = $item.File.Name;
          #write-host $fileName
          [int]$sameFileNameCount = 0        
          foreach ($itemToCompare in $ItemsColl)
            {
                [string]$fileNameToCompare = [System.IO.Path]::GetFileNameWithoutExtension($itemToCompare.File.Name);
                #[string]$fileNameToCompare = $itemToCompare.File.Name;
                if ($fileName -eq $fileNameToCompare)              
                {
                    $sameFileNameCount=$sameFileNameCount+1
                }
            }          
            if ($sameFileNameCount -gt 1)
            {
                #write-host $item.File.Name "- " $sameFileNameCount " files exists with this name"
                [string]$fileurl=$item.Url
                $fileurl="$Url/$fileurl"
                $msg = "$global:Xref,$global:AssetID,`"$ListName`",`"$fileNameWithExt`",`"$fileName`",`"$documentType`",`"$fileurl`""   |  Out-File $LogFilePath -append
             
            }
           <# $itemSize = (($item.File.Length)/1024)/1024
            if($itemSize -Ge $fileSize)
            {
               $itemUrl = $item.Web.Url + "/" + $item.Url;
               Write-Host $itemUrl ", File size:: " $('{0:N2}' -f $itemSize) MB -ForegroundColor Green
            }#>
        }
     
        #[System.IO.Path]::GetFileNameWithoutExtension("Test Config.xlsx")
        <#foreach ($SubFolder in $list.RootFolder.SubFolders)
        {
            if ($SubFolder.Name -eq $FolderName)
            {
                $folderExists=$true;
                break;
            }                    
        } #>    
        <#if($folderExists -eq $false)
            {
                #Create a Folder
                $folderItem = $list.AddItem("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, $FolderName)
                $folderItem.Update();            
             
                $msg = "$Url, $FolderName, folder created, $ListName"  |  Out-File $LogFilePath -append
                write-host "$Url $FolderName folder created in $ListName." -foregroundcolor green
            }
            else
            {
                $msg = "$Url, $FolderName, folder already exists, $ListName"  |  Out-File $LogFilePath -append
                write-host "$Url $FolderName folder already exists in $ListName." -foregroundcolor yellow
            }#>
    }
    $web.Dispose()

}

[Microsoft.SharePoint.SPSecurity]::RunWithElevatedPrivileges(
{
    Write-Host "Process Started...Time - $(get-date -format HH:mm:ss)" -Foregroundcolor Yellow
    LoadWSSAssembly;
    $StartTime=Get-Date
    $msg = "Xref,Loan Number,Library Name,File Name,Common Name,Document Type,Path"  |  Out-File $LogFilePath -append
   Get-SPFilesInList "<Site URL>", "<List Name>"

    $StartTime=(Get-Date) - $StartTime
    write-host "Total execution time- " $StartTime
    Write-Host "Process Completed...Time - $(get-date -format HH:mm:ss)" -Foregroundcolor Yellow

})