SharePoint Tips
Saturday, July 25, 2020
Using SharePoint Picture Library Data and Showing it on Simple HTML Site
If you want to fetch data from SharePoint Picture library through Rest Service and show it in good manner, then follow this article.
By using rest service you can fetch SharePoint Picture library data and show it on simple HTML site
Sometime back my client wanted to show project photos from SharePoint Picture Library to their HTML site. Initially we thought we may need some custom coding , however we realized the power of Rest service. So we decided to use the Rest service and we done the work within 15 minutes
We have achieved the functionality by the following:
Call the Rest service >>> get the data in Json object >>> iterate the json object to show data on page (Any page, HTML, .net , asp page etc)
I have created simple HTML file and added the following code (You can copy and paste the whole HTML and change the site address and Picture library name it will work for you)
Project party Photos
Important points in above code
1) $.getJSON("http://XXXXXXXX:1000/_vti_bin/ListData.svc/ProjectsPhotos",function(data ) {
Here we are calling ListData.svc which is Rest Web service which will give us data from ProjectsPhotos(picture library) and we are saving this data in Json object.
2) $.each(data.d.results, function(i,result) { will iterate from every Jason object and we are storing src and title in JavaScript variable
3) $('#resultarea').append($(html));
And finally we have append the HTML the one which we have created by using Title and image src property( JavaScript Variables)
4) Finally HTML page will look like above
Points to be Remember:
1) When you trying to access the Rest Web service you may face issue like below
To work around this issue, you need to install patches provided by the Microsoft, please go to following link and install the patches as per your operating system.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=2343
2) Because of permission issue may be end user will not able to access list data on the page, So make sure you give read access to All Authenticated users or any specific user group if you have any.
Friday, December 25, 2015
Top Navigation
Suppose you want to create Top navigation , you can use below code.
We will have list , where we will keep our all data , so it will be dynamic. we can set the order also. We will have selflook for parent child relation.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', setTopNavigation);
function setTopNavigation() {
var leaderclientContext = new SP.ClientContext.get_current();
var leadermenuList = leaderclientContext.get_web().get_lists().getByTitle('Top Navigation Menu');
var leadercamlQuery = new SP.CamlQuery();
leadercamlQuery.set_viewXml('1 ');
leadercollListItem = leadermenuList.getItems(leadercamlQuery); leaderclientContext.load(leadercollListItem); leaderclientContext.executeQueryAsync(Function.createDelegate(this, this.onSuccess1), Function.createDelegate(this, this.onFailed1)); }
function onSuccess1(sender, args) {
var leaderlistItemData = '';
var LeaderlistItemEnumerator = leadercollListItem.getEnumerator();
var gotParent='false';
// Build Dynamic Homepage Menu
while (LeaderlistItemEnumerator.moveNext()) {
var LeaderoListItem = LeaderlistItemEnumerator.get_current();
// '\nUnique role assignments: ' + LeaderoListItem.get_hasUniqueRoleAssignments();
var LeaderpTitle = LeaderoListItem.get_item('Title');
var LeaderoParent = LeaderoListItem.get_item('ParentLink'); if(window.location.href==LeaderoListItem.get_item('URL'))
{
if(LeaderoListItem.get_item('ImageUrl')!=null || LeaderoListItem.get_item('ImageUrl')=='')
{ var imgeurlbg = LeaderoListItem.get_item('ImageUrl'); //$('#topnavbg').attr('background-image','url("'+ imgeurlbg +'")'); $('#topnavbg').css('background-image', 'url(' + imgeurlbg + ')'); } setImageText(LeaderoListItem.get_item('ImageTitle'),LeaderoListItem.get_item('ImageByLineText')); } // Append menu string if item has no ParentLink if (!LeaderoParent) { leaderlistItemData += '\n
' + LeaderpTitle + ''; if(LeaderoListItem.get_item('URL')==window.location.href) { showBreadCum('','',LeaderpTitle); } // Build menu item's submenu var LeaderlistItemEnumeratorSub = leadercollListItem.getEnumerator(); var LeadersSubHTML = ''; while (LeaderlistItemEnumeratorSub.moveNext()) { var LeaderoListItemSub = LeaderlistItemEnumeratorSub.get_current(); var LeadersParent = LeaderoListItemSub.get_item('ParentLink'); if (LeadersParent) { LeadersParent = LeadersParent.get_lookupValue().toString(); if (LeaderpTitle == LeadersParent) { LeadersSubHTML += '\n
' + LeaderoListItemSub.get_item('Title') + '
'; if((LeaderoListItemSub.get_item('URL')==window.location.href)) { showBreadCum(LeaderpTitle,LeaderoListItem.get_item('URL'),LeaderoListItemSub.get_item('Title')); } } } } if (LeadersSubHTML != '') {leaderlistItemData += '\n

We will have list , where we will keep our all data , so it will be dynamic. we can set the order also. We will have selflook for parent child relation.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', setTopNavigation);
function setTopNavigation() {
var leaderclientContext = new SP.ClientContext.get_current();
var leadermenuList = leaderclientContext.get_web().get_lists().getByTitle('Top Navigation Menu');
var leadercamlQuery = new SP.CamlQuery();
leadercamlQuery.set_viewXml('
leadercollListItem = leadermenuList.getItems(leadercamlQuery); leaderclientContext.load(leadercollListItem); leaderclientContext.executeQueryAsync(Function.createDelegate(this, this.onSuccess1), Function.createDelegate(this, this.onFailed1)); }
function onSuccess1(sender, args) {
var leaderlistItemData = '';
var LeaderlistItemEnumerator = leadercollListItem.getEnumerator();
var gotParent='false';
// Build Dynamic Homepage Menu
while (LeaderlistItemEnumerator.moveNext()) {
var LeaderoListItem = LeaderlistItemEnumerator.get_current();
// '\nUnique role assignments: ' + LeaderoListItem.get_hasUniqueRoleAssignments();
var LeaderpTitle = LeaderoListItem.get_item('Title');
var LeaderoParent = LeaderoListItem.get_item('ParentLink'); if(window.location.href==LeaderoListItem.get_item('URL'))
{
if(LeaderoListItem.get_item('ImageUrl')!=null || LeaderoListItem.get_item('ImageUrl')=='')
{ var imgeurlbg = LeaderoListItem.get_item('ImageUrl'); //$('#topnavbg').attr('background-image','url("'+ imgeurlbg +'")'); $('#topnavbg').css('background-image', 'url(' + imgeurlbg + ')'); } setImageText(LeaderoListItem.get_item('ImageTitle'),LeaderoListItem.get_item('ImageByLineText')); } // Append menu string if item has no ParentLink if (!LeaderoParent) { leaderlistItemData += '\n
- ' + LeadersSubHTML + '\n
\n
'; //alert(sMenuHTML); // Populate menu as soon as we have the data // This will not complete before element has rendered var Leaderobj = document.getElementById('asuTopNav'); if (Leaderobj) {Leaderobj.innerHTML = LeadersMenuHTML ;} }- ' + leaderlistItemData + '\n
Monday, December 14, 2015
Show SharePoint Lists in FlexSlider Manner
Show List Item in Flex Slider style.
Suppose you want to show List items (Mainly used to Features article) in flex slider manner like below.
Suppose you want to show List items (Mainly used to Features article) in flex slider manner like below.
We can do this by using some Jquery files and client object model.
Required files Jquery min , jquery.flexslider.js , flexslider.CSS can be downloaded from below location.
https://drive.google.com/folderview?id=0B75g-_BttAvZSGpDdDM3ckpna0E&usp=sharing
<link rel="stylesheet" href="https://sp.asurion.com/sites/teams/HR/alp/SiteAssets/FlexSliderFiles/flexslider.css" type="text/css"/>
<script src="https://sp.asurion.com/sites/teams/HR/alp/SiteAssets/FlexSliderFiles/jquery.min.js"></script>
<script src="https://sp.asurion.com/sites/teams/HR/alp/SiteAssets/FlexSliderFiles/jquery.flexslider.js"></script>
All these files you will get it from above drive path
Following is the JS file which will fetch data and will create HTML
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getNewsforSlider);
function getNewsforSlider()
{
var Newscontext = SP.ClientContext.get_current();
var NewscamlQuery = new SP.CamlQuery();
var Newslist = Newscontext.get_web().get_lists().getByTitle("Trending News");
NewscamlQuery = new SP.CamlQuery();
NewsspItems = Newslist.getItems(NewscamlQuery);
NewscamlQuery.set_viewXml("<View>" +
"<ViewFields>" +
"<FieldRef Name='HomePageImageURL'/>" +
"<FieldRef Name='Title'/>" +
"<FieldRef Name='ID'/>" +
"<FieldRef Name='HomePageByline'/>" +
"</ViewFields>" +
"<Query> <OrderBy> <FieldRef Name='Modified' Ascending='False' /> </OrderBy></Query></View>");
Newscontext.load(NewsspItems);
Newscontext.executeQueryAsync(Function.createDelegate(this, foodForThoughts), Function.createDelegate(this, onFail));
}
function foodForThoughts()
{
var NewslistEnumerator = NewsspItems.getEnumerator();
var Newsitem;
var AlliNewstems = [];
while (NewslistEnumerator.moveNext()) {
Newsitem = NewslistEnumerator.get_current();
var divbgimage= Newsitem.get_item('HomePageImageURL');
var divbodytext= Newsitem.get_item('HomePageByline');
var divTitletext= Newsitem.get_item('Title');
var divIDText= Newsitem.get_item('ID');
AlliNewstems.push(" <li style='background-image:url("+divbgimage +");margin:1px;'><div class='divTitle' style='height:10% !important;'></div><div class='divbody' style='height:18% !important;'><a href='Javascript:OpenNews("+ divIDText +")'>"+ divbodytext +"</a></div></li>");
}
var Newscontent = "<div class='flexslider'><div style='width:100%;height:25px;' align='right'><a style='color:Black;' href=***************/SitePages/AllNews.aspx'>View ALL</a></div><div class='flexslider carousel'><ul class='slides'>" + AlliNewstems.join() + "</ul></div></div>" ;
$('.newsDiv').append(Newscontent);
$('.flexslider').flexslider({ animation: "", animationLoop: false, itemWidth: 240, itemMargin: 3 });
}
OpenNews JS
function OpenNews(news_id){var options = {url:"/***********/DisplayNews.aspx?ID=" + news_id,
width: 850,height: 600,dialogReturnValueCallback: function(dialogResult){SP.UI.ModalDialog.RefreshPage(dialogResult)}};SP.UI.ModalDialog.showModalDialog(options);}
You can use below function to increase or decrease length of the items or height width.
$('.flexslider').flexslider({ animation: "", animationLoop: false, itemWidth: 240, itemMargin: 3 });
}
Show Today's Date
How to show Today’s Date in Month Day and Year Manner like below.
Put the JS
var Currentd = new Date();
var Currentmonth = Currentd.getMonth()+1;
var Currentday = Currentd.getDate();
var output = (Currentday<10 ? '0' : '') + Currentday;
var Currentd = new Date();
var Currentday = Currentd.getDay();
var Extractmonth = ["JAN","FEB","MARCH","APRIL","MAY","JUN","JULY","AUG","SEP","OCT","NOV","DEC"][new Date().getMonth()]
var daytext=["SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"][(new Date()).getDay()];
and HTML
<div class="DateDiv">
<div style="margin: 10px; border: 2px solid rgb(164, 164, 164); height: 200px; background-color: rgb(210, 210, 210);" class="roundedBox">
<div style="text-align: center; color: rgb(51, 51, 51); font-size: 30px; font-weight: bold; background-color: rgb(241, 241, 241);"><script language="javascript">document.write(Extractmonth);</script>DEC</div>
<div style="text-align: center; color: rgb(67, 181, 224); font-size: 80px; font-weight: bold;"><script language="javascript">document.write(output);</script>14<div style="color: rgb(0, 0, 0); font-size: 30px;"><script language="javascript">document.write(daytext);</script>MONDAY</div></div>
</div>
</div>
Client Object model to read sharepoint Calendar Data
How to show 2 calendar’s Data through Client object Model
In some cases we need to show combined data from 2 or many calendars row by row manner
Like below, so there is no way
Use below code to get the data and show like above, in below code “Calendar name1 “ Is first calendar and Calendar name 2 is the second calendar GetDevCalendarItems() gets data for first calendar , we have applied pagesize to get 10 items only if you want you can use DateOverlap and month to get the months data. GetProcessCalendarItems() gets data for 2nd calendar. After getting both calendar data we are combines it and sorting it ascending or descending. And finally we are creating HTML like above.
$(document).ready(function() { ExecuteOrDelayUntilScriptLoaded(GetDevCalendarItems, "sp.js"); });
var Calendarcontext,
web,
CalendaspItems,
position,
nextPagingInfo,
previousPagingInfo,
CalendarlistName = 'Calendar name1,
pageIndex = 1,
pageSize = 10,
Calendarlist,
CalendarcamlQuery,
sortColumn = 'Title';
var Calendarcontext;
var CalendarcamlQuery;
var Developmetsitems = [];
var Processitems = [];
var Allitems = [];
var Developmetcontent;
var Processcontent;
function GetDevCalendarItems() {
Calendarcontext = new SP.ClientContext.get_current();
CalendarcamlQuery = new SP.CamlQuery();
Calendarlist = Calendarcontext.get_web().get_lists().getByTitle(CalendarlistName);
CalendarcamlQuery = new SP.CamlQuery();
CalendarcamlQuery.set_listItemCollectionPosition(position);
CalendarcamlQuery.set_viewXml("<view>" +
"<viewfields>" +
"<fieldref name="EventDate">" +
"<fieldref name="Title">" +
"</fieldref></fieldref></viewfields>" +
"<query> <where> <geq> <fieldref name="EventDate"> "+
"<value includetimevalue="TRUE" type="DateTime"><today></today></value> </fieldref></geq> </where>"+
" <orderby> <fieldref ascending="True" name="EventDate"> </fieldref></orderby></query> "+
"<rowlimit>" + pageSize + "</rowlimit></view>");
CalendaspItems = Calendarlist.getItems(CalendarcamlQuery);
Calendarcontext.load(CalendaspItems);
Calendarcontext.executeQueryAsync(Function.createDelegate(this, onSDevuccess), Function.createDelegate(this, onFail));
}
function GetProcessCalendarItems()
{
Calendarcontext = new SP.ClientContext.get_current();
Calendarlist = Calendarcontext.get_web().get_lists().getByTitle(Calendar name 2);
CalendarcamlQuery = new SP.CamlQuery();
CalendarcamlQuery.set_listItemCollectionPosition(position)
CalendarcamlQuery.set_viewXml("<view>" +
"<viewfields>" +
"<fieldref name="EventDate">" +
"<fieldref name="Title">" +
"</fieldref></fieldref></viewfields>" +
"<query> <where> <geq> <fieldref name="EventDate"> "+
"<value includetimevalue="TRUE" type="DateTime"><today></today></value> </fieldref></geq> </where>"+
" <orderby> <fieldref ascending="True" name="EventDate"> </fieldref></orderby></query> "+
"<rowlimit>" + pageSize + "</rowlimit></view>");
CalendaspItems = Calendarlist.getItems(CalendarcamlQuery);
Calendarcontext.load(CalendaspItems); Calendarcontext.executeQueryAsync(Function.createDelegate(this, onProcessSuccess),Function.createDelegate(this, onFail));
}
function onSDevuccess() {
var CalendarlistEnumerator = CalendaspItems.getEnumerator();
var item;
while (CalendarlistEnumerator.moveNext()) {
item = CalendarlistEnumerator.get_current();
//Developmetsitems.push("
<br />
" + item.get_item('Title') + "<br />
" + item.get_item('EventDate').format("MM/dd/yyyy") + "<br />
Development Oppertunities<br />
");
Allitems.push({date: item.get_item('EventDate').format("MM/dd/yyyy"), title: "-" + item.get_item('Title'),Category:'DevelopmentOppertunities'});
}
Developmetcontent = Developmetsitems.join();
GetProcessCalendarItems();
}
function onProcessSuccess() {
var CalendarlistEnumerator = CalendaspItems.getEnumerator();
var item;
while (CalendarlistEnumerator.moveNext()) {
item = CalendarlistEnumerator.get_current();
Allitems.push({date: item.get_item('EventDate').format("MM/dd/yyyy"), title: "-" + item.get_item('Title'),Category:'Process'});
}
Allitems.sort(function(Newsa,Newsb) {
return new Date(Newsa.date) - new Date(Newsb.date);
});
var Keydates;
var keydatesitemcount =keydatesitemcount = Allitems.length;
for ( var newcount = 0; newcount < keydatesitemcount; newcount ++ ) {
var News = Allitems[newcount];
Keydates = Keydates + "" + News.date + "<br />
" + News.title + "<br />
"+ News.Category +"<br />
";
}
Keydates = Keydates .replace('undefined','');
var finalContent= "<br />
" + Keydates +"<table class="KeyDates"></table>
";
$('#CalendarContent').html(finalContent);
}
Use below code to get the data and show like above, in below code “Calendar name1 “ Is first calendar and Calendar name 2 is the second calendar GetDevCalendarItems() gets data for first calendar , we have applied pagesize to get 10 items only if you want you can use DateOverlap and month to get the months data. GetProcessCalendarItems() gets data for 2nd calendar. After getting both calendar data we are combines it and sorting it ascending or descending. And finally we are creating HTML like above.
$(document).ready(function() { ExecuteOrDelayUntilScriptLoaded(GetDevCalendarItems, "sp.js"); });
var Calendarcontext,
web,
CalendaspItems,
position,
nextPagingInfo,
previousPagingInfo,
CalendarlistName = 'Calendar name1,
pageIndex = 1,
pageSize = 10,
Calendarlist,
CalendarcamlQuery,
sortColumn = 'Title';
var Calendarcontext;
var CalendarcamlQuery;
var Developmetsitems = [];
var Processitems = [];
var Allitems = [];
var Developmetcontent;
var Processcontent;
function GetDevCalendarItems() {
Calendarcontext = new SP.ClientContext.get_current();
CalendarcamlQuery = new SP.CamlQuery();
Calendarlist = Calendarcontext.get_web().get_lists().getByTitle(CalendarlistName);
CalendarcamlQuery = new SP.CamlQuery();
CalendarcamlQuery.set_listItemCollectionPosition(position);
CalendarcamlQuery.set_viewXml("<view>" +
"<viewfields>" +
"<fieldref name="EventDate">" +
"<fieldref name="Title">" +
"</fieldref></fieldref></viewfields>" +
"<query> <where> <geq> <fieldref name="EventDate"> "+
"<value includetimevalue="TRUE" type="DateTime"><today></today></value> </fieldref></geq> </where>"+
" <orderby> <fieldref ascending="True" name="EventDate"> </fieldref></orderby></query> "+
"<rowlimit>" + pageSize + "</rowlimit></view>");
CalendaspItems = Calendarlist.getItems(CalendarcamlQuery);
Calendarcontext.load(CalendaspItems);
Calendarcontext.executeQueryAsync(Function.createDelegate(this, onSDevuccess), Function.createDelegate(this, onFail));
}
function GetProcessCalendarItems()
{
Calendarcontext = new SP.ClientContext.get_current();
Calendarlist = Calendarcontext.get_web().get_lists().getByTitle(Calendar name 2);
CalendarcamlQuery = new SP.CamlQuery();
CalendarcamlQuery.set_listItemCollectionPosition(position)
CalendarcamlQuery.set_viewXml("<view>" +
"<viewfields>" +
"<fieldref name="EventDate">" +
"<fieldref name="Title">" +
"</fieldref></fieldref></viewfields>" +
"<query> <where> <geq> <fieldref name="EventDate"> "+
"<value includetimevalue="TRUE" type="DateTime"><today></today></value> </fieldref></geq> </where>"+
" <orderby> <fieldref ascending="True" name="EventDate"> </fieldref></orderby></query> "+
"<rowlimit>" + pageSize + "</rowlimit></view>");
CalendaspItems = Calendarlist.getItems(CalendarcamlQuery);
Calendarcontext.load(CalendaspItems); Calendarcontext.executeQueryAsync(Function.createDelegate(this, onProcessSuccess),Function.createDelegate(this, onFail));
}
function onSDevuccess() {
var CalendarlistEnumerator = CalendaspItems.getEnumerator();
var item;
while (CalendarlistEnumerator.moveNext()) {
item = CalendarlistEnumerator.get_current();
//Developmetsitems.push("
<br />
" + item.get_item('Title') + "<br />
" + item.get_item('EventDate').format("MM/dd/yyyy") + "<br />
Development Oppertunities<br />
");
Allitems.push({date: item.get_item('EventDate').format("MM/dd/yyyy"), title: "-" + item.get_item('Title'),Category:'DevelopmentOppertunities'});
}
Developmetcontent = Developmetsitems.join();
GetProcessCalendarItems();
}
function onProcessSuccess() {
var CalendarlistEnumerator = CalendaspItems.getEnumerator();
var item;
while (CalendarlistEnumerator.moveNext()) {
item = CalendarlistEnumerator.get_current();
Allitems.push({date: item.get_item('EventDate').format("MM/dd/yyyy"), title: "-" + item.get_item('Title'),Category:'Process'});
}
Allitems.sort(function(Newsa,Newsb) {
return new Date(Newsa.date) - new Date(Newsb.date);
});
var Keydates;
var keydatesitemcount =keydatesitemcount = Allitems.length;
for ( var newcount = 0; newcount < keydatesitemcount; newcount ++ ) {
var News = Allitems[newcount];
Keydates = Keydates + "" + News.date + "<br />
" + News.title + "<br />
"+ News.Category +"<br />
";
}
Keydates = Keydates .replace('undefined','');
var finalContent= "<br />
" + Keydates +"<table class="KeyDates"></table>
";
$('#CalendarContent').html(finalContent);
}
Thursday, August 13, 2015
How to export all files and Folder from Document library by suing CSOM
How to export all files and Folder from Document library by using CSOM
Issue:
In many cases we need to export files and Folders from Document library. But this is very time consuming activity , because either we need to open that library in Windows explorer and copy and paste all files and folder to drive , this activity will take much time at least 4 hours if documents are more for example 1000 documents or so. Or else we can open Library in Designer and export 1 by 1 files, because through designer we cannot export all files and folder at time.By using Below code you can export it within 5 minutes.
Solution:
For this I have crated CSOM code which will export al files and folder to “C:\Export” folder
You just need to crate this folder and run below code, all files and folder will be exported, and also folder structure will also get maintained.
1) Create folder namely “Export” on C drive
2) Create Console application and give SharePoint Client DLL’s Reference
3) Replace Program.cs code with below program.cs code
4) Change the below 2 lines
static string siteUrl = "https://XXXXXX/sites/teams/SP/"; >>Here give your site URL
public static string listTitle = "Docuemnts"; >>Give Document library display Name
5) Save and run f5, this make take max 5 minutes for 1500 items
6) ) It will start exporting files on Export folder
7) Done
PROGRAM.CS
USING MICROSOFT.SHAREPOINT.CLIENT;
USING SYSTEM;
USING SYSTEM.COLLECTIONS.GENERIC;
USING SYSTEM.IO;
USING SYSTEM.LINQ;
USING SYSTEM.TEXT;
USING SP = MICROSOFT.SHAREPOINT.CLIENT;
NAMESPACE EXPORTLISTITEMS
{
CLASS PROGRAM
{
STATIC STRING SITEURL = "HTTPS://XXXXXXXX/SITES/TEAMS/SP/";
PUBLIC STATIC STRING LISTTITLE = "DOCUMENTS";
PUBLIC STATIC CLIENTCONTEXT CLIENTCONTEXT = NEW CLIENTCONTEXT(SITEURL);
STATIC VOID MAIN(STRING[] ARGS)
{
SP.LIST OLIST = CLIENTCONTEXT.WEB.LISTS.GETBYTITLE(LISTTITLE);
CAMLQUERY CAML = NEW CAMLQUERY();
FOLDER ROOTFOLDER = OLIST.ROOTFOLDER;
CLIENTCONTEXT.LOAD(ROOTFOLDER);
CLIENTCONTEXT.EXECUTEQUERY();
VAR ROOTFOLDERURL = ROOTFOLDER.SERVERRELATIVEURL;
STRING[] STRROOTFOLDERS = ((STRING)ROOTFOLDERURL).SPLIT('/');
VAR ROOTFOLDERURL = @"C:\EXPORT\";
FOREACH (STRING FOLDERNAME IN STRROOTFOLDERS)
{
IF (!STRING.ISNULLOREMPTY(FOLDERNAME))
{
ROOTFOLDERURL = PATH.COMBINE(ROOTFOLDERURL, FOLDERNAME);
SYSTEM.IO.DIRECTORY.CREATEDIRECTORY(ROOTFOLDERURL);
}
}
CREATESUBFLODERS(ROOTFOLDER);
CONSOLE.WRITELINE("DONE SUCCESFULLY");
CONSOLE.READKEY();
}
STATIC PRIVATE VOID CREATESUBFLODERS(FOLDER RTFOLDER)
{
FILECOLLECTION FILES = RTFOLDER.FILES;
CLIENTCONTEXT.LOAD(FILES);
CLIENTCONTEXT.EXECUTEQUERY();
FOLDERCOLLECTION FOLDERS = RTFOLDER.FOLDERS;
CLIENTCONTEXT.LOAD(FOLDERS);
CLIENTCONTEXT.EXECUTEQUERY();
FOREACH (MICROSOFT.SHAREPOINT.CLIENT.FILE ITEM IN RTFOLDER.FILES)
{
CLIENTCONTEXT.LOAD(ITEM);
CLIENTCONTEXT.EXECUTEQUERY();
VAR FILEREF = ITEM.SERVERRELATIVEURL;
VAR FILEINFO = MICROSOFT.SHAREPOINT.CLIENT.FILE.OPENBINARYDIRECT(CLIENTCONTEXT, FILEREF);
STRING STRFILEDREF = ((STRING)FILEREF).REPLACE("/", "\\");
VAR FILENAME = "C:\\MIGRATION" + STRFILEDREF;
USING (VAR FILESTREAM = SYSTEM.IO.FILE.CREATE(FILENAME))
{
FILEINFO.STREAM.COPYTO(FILESTREAM);
}
}
FOREACH (FOLDER SUBFOLDER IN RTFOLDER.FOLDERS)
{
STRING STRFILEDREF = ((STRING)SUBFOLDER.SERVERRELATIVEURL).REPLACE("/", "\\");
VAR FILENAME = "C:\\EXPORT" + STRFILEDREF;
SYSTEM.IO.DIRECTORY.CREATEDIRECTORY(@"C:\MIGRATION\"+ SUBFOLDER.SERVERRELATIVEURL);
CREATESUBFLODERS(SUBFOLDER);
}
}
}
}
Issue:
In many cases we need to export files and Folders from Document library. But this is very time consuming activity , because either we need to open that library in Windows explorer and copy and paste all files and folder to drive , this activity will take much time at least 4 hours if documents are more for example 1000 documents or so. Or else we can open Library in Designer and export 1 by 1 files, because through designer we cannot export all files and folder at time.By using Below code you can export it within 5 minutes.
Solution:
For this I have crated CSOM code which will export al files and folder to “C:\Export” folder
You just need to crate this folder and run below code, all files and folder will be exported, and also folder structure will also get maintained.
1) Create folder namely “Export” on C drive
2) Create Console application and give SharePoint Client DLL’s Reference
3) Replace Program.cs code with below program.cs code
4) Change the below 2 lines
static string siteUrl = "https://XXXXXX/sites/teams/SP/"; >>Here give your site URL
public static string listTitle = "Docuemnts"; >>Give Document library display Name
5) Save and run f5, this make take max 5 minutes for 1500 items
6) ) It will start exporting files on Export folder
7) Done
PROGRAM.CS
USING MICROSOFT.SHAREPOINT.CLIENT;
USING SYSTEM;
USING SYSTEM.COLLECTIONS.GENERIC;
USING SYSTEM.IO;
USING SYSTEM.LINQ;
USING SYSTEM.TEXT;
USING SP = MICROSOFT.SHAREPOINT.CLIENT;
NAMESPACE EXPORTLISTITEMS
{
CLASS PROGRAM
{
STATIC STRING SITEURL = "HTTPS://XXXXXXXX/SITES/TEAMS/SP/";
PUBLIC STATIC STRING LISTTITLE = "DOCUMENTS";
PUBLIC STATIC CLIENTCONTEXT CLIENTCONTEXT = NEW CLIENTCONTEXT(SITEURL);
STATIC VOID MAIN(STRING[] ARGS)
{
SP.LIST OLIST = CLIENTCONTEXT.WEB.LISTS.GETBYTITLE(LISTTITLE);
CAMLQUERY CAML = NEW CAMLQUERY();
FOLDER ROOTFOLDER = OLIST.ROOTFOLDER;
CLIENTCONTEXT.LOAD(ROOTFOLDER);
CLIENTCONTEXT.EXECUTEQUERY();
VAR ROOTFOLDERURL = ROOTFOLDER.SERVERRELATIVEURL;
STRING[] STRROOTFOLDERS = ((STRING)ROOTFOLDERURL).SPLIT('/');
VAR ROOTFOLDERURL = @"C:\EXPORT\";
FOREACH (STRING FOLDERNAME IN STRROOTFOLDERS)
{
IF (!STRING.ISNULLOREMPTY(FOLDERNAME))
{
ROOTFOLDERURL = PATH.COMBINE(ROOTFOLDERURL, FOLDERNAME);
SYSTEM.IO.DIRECTORY.CREATEDIRECTORY(ROOTFOLDERURL);
}
}
CREATESUBFLODERS(ROOTFOLDER);
CONSOLE.WRITELINE("DONE SUCCESFULLY");
CONSOLE.READKEY();
}
STATIC PRIVATE VOID CREATESUBFLODERS(FOLDER RTFOLDER)
{
FILECOLLECTION FILES = RTFOLDER.FILES;
CLIENTCONTEXT.LOAD(FILES);
CLIENTCONTEXT.EXECUTEQUERY();
FOLDERCOLLECTION FOLDERS = RTFOLDER.FOLDERS;
CLIENTCONTEXT.LOAD(FOLDERS);
CLIENTCONTEXT.EXECUTEQUERY();
FOREACH (MICROSOFT.SHAREPOINT.CLIENT.FILE ITEM IN RTFOLDER.FILES)
{
CLIENTCONTEXT.LOAD(ITEM);
CLIENTCONTEXT.EXECUTEQUERY();
VAR FILEREF = ITEM.SERVERRELATIVEURL;
VAR FILEINFO = MICROSOFT.SHAREPOINT.CLIENT.FILE.OPENBINARYDIRECT(CLIENTCONTEXT, FILEREF);
STRING STRFILEDREF = ((STRING)FILEREF).REPLACE("/", "\\");
VAR FILENAME = "C:\\MIGRATION" + STRFILEDREF;
USING (VAR FILESTREAM = SYSTEM.IO.FILE.CREATE(FILENAME))
{
FILEINFO.STREAM.COPYTO(FILESTREAM);
}
}
FOREACH (FOLDER SUBFOLDER IN RTFOLDER.FOLDERS)
{
STRING STRFILEDREF = ((STRING)SUBFOLDER.SERVERRELATIVEURL).REPLACE("/", "\\");
VAR FILENAME = "C:\\EXPORT" + STRFILEDREF;
SYSTEM.IO.DIRECTORY.CREATEDIRECTORY(@"C:\MIGRATION\"+ SUBFOLDER.SERVERRELATIVEURL);
CREATESUBFLODERS(SUBFOLDER);
}
}
}
}
Tuesday, August 11, 2015
How to solve SharePoint Thershold issue
What to do when List View throws Threshold Error, and same time you have not set indexing on columns.
Scenario:
You have list which is having more than 300k records and threshold set is about 80K, now you tried to view the list, it will throw Thershold error. Now you are thinking to create views on that which will return list item count below Thershold 80K (Which We have set, default is 5000 though) but now you understand that , you have not crated indexes columns, now you try to create index columns it will again through Thershold error , “You cannot create Index, list is having threshold issue”Now what to do, this is very tricky situation
Solution:
Brief Idea1) Create different views, filter on ID (As ID column will have default indexing)
2) Create webpart page and add list view webpart and get the parameters from Query string.
3) Add Button called “Latest Items” and redirect to latest page with ID’s in query string.
Detailed
1) Create different views, filter on ID (As ID column will have default indexing)Create view like below
0-80K Filter ID greater than 0 and less than 80K
This view will show items, which Id fall in between 0 to 80K, here we will not get the threshold issue, because items written are less than threshold value (80K, in your case it may be 5000)
80-160K Filter ID greater than 80K and less than 160K
160-240K Filter ID greater than 160K and less than 240K
240-320K Filter ID greater than 240K and less than 320K
320-400K Filter ID greater than 320K and less than 400K
400-480K Filter ID greater than 400K and less than 480K
480-560K Filter ID greater than 480K and less than 560K
Now these view will show items, user can check any data. But what abput latest data , Suppose I want to show latest 80K or latest 5000 , above will show data based on ID’s range, but end user will not knowing ID, he may be searching his item in list expecting should come at top , for that we need second solution
2) Idea here is to show last 5000 or 10000 items.
Create webpart page and add list view webpart.Create Webpart page, and add List view webpart through UI Make sure you are adding Listview which should return atleast some items , it should not through threshold issue , because we want to make some changes through designer as well, So I crated view where ID=100 and set as default view. Now after adding the webpart, open the page in designer, and add Parameter like StartID and EndID and type as Querystring set any default value.
Now you have to filter ID based on parameter which we have set in previous steps like below
Order by ID desc, so this page will show ID range which we have passed from querysting
So now suppose you hit this page like
https://XXXXXXXXXX/sitePages/latest.aspx?StartID=393690&EndID=398690
This page will show items like below, now it is your hand how many items you want to show on this page , you can just adjust your query sting to show items .
However now suppose you want to show last 5000 only then how you will understand that which is last ID and -5000, this tricky right? For that read #3
3) Get the last ID from Rest service like below
https://XXXXXXXXX/sites/_vti_bin/ListData.svc/ListName?$top=1&$orderby=Id%20desc
this rest call will give you last Item which added in list , so you Jason object to get the ID
got to list All item page and edit that page and below HTML code for Button
Now on click on this Button we will call rest service to get Latest ID, and do some mat to get end ID which is less than 5000 and create HREF and redirect to page which we have created in step2
<Script>
var startID;
var EndID;
$('input:button[Title=Show Latest Ticket]').click(function(){ redirecttolatest()});
function redirecttolatest()
{
getListItem();
}
function getListItem() {
// Getting our list items
$.ajax({
url: "https://XXXXXXXX/_vti_bin/ListData.svc/listName?$top=1&$orderby=Id%20desc",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
// Returning the results
complete(data);
},
error: function (data) {
failure(data);
}
});
}
function complete(data)
{
startID= data.d[0].Id
EndID= startID- 5000;
window.location.href = "https://XXXXXXXX/sitePages/latest.aspx?StartID="+EndID+"&EndID="+startID;
}</Script>
Little Explanation:
1) Below will add click event to button which will eventually call redirecttolatest() function
$('input:button[Title=Show Latest Ticket]').click(function(){ redirecttolatest()});
2) Function redirecttolatest() will call rest service to get the latest ID.
Replace URL with your site’s ID
URL: "https://XXXXXXXX/_vti_bin/ListData.svc/listName?$top=1&$orderby=Id%20desc",
Function will do some Math and finally it will redirect to latest.aspx , with querystring in it
So that page will show latest Items.
Subscribe to:
Posts (Atom)







