List subsites using the JavaScript client object model in SharePoint 2013

SharePoint Office 365 Site Creation JavaScript

To do this, use the script editor web part or the page viewer web part (and put the HTML file in a document library).

To start off, setup the HTML to include jQuery and sp.js (see below).

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
 //alert('loaded');
});

JQuery functions are used to populate HTML containers on the page.

<div id="tonycontent">
	<!-- Dashboard -->
	<div id="tonydashboard" class="tonycontenttable">
	</div>
</div>

The first function loads the current site. The get_current function returns the current context of the user from which the subsites can be retrieved (see below).

function getSubWebs(){
	clientContext = new SP.ClientContext.get_current();
	web = clientContext.get_web();
    	webCollection = web.getSubwebsForCurrentUser(null);
    	clientContext.load(webCollection);
    	clientContext.executeQueryAsync(onGetSubwebsSuccess, onGetSubwebsFail);
}

If the query is successful it will load the onGetSubwebsSuccess function, otherwise it will run onGetSubwebsFail function.

In the success function, the webCollection variable is looped through to retrieve the URL and the title of each subsite. JQuery functions are then used to append the HTML containers.

function onGetSubwebsSuccess(sender, args){
	jQuery("#tonydashboard").empty();
	var html4 ="<div class='tonycontenttablerow'><div class='tonycontenttabletitle'>Site Name</div><div class='tonycontenttabletitle'>Site URL</div></div>";
	jQuery("#tonydashboard").append(html4);
    var webEnumerator = webCollection.getEnumerator();	
    while (webEnumerator.moveNext()){
        var web = webEnumerator.get_current();
		var webtitle = web.get_title();
		var weburl = web.get_serverRelativeUrl();
        var html3="<div class='tonycontenttablerow'><div class='tonycontenttablecolumn'>" + webtitle + "</div><div class='tonycontenttablecolumn'>" + weburl + "</div></div>";
		jQuery("#tonydashboard").append(html3);
    }
}

Download the full code here

The client object model can also be used to create subsites from templates, permission sites, create lists and much more! This method works on both 365 SharePoint Online and SharePoint 2010 and SharePoint 2013 on-premises.

SharePoint 2013 JavaScript Client Object Model

Using document templates in SharePoint (365 and on premise)

Document Library Templates

Each content type in a document library can be assigned an individual document templates. In the document library below, two different content types have been added, each with a different template.

Tony is here

To edit the word templates, open the site in SharePoint designer 2013.

SharePoint Designer

Open the document library.

SharePoint Designer

In the content types section, open the content type (in this case it is called Policy).

Content Types

In the ribbon select “Edit Document Template”.

Edit Template

This will allow you to create a dotx document which will be the template for this particular content type in this library. Once the template has been saved, it will be available as the main template for the content type.

Select Document

When users create a document using the Policy content type from the new menu, it will prompt them to enter a name for the new document.

Name Document

Please note that currently, the new templates will only open in Office Web Apps (online) if using Internet Explorer. Other browsers will prompt to open in the client application.

Office web Apps online

JavaScript Client Object Model in SharePoint 2013

SharePoint 2013 has a new and more complete JavaScript Client Object Model API. Some of the additional functionality is using social networking.

Using the JS COM, followers can be pulled from SharePoint for the current user or a specific user. This might be used for creating a new social networking interface

My Followers

First load JQuery and the SharePoint 2013 JavaScript functions. The JavaScript functions are loaded on the page so it is just a case of waiting for specific functions to be loaded before the script will work correctly (see below):

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
	SP.SOD.executeFunc('userprofile', 'SP.UserProfiles', function () {
		tonyishereGetUserProfileProperties();
	});
});

Once the functions are loaded, the People manager object can be created. The example below was taken from the Micrsoft site and modified, this is a great resource if you are starting out with the client object model.

http://msdn.microsoft.com/en-us/library/office/jj679673.aspx

function tonyishereGetUserProfileProperties() {
    // Get the current client context.
    var clientContext = SP.ClientContext.get_current();
    // Get the PeopleManager instance.
    var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
    // Get the people who are following the current user.
    Followers = peopleManager.getMyFollowers();
    clientContext.load(Followers);
    // Send the request to the server.
    clientContext.executeQueryAsync(displayFollowers, requestFailed)
}

Once the object has been loaded successfully, functions can be run to pull out the required data. In the example below, the data is stored in a string which is then displayed as HTML in a div using JQuery.

function displayFollowers() {
    var results = Followers.getEnumerator();
	var myFollowers = "Followers<br />";
    while (results.moveNext()) {
    var person = results.get_current();
		myFollowers = myFollowers + "<br />" + person.get_displayName();
    }
	jQuery("#MyFollowers").html(myFollowers);
}

The script was added to the page without the use of Visual Studio or SharePoint Designer 2013. The script was inserted using the Script Editor web part. This web part runs client side code such as HTML and JavaScript.

Script Editor

The same methods can be used to pull out a whole host of data from the social aspects of SharePoint 2013 including the profile picture, display name, hash tags and trending topics.

Profile web part

Troubleshooting Office Web App Farm Installations

New functionality in Microsoft Office Web Apps is the preview feature in search (see below). Setting up a separate farm for Office Web Apps is a great way to improve performance and make a scalable solution but it can bring up some new technical challenges. A couple of the most common issues are listed below.

Web Apps Search Preview

Do the internal and external URLs of the Web Apps Server resolve from the SharePoint server?

Test: https://webapps.contoso.com/hosting/discovery
Should return XML without certificate error

Test: https://WebAppServer01.contoso.com/hosting/discovery
Should return XML without certificate error

Certificate Error?

When setting up the web apps farm, a SAN certificate needs to be specified with both the internal URL and the external URL (see below). Wildcard or single host certificates will not work.

SAN Certificate
404 not found?

Both the SharePoint and Web App server need to see each other. Make sure that internal DNS is setup for the external web app address. Run ipconfig /flushdns on the SharePoint server. The SharePoint server needs to resolve both addresses internally.

The Web Apps server also needs to have an entry for the SharePoint site URL. Ensure that the SharePoint site has an internal DNS entry and flush the DNS on the web apps server. Browse to the SharePoint site on the web apps server to ensure that it can see the site without any certificate errors.

How to enable blob cache for SharePoint 2013 image renditions

One of the new features of SharePoint 2013 is the image renditions. When configuring this you may find the following error:

The blob cache is not enabled in this web application. Image renditions will not be generated until the blob cache is enabled. For information on turning on the blob cache, please review the product documentation.

Image Renditions Error SharePoint 2013

Resolution:

Open the web.config file for the web application in a text editor. Search for “blobcache location”.

Inside this tag, change the “enabled” attribute from false to true (see below). This will enable blob cache on the server to enable SharePoint 2013 image renditions.

 
<BlobCache location="C:\BlobCache\14" path="\.(gif|jpg|jpeg|jpe|jfif|bmp|dib|tif|tiff|themedbmp|themedcss|themedgif|themedjpg|themedpng|ico|png|wdp|hdp|css|js|asf|avi|flv|m4v|mov|mp3|mp4|mpeg|mpg|rm|rmvb|wma|wmv|ogg|ogv|oga|webm|xap)$" maxSize="10" enabled="true" />

Save the web.config file and refresh your browser page. All sorted!

Image Rendition Working in SharePoint 2013

Client-side RSS feed viewer using JavaScript

There are plenty of server-side RSS feed viewers out there but very little in the case of client-side JavaScript based viewers. Below I will go through the steps of creating a simple JavaScript based RSS feed viewer. Please note that this will only work with RSS feeds on the same domain. JavaScript does not allow cross domain scripting. You may find ways round this by using some of the Google API.

RSS Viewer
Create HTML Container

First begin by creating a HTML div container with a unique ID.

<div id="myDiv"></div>

Make a XML HTTP Request

The following function returns the data from an RSS (XML) page. As far as I am aware there is no way to use this cross domain, so you will have to look for a server-side script to work cross domains.

function httpGet(theUrl) {
			var xmlHttp = null;
			xmlHttp = new XMLHttpRequest();
			xmlHttp.open("GET", theUrl, false);
			xmlHttp.send();
			return xmlHttp.responseXML;
		}
var rssFeedData = httpGet('http://www.tonyishere.co.uk/RSSExample/rss.xml');

Loop through the data and retrieve tags by name

Once this data has been stored in the variable as an object, we can use the “getElementsByTagName” function to pull out a particular tag (title in this case). Looping through all the tags called “title” will go through all of the XML from top to bottom. While looping through the tags, we can store the title and description in arrays to use later.

			var i=0;
			var allTitles = [];
		var allDescriptions = [];
			// loop through all of the items and put them in arrays
			while (rssFeedData.getElementsByTagName("title")[i])
			{
					allTitles[i] = rssFeedData.getElementsByTagName("title")[i];
					allDescriptions[i] = rssFeedData.getElementsByTagName("description")[i];
					flag=i;
					i=i+1;
			}

Loop through the arrays and render the data

Looking at the structure of the XML, you should be able to pick out the child nodes. In this case, each item is the first node (numbering starts from 0).

This can then be rendered as HTML and inserted into the div created earlier. In the example below I have decided to store the description and call an onclick function to show the description.

for (i=0;i<flag;i++){
				titles[i]=allTitles[i].childNodes[0].nodeValue;
				descriptions[i]=allDescriptions[i].childNodes[0].nodeValue;
				document.getElementById('myDiv').innerHTML = newHTML;
				newHTML = document.getElementById('myDiv').innerHTML;
				newHTML = newHTML + "<div class=\"titlearea\" id=\"title" + i + "\" onclick=\"showdesc('" + i + "');\">" + titles[i] +"</div><div id=\"desc" + i + "\"></div>";
				document.getElementById('myDiv').innerHTML = newHTML;
			}

Show the description

When the onclick function to display the description is run, the function below inserts the description stored in the array into the desc div. The array position was called as an argument to the function. This enables us to display the correct description in the div.

function showdesc(idc){
			var idcdesc = "desc" + idc;
			document.getElementById(idcdesc).innerHTML = descriptions[(idc-1)];
		}

Starting point for RSS feed viewer

Click on the link below to see the full code working. This is a very simple example of what can be done with RSS feeds using client-side scripting only. Hope this is of interest, please contact me on twitter for feedback and questions.

RSS Viewer Example

Fixing SharePoint 2010 dynamic menus on the iPad

When using an iPad with the default v4 Master Page in SharePoint 2010, the dynamic drop down menus do not function as expected. When using a mouse, a simple hover over the menu item will drop down the dynamic menu child items (as shown below).

SharePoint 2010 menu on ipad

When using an iPad, iPhone and most other smart phone/tablets device, there is no mouse and no hover over action. When clicking on the parent menu item, the user is taken to that link instead of showing the child items.

To solve this issue (partially), I created some jQuery code to allow the first tap to drop down the menu items and the second tap to take the user to the chosen page.

First I use the jQuery ready function to load my script when the page has fully loaded.

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

When the page has finished loading, the type of device needs to be detected. In the example below I have used the iPhone, iPad and iPod devices. There are alternative devices!

if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
}

This solution involves using a counter to detect the first tap of a dynamic menu item as a hover over and the second tap as the actual click. First, set the counter to 0.

var countipad=0;

Another handy jQuery function is used to detect when a dynamic menu item is clicked. Using this class “dynamic-children” ensures that only the first click of a drop down menu is cancelled.

jQuery("a.dynamic-children").click(function() {
}

If the click is the first click, the default action (redirect) is prevented. The counter is then incremented ready for the next click.

if(countipad==0){
	event.preventDefault();
	countipad=countipad+1;
}

The full solution is as follows:

jQuery(document).ready(function() {
	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
		var countipad=0;
 		jQuery("a.dynamic-children").click(function() {
			if(countipad==0){
				event.preventDefault();
				countipad=countipad+1;
			}
		});
	}
});

This isn’t a great solution as the second click will always take you to the link. A better solution would detect which link is selected and only redirect on the second click of that particular menu item.

ipad menu SharePoint 2010

Design Manager in SharePoint 2013

There are a number of options available for visual designers and information architects. One of the great new features in SharePoint 2013 is the Design Manager. You can locate this by going to the settings menu and selecting “Design Manager”

Screen 1

Design Manager is a series of pages and links to take you to the design libraries similar to those found in SharePoint 2010. From welcome page you can import wsp packaged designs or pick from a pre-installed master page.

Screen 3

“Manage Device Channels” is a new feature which allows you to change the look and feel of a site based on the client’s device or browser. This is great for optimising the rendering of the page in mobile devices.

Screen 4

The “Upload Design Files” is a link to the _catalogs folder which was also used in SharePoint 2010 and MOSS to store the Master Pages. It recommends that this is mapped as a network drive.

Screen 5

“Editing Master Pages” is a link to the _catalogs folder which was also used in SharePoint 2010 and MOSS to store the Master Pages.

screen 6

“Edit Design Templates” is another new feature in SharePoint 2013. It allows customisation of the way content is displayed. This might be used to customise search results by defining fields but also presentation. More information can be found here http://msdn.microsoft.com/en-us/library/jj163942%28v=office.15%29.aspx

screen 7

“Edit Page Layouts” is another shortcut to a library which was also used in SharePoint 2010 and MOSS. It displays the page layout content types from the master page gallery.

screen 8

The page shown below reminds the designer to publish all of the files before applying the design to the site. A handy link to apply the Master Page is provided.

Create design package allows the design to be exported and used on other sites. This is really useful for taking a design from a development environment to the live site. To create this package previously would have required creating a solution or feature in Visual Studio and deploying it to the server or site collection. This is a handy tool to do this for you.

All of the features below are described in more detail on Microsoft’s site.
http://msdn.microsoft.com/en-us/library/jj163942%28v=office.15%29.aspx

While the design manager is more of a guide than somewhere an experienced designer will actually upload there designs to (SharePoint Designer will be the main tool), it does make the design process clearer and provides some neat tools for the new functionality about to be released in Microsoft SharePoint 2013.

SharePoint 2013 Design Manager

SharePoint 2013 Preview

SharePoint 2013 Preview

SharePoint 2013 Preview version was released this week. I took the chance to install it and get a first look at the new version of Microsoft’s powerful integration content management software.

Resources:
Install files can be found here
http://www.microsoft.com/en-us/download/details.aspx?id=30345
SharePoint 15 Training files
http://technet.microsoft.com/en-US/sharepoint/fp123606

SharePoint 2013 Preview Home
Install notes:

The install is very similar to SharePoint 2010. Hardware requirements seem to be exactly the same as the previous version. The only additional work I had to do was upgrade SQL Server 2008 R2 to service pack 1.

Office Web Apps:

Office web apps are no longer a service application within SharePoint. In fact they are now set up as a completely separate farm from SharePoint. This is because other products/services can integrate with this farm such as exchange. This also allows web app system usage and load to be completely independent from the SharePoint farm.

Mobile View:

The new version of SharePoint will have device detection to redirect to a mobile site. Also capable of mobile push notifications.

Sharing:

When a site is created, the site owner is encouraged to share the site using the share button at the top of the page. This seems to be more of a rewording/rearrangement of the site permissions page.

Apps:

Lists and Libraries have been renamed Apps. You can download additional Apps from the SharePoint Store (very original).

Apps
Ribbon:

The ribbon has been restyled slightly but the biggest improvement is in the performance of the ribbon appearing when editing the page. Waiting for the ribbon to load a tab in SharePoint 2010 no longer happens in SharePoint 2013, the ribbon slides out instantly and smoothly.

Ribbon

Of course there is far more to SharePoint 2013 than just this. I will post back when I have dug a little deeper.

Theming