All posts in Development

Customize SharePoint Forms with KendoUI Grid

Today I am going to shift gears a bit from ITPro\Admin topics to a dev based topic. I would like to show you how to customize SharePoint forms with KendoUI Grid. Everything I cover in this post can be done in either SharePoint On-Premise or SharePoint Online (O365).

I recently had a need to add a field to a SharePoint form that contained multiple columns of its own data. For example a table or grid within the form itself. A couple of OOTB ideas to handle this could be a lookup field that also brings in additional fields from the lookup list:

Read more

Create a List of SharePoint Views Using REST

My client has a sub site that has the sole purpose of housing their policy documents.  They don’t want any other team site features on this site, just the library.  The library contains a couple thousand documents all nicely categorized using metadata and organized by views.  A recent request from them was to clear their site’s landing page of the default web parts and replace it with a list of the views.  Each view in the list should link directly to that view in the library.  To facilitate their request I decided to create a list of SharePoint views using REST services.

Choosing a Method

A number of methods are available for us to accomplish this:

  1. Server-side Web Part: Bad.  Don’t do this anymore.  Stay as far away from server side code as much as possible.  This is a discussion for another day and there are lots of resources out there outlining why we shouldn’t, but suffice to say, don’t do it.
  2. CSOM Add-In: This is a strong possibility and one that is generally used, but we have developed a policy to avoid CSOM solutions because it still requires assemblies that have to be maintained
  3. JSOM Add-In: This method is perfectly fine and something available to any SharePoint solution.  It would suffice for my needs.  I just chose a different method.
  4. JavaScript and REST: I chose this method not because it is better than any of the others listed, but simply because my need was very basic and I didn’t need to build out a full solution to achieve my requirements.  I could create my solution using a Content Editor Web Part (CEWP) and a single JavaScript file (well two because I used JQuery as well).

Create a List of SharePoint Views Using REST

The solution is pretty straight forward and uses very little custom code.  The gist of the solution is removing all the web parts from the page.  Adding the CEWP to the page.  Uploading JQuery and my custom code file to Site Assets and referencing them from within the CEWP.

ListCollection REST Endpoint

To get the data from the list we need to make use of the ListCollection resource.  A method within the resource allows us to access a list within by it’s name.  So your REST call will have a base something like: “/<Site Name >/_api/web/lists/getbytitle(<List Title>)”  So this gives us the list object.  Instead of using the return data from SharePoint on this, we are able to tell the call that we want the views property within.  So in the end our REST call is going to be http://teams.drevsp2013.com/bcs/_api/web/lists/getbytitle(‘Laptop Request Form’)/Views

Because it is so easy to work with we of course want to ensure we tell the service call we would like the results in JSON format.  So we need to add an accept to the header “accept: application/json;odata=verbose

Test with Fiddler

When checking out any REST endpoint I always use Fiddler.  Two reasons:

  1. Ensure I format my REST call correctly
  2. Take a look at how the data is coming back so I know how to handle it in code

Setup and execute a Fiddler test as follows:

Create a List of SharePoint Views Using REST - FiddlerCall

Taking a look at the JSON return, we see that we want to make use of the Title and the ServerRelativeUrl fields:

Create a List of SharePoint Views Using REST - Fiddler REST Return

Create the REST Call

So building out this knowledge I wrote a little method called GetViewDetails.  It accesses the REST endpoint and builds an associative array (I’ll explain why in a minute) to store the title and URL of the views.

function GetViewDetails(siteName, listName){
    var restURL = "/" + siteName + "/_api/web/lists/getbytitle('" + listName + "')/views";
    var viewArray = [];
    
    //Call the list API and gather information on all the views.
    $.ajax({        
        url:restURL,
        type:"GET",
        headers: {"accept": "application/json;odata=verbose"},
        async: false,
        success: function(data){
            $.each(data.d.results, function(index, item){
                //Need to ignore the All Documents and the hidden views:
                if(item.Title != "All Documents" && item.Title != "Merge Documents" && item.Title != "Relink Documents" && item.Title != "assetLibTemp")
                {
                    //build the associative array
                    viewArray[item.Title] = item.ServerRelativeUrl;                   
                }
            });
        },
        error: function(error){
            $('#DisplayViews').append("<p>An Error occurred building list of policy groups. Error received: " + JSON.stringify(error) + "  Please contact the service desk");
        }
    });     
    
    return viewArray;
}

Because the client only wanted their custom views I do not add All Documents or the internal hidden views to the array.  Also note that I do not want this to be called asynchronously.  Reason being is I am building out that array and I want to be able to return the values.  If I don’t do this, it will return the data before the array is built.

Another requirement is to place all the views in alphabetical order.  The REST service doesn’t do that by default.  It actually returns the views in the order they were created.  Enter the Associative Array.  The associative array in Javascript is a Key\Value based array.  So basically a dictionary or hashtable.  By placing my data into this array I can sort the data on the key (view title) portion of the array.  Before I show you that part, I am going to first add the necessary code to my CEWP as I make reference to some HTML in the web part within the next method.

After you add the CEWP, edit the source of the web parts content.  Inside the HTML we are going to add the a div that our code can hook into and the script calls for the JS files.

Create a List of SharePoint Views Using REST - DIVInCEWP

So back to the JavaScript.  The final piece to write is the portion that sorts the array and writes to the CEWP.  The code to handle this:

function displaySortedViews(viewArray) {              
    //sort the array keys
    var sortedKeys = Object.keys(viewArray).sort();
    
    //create an unordered list on the page
    $('#DisplayViews').append("<ul id='viewList'></ul>");
    
    //loop through each view and add to the page.
    for(var i=0; i < sortedKeys.length; i++)            
    {
        $('#viewList').append("<li> <a href='" + viewArray[sortedKeys[i]] + "'>" + sortedKeys[i] + "</a></li>");
    }
}

In the code above, it sorts the key values of the array and places them into a new variable.  We then use that order to loop through every item in the array and display them as needed.  viewArray[sortedKeys[i]] is basically saying give me the value of the array when the key is equal to the value at ‘i’.  We then attach to the un-ordered list created before the loop and for each entry in the array we add a list item to the un-ordered list.

So what we end up with is a list of links that correspond to each view and the url of the view.

Create a List of SharePoint Views Using REST - List of Views

 

The final JavaScript file looks like this:

/**********************************************************************************************
* Title: createViewLinks.js                                                                   *
*                                                                                             *
* Date             Who             Comments                                                   *
* April 28, 2016   David Drever    Created to gather the views and their URLS in a            *
*                                  library and build a list to directly link to               *
*                                  them                                                       *
***********************************************************************************************/

$(document).ready( function() { 
    var siteName = "bcs";
    var listName = "Laptop Request Form";   
    var arrayViews = GetViewDetails(siteName, listName);
    displaySortedViews(arrayViews);
});


/**********************************************************************************************
*Function Name: GetViewDetails              												  *
*Parameters: siteName - URL Sitename of site we are accessing data from 				      *
*            listName - Name of the list to access                 							  *
*			                                 												  *
*Return Value: Returns associative array containing Item Title (key) and URL (Value)          *
*Purpose: Accesses the list's view endpoint to gather data on each view within the list       *
***********************************************************************************************
*/
function GetViewDetails(siteName, listName){
    var restURL = "/" + siteName + "/_api/web/lists/getbytitle('" + listName + "')/views";
    var viewArray = [];
    
    //Call the list API and gather information on all the views.
    $.ajax({        
        url:restURL,
        type:"GET",
        headers: {"accept": "application/json;odata=verbose"},
        async: false,
        success: function(data){
            $.each(data.d.results, function(index, item){
                //Need to ignore the All Documents and the hidden views:
                if(item.Title != "All Documents" && item.Title != "Merge Documents" && item.Title != "Relink Documents" && item.Title != "assetLibTemp")
                {
                    //build the associative array
                    viewArray[item.Title] = item.ServerRelativeUrl;                   
                }
            });
        },
        error: function(error){
            $('#DisplayViews').append("<p>An Error occurred building list of policy groups. Error received: " + JSON.stringify(error) + "  Please contact the service desk");
        }
    });     
    
    return viewArray;
}


/**********************************************************************************************
*Function Name: displaySortedViews             												  *
*Parameters: viewArray - Associative array of view title\URLs            				      *
*			                                 												  *
*Return Value: None                                                                           *
*Purpose: Sorts list of views and displays to page                                            *
***********************************************************************************************
*/
function displaySortedViews(viewArray) {              
    //sort the array keys
    var sortedKeys = Object.keys(viewArray).sort();
    
    //create an unordered list on the page
    $('#DisplayViews').append("<ul id='viewList'></ul>");
    
    //loop through each view and add to the page.
    for(var i=0; i < sortedKeys.length; i++)            
    {
        $('#viewList').append("<li> <a href='" + viewArray[sortedKeys[i]] + "'>" + sortedKeys[i] + "</a></li>");
    }
}

 

Thanks for reading!!

Stop Looping through Sites and Lists in SharePoint There are Better Ways

I recently received a request at my client site to review a custom built feature that was no longer responding\functioning properly within our SharePoint environment. The feature was designed to copy selected files from a project site to the team site of the group whom would be taking over daily operations of the project once the solution was in production. Once copied the documents were declared as records within our Record Management System. The process was to select the files to be moved and then from the ribbon select the option to set the destination. This is the part that was not working.

Read more

Build Views on the Fly When Gathering Data from SharePoint

So recently at my client site we had a report that was running incredibly long.  This was a while ago, so unfortunately I can’t remember the run time, but I believe it was greater than 12 hours.  The report was pretty basic, just a determination of which documents were created within the month and an output that displayed things like location, file name, created date and creator.

When reviewing the code I noticed the original solution had been coded to loop through each site in the web and then grab all the documents within a particular date range.  The line in particular that scanned the documents was as follows:

 

[code language=”csharp”]
var listAddedItems = listItems.Where(x => ((DateTime)x["Created"] >= reportManager.ReportStartDate && (DateTime)x["Created"] <= reportManager.ReportEndDate) || ((DateTime)x["Modified"] >= reportManager.ReportStartDate && (DateTime)x["Modified"] <= reportManager.ReportEndDate));
[/code]

Pretty straight forward, but what it’s actually doing is going through and gathering all the data and throwing out what you don’t need.  Not a big deal unless you are working with a lot of data.  Right now we are sitting at around 1 million items in our SP farm.  I think I found the culprit.

Read more

Leading Practices for Planning and Implementing a SharePoint Environment

This month I traveled to Saskatoon, Edmonton and Calgary to present on the Leading Practices of Planning and Implementing a SharePoint Environment.  This was not meant as a technical discussion, but instead a discussion on implementing a SharePoint environment.  There is a bit of technical topics within it, but the focus is how to plan out your entire project to get the best SharePoint implementation you can.  I had a lot of great discussions and questions from everyone that attended and really enjoyed myself.   I promised everyone I would post my slide deck so they could reference it and use it should they choose to.

I would really like to thank the Saskatchewan SharePoint User Group,  Edmonton Microsoft User Group, and the Calgary SharePoint User Group for hosting me for these presentations.  I really enjoyed myself and hope to return soon with another presentation.  I would also like to thank Solvera Solutions for making this all possible as well.

As promised… the slide deck.

Leading Practices for Planning and Implementing SharePoint