Monday, 23 May 2016

Breadcrumb when navigating folders in a Sharepoint 2010 Document Library WebPart

Breadcrumb when navigating folders in a Sharepoint 2010 Document Library WebPart



Thanks to this post, helped me with adding breadcrum to webpart title in sharepoint document library.

Just add the content editor webpart and add below script.

I used this script to home page to default team site shared documents webpart.

<script>
_spBodyOnLoadFunctionNames.push("doBreadCrumbs");//execute after DOM loaded

function doBreadCrumbs(){
// Get 'RootFolder' value in URL
var rootStr = getUrlParam('RootFolder');  
if (rootStr != '') {
// Get all links in WebParts titles (IE8+)
var webpartHeaders = document.querySelectorAll('.ms-WPTitle a');
// For each link
for(var i = 0; i < webpartHeaders.length; i++){
var webpartHeader = webpartHeaders[i];
// Get link target
var link = decodeURIComponent(webpartHeader.getAttribute('href'));
// If target contains 'RootFolder' value, then we have our Web Part.
// Let's generate our breadcrumb
if(rootStr.indexOf(link) != -1){
var path = rootStr.replace(link, ''); // Folder path, relative to Doc Lib
var basepath = rootStr.replace(path, ''); // Doc Lib path

var breadcrumb = '<span class="breadcrumb">';
breadcrumb += '<a href="' + location.pathname + '">Home</a>'; // link to base page

// Create link for each sub-folder
var folders = path.split('/');
for(var i = 1; i < folders.length; i++){
var currentfolder = folders[i];
basepath += "/" + currentfolder;

// Replace 'RootFolder' value in URL without touching any other variables(orderby, etc.)
var folderlink = window.location.search.replace('RootFolder=' + encodeURIComponent(rootStr), 'RootFolder=' + encodeURIComponent(basepath));

breadcrumb += ' &gt; <a href="' + folderlink + '">' + currentfolder  + '</a>';
}
breadcrumb += '</span>';

// Insert breadcrumb
webpartHeader.parentNode.innerHTML = breadcrumb;
}
}
}
}

/* Get param value from query string */
function getUrlParam(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.search);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}</script>
<style>
.ms-WPHeader .breadcrumbs{
display:block;
font-style:italic;
}
.ms-WPHeader .breadcrumbs,.ms-WPHeader .breadcrumbs a{
font-size: 0.8em;
color:#D1D1D1;
}
</style>

Monday, 9 May 2016

SharePoint online Provider hosted app

My First SharePoint online Provider Hosted App


Prerequisites:
1.       SharePoint online subscription
2.       Azure website
3.       Visual Studio.

Let’s start with creating app project in visual studio 2013:
Project Name: MyFirstProviderHostedApp




Click ok and select Provider-Hosted Option



Click Next, I am using ASP.NET web forms application,





Select Azure Access control, Click Finish.
Hope you have azure setting profile, in this step we are going to import all settings.

Right Click on your web project and click publish.




Click on import profileà Select your profile.





Validate your connection and click publish.

Now let’s register this app on your SharePoint online site. Go your site and using below URL to register app



Generate client id and secret and click create, save details somewhere, will use it later.
Now, got to web.config file of your web project and open it.



Add your client id and secret and save it.

Now open code view of AppManifest.xml file and change start page url, client id.



Now open designer view of your app manifest app and give full control to web.



That’s it, now hot F5 and trust your app in SharePoint.





You can see the website hosted on Azure.








Friday, 6 May 2016

Get Data between start date and end date in Sharepoint Rest API

Query list data between two dates in SharePoint hosted app 2013 using REST API


Using below query i am getting data from last one month

  • DateTime is my date time column
  • PP is people picker column
  • Fetching 5000 items in one query
  • Fetching People picker and lookup column as well.
var hostweburl;
var appweburl;
var _listName;
var employeeListQueryUrl;
var EmployeesList = 'EmployeesList';
var EndDate = new Date();
    var startdate = new Date();
    startdate.setDate(startdate.getDate() - 30);


employeeListQueryUrl = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbyTitle('" + EmployeesList + "')/Items?@target='" + hostweburl + "'&

$select=Title,DateTime,Email,ContactNo,Address,ID,PP/ID,PP/Title,Lookup/ID,Lookup/Title&$expand=PP/ID,PP/TitleLookup/ID,Lookup/Title&

$orderby=Created asc&

$top=5000&

$filter=DateTime ge datetime'" + startdate.toISOString() + "' and (DateTime le datetime'" + EndDate.toISOString() + "')"
 
Complete query:

employeeListQueryUrl = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbyTitle('" + EmployeesList + "')/Items?@target='" + hostweburl + "'&$select=Title,DateTime,Email,ContactNo,Address,ID,PP/ID,PP/Title,Lookup/ID,Lookup/Title&$expand=PP/ID,PP/TitleLookup/ID,Lookup/Title&$orderby=Created asc&$top=5000&$filter=DateTime ge datetime'" + startdate.toISOString() + "' and (DateTime le datetime'" + EndDate.toISOString() + "')"
   

Thursday, 5 May 2016

Bind Sharepoint list to Jquery Datatable in SharePoint Hosted App

In this post i am going to describe how you can bind SharePoint list to Jquery datatable (just like grid view) with rich features like Export to excel, Export to PDF etc.


Key Points:

  • Querying people picker and lookup columns using REST API
  • Getting 5000 items in one query
  • Showing first column as hyperlink column to my list item display form.
  • Change column header name dynamically after page load
  • Export to excel, pdf, notepad, csv
  • List view search
  • Paging
  • This grid can be added as app part in sharepoint page as well (Same like list view webpart with rich features)
Thanks to this article. 

Steps:
  1. Create SharePoint hosted app using VS ( i used 2013).
  2. Added below code to default.aspx page.
  3. Add references to your datatable js files
 <link rel="stylesheet" href="../Scripts/css/DashboardStyle.css" />
     <link rel="stylesheet" href="../Scripts/css/dataTables.tableTools.css" />
     <link rel="stylesheet" href="../Scripts/css/jquery.dataTables.css" />
    <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="../Scripts/EmployeeLists.js"></script>
    <script type="text/javascript" src="../Scripts/jquery.datatables-1.9.4.min.js"></script>    
    <script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>
   <script type="text/javascript" src="../Scripts/dataTables.tableTools.js"></script>

4. Add HTML in div tag

 <p id="message">
            <!-- The following content will be replaced with the user name when you run the app - see App.js -->
            initializing...
        </p>
         <table id="employeeList" class="table table-striped table-bordered1 table-condensed table-hover table-fullfixed">
            <thead>
                <tr>
                    <th >Title</th>
                    <th>Last Name</th>
                    <th>Email</th>
                    <th id="week1th">Week1Date</th>
                    <th id="week2th">Week2Date</th>
                    
               
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
5. Created one js file and added below code, change column names and list name accordingly.

'use strict';
var hostweburl;
var appweburl;
var _listName;
var employeeListQueryUrl;
var EmployeesList = 'EmployeesList';
// This code runs when the DOM is ready and creates a context object which is   
// needed to use the SharePoint object model  
$(document).ready(function () {
    
   
    //Get the URI decoded URLs.   
    hostweburl =
        decodeURIComponent(
            getQueryStringParameter("SPHostUrl"));
    appweburl =
        decodeURIComponent(
            getQueryStringParameter("SPAppWebUrl"));
    // Resources are in URLs in the form:  
    // web_url/_layouts/15/resource  

    var scriptbase = hostweburl + "/_layouts/15/";

// Using below string i am querying 5000 items and getting values of People picker column, lookup column as well.


    employeeListQueryUrl = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbyTitle('" + EmployeesList + "')/Items?@target='" + hostweburl + "'&$select=Title,LastName,Email,ContactNo,Address,ID,PP/ID,PP/Title,Lookup/ID,Lookup/Title&$expand=PP/ID,PP/TitleLookup/ID,Lookup/Title&$orderby=Created asc&$top=5000";



    // Load the js file and continue to load the page with information about the list top level folders.  
    // SP.RequestExecutor.js to make cross-domain requests  

    // Load the js files and continue to the successHandler  
    $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
});

// Function to prepare and issue the request to get  
//  SharePoint data  
function execCrossDomainRequest() {
    var executor;
    executor = new SP.RequestExecutor(appweburl);

    executor.executeAsync(
        {
            url: employeeListQueryUrl,
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: employeeSuccessHandler,
            error: errorHandler
        }
    );
   
}

function employeeSuccessHandler(data) {
    var jsonObject = JSON.parse(data.body);
    var results = jsonObject.d.results;
    fillData(results, EmployeesList);
    $('#employeeList').dataTable({
        "fnRowCallback": function (nRow, results, iDisplayIndex) {
            $('td:eq(0)', nRow).html('<a target="_blank" href="' + hostweburl + '/Lists/' + EmployeesList + '/Dispform.aspx?ID=' + results[0] + '">' +
            results[0] + '</a>');

            //$('td:eq(0)', nRow).html('<a target="_blank" href="' + hostweburl + '/Lists/' + EmployeesList + '/Dispform.aspx?ID=' + results[0] + '"><img src="../Images/View_icon.png" border="0"/></a>');
        return nRow;
        },

        //"createdRow": function (row, results, index) {
        //    if (results[2].indexOf('Y') == 1) {
        //        $('td', row).eq(2).addClass('highlight');
        //    }
        //},   
       
    });    
    var table = $('#employeeList').dataTable();
    var tableTools = new $.fn.dataTable.TableTools(table, {        

        aaSorting: [[4, 'desc']],
        'aButtons': [
            {
                'sExtends': 'xls',
                'sButtonText': 'Save to Excel',
                'sFileName': 'Data.xls'
            },
            {
                'sExtends': 'print',
                'bShowAll': true,
            },
            {
                'sExtends': 'pdf',
                'bFooter': false
            },
            'copy',
            'csv'
        ],       
      
        'sSwfPath': '//cdn.datatables.net/tabletools/2.2.4/swf/copy_csv_xls_pdf.swf'
    });
    document.getElementById('week1th').innerHTML = "Dynamic Column Name";

}

function errorHandler(data, errorCode, errorMessage) {
    alert(data + ' >> ' + errorCode + ' >> ' + errorMessage);
}


function fillData(results, _ListName) {
    var $appContent = $('#employeeList tbody');

    for (var i = 0; i < results.length; i++) {

        var $tr = $('<tr/>');

        $('<td/>').text(results[i].ID).appendTo($tr);
        $('<td/>').text(results[i].Title).appendTo($tr);
        $('<td/>').text(results[i].Email + "Y").appendTo($tr);
        $('<td/>').text(results[i].Lookup['Title']).appendTo($tr); // Set lookup text
        $('<td/>').text(results[i].PP['Title']).appendTo($tr); // Set people picker value
        $tr.appendTo($appContent);
    }


}

// This function prepares, loads, and then executes a SharePoint query to get   
// the current users information  

//Utilities   

// Retrieve a query string value.   
// For production purposes you may want to use   
// a library to handle the query string.   
function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}

Final Output: