Graph API in SharePoint custom page layout

Azure Active Directory App
We have to create an Azure AD app for access graph API, this app will help to access from particular URL and limit the permission to access the particular data, let we see the steps to create the new Azure AD app, we don’t have pay for Azure AD app and It’s always free.

result


Step 1
Sign in to your Azure account https://portal.azure.com, if you don’t have an Azure account the sign-up for a free account.
Step 2
Navigate to Azure Active Directory > App Registration > New application registration

Azure01


Step 3
In the create form give any name for your app and application type is Web app and enter your SharePoint tenet URL in the sign-on URL section then click Create button in the bottom
Step 4
Once app created select the app and click settings then select required permissions, click add and select permission based on your requirement after selected permission don’t forgot click grant permission, this button located next to the Add button
Step 5
Back to select newly created app and click Manifest, in the manifest file oauth2AllowImplicitFlow to true

If you have any questions about creating new custom page layout please refer my previous article Create custom page layout in SharePoint Online

We are used Active Directory Authentication Library (ADAL) JS for authentication, so we have add “adal.min.js” reference in the page layout. In the below JavaScript function we have to pass the Client ID as the Azure AD app ID and subscription id is <your tenant name>.onmicrosoft.com.
Even you want to get or post only while clicking any button, you have to get token once in the document ready event.

Please be make sure that you using latest version of adal.js, old version having issues in IE browser, also have to add the SharePoint tenant URL under trusted settings in internet options


$( document ).ready(function() {
"use strict";
var subscriptionId = "ravichandran.onmicrosoft.com"; /* [AzureTenantname] from azure */
var clientId = "6cf00073-3103-4af8-84a4-ee2229e3e83e"; /* [AzureADClientID] from azure */
window.config = {
subscriptionId: subscriptionId,
clientId: clientId,
postLogoutRedirectUri: window.location.origin,
endpoints: {
graphApiUri: 'https://graph.microsoft.com'
},
cacheLocation: 'localStorage' // enable this for IE, as sessionStorage does not work for localhost.
};
var authContext = new AuthenticationContext(config);
// Check For & Handle Redirect From AAD After Login
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
// If not logged in force login
var user = authContext.getCachedUser();
if (user) {
// Logged in already
}
else {
authContext.login();
}
authContext.acquireToken(config.endpoints.graphApiUri, function (error, token) {
if (error || !token) {
console.log('ADAL error occurred: ' + error);
return;
}
var TeamUri = config.endpoints.graphApiUri + "/v1.0/sites/root/lists";
$.ajax({
type: "GET",
url: TeamUri,
headers: { "Authorization": "Bearer " + token, "Content-Type": "application/json" }
}).done(function (response) {
$.each(response.value,function(i,v){
$('#main').append('

' + v.displayName + '

');
});
}).fail(function (xhr, textStatus, errorThrown) {
if (xhr.responseJSON.error.code.indexOf('AccessDenied') !== -1) {
console.log('Access Denied.');
}
else {
console.log(xhr.responseJSON.error.code);
}
});
});
});

Sharing is caring!

If you have any questions, feel free to let me know in the comments section.
Happy coding!!!

Fabric React DatePicker in SPFx

As we know Office UI Fabric which is official front-end framework for building a user interface that fits seamlessly into SharePoint modern experience. In this article, we going to see more detail about the Date picker component. Also, we saving and retrieving data into the SharePoint list. Herewith you can find the complete project download link.

Fabric React DatePicker in SPFx

Creating a new SharePoint Framework web part
The first step we have to create new SharePoint framework web part project, I have used SharePoint Framework version 1.8, if you have any question for you then you can refer my one of the previous article where I explained simple steps to set up a new development environment and create the new project. While creating a project in the PowerShell you have to select react framework.

Fabric React DatePicker in SPFx create web part

Important files
In the new SharePoint framework web part solution contains tons of files, understanding each file’s purpose is really awesome, but in this articale we going take look only four files, because making changes in those four files is enough
1. src\webparts\fabricDatePicker\FabricDatePickerWebPart.ts
2. src\webparts\fabricDatePicker\components\IFabricDatePickerProps.ts
3. src\webparts\fabricDatePicker\components\FabricDatePicker.tsx
4. src\webparts\fabricDatePicker\components\FabricDatePicker.module.scss

Web part TS file (FabricDatePickerWebPart.ts)
In this file, we just calling create react element and created element assigned to the react DOM, also we passing web part context as props so we can access this props in while create react component.

 

import * as React from 'react';
import * as ReactDom from 'react-dom';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import FabricDatePicker from './components/FabricDatePicker';
import { IFabricDatePickerProps, IFabricDatePickerWebpartProps } from './components/IFabricDatePickerProps';
export default class FabricPeoplePickerWebPart extends BaseClientSideWebPart<IFabricDatePickerWebpartProps> {
    public render(): void {
        const element: React.ReactElement<IFabricDatePickerProps> = React.createElement(
          FabricDatePicker,
            {
                spcontect: this.context
            }
        );
        ReactDom.render(element, this.domElement);
    }
}

 

Property file (IFabricDatePickerProps.ts)
In the props file we just created two interfaces, one is IFabricDatePickerProps will pass the props which are read-only, so we only passing context and another one is IFabricDatePickerWebpartProps will carry all states for the react components. so we can set and get values to the controls.

//Set all read only values
export interface IFabricDatePickerProps {
  spcontect?:any|null
}

//Set all read and write only values
export interface IFabricDatePickerWebpartProps {
  birthday?:any|null;
  message:string
}

Component file (FabricDatePicker.tsx)
In this file we do most of the things like building date picker, retiring data from SharePoint and assign that value to the date picker and save changes back into the SharePoint list.
In the constructor, we retrieve the value from SharePoint and assign the value to the date picker also we injecting props to the button click event for accessing all props inside the click event.
In the render event, we returning the HTML content for the user interface,
In the select date event, we receive the value and assign back to the component state
In the format date event, we can set which format date picker have to display the value,
In the button click event, we updating value into the SharePoint list

import * as React from 'react';
import { IFabricDatePickerProps, IFabricDatePickerWebpartProps } from './IFabricDatePickerProps';
import { Environment, EnvironmentType } from '@microsoft/sp-core-library';
import { SPHttpClient, SPHttpClientResponse, ISPHttpClientOptions, IHttpClientOptions } from '@microsoft/sp-http'
import { DatePicker } from 'office-ui-fabric-react/lib/DatePicker';
import { Label } from 'office-ui-fabric-react/lib/Label';
import { PrimaryButton } from 'office-ui-fabric-react/lib/Button';
import styles from './FabricDatePicker.module.scss';

export default class FabricDatePicker extends React.Component<IFabricDatePickerProps, IFabricDatePickerWebpartProps> {

    private etag: String = undefined;
    public constructor(props: IFabricDatePickerProps, state: IFabricDatePickerWebpartProps) {
        super(props);
        this.state = {
            birthday: null,
            message:''
        };

        if (Environment.type === EnvironmentType.SharePoint) {
            this.props.spcontect.spHttpClient.get(this.props.spcontect.pageContext.web.absoluteUrl + '/_api/web/lists/getbytitle(\'sampleLIST\')/items(1)', SPHttpClient.configurations.v1).then
                ((Response: SPHttpClientResponse) => {
                   // this.etag = Response.headers.get('ETag');
                    Response.json().then((listItem: any) => {
                        this.setState({ birthday: new Date(listItem.Birthday) });
                    });
                });

        }
        else if (Environment.type === EnvironmentType.Local) {
            // return (<div>Whoops! you are using local host...</div>);
        }

        this._alertClicked = this._alertClicked.bind(this);
    }

    public render(): React.ReactElement<IFabricDatePickerProps> {
        return (
            <div className={styles.fabricDatePicker}>
                <div id="DivLocalHost"></div>
                <div className={styles.container}>
                    <div className={styles.row}>
                        <Label>Birthday</Label>
                        <DatePicker placeholder="Select a date..."
                            onSelectDate={this._onSelectDate}
                            value={this.state.birthday}
                            formatDate={this._onFormatDate}
                        />
                        <div>
                        <div className={styles.label}>
                        <label>{this.state.message}</label>
                        </div>
                        <div className={styles.button}>                     
                            <PrimaryButton data-automation-id="test"
                                text="Save"
                                onClick={this._alertClicked} />
                        </div>
                        </div>
                    </div>
                </div>
            </div>
        );

    }

    private _onSelectDate = (date: Date | null | undefined): void => {
        this.setState({ birthday: date });
    };

    private _onFormatDate = (date: Date): string => {
        return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
    };

    private _alertClicked(): void {
        const body: string = JSON.stringify({
            '__metadata': {
                'type': 'SP.Data.SampleLISTListItem'
            },
            'Birthday': this.state.birthday
        });
        this.props.spcontect.spHttpClient.get(this.props.spcontect.pageContext.web.absoluteUrl + '/_api/web/lists/getbytitle(\'sampleLIST\')/items(1)', SPHttpClient.configurations.v1).then
        ((Response: SPHttpClientResponse) => {
          this.props.spcontect.spHttpClient.post(this.props.spcontect.pageContext.web.absoluteUrl + `/_api/web/lists/getbytitle('sampleLIST')/items(1)`,
          SPHttpClient.configurations.v1,
          {
              headers: {
                  'Accept': 'application/json;odata=nometadata',
                  'Content-type': 'application/json;odata=verbose',
                  'odata-version': '',
                  'IF-MATCH': Response.headers.get('ETag'),
                  'X-HTTP-Method': 'MERGE'
              },
              body: body
          }).then((response: SPHttpClientResponse) => {
              // Access properties of the response object. 
              this.setState({ message: 'Successfully saved' });
              console.log(`Status code: ${response.status}`);
              console.log(`Status text: ${response.statusText}`);

              //response.json() returns a promise so you get access to the json in the resolve callback.
              response.json().then((responseJSON: JSON) => {
                  console.log(responseJSON);
              });
          });
        });

    }

}

Style file (FabricDatePicker.module.scss)
This file contains the CSS module, but we using sass because we wanted to call the CSS class name from javascript as a javascript object.

Date Picker properties
We can customize the date picker using date picker properties, you can find the many properties in the official documentation, here we take look some of them, by default date picker looks like this,

isMonthPickerVisible true

isMonthPickerVisible
this property by default is true, we can make false if we don’t need month picker in the calendar. example

<DatePicker placeholder="Select a date..." isMonthPickerVisible={false}/>

isMonthPickerVisible

minDate
Using this property we can set the minimum date for the date picker, so date picker does not allow to chose less than that. Example

<DatePicker placeholder="Select a date..." minDate={new Date(2000,12,30)}/>

minDate

Please feel free to let me know if you have any queries in the comment section, I’m happy to help you!!
Source Code Download link

174https://code.msdn.microsoft.com/Fabric-React-DatePicker-in-d25382bb

Simple steps to create a new web part using the SharePoint framework

Microsoft provided extremely detail documentation for setup an environment for SharePoint Framework development, but if you already work in SharePoint then below simple steps pretty enough to set up a development environment and create your first web part using SharePoint framework.

Set up your development environment.

Step 1 (Create Developer Site):

Using below link to sign up for Office 365 Enterprise E3 Trial,

For create new create a new app catalog site, go to the SharePoint Admin Centre (https://<tenant>admin.sharepoint.com) → Apps → App catalog

Create a site collection using  the Developer Site template

Step 2 (Install node JS and Visual Studio code):

https://nodejs.org/dist/latest-v10.x/

https://code.visualstudio.com/Download

Step 3 (install node modules):

Run PowerShell as Administrator

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
npm install gulp yo @microsoft/generator-sharepoint --global
npm install -g windows-build-tools
npm install -g @microsoft/sp-build-web

To create a new web part project


md c:\spfx\helloworld-webpart

cd c:\spfx\helloworld-webpart

yo @microsoft/sharepoint

gulp trust-dev-cert

gulp serve

now you can access your web part in localhost and in the SharePoint /_layouts/workbench.aspx

but still, files are referred from the local host

Enable SharePoint CDN

run below comment in PowerShell to make ready for SharePoint CDN deployment, below PowerShell comments required to run only once for a SharePoint portal.


Connect-SPOService -Url https://<tenant>-admin.sharepoint.com

Set-SPOTenantCdnEnabled -CdnType Public

Deploy into SharePoint

below PowerShell comments will create a SharePoint package file, file extension will be .sppkg


gulp bundle --ship

gulp package-solution --ship

under SharePoint/solution folder can find the .sppkg extension file, upload that file into the SharePoint’s app catalog and deploy it. Now web part ready to use by everyone.

Please let me know if you struck anywhere, I can help you.