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();
	});

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 Online – Setting up PowerShell

SharePoint global administrator can use the SharePoint Online Management Shell to manage the site and content.

Following are the steps we should do for that

  1. Install Windows Management Framework 3.0 – You can download it from http://go.microsoft.com/fwlink/p/?LinkID=244693. This require a system restart
  2. Install SharePoint Online Management Shell – You can download it from http://go.microsoft.com/fwlink/p/?LinkId=255251

Once this is done, you can start “SharePoint Online Management Shell” and use following command to connect

Connect-SPOService -Url https://tenant-admin.sharepoint.com -credential admin@tenant.com

After connection, you can execute SPO cmdlets and work remotely.

Example:

Get-SPOSite

will retrieve all sites.

Take a look at this http://technet.microsoft.com/en-us/library/cb90889b-9c1e-4cec-ab0f-774be623022f(v=office.15) to find the list of supported cmdlets

Categories: Misc, SharePoint Online Tags:

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 – Updating External Lookup Field

November 21, 2014 Leave a comment

Updating an external look up is a bit different compared to updating other look up fields.

Below is a small snippet which can help you with this task

SPBusinessDataField dataField = item.Fields["Field Display Name"] as SPBusinessDataField;
item[dataField.RelatedField] = EntityInstanceIdEncoder.EncodeEntityInstanceId(new object[] { NEWVALUE }); ;
item["Field_x0020_Internal_x0020_Name"] = newCRMNumber;

For getting SPBusinessDataField you need to get the fields from item which is the listitem we are trying to modify.

item.Fields["Field Display Name"] – This require you to pass the Field Display name

SharePoint – Programatically Starting a Workflow

Here is a code snippet I recently developed for starting a sharepoint workflow from code behind.

public void StartWorkFlow(string listName, int itemID, string workflowName)
{
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
        {
            using (SPWeb oWeb = oSite.OpenWeb())
            {
                oWeb.AllowUnsafeUpdates = true;
                SPList oList = oWeb.Lists[listName];
                SPListItem oItem = list.GetItemById(itemID);
                SPWorkflowManager wfManager = oSite.WorkflowManager;

                foreach (SPWorkflowAssociation association in oList.WorkflowAssociations)
                {
                    if (association.Name == workflowName)
                    {
                        string associationData = association.AssociationData;
                        wfManager.StartWorkflow(oItem, association, associationData);                                
                        break;
                    }
                }
                oWeb.AllowUnsafeUpdates = false;
            }
        }
    });
}
Categories: SharePoint, SharePoint 2010 Tags:
Follow

Get every new post delivered to your Inbox.

Join 396 other followers