How to show Friendly Date in SharePoint using Javascript or using Server side code



You can use following javascript code in order to show Date field value in Friendly format

var yourDate = new Date();

var friendlyDate = SP.DateTimeUtil.SPRelativeDateTime.getRelativeDateTimeString(yourDate , true, SP.DateTimeUtil.SPCalendarType.none, false)



Note that you need to add reference of “SP.dateTimeUtil.js” js in your page

<script type="text/javascript" src="/_layouts/15/SP.dateTimeUtil.js></script>

Following is the description about method argument:
1. Your date (Date ISO8601)
2. Specify whether want to include tiem or not(IncludeTime)
3. Calendar type (CalendarType)
4. Specify whether want to adjust time with server(AdjustToServersNowTime)

DateTime date = DateTime.Now;
string friendlyDate = SPRelativeDateTime.GetRelativeDateString(web, date.ToUniversalTime(), date); 

I Hope it will same someone’s time.


Event Receivers fires for all lists and libraries

Issue Case – Event Receiver behaving unexpectedly

I want to add my event receiver in all the document library in whole site collection.So i added event receiver like
<?xml version=”1.0″ encoding=”utf-8″?>
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/“>
<Receivers ListTemplateId=”101”>
<Class>[Class Path]</Class>

The scope of the feature is “Site” as i want to add event receiver in all the sub site also.

When i activated my event receiver feature, event receiver fires for all the list and libraries.

Issue Case – Event Receiver behaving unexpectedly



By Just changing  the scope of the feature “Site” to “web” my problem was resolved

Don’t know whether its sharepoint bug or not:). Hope it will save some time



Update Master Page of SharepointSite Using PowerShell


In this post i have written about how to Update master page of any site of SharePoint.
It can also achieve through OOTB within few click, but it can also achieve using powershell

$site = Get-SPSite http://sp:2000/sites/Ex15
foreach ($web in $site.AllWebs)
    $web.MasterUrl = $site.RootWeb.ServerRelativeUrl +  &quot;/_catalogs/masterpage/oslo.master&quot;;
    $web.CustomMasterUrl = $site.RootWeb.ServerRelativeUrl + &quot;/_catalogs/masterpage/oslo.master&quot;;
    Write-Host $web.Url $web.MasterUrl $web.CustomMasterUrl;

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    #Get All site collections
    $SiteCollections = Get-SPWebApplication | Get-SPSite -Limit All
    #Loop through all site collections
       foreach($Site in $SiteCollections)
            #Loop throuh all Sub Sites
           foreach($Web in $Site.AllWebs)
		$web.MasterUrl = $site.RootWeb.ServerRelativeUrl +  &quot;/_catalogs/masterpage/oslo.master&quot;;
		$web.CustomMasterUrl = $site.RootWeb.ServerRelativeUrl + &quot;/_catalogs/masterpage/oslo.master&quot;;
		Write-Host $web.Url $web.MasterUrl $web.CustomMasterUrl;



Delete Site Collection Using PowerShell


Here is Power Shell Code for Delete Site Collection from Particular webApplication

$tmpRoot = Get-SPWebApplication -Identity http://SP:2000
#Enumerate through each site collection
for ($index=$tmpRootColl.Count-1 ; $index-ge 0 ; $index–-)
  Remove-SPSite -Identity $tmpRootColl.Item($index) -GradualDelete -Confirm:$false
Get-SPDeletedSite | Remove-SPDeletedSite



Exports Site Columns Using Powershell


Here is I am  Explain you  how to export site column using Power shell

Open your notpade++  and copy past below code inthe file save file as .ps1

in this powerhsell code i have generate log file you can notice it from code snippet

just give Export location as per your convince

I assume that you are aware of how to run power shell script in SharePoint managment Shell

pass webUrl as parameter

Remarks-Change groups name with your Group name which you want toin Code

#Necessary Parameters
#Necessary Parameters
	[string] $Web
#/// <summary>
#/// Remove Default Group Permission
#/// </summary>
Function ExportSiteColumnXml([string] $web)
      		if($web -ne "")
			    $sourceWeb = Get-SPWeb $web
				$xmlFilePath = "C:\Script-SiteColumns.xml"

				#Create Export Files
				New-Item $xmlFilePath -type file -force

				#Export Site Columns to XML file
				Add-Content $xmlFilePath "<?xml version=`"1.0`" encoding=`"utf-8`"?>"
				Add-Content $xmlFilePath "`n<Fields>"
				$sourceWeb.Fields | ForEach-Object {
					if ($_.Group -eq "Your Site Columns Group Name") {
						Add-Content $xmlFilePath $_.SchemaXml
				Add-Content $xmlFilePath "</Fields>"	                            
                 Write-Host "Please provide proper parameters" -ForegroundColor Red
				LogInfo "Please provide proper parameters"
      Write-Host "Something went wrong. Please check Logs for additional information" -ForegroundColor Red
        LogError $_

        #Dispose your site when process end Successivly
		 if($sourceWeb -ne $null)
			LogInfo "Process Ended"


#/// <summary>
#/// Prints errors if generated
#/// </summary>
Function LogError($message)
     $timeStamp = Get-Date -format "dd/MM/yyyy HH:mm:ss"
     $outContent = "$timeStamp`tError`t`t$message`n"
     Add-Content $Logfile $outContent

#/// <summary>
#/// Prints logs in log file
#/// </summary>
Function LogInfo($message)
     $timeStamp = Get-Date -format "dd/MM/yyyy HH:mm:ss"
     $outContent = "$timeStamp`tInfo`t`t$message`n"
     Add-Content $Logfile $outContent

#/// <summary>
#/// Load the SharePoint Snapin 
#/// </summary>
#/// <returns>
#/// </returns>
Function Load-SharePoint-Powershell
    Write-Host "TEST"
	if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
	      Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction Stop

$Logfile = "c:\RTED\RTED-$(get-date -f MMddyyyy_HHmmss).log";
ExportSiteColumnXml $web


Get recurring event from calendar list using Angular JS

Getting recurring event from calendar list using Angular JS is some bit tricky.
I am going to implement through CEWP(Content editor web part) in SharePoint.

1. Create HTML file for display events description(Angular View)

<html ng-app="myApp">
	<head lang="en">
		<script src="jquery.min.js"></script> 
		<script src="angular.min.js"></script>
		<script type="text/javascript" src="main.js"></script> 
        <div ng-app="myApp" ng-controller="myCtrl">
            <div ng-repeat="result in results">   

Give the reference of Jquery and Angular js from your SharePoint site.

If you want to display upcoming limited(suppose top 5) events then you can add condition which is inbuilt facility of Angular JS

Add condition(ng-if) in Angular repeat section

<div ng-repeat="result in results" ng-if="$index < 4">   

2. Now Create one JavaScript which will get all events from calendar event list and check event start date with current date and display only feature events only.

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) 
    $scope.results = [];
	var currSiteUrl = _spPageContextInfo.siteAbsoluteUrl;
	var webUrl, calendarListName;
	webUrl= currSiteUrl;
	wsURL = webUrl + "/_vti_bin/Lists.asmx";	 
    $scope.request =
        "<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/'> <soap:Body>" +
        "<GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>" +
        "<listName>" + calendarListName+ "</listName>" +
        "<query>" +
        "<Query>" +
        "<Where>" +
           "<DateRangesOverlap>" +
           "<FieldRef Name='EventDate' />" +
           "<FieldRef Name='EndDate' />" +
           "<FieldRef Name='RecurrenceID' />" +
           "<Value Type='DateTime'><Year/></Value>" +
           "</DateRangesOverlap>" +
        "</Where>" +
        "</Query>" +
        "</query>" +
        "<queryOptions>" +
        "<QueryOptions>" +
            "<ExpandRecurrence>TRUE</ExpandRecurrence>" +
        "</QueryOptions>" +
        "</queryOptions>" +
        "</GetListItems>" +
	var results1 = [];
        method: 'POST', 
        url: wsURL, 
        async: false,
        data: $scope.request, 
        headers: {
            'Content-Type': 'text/xml; charset=\"utf-8\; action="http://schemas.microsoft.com/sqlserver/reporting/2010/03/01/ReportServer"'
    .success(function(xData, status, headers, config){       
        if (status === 200)
             var root = $(xData);
                    root.find("listitems").children().children().each(function () {
						$this = $(this);
						var ids = $this.attr("ows_UniqueId").split(";");
						var rec = $this.attr("ows_fRecurrence");
							"StartTime": $this.attr("ows_EventDate"),
							"EndTime": $this.attr("ows_EndDate"),
							"Title": $this.attr("ows_Title"),
							"Recurrence": (rec === "1" ? true : false),
							"Description": $this.attr("ows_Description"),
							"Guid": ids[1],
							"Id": ids[0],
	    var filtered_item = [];
	    for (var i = 0; i < results1.length; i++) 
			var current_Time = new Date().getTime()
			var Start_Time = new Date(results1[i].StartTime).getTime();
			if (Start_Time  >= current_Time) {
      $scope.results =  filtered_item;
    .error(function(data, status, headers, config){
        console.log('In Error');

To get the recurrence event we have added parameter “ExpandRecurrence” with value “True” by which we can identify that event is recurrence or not.

In output you will get Title, Description, Start time and location of event. You can customize as per your requirement and apply css also.


Upload Document using c# code to Share-Point library

Hello everyone,

I was facing the following exception.So i had searched and got the solution.

Only String, int, and DateTime data types can be used as the value in Properties while adding list item in document library.

I am including following concept with this blog.

1) how to upload document in to SharePoint library from the other library.
2) pass the document metadata using hash table.
3) How to update custom field of SharePoint library with uploaded document.
4) Limitations of Files.Add() methods with hash table.

Key Concept :
What is hash Table?

  • The Hashtable class represents a collection of key-and-value pairs that are
  • organized based on the hash code of the key.
  • It uses the key to access the elements in the collection.
  • A hash table is used when you need to access elements by using key, and you can identify a useful key value.
  • Each item in the hash table has a key/value pair.
  • The key is used to access the items in the collection.

1)How can I upload document in to the Document library from the other document library and update Document library meta data in share point?
2)How can I update document library custom field with user type and Date time type Using c# code?
Let’s take document library:
1) UserInformation(Destination Library)
Custom Fields : 1) DocUpdateDate: DateTime 2)DocAddedBy: User
2) BioData(Source library)


//Get the Source library
 SPList BioData = elevatedWeb.Lists.Cast().FirstOrDefault(l => l.id == listID);
 if (bioData!=null)
 spListItem bioDataItem = bioData.GetItemById(itemID);
 // get file from the item which you want to upload the destination.
 SpFile objFile = Item.File;
 string fileName = objFile.Name;
 //Getting latest published version file content
 byte[] fileContent = null;
 if (objFile.UIVersionLabel.Contains(".0"))
 fileContent = file.OpenBinary();
 string versionString = string.Format("{0}.0", objFile.MajorVersion.ToString());
 SPFileVersion version = objFile.Versions.GetVersionFromLabel(versionString);
 fileContent = version.OpenBinary();
 // Now open the Destination library where you want to upload document.
 SpList UserInformation = elevatedWeb.Lists.Cast().FirstOrDefault(l => l.ID == listID);
 // create a hastable to stored the Document metadata.
 HashTable properties = new HashTable();
 // Add metadata key and value of the document.
 // you can number of properties as per the business requirement.
 // now upload the document in to the library.
 // to upload the file ,open the object of the SpFile.
 elevatedWeb.AllowUnsafeUpdates = true;
 SpFile uploadFile = UserInformation.RootFolder.Files.Add(fileName, fileContent, properties);



Limitations of Files.Add() methods with hash table.
If I add a column of type Currency then the code will break and it won’t add the list item to the library at all.Because the function list.RootFolder.Files.Add() will not accept the properties other than the 3 types mentioned,through HashTable
This is the problem with the function. To avoid that below is the code i used and this problem went away.


// create a SPListItem object from the objFile.
spListItem objListItem = uploadFile.Item;
objListItem[“DocUpdateDate”] = DateTime.Now;
// update list item
elevatedWeb.AllowUnsafeUpdates = false;


Finally, updating the list item and updating the file to reflect the changes to the document library list items.

Please feel free to post your ideas, comments and question here.

Happy Coding🙂


Create folder in list using workflow

For workflow being able to create folders, you need to assign the folder content type to the list and then create new item from workflow using folder content type.

Add folder content type in list

  1. Open the list in an internet browser. There will be an option bar at the top.
  2. Select “List” and choose “List Settings” in the new ribbon.
  3. Click on “Advanced Settings”, activate the option “Enable management of content types” and click on “OK”.
  4. Back to the list settings.
  5. Click on “Add from existing content types”.
  6. In the new page, select “Folder Content Type” from the dropdown menu.
  7. Add the content type named “Folder” to the list content types by selecting it and clicking on the arrow pointing to the right.
  8. Click on “OK” to save the new assignment.


Now folder content type is added in list. Now create workflow on list which will create folder in list

Create folder using workflow

  1. To create a folder, choose the action “Create a list item”.
  2. Click on action to fill more information.
  3. Choose the list where the folder shall be added from the dropdown field.
  4. If your list has multiple content types, a field to assign a value to, will automatically be added. It is called “Content Type ID”. If it is not present, click on “Add” to add this field.
  5. Select “folder” from dropdown.
  6. Set title field for folder name.


Now your folder will be create through workflow. Folder can also create in document library through workflow by same procedure.


URL & Locations in SharePoint

In this blog i am sharing some important URLs and Locations in SharePoint which can help developer as well as administrator to access resources easily.


1. Sign in as a different user

2. Change Site Master Page

3. Page Layouts and Site Templates

4. User Information List:

5. Sandboxed Solution Gallery:

6. All site content page (Site content):

7. Site settings page:

8. Site collection features(CASE SENSITIVE):

9. Site features:

10. Get the version of the SharePoint server (Patch level):

11. Web Part Maintenance Page:

12. Save Site as a template

13. Master Pages library

14. Master Page Gallery

15. Site Column Gallery

16. Site Content Types

17. Managed Metadata (Subset used terms on site) -Added by DAMIAN

18. Test Sample Page (If trouble with username in site) -Added by DAMIAN

19. Site Manager (Site Structure) -Added by HUGO CARREIROS

20. Save site as Template (Office365)