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:



Tuesday, 12 April 2016

My Findings while migrating SharePoint 2010 to SharePoint 2013

I am in process of migrating SharePoint 2010 to SharePoint 13, here are some of my findings till date:

Please note i have not migrated using content DB attach detach, i am taking STP's or trying to implement same css, scripts in 2013 environment.


Working Perfectly:



  1. My sandbox solution is working as expected after starting the sandbox services
  2. Silverlignt webpart working as expected 
  3. Most of the infopath is working, one issue i noted till date is mentioned below




Not working as expected:

  1. Infopath 
    1. GetUserProfileByName webservice is not working due to claims based, working on it to fix it.
  2. CSS
    1. #RibbonContainer-TabRowLeft changed to #RibbonContainer-TabRowRight
    2.  #s4-leftpanel  changed to #sideNavBox  and  .s4-ca changed to #contentBox
    3. Some new CSS i mentioned in my post
  3. Minimal Download Strategy- Facing issues if this feature is enabled
    1. Page is redirecting with _layouts/15/start.aspx#
    2. Connect to outlook greyed out
    3. Quick edit greyed out
    4. Error when Modifying a View on a List
    5. Error when Creating pages, lists, error "cannot complete this action"

CSS to hide quick launch, ribbon, newsfeed, site action, title row in SharePoint 2013


Below are the css which could be useful to hide tags in sharepoint 2013 pages

// hide newsfeed , skydrive and sites section

#suiteLinksBox
{
DISPLAY: none !important
}

// hide site action button

#siteactiontd
{
DISPLAY: none !important
}

// hide search box , top navigation, site  logo, site title

#s4-titlerow {
DISPLAY: none !important
}


//hide share follow and  edit button

#RibbonContainer-TabRowRight {
DISPLAY: none !important
}


// Hide ribbon 

.ms-cui-tts {
DISPLAY: none !important
}

// Hide Side navigation or quick launch

#sideNavBox
{
DISPLAY: none
}
#contentBox
 {
MARGIN-LEFT: 0px
}

Wednesday, 6 April 2016

Export excel to data table using c#

Export excel to data table in c# using OleDbConnection 


 DataTable dt = new DataTable();  
string strpath = "C:\\SheetFinal.xlsx";       
String connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strpath + ";Extended Properties=Excel 12.0;";
            OleDbConnection con = new OleDbConnection(connstring);          
            OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);          
            da.Fill(dt);            

Monday, 4 April 2016

Remove hyperlink from lookup/people picker column of Sharepoint list display form


Add below lines of code in your default display form using CEWP, it will remove the hyperlinks from the columns like lookup, people picker

<script src="/sites/SiteName/SiteAssets/jquery-1.8.3.min.js"></script><script language="javascript">

// For muti user column
$("td.ms-formbody[id$='SPFieldUserMulti'] a").each(function (i,n) { $(n).replaceWith("" + $(n).text() + ""); });

// People Picker Column
$("td.ms-formbody[id$='SPFieldUser'] a").each(function (i,n) { $(n).replaceWith("" + $(n).text() + ""); });

// Lookup Column
$("td.ms-formbody[id$='SPFieldLookup'] a").each(function (i,n) { $(n).replaceWith("" + $(n).text() + ""); });
</script>