SharePoint Online Document Library Information Dynamically – React n Rest Api


I have come out with one requirement which can tell the number files in the document library. Regardless the number of document in the library. I have used React with rest api to get all the folder, and document type count with some ready made components on react. I would like others input to make it more optimize and speedy.

Web part takes document library name from the property name dynamically.

 

Code is already uploaded on Git Hub.

Resultant screen shot of our solution will be like below.

 

 

 

SP Document Library Information
SP Document Library Information

Step 1.  yo @microsoft/sharePoint
Step 2. Choose SharePoint Online only (latest)
Step 3. Use the current folder
Step 4. Do you want to allow the tenant admin the choice of being able to deploy the solution to all sites immediately without running any feature deployment or adding
apps in sites? (y/N) Choose y
Step 5. Select WebPart
Step 6.What is your Web part name?
Step 7 What is your Web part description?
Step 8. Which framework would you like to use? Chooe React
wait around 3 minutes npm to make necessary files………

Install Jquery and react-countup
i.e. npm install jquery –save Similary
npm install react-countup –save

Go to the component tsx file inside src – > webpart – > yourwebparname.tsx

Go to the interface your webpart calss is inheriting….. and update with below.

import { SPHttpClient } from ‘@microsoft/sp-http’;

export interface IWpDocumentLibInfoProps {
spHttpClient: SPHttpClient;
TotalItem:string;
TotalFolders:string;
TotalFiles:string;
description: string;
siteurl:string;
ItemStart:number;
ItemEnd:number;
LoopForList:number;
FileArray:Array<string>;
DocFiles:number;
XlsFiles:number;
PDFFiles:number;
P3Files:number;
Photos:number;
Drawing:number;
TextFiles:number;
MISCFiles:number;
DocumentLibraryName:string;
}

Now come back to tsx file and add the below function one by one.

import CountUp from ‘react-countup’;
import * as jquery from ‘jquery’;

1. Constructor

2. Add below code : It will run during initializing and bring the cound of the document library using rest.
componentDidMount() {
this._GetListTotalCount();
}

private _GetListTotalCount(): void {
var reactHandler = this;
var NewISiteUrl = this.props.siteurl;
var NewSiteUrl = NewISiteUrl.replace(“SitePages”, “”);
if (this.state.DocumentLibraryName==””){return;}
console.log(NewSiteUrl);
jquery.ajax({
url: `${NewSiteUrl}/_api/web/Lists/getbytitle(‘${this.state.DocumentLibraryName}’)/ItemCount`,
type: “GET”,
headers: { ‘Accept’: ‘application/json; odata=verbose;’ },
success: function (resultData) {
this.setState({ TotalItem: resultData.d.ItemCount })
var number = parseInt(this.state.TotalItem);
var LoopToQuery = number / 4000;
var LooingItemInt = Math.ceil(LoopToQuery)
this.setState({ LoopForList: LooingItemInt });
this.QueryFilesAndFoldersWrapper();
}.bind(this),
error: function (jqXHR, textStatus, errorThrown) {
}

});
}

3.Add this function QueryFilesAndFoldersWrapper # Code is already on the Git Hub

4.QueryITems in Loop because due to 5000 threshold limit we can query rest in chunks of 4999 records.

5. Add the render Method # from git hub.

We can change the Document Library Name from the Property Pane save and refresh.

 

#Kindly download the code and help me to make it more optimize and more usable for others.

#Happy sharing…..

 

 

Advertisements

SharePoint Framework Custom Form- React JS – SPFX – Complex Forms


In this blog I have create a simplest react project with complex form which can save others time to use in the project. Project is uploaded on Git, it is a SharePoint framework web part with react framework. In this project, a forms with DropDown, Datetime picker, Upload File to SharePoint, Input Fields, HtmlTextEdtir,CheckBoxes  which will submit data to SharePoint List using pnp. Below are components

(1) react-select to bind with SharePoint List

(2) react-datetime for Date Time on the Form

(3) react-file-reader to Upload File to SharePoint Document Library

(4) react-checkbox-group for Checkbox in the Form

(5)  sp-pnp-js to Upload file and submit data to List.

(6) react-medium-editor is used for rich textbox in the form.

 

Need to install below external compoenent.

react-file-reader  (for Uploading Files)

react-medium-editor (for Rich Textbox)

react-datetime (for DateTime Calender)

react-checkbox-group (for checkbox group)

Have a look

Upload button will upload the file to the SharePoint document Library, I used pnp framework to upload, which allow us to update metadata easily.

Now code will insert item to SharePoint List on button click.It will upload file to My Docs in the Same site and insert to list with unique Guid, to maintain relationship between List and document library.

 

SharePoint Framework Custom Form- React JS – SPFX – Complex Forms
SharePoint Framework Custom Form- React JS – SPFX – Complex Forms

Installing required libs i.e. jquery, pnpjs, checkbox, react-file-uploader

react-medium-editor
react-medium-editor

 

Upload Docs to SharePoint Library & Update Columns using Pnp.js


Microsoft SharePoint Pattern and practices libraries makes it very simple to deal with SharePoint site. Less code and easy to understand. Link to SharePoint PNP-JS-Core.

In this article I will use pnp.js library to upload document and update the other fields in the same item uploaded in SharePoint document library.

(1 ) We need to reference the 4 files to work with pnp.js

/SiteAssets/4.0.5/es6-promise.js
/SiteAssets/4.0.5/es6-promise.auto.js
/SiteAssets/pnp.js
/SiteAssets/fetch.js

 

(2)I have reference the bootstrap in my page and use bootstrap classes.

Html of upload file, I have attached the link of Html Code in the PDF file, just copy and paste.

(3)  Now Call Simple JS Function UploadFiles() to Upload file and update the fields in the same item uploaded. Copy the below Code in JS File.

function UploadFiles() {
var files = document.getElementById(‘exampleInputFile’).files;
var file = files[0]; //using File Api
if (file!=undefined || file!=null){
$pnp.sp.web.getFolderByServerRelativeUrl(“/Documents”)
.files.add(file.name, file, true)
.then(function (data) {
var RelativeUrls=”/Documents/”+file.name;

//Retrive Document which is uploaded. Start
$pnp.sp.web.getFolderByServerRelativeUrl(RelativeUrls).getItem().then(item => {
//update start Below Call to Doc List will update the Row baseed on Item.ID
$pnp.sp.web.lists.getByTitle(“Documents”).items.getById(item.ID).update({
ColumnName: ‘New Value’
}).then(r => {
alert(file.name + ” upload successfully!”);
});
//update end
}); //Retrive Doc Info End
}); //Upload Document End

}

 

 

Below are the References to pnp js core library to deal with files and update item by id.  PDF file contain the html part.

Links

Get 50000 items from SharePoint List using JS-SharePoint Item 5000 Threshold Issue [Solved] –


My blog will help to load data from SharePoint list regardless of list-view threshold limit . I have been through many forums and even I experienced bit difficulty to load data from list having record greater than limit defined by the SharePoint administrator (threshold limit). I have created a simple JS file with some functions to load data in chunks. i.e. My JS function will automatically take the total count of list and break them in the chunks and iterate them. In the result it will provide the array of items requested by the user.

Global Varaiable
Screen shot is to provide the global variable for our JS File
Initial Method to Call from my js
Initial Method to Call from my js
Internal method of JS File, This methods will take the cound of the List and divide them as 5000 each cycle
Internal method of JS File, This methods will take the cound of the List and divide them as 5000 each cycle

 

 

 

Final Methods will runs once all the data finish loading

Final Methods will runs once all the data finish loading

Just add the attached JS file to your SharePoint Solution and call the below mentioned function. In return once the data get loaded , it will write the desired array to flatArray and update var TransactionComplete = 1; further you can use flatArray with data in your app.
JS File – Click here to Download – Rename PDF to JS

Funciton to call GetListItem(siteurl,listname,columns)

siteurl = http://sitename

listname=testlist

columns=ID,Created,Title,Column1,Column2,Column4,Column5

Result = flatArray as Array

Resultant Screen shot.

ResultArray
ResultArray

 

I hope my little efforts may save time for those who are struggling with SharePoint threshold 5000 issue.

[ios][SharePoint]-Upload Image to SharePoint from IPhone App using Swift and ASP.NET WebApi


This article will show some simple steps to upload a picture, document to SharePoint Library using XCode Swift, Asp.net Web api. I will create Native IPhone app using swift language and another app will be asp.net mvc web api to receive images with other information and upload to SharePoint. Both the project are uploaded on below link.
Iphone Project   , Open in the Xcode and Build.
Asp.net Web Api – Project..   Host the Web Application on IIS and published.
I have used the below link to get help to create Iphone native app using swift language, very simple and helpful to create Iphone App.
Image upload example with Swift To Create From Scratch
Below is the Simple example to createWeb Api.
Tutorial How to Create Asp.net Web Api To Create from scratch.

We just need to edit the url of the web api, once the web api receive the request from IPhone app, it will save file locally, than call another function to read image convert and upload to SharePoint 2013.

let myUrl = NSURL(string: http://Webserver/UploadFilesWebApi/api/fileupload/uploadfile”);

I guess it will little helpful for the readers because I didnt find any tutorial to upload from iphone to SharePoint. Below I have mentioned some screen shot.s

 defineRouteInEmptyMvcProject image2

Develop Polymer material with Share Point 2013 Binding Polymer Template with Share Point 2013 using CSOM,


In this blog I am going to merge Polymer Template through Angular JS Framework with SharePoint List. I am new to polymer and as well as on angular js but it is pretty much cool ready made stuff :).

You just need to have some knowledge of SharePoint to complete this simple example. I have shared the source code below just upload to SharePoint Library (Add one List Area) and run the page.
For More Knowledge (Polymer)
For More Knowledge (Angular)
For More Knowledge (SharePoint CSOM)

In this demo I will use the below Polymer template. Polymer elements are based on the set of htmls files libraries which are need to be import on the page. On the back end polyer html pages used the JS and CSS. There is a folder of libraries which we need to put in our root folder. When I tried to copy the Libraries folder in my sharepoint desiger page it block due to jason files. Actually JSON files are objects of array for tutorial of polymer, In our databinding we dont need any hard coded JSON files.

7

8

We Just create a Single Folder in my site .
2
Create a Single aspx Page, in which we will add our Angulr JS, SharPoint JS Api’s and design it using Polymer core elements. I name it as TestPolymer.aspx
3
I removed all the json files because SPD dont allow to copy the JSON files, These jason files are used in as a data source in the polymer template. So now we copy and paste that libraries inside our SampleTest Folder which we created above. We will create another JS file for angular and we named it as app.js.(we will put our module, controller inside).

WE will also copy the angular.js file to work with the angular framework. So far our folder will be look like .

4
Below our blank page.

5

  • Import Polymer libraries on our page. Libraries folder I mentioned above and shared in the OneDrive to just copy and paste in the aspx page folder.
  • Import all the Polyer Script, jquery file, angular.js file and I add CSS for our views.

<!–importing the anguar Script and the Libraries of the Polyer –>

<!–Start –>

http://./Libraries/webcomponentsjs/webcomponents.js/
http://./Libraries/webcomponentsjs/jquery-1.9.1.js
/_layouts/15/init.js
http://./Libraries/webcomponentsjs/MicrosoftAjax.js
<link href=”./Libraries/core-toolbar/core-toolbar.html” rel=”import” />
<link rel=”import” href=”./Libraries/core-header-panel/core-header-panel.html” />
<link href=”./Libraries/core-icon/core-icon.html” rel=”import” />
<link rel=”import” href=”./Libraries/paper-icon-button/paper-icon-button.html” />
<link href=”./Libraries/core-icon-button/core-icon-button.html” rel=”import” />
<link rel=”import” href=”./Libraries/paper-tabs/paper-tab.html” />
<link rel=”stylesheet” href=”./Libraries/core-animated-pages/core-animated-pages.css” />
<link rel=”import” href=”./Libraries/core-animated-pages/core-animated-pages.html” />
<link href=”./Libraries/polymer/polymer.html” rel=”import” />
<!–Polyer Import End –>
<!– SharePoint Libraries –>
/_layouts/15/sp.core.js
/_layouts/15/sp.runtime.js
/_layouts/15/sp.js
/_layouts/15/core.js
<!– angular js  –>
http://./angular.js
<!– our js file for declaring controller and directive –>
http://app.js

Add the html part of the body.
<body fullbleed vertical layout unresolved> <!– use fullbleed attribute to specify the body should fill the viewport –>
<template is=”auto-binding” ng-controller=”SampleTestController”> <!– This is our Template which will repeate its child , I also attached this with my Controller Defined in app.js file–>
<core-toolbar class=”medium-tall”> <!–This is our toolbar for header–>
<core-icon-button icon=”{{$.pages.selected != 0 ? ‘arrow-back’ : ‘menu’}}” on-tap=”{{back}}”></core-icon-button> <!–This icon button will call funciton on tap or on click–>
<span id=”axix” style=”color:white”> You Name</span><!– Simply for header–>

Test Result Result

<core-icon-button on-tap=”{{backs}}”><img src=”http://dev:35897/myiner/logo.png&#8221; /></core-icon-button><!–you can put any logo here for your company as i did–>
</core-toolbar> <!–toobar ends–>
<!– core element of Polyer which will show the boxes on the page–>
<!– I will fetch data from SharPEoint and put in Array name items and pass this array to the template inside–>
<core-animated-pages id=”pages” flex selected=”0″ on-core-animated-pages-transition-end=”{{transitionend}}” transitions=”cross-fade-all hero-transition”>
<section vertical layout>

{{item.name}}

</template>
</div>
</div>
</section>
<template repeat=”{{item in items}}”>
<section vertical layout>

{{item.name}}

Interviewer Detail

</section>
</template>
</core-animated-pages>
</template>
</body>
Now the Javascript Part.
‘use strict’;
var currentUser;
var serverUrl = “http://siteurl/&#8221;;
var taskListItem = ”;
var collListItem = ”;
var items = [];
var itemsx = [];
//I m using the Jquery on ready function to load the SharEOoint List and add them in the array.
//Two function to load user and to get data from list.
//we can also create a controller or module dependency in the anguar and load them first

$(document).ready(function () {
ExecuteOrDelayUntilScriptLoaded(getuser, “sp.js”);
ExecuteOrDelayUntilScriptLoaded(loadlist, “sp.js”);
});
//This is my Load List and Add them in Array itemx.
function loadlist() {
console.log(“load me first”);
var context = new SP.ClientContext(“http://dev:35897&#8221;);
var web = context.get_web();
var myList = web.get_lists().getByTitle(“Area”);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(‘<View><Query><Where><Gt><FieldRef Name=”ID”/><Value Type=”Counter”>1</Value></Gt></Where></Query><ViewFields><FieldRef Name=”Title” /></ViewFields></View>”‘);
collListItem = myList.getItems(camlQuery);
context.load(collListItem);
context.executeQueryAsync(getInterviewSuccessfully, “failer”);
}
function getInterviewSuccessfully(sender, args) {
var listItemInfo = ”;
var listItemEnumerator = collListItem.getEnumerator();
var str = ”;
var strg = ”;
var count = 0;
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
count++;
items.push({
name: oListItem.get_item(‘Title’),
snippet: oListItem.get_item(‘Title’),
age: oListItem.get_item(‘ID’),

});

}
//console.log(items);
}
//This is my function to loa user.
function getuser() {
var context = new SP.ClientContext(serverUrl);
var web = context.get_web();
currentUser = web.get_currentUser();
context.load(currentUser);
context.executeQueryAsync(  //submit query to the server
function () {
$(“#axix”).text(currentUser.get_loginName().split(“\\”)[1]);
},
function (sender, args) {
alert(‘Request failed. \nError: ‘ + args.get_message() + ‘\nStackTrace: ‘ + args.get_stackTrace());
}
);

}

//Angular Part.
//Defining the module
var SampleTestApp = angular.module(‘SampleTestAppModule’, []);
SampleTestApp.controller(‘SampleTestController’, function ($scope, $http) {
$scope.itemsx = [];
$scope.FillAreas = function () {
var context = new SP.ClientContext(“http://dev:35897&#8221;);
var web = context.get_web();
var myList = web.get_lists().getByTitle(“Area”);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(‘<View><Query><Where><Gt><FieldRef Name=”ID”/><Value Type=”Counter”>1</Value></Gt></Where></Query><ViewFields><FieldRef Name=”Title” /></ViewFields></View>”‘);
collListItem = myList.getItems(camlQuery);
context.load(collListItem);
context.executeQueryAsync($scope.getInterviewSuccessfully, “failer”);
}

$scope.getInterviewSuccessfully = function (sender, args) {
var listItemInfo = ”;

var listItemEnumerator = collListItem.getEnumerator();

var str = ”;
var strg = ”;
var count = 0;
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
count++;
$scope.itemsx.push({
name: oListItem.get_item(‘Title’),
snippet: oListItem.get_item(‘Title’),
age: count,
});

}

console.log($scope.itemsx)
}
function errorHandlerArea(sender, args) {
alert(‘Request failed111. ‘ + args.get_message());
}
$scope.FillAreas2 = function () {
addEventListener(‘template-bound’, function (e) {
var scope = e.target;
scope.items = items;//axix();
scope.selectView = function (e) {
var i = e.target.templateInstance.model.item.age;
this.$.pages.selected = i + 1;
}
scope.back = function () {
this.lastSelected = this.$.pages.selected;
console.log(this.lastSelected);
this.$.pages.selected = 0;
}
scope.transitionend = function () {
if (this.lastSelected) {
this.lastSelected = null;
}
}
});

}
$scope.FillAreas2();

});

//Simple function which defined the jason object to deubg.

function axix() {

var x = [
{
‘name’: ‘Nexus S’,
‘snippet’: ‘Fast just got faster with Nexus S.’,
‘age’: 1
},
{
‘name’: ‘Motorola XOOM™ with Wi-Fi’,
‘snippet’: ‘The Next, Next Generation tablet.’,
‘age’: 2
},
{
‘name’: ‘Motorola XOOM™ with Wi-Fi’,
‘snippet’: ‘The Next, Next Generation tablet.’,
‘age’: 4
},
];

//console.log(x);
return x;
}

&nsp;
Below is the source code all, You actually it is an stp file. How to use it.

  • Upload it on the list template library.
  • Create an instance of this.
  • Go to the SharePoint designer open the content and browse or directly browse it form url of your library.

Souce Code
https://www.dropbox.com/sh/bjm59umlh2kmjqk/AADIvDxGi5GvUBXmP8FkOqJ7a?dl=0
4