Added react-dynamics-crm-api sample

This commit is contained in:
Ramin Ahmadi 2020-07-22 20:42:29 +01:00
parent 03baa515d6
commit 46352b4e9b
32 changed files with 696 additions and 0 deletions

View File

@ -0,0 +1,25 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
# change these settings to your own preference
indent_style = space
indent_size = 2
# we recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[{package,bower}.json]
indent_style = space
indent_size = 2

View File

@ -0,0 +1,32 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
solution
temp
*.sppkg
# Coverage directory used by tools like istanbul
coverage
# OSX
.DS_Store
# Visual Studio files
.ntvs_analysis.dat
.vs
bin
obj
# Resx Generated Code
*.resx.ts
# Styles Generated Code
*.scss.ts

View File

@ -0,0 +1,12 @@
{
"@microsoft/generator-sharepoint": {
"isCreatingSolution": true,
"environment": "spo",
"version": "1.10.0",
"libraryName": "react-dynamic-365",
"libraryId": "5bc3855d-9c59-4322-95e0-78e17dcd809e",
"packageManager": "npm",
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,47 @@
# React Dynamics CRM API
## Summary
This sample shows how to consume Dynamics CRM API using AadTokenProvider class.
![react-dynamics365-api](./assets/screenshot.gif)
## Used SharePoint Framework Version
![SPFx v1.10.0](https://img.shields.io/badge/SPFx-1.10.0-green.svg)
## Applies to
* [SharePoint Framework Developer](http://dev.office.com/sharepoint/docs/spfx/sharepoint-framework-overview)
* [Office 365 developer tenant](http://dev.office.com/sharepoint/docs/spfx/set-up-your-developer-tenant)
## Solution
Solution|Author(s)
--------|---------
react-dynamics365-api|Ramin Ahmadi
## Version history
Version|Date|Comments
-------|----|--------
1.0.0|Jul 12, 2020|Initial release
## Disclaimer
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**
---
## Features
This sample illustrates the following concepts on top of the SharePoint Framework:
* Using AadTokenProvide to consume Dynamics CRM API.
* How to get Accounts/Contacts information from Dynamics 365.
* React Hooks
* Using async / await for the async calls
* Ant design for the UI.
## Configuration
Read my blog post for more information from [here](https://ramin.expert/?p=363).

Binary file not shown.

After

Width:  |  Height:  |  Size: 490 KiB

View File

@ -0,0 +1,18 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"dynamic-365-sales-accounts-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/dynamic365SalesAccounts/Dynamic365SalesAccountsWebPart.js",
"manifest": "./src/webparts/dynamic365SalesAccounts/Dynamic365SalesAccountsWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"Dynamic365SalesAccountsWebPartStrings": "lib/webparts/dynamic365SalesAccounts/loc/{locale}.js"
}
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/copy-assets.schema.json",
"deployCdnPath": "temp/deploy"
}

View File

@ -0,0 +1,7 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./temp/deploy/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "react-dynamic-365",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,21 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-dynamic-365-client-side-solution",
"id": "5bc3855d-9c59-4322-95e0-78e17dcd809e",
"version": "1.0.0.1",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"webApiPermissionRequests": [
{
"resource": "Windows Azure Active Directory",
"scope": "User.Read"
}
]
},
"paths": {
"zippedPackage": "solution/react-dynamic-365.sppkg"
}
}

View File

@ -0,0 +1,10 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://localhost:5432/workbench",
"api": {
"port": 5432,
"entryPath": "node_modules/@microsoft/sp-webpart-workbench/lib/api/"
}
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
"cdnBasePath": "<!-- PATH TO CDN -->"
}

View File

@ -0,0 +1,7 @@
'use strict';
const build = require('@microsoft/sp-build-web');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
build.initialize(require('gulp'));

View File

@ -0,0 +1,44 @@
{
"name": "react-dynamic-365",
"version": "0.0.1",
"private": true,
"main": "lib/index.js",
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@microsoft/sp-core-library": "1.10.0",
"@microsoft/sp-lodash-subset": "1.10.0",
"@microsoft/sp-office-ui-fabric-core": "1.10.0",
"@microsoft/sp-property-pane": "1.10.0",
"@microsoft/sp-webpart-base": "1.10.0",
"@types/es6-promise": "0.0.33",
"@types/react": "16.8.8",
"@types/react-dom": "16.8.3",
"@types/webpack-env": "1.13.1",
"antd": "^4.4.2",
"axios": "^0.19.2",
"office-ui-fabric-react": "6.189.2",
"react": "16.8.5",
"react-dom": "16.8.5"
},
"resolutions": {
"@types/react": "16.8.8"
},
"devDependencies": {
"@microsoft/rush-stack-compiler-3.7": "^0.6.1",
"@microsoft/sp-build-web": "1.10.0",
"@microsoft/sp-module-interfaces": "1.10.0",
"@microsoft/sp-tslint-rules": "1.10.0",
"@microsoft/sp-webpart-workbench": "1.10.0",
"@types/chai": "3.4.34",
"@types/mocha": "2.2.38",
"ajv": "~5.2.2",
"gulp": "~3.9.1"
}
}

View File

@ -0,0 +1,27 @@
type Listener<T> = (val: T) => void;
type Unsubscriber = () => void;
export class Observable<T> {
private _listeners: Listener<T>[] = [];
constructor(private _val: T) {
}
public get(): T {
return this._val;
}
public set(val: T) {
if (this._val !== val) {
this._val = val;
this._listeners.forEach(l => l(val));
}
}
public subscribe(listener: Listener<T>): Unsubscriber {
this._listeners.push(listener);
return () => {
this._listeners = this._listeners.filter(l => l !== listener);
};
}
}

View File

@ -0,0 +1,12 @@
import { useEffect, useState } from "react";
import { Observable } from "./observable";
export default function useObservable<T>(observable: Observable<T>): T {
const [val, setVal] = useState(observable.get());
useEffect(() => {
return observable.subscribe(setVal);
}, [observable]);
return val;
}

View File

@ -0,0 +1 @@
// A file is required to be in the root of the /src directory by the TypeScript compiler

View File

@ -0,0 +1,5 @@
export default interface IAccount{
name:string;
emailaddress1:string;
accountid:string;
}

View File

@ -0,0 +1,6 @@
export default interface IContact{
fullname : string;
emailaddress1:string;
telephone1:string;
address1_city:string;
}

View File

@ -0,0 +1,60 @@
import axios from "axios";
import { Observable } from "../hooks/observable";
import { AadTokenProviderFactory } from "@microsoft/sp-http";
export default class DynamicsService {
public readonly errorMessage = new Observable<string>(null);
private accessToken: string;
public aadTokenProviderFactory: AadTokenProviderFactory;
// update ResourceURI based on your dynamic crm uri
public resourceUri:string;
public async getAccessToken(){
const token = sessionStorage.getItem("dynamic365Token");
if(token)
this.accessToken = token;
else{
await
this.aadTokenProviderFactory
.getTokenProvider()
.then((tokenProvider) => {
tokenProvider
.getToken(this.resourceUri)
.then((t) => {
this.accessToken = t;
sessionStorage.setItem("dynamic365Token",t);
})
.catch((err) => console.log("Error: " + err));
});
}
}
public async getAccounts() {
const url = `${this.resourceUri}/api/data/v9.0/accounts?$top=20&$select=name,emailaddress1`;
const response = await axios({
url,
method: "GET",
headers:{"Authorization":`Bearer ${this.accessToken}`}
});
return response.data.value;
}
public async getContacts(id:string){
const url = `${this.resourceUri}/api/data/v9.0/contacts?$top=5&$select=fullname,emailaddress1,telephone1,address1_city&$filter=_accountid_value eq '${id}'`;
const response = await axios({
url,
method: "GET",
headers:{"Authorization":`Bearer ${this.accessToken}`}
});
return response.data.value;
}
public async searchAccounts (name:string){
const url = `${this.resourceUri}/api/data/v9.0/accounts?$top=20&$select=name,emailaddress1&$filter=contains(name,'${name}')`;
const response = await axios({
url,
method: "GET",
headers:{"Authorization":`Bearer ${this.accessToken}`}
});
return response.data.value;
}
}

View File

@ -0,0 +1,2 @@
import DynamicsService from './dynamicsService';
export const dynamicsService = new DynamicsService();

View File

@ -0,0 +1,27 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "2a144942-a8bc-4e51-8f37-6ca58450bc00",
"alias": "Dynamic365SalesAccountsWebPart",
"componentType": "WebPart",
// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,
// If true, the component can only be installed on sites where Custom Script is allowed.
// Components that allow authors to embed arbitrary script code should set this to true.
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
"requiresCustomScript": false,
"supportedHosts": ["SharePointWebPart","TeamsPersonalApp","TeamsTab"],
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
"group": { "default": "Other" },
"title": { "default": "Dynamic 365 Sales Accounts" },
"description": { "default": "Dynamic 365 Sales Accounts description" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "Dynamic 365 Sales Accounts"
}
}]
}

View File

@ -0,0 +1,64 @@
import { dynamicsService } from "./../../services/services";
import * as React from "react";
import * as ReactDom from "react-dom";
import { Version } from "@microsoft/sp-core-library";
import {
IPropertyPaneConfiguration,
PropertyPaneTextField,
} from "@microsoft/sp-property-pane";
import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base";
import * as strings from "Dynamic365SalesAccountsWebPartStrings";
import Dynamic365SalesAccounts from "./components/Dynamic365SalesAccounts";
import { IDynamic365SalesAccountsProps } from "./components/IDynamic365SalesAccountsProps";
import "antd/dist/antd.css";
export interface IDynamic365SalesAccountsWebPartProps {
dynamicCRMDomain: string;
}
export default class Dynamic365SalesAccountsWebPart extends BaseClientSideWebPart<
IDynamic365SalesAccountsWebPartProps
> {
public async onInit(): Promise<void> {
dynamicsService.aadTokenProviderFactory = this.context.aadTokenProviderFactory;
dynamicsService.resourceUri = `https://${this.properties.dynamicCRMDomain}.dynamics.com`;
}
public render(): void {
const element: React.ReactElement<IDynamic365SalesAccountsProps> = React.createElement(
Dynamic365SalesAccounts
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse("1.0");
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription,
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField("dynamicCRMDomain", {
label: strings.DynamicCrmDomainFieldLabel,
}),
],
},
],
},
],
};
}
}

View File

@ -0,0 +1,74 @@
@import '~office-ui-fabric-react/dist/sass/References.scss';
.dynamic365SalesAccounts {
.container {
max-width: 700px;
margin: 0px auto;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
.row {
@include ms-Grid-row;
@include ms-fontColor-white;
background-color: $ms-color-themeDark;
padding: 20px;
}
.column {
@include ms-Grid-col;
@include ms-lg10;
@include ms-xl8;
@include ms-xlPush2;
@include ms-lgPush1;
}
.title {
@include ms-font-xl;
@include ms-fontColor-white;
}
.subTitle {
@include ms-font-l;
@include ms-fontColor-white;
}
.description {
@include ms-font-l;
@include ms-fontColor-white;
}
.button {
// Our button
text-decoration: none;
height: 32px;
// Primary Button
min-width: 80px;
background-color: $ms-color-themePrimary;
border-color: $ms-color-themePrimary;
color: $ms-color-white;
// Basic Button
outline: transparent;
position: relative;
font-family: "Segoe UI WestEuropean","Segoe UI",-apple-system,BlinkMacSystemFont,Roboto,"Helvetica Neue",sans-serif;
-webkit-font-smoothing: antialiased;
font-size: $ms-font-size-m;
font-weight: $ms-font-weight-regular;
border-width: 0;
text-align: center;
cursor: pointer;
display: inline-block;
padding: 0 16px;
.label {
font-weight: $ms-font-weight-semibold;
font-size: $ms-font-size-m;
height: 32px;
line-height: 32px;
margin: 0 4px;
vertical-align: top;
display: inline-block;
}
}
}

View File

@ -0,0 +1,57 @@
import * as React from "react";
import styles from "./Dynamic365SalesAccounts.module.scss";
import { dynamicsService } from "../../../services/services";
import IAccount from "../../../model/IAccount";
import Search from "antd/lib/input/Search";
import { Table, Divider } from 'antd';
import Contacts from './contacts';
const Dynamic365SalesAccounts = () => {
const [accounts, setAccounts] = React.useState<IAccount[]>([]);
const [selectedRowKeys,setSelectedRowKeys] = React.useState([]);
const [selectedRows,setSelectedRows] = React.useState<IAccount[]>([]);
const columns = [
{
title: 'Name',
dataIndex: 'name'
},
{
title: 'Email',
dataIndex: 'emailaddress1'
}
];
React.useEffect(() => {
dynamicsService.getAccessToken().then(_=>{
dynamicsService.getAccounts().then((accs) => setAccounts(accs.map(a=>({...a,key:a.accountid}))));
});
}, []);
const searchAccounts = async (value) =>{
const result: IAccount[] = await dynamicsService.searchAccounts(value);
const accs = result.map(acc=> ({...acc,key:acc.accountid}));
setAccounts(accs);
};
const rowSelection = {
selectedRowKeys,
onChange: (_selectedRowKeys, _selectedRows) => {
setSelectedRowKeys(_selectedRowKeys);
setSelectedRows(_selectedRows);
}
};
return (
<div className={styles.dynamic365SalesAccounts}>
<Search placeholder="Search accounts" onSearch={value => searchAccounts(value)} enterButton />
<Divider/>
<Table
columns={columns}
expandable={{expandedRowRender: record=> <Contacts Id={record.accountid}/>}}
dataSource={accounts}
/>
</div>
);
};
export default Dynamic365SalesAccounts;

View File

@ -0,0 +1,3 @@
export interface IDynamic365SalesAccountsProps {
description: string;
}

View File

@ -0,0 +1,43 @@
import * as React from "react";
import { Table } from "antd";
import IContact from "../../../model/IContact";
import { dynamicsService } from "../../../services/services";
export interface IContactsProps {
Id: string;
}
const Contacts: React.FC<IContactsProps> = (props) => {
const [data, setData] = React.useState<IContact[]>([]);
React.useEffect(()=>{
dynamicsService.getContacts(props.Id).then(res => setData(res));
},[]);
const columns = [
{
title: "Full Name",
dataIndex: "fullname",
render: (text) => <b>{text}</b>
},
{
title: "City",
dataIndex: "address1_city"
},
{
title: "Email",
dataIndex: "emailaddress1"
},
{
title: "Business Phone",
dataIndex: "telephone1",
render: (text)=><a>{text}</a>
},
];
return (
<>
<Table columns={columns} dataSource={data} pagination={false} />
</>
);
};
export default Contacts;

View File

@ -0,0 +1,7 @@
define([], function() {
return {
"PropertyPaneDescription": "Description",
"BasicGroupName": "Dynamic CRM Settings",
"DynamicCrmDomainFieldLabel": "Dynamic CRM Domain (e.x., contoso.crm11)"
}
});

View File

@ -0,0 +1,10 @@
declare interface IDynamic365SalesAccountsWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DynamicCrmDomainFieldLabel: string;
}
declare module 'Dynamic365SalesAccountsWebPartStrings' {
const strings: IDynamic365SalesAccountsWebPartStrings;
export = strings;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -0,0 +1,38 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-3.7/includes/tsconfig-web.json",
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "lib",
"inlineSources": false,
"strictNullChecks": false,
"noUnusedLocals": false,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"es6-promise",
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection"
]
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules",
"lib"
]
}

View File

@ -0,0 +1,29 @@
{
"extends": "@microsoft/sp-tslint-rules/base-tslint.json",
"rules": {
"class-name": false,
"export-name": false,
"forin": false,
"label-position": false,
"member-access": true,
"no-arg": false,
"no-console": false,
"no-construct": false,
"no-duplicate-variable": true,
"no-eval": false,
"no-function-expression": true,
"no-internal-module": true,
"no-shadowed-variable": true,
"no-switch-case-fall-through": true,
"no-unnecessary-semicolons": true,
"no-unused-expression": true,
"no-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"variable-name": false,
"whitespace": false
}
}