Archive

Archive for the ‘SharePoint 2013’ Category

SharePoint – Creating a Rotating Image Banner using JavaScript

April 27, 2015 2 comments

In this post I will show you how easily we can create a Rotating Image banner in SharePoint 2013. (I saw the requirement from http://sharepoint.stackexchange.com/a/139738/34350)

Images are stored in an Images Library (Picture Library)

First you need to place anĀ img tag into the Page. This is the tag which loads Images from Library and cycles images every 5 seconds.

<img id="imageRotator" >

Once this is added, you can use below JavaScript code


	var arrayOfImageObjects = new Array();
	var currentImageIndex = 0;
	
	function GetImagesAndRotate() {
		var url = "http://siteurl/_api/web/lists/getbytitle('ImageLibrary')/items?$expand=File"
		
		jQuery.ajax({
			url: url,
			type: "GET",
			headers: { 
				"X-HTTP-Method":"MERGE",
				"accept": "application/json;odata=verbose",
				"content-type": "application/json;odata=verbose",
				"X-RequestDigest": $("#__REQUESTDIGEST").val(),				
			},
			success: function(data){
				var result = data.d.results;
				for(i=0;i<result.length;i++){
					var image = result[i];
					var imageObject = { };
					imageObject.Name = image.File.Name;
					imageObject.Url = image.File.ServerRelativeUrl;
					imageObject.Width = image.File.ImageWidth;
					imageObject.Height = image.File.ImageHeight;					
					arrayOfImageObjects.push(imageObject);
				}				
				setTimeout(NextImage,5000);
			},
			error: function(){
				alert("request failed");
			}
		});
	}
	
	function NextImage(){		
		if(currentImageIndex < arrayOfImageObjects.length) {
			jQuery('#imageRotator').attr('src',arrayOfImageObjects[currentImageIndex].Url);
			currentImageIndex++;
		}
		else
			currentImageIndex = 0;		
		setTimeout(NextImage,5000);
	}

Finally you can invoke this using

	jQuery(document).ready(function(){
		GetImagesAndRotate();
	});
Advertisements

SharePoint – Retrieve SharePoint Timer Job Schedule

Here is a utility function which can give you the Job Schedule

string GetTimerJobStatus(string timerJobName) 
{
    string schedule = string.Empty;

    SPSecurity.RunWithElevatedPrivileges(() => 
    { 
        SPWebApplication webApp = SPContext.Current.CurrentWeb.WebApplication;
        foreach (SPJobDefinition job in webApp.JobDefinitions)
        {
            if (job.Name.Equals(timerJobName))
            {
                schedule = job.Schedule.GetType().FullName;
                break;
            }
        }
    });

    return schedule;
}

SharePoint – JSOM Sample for SP.AttachmentCollection.getByFileName Method

Today I found a question in StackExchange.

http://sharepoint.stackexchange.com/questions/136304/fetch-list-item-attachment-by-name

The OP was asking how to use this method using Client Side Object Model. Since this is not available in MSDN (https://msdn.microsoft.com/en-us/library/office/jj245502.aspx) I thought of creating it.

Here is the sample – You should change the LISTNAME, ID & FILENAME

var clientContext = SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle("LISTNAME");
var listItem = list.getItemById(ID);
clientContext.load(listItem);
clientContext.load(listItem.get_attachmentFiles().getByFileName("FILENAME"));
clientContext.executeQueryAsync(Function.createDelegate(this, onSuccess), Function.createDelegate(this, onFailure));

function onSuccess(sender, args) {
	var item = listItem;
	var total = item.get_attachmentFiles().get_count();
	if (total > 0) {
		console.log(total + " file attachments");
	}		
}

function onFailure(sender, args) {
	//failed
}

SharePoint 2013 – Read List Items using REST API

December 23, 2014 1 comment

SharePoint 2013 introduced Rich REST endpoints, we can use this to query data asynchronously using jQuery/JavaScript.

Here is a sample code which can be used to read items from a SharePoint list

var siteUrl = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl;

jQuery.ajax({
	url: siteUrl + "/_api/lists/getbytitle('ListTitle')/Items?$select Title",
	type: "GET",    
	headers: { 
		"accept": "application/json;odata=verbose",
		"content-type":"application/json;odata=verbose",
		"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
	},
	success: function(d) {
		var stringData = JSON.stringify(d);
		var jsonObject = JSON.parse(stringData);
		var results = jsonObject.d.results;
		for(i = 0; i < results.length;i++) {
			console.log(results[i]["Title"])
		}
	},
	error: function() {
		console.log('fail');
	}
});

We are dynamically forming the site url using various tokens.

First we need to get the SharePoint list, for that we use REST method GetByTitle and pass the list title. Then we are selecting the item Title. You can add more fields by separating with comma.

The result is then converted to JSON object using JSON.Parse method.

Finally a loop is used to iterate through the items.

Categories: SharePoint 2013 Tags: , , ,

SharePoint 2013 – Hide page title

December 4, 2013 7 comments

Here is a snippet which can be used to hide page title. All you need to do is edit the master page and place the script inside head tag

<script type="text/javascript">
	function hidePageTitle() {
		var elem = document.getElementById('pageTitle');
		elem.style.display = 'block';
	}

	_spBodyOnLoadFunctionNames.push("hidePageTitle"); 
</script>

SharePoint 2013 – Open folder in new window

December 3, 2013 Leave a comment

I found a question related to opening folder in new window.
http://social.msdn.microsoft.com/Forums/vstudio/en-US/6fb8e8e7-c3f8-4df9-9ecf-cf48851dc1c0/open-links-from-folders-in-document-libraries-from-a-new-window?forum=sharepointgeneral

The solution is to override HandleFolder method and use the script below

function HandleFolder(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) {
	var parts = new Array();
        parts = c.toLowerCase().split('%2f');
        c = c.replace('SitePages/Home.aspx',parts[1]);
	window.open(c);
	return false;
}

Edit page, add new script editor webpart and use the script.