Thursday, 25 August 2016

create nested folders and upload docs using CSOM in SharePoint

Use below code to upload docs and create any number of nested folders using client object model from local machine
Check if library exists, if not then create library and then upload docs 

Create folders and files inside folders :

class Program
    {
        static ClientContext clientContext;
        static List list;
        static void Main(string[] args)

        {
            clientContext = new ClientContext("https://sharepointsite");
            list = GetListByTitleCS(clientContext, "TargetFolder");
            if (list == null)
            {
                ListCreationInformation lci = new ListCreationInformation();
                lci.Title = "TargetFolder";
                lci.Description = "TargetFolder";
                lci.TemplateType = (Int32)ListTemplateType.DocumentLibrary;
                lci.QuickLaunchOption = QuickLaunchOptions.On;
                List library = clientContext.Web.Lists.Add(lci);
                clientContext.ExecuteQuery();
            }

            //DataTable dt = new DataTable();
            //DataTable dtRecords = new DataTable();
            //dtRecords.Columns.Add("Ref");
            //dtRecords.Columns.Add("Title");
            //dtRecords.Columns.Add("Exception");
            try
            {

             
                string[] files;
                string relativeurl;

                // dirs = Directory.GetFiles("C:\\archives Multiple");

                string root = @"C:\archives Multiple";
                // Get all subdirectories
                string[] subdirectoryEntries = Directory.GetDirectories(root);
                // Loop through them to see if they have any other subdirectories
                foreach (string subdirectory in subdirectoryEntries)
                {
                 
                    ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                    var foldernames = subdirectory.Split('\\');
                    var foldername = foldernames[foldernames.Length - 1];
                    itemCreateInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
                    itemCreateInfo.LeafName = foldername;

                    ListItem newItem = list.AddItem(itemCreateInfo);
                    newItem["Title"] = foldername;
                    newItem.Update();
                    clientContext.ExecuteQuery();
                    LoadSubDirs(subdirectory);
                }
                files = Directory.GetFiles(root);
                foreach (string file in files)
                {
                 
                    try
                    {

                        List documentsList = clientContext.Web.Lists.GetByTitle("TargetFolder");
                        clientContext.Load(documentsList.RootFolder);
                        clientContext.ExecuteQuery();
                        if (Path.GetFileName(file) == "Thumbs.db") continue;
                        var filepathreplace = Path.GetFileName(file);
                        if (filepathreplace != null)
                        {
                            filepathreplace = new Regex("([~!@#$%^&*()]|(?:[.](?![a-z0-9]+$)))", RegexOptions.IgnoreCase).Replace(filepathreplace, "_");
                        }
                        using (var fileStream = new FileStream(file, FileMode.Open))
                        {

                            relativeurl = documentsList.RootFolder.ServerRelativeUrl + "/" + filepathreplace;

                            Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, relativeurl, fileStream,
                                                                              true);
                            clientContext.ExecuteQuery();
                        }
                    }
                    catch (Exception ex)
                    {

                        // libOperations.ErrorLog(ex, file);
                    }


                }

            }
            catch (Exception ex)
            {

                //dtRecords.Rows.Add(Convert.ToString(row["Doc Id"]).Trim(), Convert.ToString(row["Subject"]).Trim(), ex.Message);
                //  libOperations.ErrorLog(ex, Convert.ToString(row["Doc Id"]));
            }
        }
        private static void LoadSubDirs(string dir)
        {

            string parentfolder = dir.Split(new string[] { "archives Multiple" }, StringSplitOptions.None).Last();
            parentfolder = parentfolder.Replace(@"\", "/");
            //Console.WriteLine(dir);
            var web = clientContext.Web;
            string[] subdirectoryEntries = Directory.GetDirectories(dir);
            foreach (string subdirectory in subdirectoryEntries)
            {
                string Fullfilenamepath = subdirectory.Split(new string[] { "archives Multiple" }, StringSplitOptions.None).Last();
                //string searchInputs = "and and and and and asp.net and C# and Sqlserver and java and and and and";            
                var foldernames = subdirectory.Split('\\');
                var foldername = foldernames[foldernames.Length - 1];
                clientContext.Load(list.RootFolder);
                web.Context.ExecuteQuery();
                string listrootfolder = list.RootFolder.Name.ToString();

                string targetFolderUrl = list.RootFolder.ServerRelativeUrl + parentfolder;
                var folder1 = clientContext.Web.GetFolderByServerRelativeUrl(targetFolderUrl);
                clientContext.Web.Context.Load(folder1);
                clientContext.Load(folder1);
                web.Context.ExecuteQuery();
                var curFolder = folder1.Folders.Add(foldername);            
                web.Context.ExecuteQuery();            
                LoadSubDirs(subdirectory);
            }
            string[] files;
            string[] directories;
            string relativeurl;
           // int foldercounter = 0;
            files = Directory.GetFiles(dir);          
                foreach (string file in files)
                {

                    //foldercounter++;
                    try
                    {
                        var foldernames = dir.Split('\\');
                        string Fullfilenamepath = file.Split(new string[] { "archives Multiple" }, StringSplitOptions.None).Last();
                        Fullfilenamepath = Fullfilenamepath.Replace(@"\", "/");
                        var foldername = foldernames[foldernames.Length - 1];
                        List documentsList = clientContext.Web.Lists.GetByTitle("TargetFolder");
                        clientContext.Load(documentsList.RootFolder);
                        clientContext.ExecuteQuery();
                        if (Path.GetFileName(file) == "Thumbs.db") continue;
                        var filepathreplace = Path.GetFileName(file);
                        if (filepathreplace != null)
                        {
                            filepathreplace = new Regex("([~!@#$%^&*()]|(?:[.](?![a-z0-9]+$)))", RegexOptions.IgnoreCase).Replace(filepathreplace, "_");
                        }
                        using (var fileStream = new FileStream(file, FileMode.Open))
                        {

                            relativeurl = documentsList.RootFolder.ServerRelativeUrl + "/" + Fullfilenamepath;
                              //relativeurl = documentsList.RootFolder.ServerRelativeUrl + "/" +  dir.Split('C:\\archives Multiple\\') +  foldername + "/" + filepathreplace;

                            Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, relativeurl, fileStream,
                                                                              true);
                            clientContext.ExecuteQuery();
                        }
                    }
                    catch (Exception ex)
                    {

                       // libOperations.ErrorLog(ex, file);
                    }


                }
        }
        public static List GetListByTitleCS(ClientContext clientContext, String listTitle)
        {
            List existingList;

            Web web = clientContext.Web;
            ListCollection lists = web.Lists;

            IEnumerable<List> existingLists = clientContext.LoadQuery(
                    lists.Where(
                    list => list.Title == listTitle)
                    );
            clientContext.ExecuteQuery();

            existingList = existingLists.FirstOrDefault();

            return existingList;
        }

     


        //  libOperations.Excel_FromDataTable(dtRecords);
    }

Wednesday, 15 June 2016

Remove hyperlink from name and picture in People picker column Sharepoint list view

Remove hyperlink from name and picture in People picker column - Sharepoint List view



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

$(".ms-vb-user").find('a').each(function(){
  $(this).attr('href','#');
});

</script>

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:



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>

Thursday, 31 March 2016

Check if browser is IE in SharePoint



<script language="javascript">
function GetIEVersion() {
  var sAgent = window.navigator.userAgent;
  var Idx = sAgent.indexOf("MSIE");

  // If IE, return version number.
  if (Idx > 0)
    return parseInt(sAgent.substring(Idx+ 5, sAgent.indexOf(".", Idx)));

  // If IE 11 then look for Updated user agent string.
  else if (!!navigator.userAgent.match(/Trident\/7\./))
    return 11;

  else
    return 0; //It is not IE
}

if (GetIEVersion() > 0)
   alert("This is IE " + GetIEVersion());
else
   alert("This is not IE.");

</script>

Monday, 28 March 2016

Exception logging and export datatable to excel using c#

Log exception to Text

Log.ErrorLog(ex, "excel"); to export to text file in your exception handling

Log Datatable to excel

Log.Excel_FromDataTable(datatable);

below class will export to text file and excel.

using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace DataMigrationHDM
{
    internal class Log
    {
        public static void Excel_FromDataTable(System.Data.DataTable dt)
        {
            try
            {


                // Create an Excel object and add workbook...

                ApplicationClass excel = new ApplicationClass();

                Workbook workbook = excel.Application.Workbooks.Add(true); // true for object template???

                // Add column headings...
                int iCol = 0;
                foreach (DataColumn c in dt.Columns)
                {
                    iCol++;
                    excel.Cells[1, iCol] = c.ColumnName;
                }
                // for each row of data...
                int iRow = 0;
                foreach (DataRow r in dt.Rows)
                {
                    iRow++;

                    // add each row's cell data...
                    iCol = 0;
                    foreach (DataColumn c in dt.Columns)
                    {
                        iCol++;
                        excel.Cells[iRow + 1, iCol] = r[c.ColumnName];
                    }
                }

                // Global missing reference for objects we are not defining...
                object missing = System.Reflection.Missing.Value;
                Worksheet worksheet = (Worksheet)excel.ActiveSheet;
               
                string RDir = Directory.GetCurrentDirectory();
                string sYear = DateTime.Now.Year.ToString();
                string sMonth = DateTime.Now.Month.ToString(CultureInfo.InvariantCulture);
                string sDay = DateTime.Now.Day.ToString();
                string dirPath = RDir + @"\ReleasedStandards\" + sMonth + "-" + sDay + "-" + sYear;
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                //string dateT = DateTime.Now.ToLongDateString();

                string sErrorTime = sDay + "-" + sMonth + "-" + sYear + " " + DateTime.Now.Hour.ToString() + "-" + DateTime.Now.Minute;
                workbook.SaveAs(dirPath + "\\Report_" + sErrorTime + ".xls",
           XlFileFormat.xlXMLSpreadsheet, missing, missing,
            false, false, XlSaveAsAccessMode.xlNoChange,
            missing, missing, missing, missing, missing);

                // If wanting to make Excel visible and activate the worksheet...
                excel.Visible = true;

                ((_Worksheet)worksheet).Activate();

                // //format excel on run time 



                // If wanting excel to shutdown...
                ((_Application)excel).Quit();
                MessageBox.Show("Report Generated", "Maintenance Tool...", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            catch (Exception ex)
            {
                //MessageBox.Show("Error in webservice while Saving Excel.", "Maintenance Tool...", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                ErrorLog(ex, "Writng to excel");

            }
        }
        public static void ErrorLog(Exception ex,String info)
        {
            StreamWriter sw = null;

            try
            {
                string sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " +
                                    DateTime.Now.ToLongTimeString().ToString() + " ==> ";

                string sPathName = Directory.GetCurrentDirectory();

                string sYear = DateTime.Now.Year.ToString();
                string sMonth = DateTime.Now.Month.ToString();
                string sDay = DateTime.Now.Day.ToString();

                string sErrorTime = sDay + "-" + sMonth + "-" + sYear;
                string dirPath = sPathName + @"\Logs\";
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                sw = new StreamWriter(dirPath + "\\DocumentLibrary_ErrorLog_" + sErrorTime + ".txt", true);

                sw.WriteLine(sLogFormat + ex.Message + ex.StackTrace + info);
                sw.Flush();

            }
            catch (Exception ex1)
            {
                ErrorLog(ex1,"Lib");
            }
            finally
            {
                if (sw != null)
                {
                    sw.Dispose();
                    sw.Close();
                }
            }

        }
    }
}

Read excel to datatable using openXML DLL

Need to add openxml DLL reference from codeplex and use below code to read excel to datatable

static void Main(string[] args)
        {
DataTable dtRecords;
            dtRecords = new DataTable();
            dtRecords.Columns.Add("URL");        
            DataTable dt = new DataTable();

            SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open("C:\\Sites.xlsx.", false);
            {
                IEnumerable<Sheet> sheets =
                    spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
                string relationshipId = sheets.First().Id.Value;
                WorksheetPart worksheetPart =
                    (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
                Worksheet workSheet = worksheetPart.Worksheet;
                SheetData sheetData = workSheet.GetFirstChild<SheetData>();
                IEnumerable<Row> rows = sheetData.Descendants<Row>();
                foreach (Cell cell in rows.ElementAt(0))
                {
                    dt.Columns.Add(GetCellValue(spreadSheetDocument, cell));
                }
                foreach (Row row in rows)
                {
                    DataRow tempRow = dt.NewRow();
                    for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
                    {
                        tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
                    }
                    dt.Rows.Add(tempRow);
                }
                dt.Rows.RemoveAt(0);
                //CreateDocumentSetInMeetings(dt);
            }
            foreach (DataRow row in dt.Rows)
            {
           //do your stuff
            }
}
public static string GetCellValue(SpreadsheetDocument document, Cell cell)
        {
            SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
            if (cell.CellValue == null)
            {
                return "";
            }
            string value = cell.CellValue.InnerXml;
            if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
            {
                return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
            }
            else
            {
                return value;
            }
        }

Tuesday, 22 March 2016

Create update list item using .net client object model

Create List Item:

 ClientContext context = new ClientContext("Site Url");
            Web site = context.Web;
List announcementsList = context.Web.Lists.GetByTitle("List Name");
                        ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                        ListItem newItem = announcementsList.AddItem(itemCreateInfo);
                        newItem["Title"] = "test";
                        newItem["Col1"] = "";
                        newItem["Col2"] = "";
                        newItem["Col3"] = "";
                        newItem.Update();
                        context.ExecuteQuery();

Update list Item:

                        List Offboarding = context.Web.Lists.GetByTitle("List Name");
                        CamlQuery queryoff = new CamlQuery();
                        queryoff.ViewXml = "<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Text'>" + id + "</Value></Eq></Where></Query></View>";
                        ListItemCollection OffboardingItems = Offboarding.GetItems(queryoff);
                        context.Load(Offboarding);
                        context.Load(OffboardingItems);
                        context.ExecuteQuery();
                        foreach (var itemoff in OffboardingItems)
                        {
                            itemoff["Title"] = "test";                          
                            itemoff.Update();

                        }
                        context.ExecuteQuery();

Access external list using .net client object model (CSOM)

ClientContext context = new ClientContext("Site URL");
            Web site = context.Web;
            var StudentList = site.Lists.GetByTitle(" Ext List Name");
            CamlQuery camlQuery = new CamlQuery();

            IQueryable<ListItem> termEmps = StudentList.GetItems(camlQuery);
            IEnumerable<ListItem> externalList = context.LoadQuery(termEmps);
            context.ExecuteQuery();

            var studentListData = from term in externalList
                                  select new
                                  {
                                      FULLNAME = term.FieldValues.ElementAt(1).Value.ToString(),
                                      Employeeid = term.FieldValues.ElementAt(2).Value.ToString(),
                                      SEPERATIONDATE = term.FieldValues.ElementAt(4).Value.ToString()
                                  };
            foreach (var empterm in studentListData)
            {
//do your stuff
}

Wednesday, 9 March 2016

Header style sharepoint list view 2010

Please use webpart ID to use below styles

<style type="text/css">

/* === Title bar CSS === */

/* TR - title bar for web part */
#MSOZoneCell_WebPartWPQ5 .ms-WPHeader
{
  background-color:green;
}

/* H3 - Text in title bar of web part */
#MSOZoneCell_WebPartWPQ5 .ms-WPTitle a   
{
  color:white;
  font-family:"Comic Sans MS";
  font-size:24pt;
}

/* TD - far left and far right (corner) cells of title bar - useful for round corner tricks */
#MSOZoneCell_WebPartWPQ5 .ms-wpTdSpace
{
  /* background-image:url(' someimagepath '); */
  width:30px !important;
  background-color:red;
}

/* web part check box */
#MSOZoneCell_WebPartWPQ5 .ms-WPHeaderCbxHidden 
{
  display:none;   
}


/* === Web part background CSS === */

/* TD - background for all but title bar of web part */
#MSOZoneCell_WebPartWPQ5.s4-wpcell 
{
  background-color:lightgreen;
  /* border-style:dashed; */
  border-style:dashed;
  border-width:5px;
}

/* TD - paging area (i.e. 1 - 5) */ #MSOZoneCell_WebPartWPQ5 .ms-bottompaging td { background-color:yellow !important; } /* hide the gray line above "add new" link */   
#MSOZoneCell_WebPartWPQ5 .ms-partline
{
  display:none;
}

/* selected (clicked) web part background */ #MSOZoneCell_WebPartWPQ5.s4-wpActive { background-color:fuchsia; border-color:red; /* border-style:dotted; */
}   


/* === Column headings === */

/* color for sortable column headings */
#MSOZoneCell_WebPartWPQ5 .ms-vh-div a
{
  color:red !important;
}
/* color for non-sortable column headings */
#MSOZoneCell_WebPartWPQ5 .ms-vh-div
{
  color:red !important;
}


/* === List text CSS === */

/* item description text */
#MSOZoneCell_WebPartWPQ5 .ms-vb2,
#MSOZoneCell_WebPartWPQ5 .ms-vb-user a,
#MSOZoneCell_WebPartWPQ5 .ms-vb-title a
{
  color:yellow !important;
  font-size:12pt;
}

/* TR - alternating (#2,#4,#6...) row of web part */
#MSOZoneCell_WebPartWPQ5 .ms-alternating 
{
  background-color:navy;
}

</style>

Hide ribbon on item selection in sharepoint 2010 list view using jquery

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


 $(".s4-wpcell").removeAttr('onkeyup').removeAttr('onmouseup');

 </script>

Style to hide ribbon. title area and left navigation

<style type="text/css">
#s4-titlerow {
 DISPLAY: none !important
}
#RibbonContainer-TabRowLeft {
 DISPLAY: none !important
}
.ms-cui-tts {
 DISPLAY: none !important
}
.s4-ca {
 MARGIN-LEFT: 0px
}
#s4-leftpanel
{
DISPLAY: none
}
</style>

Friday, 19 February 2016

Get SharePoint list column value using javascript

Below is the function to easily get sharepoint list column value using internal name, its better to get value then using column id.

function getField(fieldType,fieldTitle) {
    var docTags = document.getElementsByTagName(fieldType);
    for (var i=0; i < docTags.length; i++) {
        if (docTags[i].title == fieldTitle) {
            return docTags[i]
        }
    }
}

to get single line text use :

getField('input' , 'Title');

Choice Colum:

 getField('select' , 'col name');

Hide SharePoint list form fields using jQuery/Javascript


Just add jQuery reference and use below lines

Single line/Multi Line

$("input[title$='Col Name']").closest('tr').hide();

Dropdown

$("select[title$='Col Name']").closest('tr').hide();

to show field use below line

$("select[title$='Col Name']").closest('tr').show();

People Picker or any other field

$("nobr:contains('Col Name')").closest('tr').hide();

Readonly text colum:

$("input[title='Col Name']").attr("readonly",true);