Monday, 25 May 2015

Get document wise versions list using Powershell

function Get-DocumentItemVersionsList([string]$WebURL, [String[]]$listName)
{
[void][System.reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

set-variable -option constant -name out -value "C:\Get-ListItemVersionsList_Output.csv"
"Item_ID|Item Title|Item URL|Version Count" | Out-File $out -Append

write-host "--IN"
$web = get-spweb $WebURL
write-host "--Web initiated"
$list = $web.Lists.TryGetList($listName)
write-host "--List initiated"
$listItems = $list.Items;

write-host "--List Items Count = " $listItems.Count

foreach($item in $listItems)
{
$itemTitle = $item["Name"]
$itemURL = $item.Url
$itemID = [string]$item.Id
$itemVersCount = $item.Versions.Count

#write-host "--List Item - " $itemTitle " Versions - " $itemVersCount
#$itemTitle + "|" + $itemVersCount + "|" | Out-File $out -Append

if($itemVersCount -gt 1)
{
$itemID + "|" + $itemTitle + "|" + $itemURL + "|" + $itemVersCount | Out-File $out -Append

}
}

$web.Dispose()
}

Get-DocumentItemVersionsList -WebURL:'http://user.company.com/hr/' -listName:'Shared Documents'

How to Activate MIME Type using Powershell

$mime = "text/html"
$webAppUrl = "http://test.company.com"
$webApp = Get-SPWebApplication $webAppUrl

If ($webApp.AllowedInlineDownloadedMimeTypes -notcontains $mime)
{
    Write-Host -ForegroundColor White "Adding MIME Type "$mime
    #$webApp.AllowedInlineDownloadedMimeTypes.Add($mime)
     #$webApp.Update()
     Write-Host -ForegroundColor Green "MIME Type added and saved."
    }
Else
 {
    Write-Host -ForegroundColor Yellow $mime" MIME type is already added."
   
 }

How to update SharePoint's Group Owner using PowerShell

#Enter the site URL for which the group owner needs to be updated
$webUrl = "http://test.company.com/man"

Write-Output "Getting site object"
$web = Get-SPWeb $webUrl
Write-Output "Success"

Write-Output "Getting User Group"
$spGroups = $web.groups
#Get the owner group
$UserGroup = $spGroups | where {$_.Name -eq "User"}
Write-Output "Success"

foreach($group in $spGroups)
{
if($group.Name.StartsWith("User"))
{
Write-Output "Updating owner of group - $group"
$group.Owner = $UserGroup
$group.Update()
Write-Output "Successfully updated"
}
}

$web.Dispose()
Write-Output "script ended"

Saturday, 23 May 2015

SharePoint SPSiteDataQuery

SPSiteDataQuery is used to Query multiple lists or to read data from all the lists in 
a site collection.

SPSiteDataQuery
Get Combined result











Below is the example to query multiple list data sources and get combined information in data table:

using (SPSite site = new SPSite(pSiteUrl))
{
     using (SPWeb web = site.OpenWeb())
     {
                        // Fetch using SPSiteDataQuery
                        SPSiteDataQuery query = new SPSiteDataQuery();

                        query.Lists = "<Lists MaxListLimit=\"5\">" +
                              "<List ID=" + web.Lists.TryGetList("Announcements").ID + " />" +
                              "<List ID=" + web.Lists.TryGetList("Content and Structure Reports").ID + " />" +
                              "<List ID=" + web.Lists.TryGetList("NavigationList").ID + " />" +
                              "<List ID=" + web.Lists.TryGetList("Reusable Content").ID + " />" +
                           "</Lists>";

                        query.ViewFields = "<FieldRef Name=\"Title\" />";
                        query.Webs = "<Webs Scope=\"Web\" />";
             
                        //Write appropriate query
                        query.Query = "";

                        query.RowLimit = 10;

                        //Convert result collection to data table

                        DataTable dataTable = web.GetSiteData(query);
           }
}

Reference:

Useful jQuery plugins

Useful jQuery plugins


Image Related Plugins




Lazy load Images (good for performance) - http://www.appelsiini.net/projects/lazyload




Rounded corners - http://steamdev.com/imgr/

Forms plugins

Masked input - restricts users to type incorrect characters


Auto tab - automatically tab between fields once completed.



Validation - http://parsleyjs.org/



Other plugins




Notifications - http://ned.im/noty/ 





Activity Indicator - jquery.spin.js

List Navigation - jquery.listnav.js


News Ticker - Qury.newsticket.com

Social plugins

Social links - Displays links to your social sites




Miscellaneous:

Fallback -  Uses modern techniques if available else fallback jQuery plugins

Friday, 22 May 2015

SharePoint 2016 expected features


  1. Better User Experience: More focus on touch based experience, responsiveness for various resolutions and different devices.                       
  2. Office 365 video with the integration of Azure media services provides secure information in a very simple manner to access from any device at any point of time. Uploading a video is as simple as dragging and dropping from browser interface or mobile device. Good integration of metadata to Share and access relevant content across organization.                              
  3. Office Graph shows more organized information beyond the capabilities of documents. More contextual information for people, calendar, conversations, emails, teams etc.                                                             
  4. The New Knowledge Management Portal in Office 365 with ready-to-go solutions, join discussions, provide feedback, and join in person.                       
  5. Social improvements with better yammer integration. more integration with office 365 groups encourages discussions and collaboration among various work spaces                                                    
  6. Easier migration from SharePoint portal to Office 365                                 
  7. Major enhancements in APIs and tools for authentication, document sharing and Office 365 development.                                                        
  8. Better Rights Management, Multi-Factor Authentication (MFA), Data Loss Prevention (DLP) and Mobile Device Management (MDM), Metadata Management and Policy Control.                                                               
  9. Power Map to plot content from excel to a graphical map content with almost no idea of programming.                                                               
  10. FAST based search enhancement from SharePoint 2016 to Azure.                
  11. Securely connecting SharePoint 2016 On-premises with Office 365.             
  12. Data loss prevention to recognize sensitive data like secure contents to help businesses comply with privacy regulations. eDiscovery component locates and enforces data retention to protect data loss prevention for files that were downloaded from on-premises file shares.                                   
  13. Expand the concept of team sites to have emails, instant messaging, tasks, contacts, personal files, social feeds, simplified permissions and more.         
  14. Power BI to look forward the vision of creating a "ready to go" solution that users and IT can get up and running in minutes.                                        
  15. Content Database size in Terabytes, up to 100000 site collections per content database, List threshold greater than 5000 items, Max file size support up to 10 GB with removed character restrictions.                           
  16. No SharePoint designer in 2016 but SharePoint designer 2013 will be supported. There might not be SharePoint Foundation 2016.                       
  17. Farm Solutions will be supported.
  18. SharePoint 2016 allows applying patches while being live with no need to take  server Off
  19. User Profile Service Application will be removed.

Generate report of all SharePoint groups along with their owner information in a SharePoint FARM using PowerShell


#-----------------------------------------------------------------------
# Location can be changed as per need
#-----------------------------------------------------------------------
$location = "GetAllOwnerReport.csv"


$Information = ""
$rptData = "Web Name, Group Name , Owner Name"

$webApps = Get-SPWebapplication

foreach($webApp in $webApps)
{
 $sites = $webApp.sites

 foreach($site in $sites)
 {
  $webs = $site.AllWebs
  
  foreach($web in $webs)
  {     
    foreach($group in $web.groups)
    {      
      $Information = $web.Url + " , " + $group.Name + " , " + $group.owner;         
      $rptData += "`r`n" + $entry
    }
    $web.Dispose()
  }
  $site.Dispose()
 }
}

$rptData | Out-File "$location" 
write-host "Competed!!"

Thursday, 21 May 2015

To set custom sub site icon in a custom master page.

I.e.
For Sub Site - A: 
.




For Sub Site - B:






Below is the approach followed from me:
1. Added below entry in master page but it was always resulting in wrong URL (404 URL not found) and referring to Site Collection URL (It was needed to refer sub site URL)

<asp:Image runat="server" id="idMainSubSiteImageLink" CssClass="subSiteIconData" ImageUrl="../../SiteAssets/banner.png"></asp:Image>

2    2. I have used trick to resolve correct URL by following steps below:
-   Added entry of View All Site Contents from SharePoint, It’s NavigateUrl part gets converted to href with correct sub site URL.
<SharePoint:SPLinkButton id="idNavLinkViewAll1123" CssClass="subSiteIcon"  runat="server" NavigateUrl="~site/SiteAssets/banner.png" Text=""/>

-   Added below JavaScript to apply correct URL to Image link mentioned above and made SPLink hidden
<script type="text/javascript">
  _spBodyOnLoadFunctionNames.push("setImageSrc");
  function setImageSrc()
  {
  var tempImageSrc = document.getElementById("ctl00_idNavLinkViewAll1123").getAttribute("href");
  document.getElementById("ctl00_idMainSubSiteImageLink").
setAttribute("src",tempImageSrc);
  }
</script>
<style type="text/css">
  .subSiteIcon {display:none;}
</style>



-          Now, it automatically applies proper image as per sub site user is navigating on.

Wednesday, 20 May 2015

Get extract of files modified after particular date from SharePoint library or folder within library (Powershell script)

Function getFilesWithin($list)
{
    foreach($item in $list.Items)
    {
if ($folderURL -ne "")
{
if ($item.Url.StartsWith($folderURL, "CurrentCultureIgnoreCase"))
{
$targetFile = $item.file;
if ($targetFile.TimeLastModified -ge (Get-Date $lastDate)){
$item.Name + ";" + $item.Url + ";" + "File;" + $($targetFile.TimeLastModified).ToString('dd/MM/yyyy') | Out-File $logWrite -Append
} else {          
write-host -f green "Not changed after given date" + $item.Url
}
}
}
else
{
$targetFile = $item.file;
if ($targetFile.TimeLastModified -ge (Get-Date $lastDate)){
$item.Name + ";" + $item.Url + ";" + "File;" + $($targetFile.TimeLastModified).ToString('dd/MM/yyyy') | Out-File $logWrite -Append
} else {          
write-host -f green "Not changed after given date" + $item.Url
}
}
}
}

$snapin = Get-PSSnapin | Where-Object { $_.Name -eq "Microsoft.SharePoint.Powershell" }
if ($snapin -eq $null) {
    Write-Host "[INIT] Loading SharePoint Powershell Snapin"
    Add-PSSnapin "Microsoft.SharePoint.Powershell"
}

#****PARAMETRES DEFINITION****
#Specify web site URL wherein Document Library exists
$web= Get-SpWeb "http://w2k8sp2010dev01:13432/"
#Specify Title of Document Library
$DocLibName = "Shared Documents"
#Specify Folder URL if in case any specific documents within folder has to be worked upon or keep blank
$folderURL = ""
#Log File Name, will be suffixed by date time 
$LogFileName = "Get_LibFiles_ModifiedAfter_Log"
#Specify date after which files modified should be extracted
$lastDate = "2015-01-30"
#****PARAMETRES DEFINITION****

$LogFileName = $($LogFileName) + "@" + $(Get-Date -format MMddyy) + ".csv"
write-host -f RED $LogFileName

set-variable -option constant -name logWrite -value $($LogFileName)
"File Name;File URL;Type;Last Modified" | Out-File $logWrite -Append

write-host -f White "Connected to Web"
$Lib=$web.Lists.TryGetList($DocLibName)
write-host -f White "Connected to Library"

if ($Lib.LastItemModifiedDate -ge (Get-Date $lastDate)){
write-host -f yellow "Changed after given date " + $($Lib.LastItemModifiedDate)
} else {          
write-host -f green "Not changed after given date"
}

getFilesWithin($Lib)

$web.Dispose();

**************SCRIPT ENDS HERE***************

Instructions to use above Power-shell script;
You will need to change parameter values and below are the definition of parameters;

  1. Web Site URL - Specify web site URL 
  2. Title of Document Library - Specify Document Library Name
  3. Folder URL - Specify Folder URL starting with Library Name For E.g. "shared documents/folder name"
  4. Log File Name - Specify Log File Name
  5. Date after which files modified - Specify Date criteria (should be in format of “yyyy-mm-dd”)


ASP.Net Cheat Sheet and best practises

I have prepared some cheat-sheet to get into consideration while working on any ASP.Net project.

  1. Authentication and authorization policies
  2. Input Validation
    Security Parameters Alignment
    Confirm the input range is checked at Form textbox controls.
    Confirm RequiredFieldValidator is implemented.
    Confirm RegularExpressionValidator is implemented.
    Confirm RangeValidator is implemented.
    Textbox is properly validating the input length and type to SQL injection attack.
    Confirm cookies and query strings are being validated by the Regex class.
    Confirm the HttpOnly cookie option is applied to defend from an XSS attack.
    Confirm if actual output is encoded with urlEncode and HtmlEncode.

  3. Parameters Handling
    Security Parameters Alignment
    Confirm query strings data are encrypted.
    Confirm form viewstate is encrypted.

  4. Session Data Handling
    Security Parameters Alignment
    Confirm connections strings are encrypted.
    Confirm session cookies data are hashed.

  5. Sensitive Data Protection
    Security Parameters Alignment
    Confirm sensitive data is not stored in web.config file in plain text.
    Confirm sensitive data does not reside in cookies, query strings, and hidden forms fields.
    Confirm server side state management is applied for clear text passing of data across the pages.

  6. Web services
    Security Parameters Alignment
    Confirm redundant Web service protocols, including HTTP GET and HTTP POST, are disabled.
    Confirm Input to Web methods is validated for, length, type, range, and format.
    Confirm Web service running with least-privileged process account.
    Confirm SOAP messages are passed only in encrypted form over communication channels.

  7. Exception Handling Management
    Security Parameters Alignment
    Confirm every occurred exception is recorded on the server.
    Confirm structure exception handling is applied to each code file.
    Confirm application level exception handling is applied.
    Confirm Page level exception handling is applied.

  8. Web.Config File Administration 
    Security Parameters Alignment
    Confirm enableViewState is disabled, if application doesn't rely on view state.
    Confirm enableViewStateMac is enabled, if application uses view state.
    Confirm httpMaxLength to prevent users from being able to upload a large-sized file.
    Confirm application is forced to use authentication by allowOverrride tofalse.
    Confirm customErrors option is enabled.

  9. Privilege Management
    Security Parameters Alignment
    Confirm ASP.NET process account has Read permission to system root directory (%windir\System32).
    Confirm impersonate account has Read permission to GAC (%windir\assembly).
    Confirm process account has Read and Execute permission to solution content directory.
    Confirm ASP.NET process account has Read and execute permission to Framework directory (%windir\Microsoft.NET\Framework).
    Confirm process account has Full control permission to Temporary files (%windir%\Microsoft.NET\Framework\{version}Temporary ASP.NET Files)

  10. Deployment
    Security Parameters Alignment
    Confirm debug compilation is disabled.
    Confirm trace is disabled.
    Confirm access is denied by authentication configuration removed.
    Confirm Bin directory doesn't have read or write permission.
    Confirm Bin directory doesn't have directory browsing permission.

Example of deleting list items one by one using CSOM (javascript)

var clientContext;
var website;
var oList;
var cnt = 0;

// Make sure the SharePoint script file 'sp.js' is loaded before your
// code runs.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);

// Create an instance of the current context.
function sharePointReady() {
    clientContext = SP.ClientContext.get_current();
    website = clientContext.get_web();
oList = website.get_lists().getByTitle('List_Name');

var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><RowLimit>100</RowLimit></View>');
    this.collListItem = oList.getItems(camlQuery);

    clientContext.load(website);
// Specify internal column names by comma separated e.g. 'Include(Id, Title) 
clientContext.load(collListItem, 'Include(Id)');
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();
var ID = oListItem.get_id();

// Create List Item object based on ID and Delete item
var oListItemDel = oList.getItemById(ID);
oListItemDel.deleteObject();
oList.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onDeleteSucceeded), Function.createDelegate(this, this.onDeleteFailed));
console.log(ID + " : Deleted");
    }
}

function onQueryFailed(sender, args) {
    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


function onDeleteFailed(sender, args) {
    console.log('Delete failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

function onDeleteSucceeded(sender, args) {
    cnt = cnt + 1;
console.log('Deleted item count : ' + cnt);
}

Create General Settings Link to the SharePoint list\library settings page

you can create a native looking General Settings in list/ library settings:
SharePoint Custom Setting














On click of the link, you can write our code behind logic with the help of SharePoint Application page.



Below are the steps:
  1. Create an Empty Visual Studio SharePoint project
  2. Right click on project and add a new Item as below:

  3. SharePoint Project












3. Add a module to the project and Add below logic which is causing the setting link to show in the General Settings section of the list:


<?xml version="1.0" encoding="utf-8"?>
  <CustomAction
    Id="MyCustomAction"
    GroupId="GeneralSettings"
    Location="Microsoft.SharePoint.ListEdit"
    Title="Empty List Items"
    Sequence="1"
    Rights="ManageLists"
    RegistrationType="ContentType"
    RegistrationId="0x">
    <UrlAction Url="~site/_layouts/EmptyList/ConfigListVersions.aspx?List={ListId}"/>
  </CustomAction>
</Elements>