Thursday 15 December 2016

Implementing SharePoint Operations Using React.js - Part Two

Here, you will see how React JavaScript plugins can be plugged in to SharePoint pages for rendering the data.
In my previous post, I explained about the basic terminology required for implementing React JavaScript logic on SharePoint pages.

Note

The core logic is implemented inside the class. The class can be created in two ways:
  • React traditionally provides React.createClass method to create the component classes.
  • Recently updated React JS version allows us to create the classes, using the React.Component method supported, using ES6 modules.
These two methods differ in implementation approaches. In this article, I will create the components, using ES6 modules.


Steps Involved

Upload the necessary plugins onto SharePoint site libraries. Instead of the local copies, the plugins can be directly accessed from cdn sites.

Create the content editor Webpart manually on the site. The custom Web parts can also be used. Inside the Web part, refer to the plugins explicitly.
  1. <script src="https://unpkg.com/react@latest/dist/react.js"></script>  
  2. <script src="https://unpkg.com/react-dom@latest/dist/react-dom.js"></script>  
  3. <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>   
Add the root HTML tag for appending the content, using JSX.
  1. <div id="listInformation"></div>  
JSX content is written inside the script tag, which is of the type text/babel. Babel plugin helps the code to be executed on the Browsers.

Create the class with custom name, using React.Component method. Class should contain a constructor, which has super() method declared. Set the state container with the necessary variables. In this sample, list name, descriptions, template ID and items count are stored.
  1. constructor(){  
  2.      super();  
  3.      this.state = {  
  4.          listInfo: {listName: '',listDescription: '', templateId:0, itemCount: 0}  
  5.      }  
  6.  }  
Since the data needs to be rendered on the page load, one of the life cycle methods is used to retrieve the list information and set it into the state variables. In this sample, the data is retrieved asynchronously. Thus, componentDidMount method is used. The custom function is created for retrieving the list information. 
  1. GetListInfo(){  
  2.     var reactHandler = this;  
  3.   
  4.     var request = new XMLHttpRequest();  
  5.     request.open('GET'"/_api/web/lists/getbytitle('TestList')"true);  
  6.     request.setRequestHeader('Content-Type''application/json; charset=UTF-8');  
  7.           
  8.     //this callback gets called when the server responds to the ajax call  
  9.     request.onreadystatechange = function(){  
  10.         if (request.readyState === 4 && request.status === 200){  
  11.             var returnedJson = JSON.parse(request.responseText);  
  12.               
  13.             reactHandler.setState({  
  14.                 listInfo:  
  15.                 {  
  16.                     listName: returnedJson.Title,  
  17.                     listDescription: returnedJson.Description,  
  18.                     templateId: returnedJson.BaseTemplate,  
  19.                     itemCount: returnedJson.ItemCount  
  20.                 }  
  21.             });  
  22.         }  
  23.         else if (request.readyState === 4 && request.status !== 200){  
  24.             console.log('Error in retrieving data!');  
  25.         }  
  26.     };  
  27.     request.send();  
  28. } 


Note

Event handlers can also be used instead of the method shown above, if the data retrieval is based on the user action.

The render method displays the data. HTML is inserted into this method. The state variables are referred to in this method to display the necessary information.
  1. render(){  
  2.     return(  
  3.     <div>  
  4.         <h2>{this.state.listInfo.listName} List Information:</h2>  
  5.         <p>{this.state.listInfo.listDescription}</p>  
  6.         <p>Template : {this.state.listInfo.templateId}</p>  
  7.         <p>Total Items: {this.state.listInfo.itemCount}</p>  
  8.     </div>  
  9.     );  
  10. }   
The render method is called to render the component data.
  1. ReactDOM.render(<ListJS />, document.getElementById('listInformation'));   
The code snippet given below shows the entire logic to retrieve the list information.
  1. <script src="https://unpkg.com/react@latest/dist/react.js"></script>  
  2. <script src="https://unpkg.com/react-dom@latest/dist/react-dom.js"></script>  
  3. <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>  
  4.   
  5. <div id="listInformation"></div>  
  6. <script type="text/babel">  
  7.       
  8.     class ListJS extends React.Component{  
  9.         constructor(){  
  10.             super();  
  11.             this.state = {  
  12.                 listInfo: {listName: '',listDescription: '', templateId:0, itemCount: 0}  
  13.             }  
  14.         }  
  15.         componentDidMount() {  
  16.             // Custom function to retrieve the list info  
  17.             this.GetListInfo();  
  18.         }  
  19.   
  20.         GetListInfo(){  
  21.             var reactHandler = this;  
  22.   
  23.             var request = new XMLHttpRequest();  
  24.             request.open('GET'"/_api/web/lists/getbytitle('TestList')"true);  
  25.             request.setRequestHeader('Content-Type''application/json; charset=UTF-8');  
  26.                   
  27.             //this callback gets called when the server responds to the ajax call  
  28.             request.onreadystatechange = function(){  
  29.                 if (request.readyState === 4 && request.status === 200){  
  30.                     var returnedJson = JSON.parse(request.responseText);  
  31.                       
  32.                     reactHandler.setState({  
  33.                         listInfo:  
  34.                         {  
  35.                             listName: returnedJson.Title,  
  36.                             listDescription: returnedJson.Description,  
  37.                             templateId: returnedJson.BaseTemplate,  
  38.                             itemCount: returnedJson.ItemCount  
  39.                         }  
  40.                     });  
  41.                 }  
  42.                 else if (request.readyState === 4 && request.status !== 200){  
  43.                     console.log('Error in retrieving data!');  
  44.                 }  
  45.             };  
  46.             request.send();  
  47.         }  
  48.   
  49.         render(){  
  50.             return(  
  51.             <div>  
  52.                 <h2>{this.state.listInfo.listName} List Information:</h2>  
  53.                 <p>{this.state.listInfo.listDescription}</p>  
  54.                 <p>Template : {this.state.listInfo.templateId}</p>  
  55.                 <p>Total Items: {this.state.listInfo.itemCount}</p>  
  56.             </div>  
  57.             );  
  58.         }  
  59.       
  60.     }  
  61.   
  62.     ReactDOM.render(<ListJS />, document.getElementById('listInformation'));  
  63. </script>   
The snapshot given below shows the Webpart, which shows the list information, using the logic stated above.



Wednesday 14 December 2016

Implementing SharePoint Operations Using React.js - Part One

In this series, you will learn how to implement basic SharePoint operations using React JavaScript libraries.

Here, you will learn the React JavaScript library basics required for implementing SharePoint operations.


ReactJS
  • React is a front-end library developed and licensed by Facebook.
  • React is a declarative, efficient, and flexible JavaScript library for building user interfaces.
  • It is famous for 'V' in MVC, which handles view layer on the web.
  • Using ReactJS, we can build reusable components. 
There are multiple ways of implementing the React JavaScript logic into SharePoint. In this article, I will use the React JavaScript libraries stored on the web. Additionally, Babel compiler is required for compiling the JSX content.

The library files referenced are,
  • react.js
  • react-dom.js
  • babel.min.js 

JSX

The core functionality is written on JSX. Here, Babel compiler is used to transform the JSX content to JS.
  • JSX content is embedded with in the script tag, which is of the type text/babel.
  • JSX contains JavaScript with HTML/XML in it.
  • JSX is faster, type safe and object-oriented programming language. 
  • JSX is not the globally accepted standard, so it is not supported on browsers.

Some of the React JavaScript basics used for our implementation are explained below. 
  1. ComponentsComponents help us split the code/UI in multiple pieces. The component contains a constructor and methods.
  2. StateState stores the data. The data can be in multiple forms. The data can be a string, number, array, etc.
  3. PropsProps are attributes defined in the components. These are immutable and passed as arguments for rendering the HTML. propTypes are used for validating the props.
  4. RenderIt is a method, which returns the HTML content that needs to be displayed on the page.
  5. ConstructorConstructor declares the variables, handlers and the methods.
  6. Component Life cycleThere are predefined set of methods executed when the component is executed. The life cycle methods are componentWillMount, componentDidMount, componentWillReceiveProps, shouldComponentUpdate, componentWillUpdate, componentDidUpdate, and componentWillUnmount. 
The React JavaScript library basics can be found on the official site https://facebook.github.io/react.


Prerequisites

In the sample, I will refer the React JavaScript and Babel plugins directly on the content editor webpart.
The sample JSX content will look like below.
  1. class Sample extends React.Component {  
  2.     constructor(){  
  3.         super();  
  4.         this.state = {  
  5.             data:''  
  6.         }  
  7.     }  
  8.     componentWillMount(){  
  9.     }  
  10.     componentDidMount() {  
  11.     }  
  12.     // Other Life Cycle Methods  
  13.   
  14.     render(){  
  15.         return(  
  16.             <div>  
  17.                 HTML  
  18.             </div>  
  19.         );  
  20.     }  
  21. }  
  22. ReactDOM.render(<Sample />, document.getElementById('divid'));   
  

Monday 4 July 2016

Working With List Columns On SharePoint Using PnP PowerShell

In this post, you will learn how we can create, retrieve and delete the columns on SharePoint lists, using PnP PowerShell. The Client Side Object Model is used internally for these operations. The update operation is not available for the site/list columns (fields).

Prerequisite:

You need to have PowerShell 3.0, available on a Windows machine. You need to install or import PnP PowerShell packages. You can download the installers or view more documentation on the official site. The installers are available here. Online version installer is preferred and is named On premise or Office 365 operations. You can also install all three installers for testing (SharePoint 2013, 2016, online).

The PnP PowerShell is supported from SharePoint 2013 on premise and Office 365 versions. The following operations are tested on SharePoint 2013 and Office 365 environments.

Connect To Site:

Connect to the site, using the snippet, given below. The PnP PowerShell code, given below, helps in getting the current context of the site, using the Client Side Object Model (CSOM).
  1. $siteurl = "https://abc.sharepoint.com"    
  2. Connect-SPOnline -Url $siteurl    
  3. $ctx = Get-SPOContext  
Once connected, you can carry out any of the operations mentioned below, based on the requirement.

Retrieve List Columns:

The list columns (fields) can be retrieved using PnP commands.
  • Get-SPOField command is used to get all the columns available on the SharePoint list.
  • The required parameters to get list column are list and identity. The list name is passed through list parameter. The field name is passed through identity parameter.
  • The properties like title, internal name, default value, description, etc. can be accessed.
The code snippet, given below, shows getting properties of a list column from the SharePoint list using column name.
  1. $column = Get-SPOField -List "PnPList" -Identity "PnPListColumn"  
  2. Write-Host "Column Title  :" $column.Title  
  3. Write-Host "Description   :" $column.Description  
  4. Write-Host "Group Name    :" $column.Group  
  5. Write-Host "Internal Name :" $column.InternalName  
  6. Write-Host "Static Name   :" $column.StaticName  
  7. Write-Host "Scope         :" $column.Scope  
  8. Write-Host "Type          :" $column.TypeDisplayName  
  9. Write-Host "Schema XML    :" $column.SchemaXml  
  10. Write-Host "Is Required?  :" $column.Required  
  11. Write-Host "Is read only? :" $column.ReadOnlyField  
  12. Write-Host "Unique?       :" $column.EnforceUniqueValues  
  13. Write-Host "-------------------------------------------"  
To get all the fields from a SharePoint list, identity parameter is not required. The code snippet, given below, shows getting all columns from the SharePoint list.
  1. $columns = Get-SPOField -List "PnPList"  
  2. foreach($column in $columns){  
  3.     Write-Host "Column Title  :" $column.Title  
  4.     Write-Host "Description   :" $column.Description  
  5.     Write-Host "Group Name    :" $column.Group  
  6.     Write-Host "Internal Name :" $column.InternalName  
  7.     Write-Host "Static Name   :" $column.StaticName  
  8.     Write-Host "Scope         :" $column.Scope  
  9.     Write-Host "Type          :" $column.TypeDisplayName  
  10.     Write-Host "Schema XML    :" $column.SchemaXml  
  11.     Write-Host "Is Required?  :" $column.Required  
  12.     Write-Host "Is read only? :" $column.ReadOnlyField  
  13.     Write-Host "Unique?       :" $column.EnforceUniqueValues  
  14.     Write-Host "-------------------------------------------"  
  15. }  

Create List Column:

The columns can be created on the lists available on SharePoint site or sub site by setting the context, using the site URL. PnP CSOM PowerShell can be used to complete the operation. 
  • Add-SPOField command, which is used to create the columns on SharePoint lists.
  • The required parameters for creating new column on the list are display name, internal name, group name and field type. 
  • The new values can be passed as the parameters. 
  • AddToDefaultView option is used to make to list column available on default views. The column can be made as mandatory, using the required parameter.
In my example, I have created the new column called "PnPListColumn", which is a text type. The below code snippet shows adding new column. 
  1. Add-SPOField -DisplayName "PnPListColumn" -InternalName "PnPListColumn" -Group "PnPGroup" -Type Text -List "PnPList" -AddToDefaultView -Required  
 As of now, only few properties can be updated while creating the fields.

The image given below shows list default view with list column.


Delete List Column:

The columns can be deleted from a SharePoint list, using PnP PowerShell.
  • Remove-SPOField is used to delete the columns (fields).
  • The field name and list name are required to delete the column. The name or Id can be passed with the command, using the identity parameter. The list name is passed using list parameter.
  • The force attribute is used to delete the field without any confirmation prompts.
The below code snippet shows removing list column.
  1. Remove-SPOField -List "PnPList" -Identity "PnPListColumn" -Force  

Note: The above operations are tested on SharePoint 2013 and Office 365 environments.

Sunday 3 July 2016

Working With Site Columns On SharePoint Using PnP PowerShell

In this post, you will learn, how we can create, retrieve and delete the site columns on SharePoint sites, using PnP PowerShell. Also you will see how to add site column to a site content type. The Client Side Object Model is used internally for these operations. The update operation is not available for the site columns.

Prerequisite:

You need to have PowerShell 3.0 available on a Windows machine. You need to install or import PnP PowerShell packages. You can download the installers or view more documentation on the official site. The installers are available here. Online version installer is preferred for on premise or office 365 operations. You can also install all three installers for testing (SharePoint 2013, 2016, online).

The following operations will be compatible with SharePoint 2013 on premise and Office 365 versions.

Connect To Site:

Connect to the site, using the snippet, given below. The PnP PowerShell code, given below, helps in getting the current context of the site, using the Client Side Object Model (CSOM).
  1. $siteurl = "https://abc.sharepoint.com"  
  2. Connect-SPOnline -Url $siteurl  
  3. $ctx = Get-SPOContext  
Once connected, you can carry out any of the operations mentioned below, based on the requirement.

Create Site Column:

The columns can be created on the site collections by setting the context, using the site URL. PnP CSOM PowerShell can be used to complete the operation.
Add-SPOField command is used to create the site columns on SharePoint sites. The required parameters to create the new site column are display name, internal name, group and type. The column can be made as mandatory using required parameter. The new values can be passed as the parameters. In my example, I have created new site column called "PnPTextColumn" which is text type.
  1. Add-SPOField -DisplayName "PnPTextColumn" -InternalName "PnPTextColumn" -Group "PnPGroup" -Type Text -Required  
The below code snippet shows creating new column with choice type. Similarly other field types can be created.
  1. Add-SPOField -DisplayName "PnPColorColumn" -InternalName "PnPColorColumn" -Group "PnPGroup" -Type Choice -Choices @("red","blue","green")  
 As of now only few properties can be supported for creating site columns.
The below image shows creating new site column using PowerShell.



The below image shows the site column created. The page can be accessed from http://siteurl/_layouts/15/mngfield.aspx.


Retrieve Site Columns:

The site columns can be retrieved using PnP commands. Get-SPOField command is used to get all the site columns available on the SharePoint site collection. The identity parameter is used to retrieve specific site columns. The properties like title, internal name, default value, description, is required can be accessed.

The below code snippet shows getting all the site columns from the site.
  1. Get-SPOField  
 The below code snippet shows getting a site column using column name.
  1. $field = Get-SPOField -Identity "PnPTextColumn"  
  2. Write-Host "Title " $field.Title  
  3. Write-Host "Internal Name" $field.InternalName  
  4. Write-Host "Default value " $field.DefaultValue  
  5. Write-Host "Description " $field.Description  
  6. Write-Host "Is Required" $field.Required  
The below image shows the get operation for birthday field or column.


Add Site Column To Content Type:
The site columns can be added to site content types. The column and content type should exist before adding. Add - SPOFieldToContentType command is used in adding the fields as site columns to content types. The below code snippet shows adding text column to a content type using names.
  1. Add-SPOFieldToContentType -Field "PnPTextColumn" -ContentType "PnPContentType"  
The below code snippet shows adding field to content type using identities.
  1. $colorColumn = Get-SPOField -Identity "PnPColorColumn"  
  2. $pnpCT = Get-SPOContentType -Identity "PnPContentType"  
  3. Add-SPOFieldToContentType -Field $colorColumn -ContentType $pnpCT 


Delete Site Column:

The site column can be deleted from SharePoint site or sub site, using PnP PowerShell. Remove-SPOField is used to delete the columns (fields). The field name is passed for deleting the column. The name or ID can be passed with the command, using the identity parameter. The force attribute is used to delete the field without any confirmation prompts.
  1. Remove-SPOField -Identity "PnPTextColumn" -Force