Ms Graph With SPFx Part 1

Demo of get Group information using Ms Graph and SPFx

Business Scenario:
If we need to know that how many groups are available in directory or in which group i am member of.
We need to go to admin center and check there.Now think if we don’t have the administrator access to check the certain things in sharepoint admin.So we stuck to bottle neck or dependent to the person who have the admin access.
Solution:
We can get group related information or membership information using graph API in SharePoint SPfx Webpart.We need to provide access one time then webpart can access the directory to get information using admin consented.

What is Ms Graph?
Microsoft Graph is a developers’ API platform to connect to the data that drives productivity. It’s built on top of Office 365 and allows developers to integrate their services with Azure AD, Excel, Intune, Outlook, One Drive, OneNote, SharePoint, Planner, and other Microsoft products.
Reference Link : Click here

What is SPFx?
The SharePoint Framework (SPFx) is a page and web part model that provides full support for client-side SharePoint development, easy integration with SharePoint data, and support for open source tooling.
Reference Link : Click here

See the Sample Demo as below
Click here to get full source code

Get Groups and membership of users

Let’s Start to develop solution

Prerequisites:
Please install below packages in your solution

npm i react-csv
npm i @pnp/spfx-controls-react


Step 1 : Create a SPFx Solution with React Javascript framework using below link
Reference Link : Click here to open
Step 2 : Create Service.ts file and add below methods to connect with Graph Client.
Methods to get the content from the directory using MsGraph
Click here to get source code for service

import { WebPartContext } from "@microsoft/sp-webpart-base";
import { SPHttpClient,MSGraphClient } from "@microsoft/sp-http";
import { arraysEqual } from "office-ui-fabric-react/lib/Utilities";

export class MsGraphService{

public static async GetOrganizationGroups(context:WebPartContext):Promise<any>{
    let  allGroups:string[] = [];
    try {
      let client:MSGraphClient = await context.msGraphClientFactory.getClient().then();
      let response = await client
      .api("/groups")
      .version("v1.0")
      .select(['description','displayName','groupTypes','mailEnabled','mailNickname','securityEnabled','visibility']).get();
      response.value.map((group:any)=>{
        allGroups.push(group);
      });
    } catch (error) {
      console.log("MSGraphService.GetOrganizationGroups Error: ", error);
    }
    console.log("MSGraphService.GetOrganizationGroups Error: ",allGroups);
    return allGroups;
  }

/**
   * Gets all the groups the me is part of using MS Graph API
   * @param context context Web part context
   */

  public static async GetMyUserGroups(context:WebPartContext):Promise<any[]>{
    let groups:string[]=[];
    try {
      let client:MSGraphClient = await context.msGraphClientFactory.getClient().then();
      let response = await client.api('/me/memberOf').version('v1.0')
        .select(['groupTypes', 'displayName', 'mailEnabled', 'securityEnabled', 'description'])
        .get();

        response.value.map((item: any) => {
          groups.push(item);
        });
    } catch (error) {
      console.log("MsGraphService.GetMyUserGroups Error: ",error);
    }
    console.log("MsGraphService.GetMyUserGroups groups : " ,groups);
    return groups;
  }

}

Step 3 : Create a interfaces to store the output attributes
Create file with name IGroupItem.ts and add below code in it
Click here to get source code

export interface IGroupItem{
  name: string;
  description: string;
  groupTypes: string;
}

export interface IUserItem {
  displayName: string;
  mail: string;
}

Step 4 : Update <webpart>NameProps.ts file with below code

import { WebPartContext } from '@microsoft/sp-webpart-base';

export interface ICheckGroupMembersProps {
  context: WebPartContext;
}

Step 5 : Create a new file with name <webpartName>State.ts and add below code
Click here to get source code

import { IUserItem } from "../../../../Common/IUserItem";
import { IColumn } from 'office-ui-fabric-react/lib/DetailsList';

export interface ICheckGroupMembersState {
  userItems: IUserItem[];
  columns: IColumn[];
  memberStatus: string;
  loading: boolean;
  GroupId:string;
}

Step 6: Open .tsx file and import below modules.
Click here to get source code

import * as React from "react";
import styles from "../ReactGroupSamples.module.scss";
import { PeoplePicker, PrincipalType } from '@pnp/spfx-controls-react/lib/PeoplePicker';
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { DetailsList, DetailsListLayoutMode, IColumn, SelectionMode } from 'office-ui-fabric-react/lib/DetailsList';
import { CommandBarButton } from 'office-ui-fabric-react/lib/Button';
import { Spinner } from 'office-ui-fabric-react/lib/Spinner';
import { ICheckGroupMembersProps } from "./CheckGroupMembersProps";
import { ICheckGroupMembersState } from "./CheckGroupMembersState";
import { MsGraphService } from "../../../../Service/MsGraphService";
import { IUserItem } from "../../../../Common/IUserItem";
import { CSVLink } from "react-csv";
// Add below method to call service method from react file.

private _GetGroupMembers = (items:any[]) => {
this.setState({loading:true},async()=>{
  let userItems: IUserItem[] = [];
  let memberStatus: string = '';
  try {
    if(items.length > 0){
      this.setState({
        GroupId:items[0].id.split('|').pop()
      });
      let users = await MsGraphService.GetGroupMembers(this.props.context,items[0].id.split('|').pop());
      if(users.length === 0){
        memberStatus = 'The selected group does not have any members';
      }
      else
      {
        users.map((user, i) => {
          userItems.push({
            displayName: user.displayName,
            mail: user.mail
          });
        });
      }
    }
  } catch (error) {
    console.log("CheckGroupMembers._GetGroupMembers Error:",error);
  }
  console.log("CheckGroupMembers._GetGroupMembers Users:",userItems);
  this.userItems = userItems;
  this.setState({ userItems, memberStatus, loading: false });
});
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.