Interview preparation for SharePoint SPFx and Power Apps

CSOM 

CSOM allows users to access SharePoint site which are hosted outside with out using webservices like REST APIs.

We have 2 options in SP.

1. .Net C# CSOM

2. JSOM

CSOM happens behind.

Converts API call in to XML and send to the server.

Server receives the request and make appropriate calls

Server gives back the data to SharePoint in the format of JSON

Step 1: Create the context

Step 2: Use load/loadquery to specify what data we wish to get

Step 3: ExecuteQuery/ ExecuteQueryAsync Sending the request to the server

Here API request sending to the server in the format of XML

Step 4: Make changes to the data

Step 5: Save the data using ExecuteQuery/ExecuteQueryAsyn 

Here data received from the server in the format of JSON


If we create sharepoint solution in VS 2012, default using Microsoft.SharePoint.Client

Otherwise, for general C# code we need to add the dll and specify in .cs file

Microsoft.SharePoint.Client

Refer: https://www.c-sharpcorner.com/article/sharepoint-client-object-modal-csom/

By using the clientcontext object, get the context from the site URL

Clientcontext clientcontext = new Clientcontext("siteurl");//// Get SharePoint web

Web web = clientcontext.web;

ListCollection listcol = web.Lists.getbytitle('listname');//get list

CamlQuery query = new Camlquery();//specify what date we wish to get by using camlquery

query.ViewXml = "<View/>";

Listitemcollections items = list.GetItems(query); //

clientcontext.Load(listcol);//retrieve the list collection properties

clientcontext.Load(items);

clientcontext.ExecuteQuery();//execute the query to the server

We are getting the data in the format of JSON

foreach(List list in items ){
    console.WriteLine("List ID"+list.ID+" List Title"+list.Title);

}

SPFx


Question: What are prerequisites?

What is spfx:
It does not require IFrame, directly javascript embedded on the page.
The controls can be rendered in the page. responsive in nature.
It enables the developers with life cycle in addition to render, load, serialize, deserialize, configration changes and more...
NPM, Typescript, Yeoman, webpack and gulp.
SPFX support both classic and modern pages.
End users can use spfx webpart by approve the site administrator on the all the sites. 
extends to teams.
HttpClient object handles the authentication to SP and office 365.

SPFX life cycle
Question: diff between props and state?
props represents properties 
props holds the properties with propertyname and its type
and state is a plain javascript object.
both holds data of render output.
props are passed to the component as parameters where as state is managed with in the component.

In SPFX, our main class from .tsx file, we are passing props and state as parameters.

In react to loop and render array values

this.state.listItems.map(function(listItem,key){
//htm here dynamic renderimg
});

Question: PropertyPane:
In Spfx, webpart properties are referred to property panes. The property panes allow controlling the behaviour and appearance of a webpart.

PropertyPaneTextField with description is comes with default scaffold.
We have few propertypane properties available.

Label, TextBox, Mutliple lines of text, Link, Dropdown, Checkbox, Choice, Toggle, Slider, Button, Horizontal rule, custom

Refer:
https://www.c-sharpcorner.com/article/sharepoint-framework-introduction-to-web-part-property-pane/

preconfigrations to the property pane or default values to the propertypane can be implemented in manifest.json file.

example:
"preconfiguredEntries": [{
    "groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
    "group": { "default": "Other" },
    "title": { "default": "AnonymouseAPIUsingReactComponent" },
    "description": { "default": "AnonymouseAPIUsingReactComponent description" },
    "officeFabricIconFontName": "Page",
    "properties": {
      "description": "AnonymouseAPIUsingReactComponent",
      "apiURL":"https://jsonplaceholder.typicode.com/users",
      "userID":"1"
    }
  }]

Question: what is render method?
We have this.domElement.innerHTML = `html code here`;
innerHTML is holding our HTML code.

In order to read the context of SP page
${}//dynamic way in htl
${this.context.pageContext.web.title }

Life cycle of webpart for showing list names:
.ts main ts file,
export interface ISPList{
Title: string,
Id: string;
}
In order to use RESTAPI call in SPFX, we have SPHttpClient, SPHttpClientResponse. It is helper class provided by SPFX.
import {SPHttpClient, SPHttpClientResponse} from '@microsoft/sp-http';

GET: 
this.context.spHttpClient.get(this.context.pageContext.web.aabsoluteUrl+`/_api/web/lists`,SPHttpClient.configurations.v1).
then((response: SPHttpClientResponse)=>{
 return response.json();
});

EnvironmentType module:
Environment and EnvironmentType
from @microsoft/sp-core-library

Question: What is Promise in RESTAPI or SPhttpClient or PnP Get item?
For example I have get item method as below

private _getListItems():Promise<ISoftwareCatalog[]>{
        const url:string = this.props.siteUrl+"/_api/web/lists/getbytitle('SoftwareCatalog')/items";
        return this.props.context.spHttpClient.get(url,SPHttpClient.configurations.v1)
        .then(response =>{
          return response.json();
        })
        .then(json=>{
          return json.value;
        }) as Promise<ISoftwareCatalog[]>;
      }

Here return type is array and defined promise. Which means we are promising the return type is Array.
In last then statement, first we receive response in json.value and return as promise return the array.

Question: What is extension?/ Application customizer?

Extensions or Application customizers are client side components the runs based on SP page context.

Injecting a script to the sharepoint page.

using serve.json under pageURL property, we provide the URL.

Question: What is import { escape } from '@microsoft/sp-lodash-subset';
In read based projects, It is automatically available in tsx file.
lodash makes JavaScript easier. Help for iterating the arrays, objects, string etc.

Question: What is Graph API?

Able to connect with office 365 or Azure using API.

provides API access token access OAUTH v2, Support OData protocol, gives data back in the format of JSON


Question: How to add SPFx webpart to teams

in the cmd prmpt while creating webpart, it asks 

"do you want to allow the tenant admin to deploy the solutions..."-Yes

manifest.json file we find the property named supportedHosts, by default it has sharepointwebpart, now we need to include one more for teams as "TeamsTab"

"supportedHosts": ["SharePointWebPart", "TeamsTab"],


Question: communication site by default custom script is not allowed, manifest.json - enable custom script by adding property requiresCustomScript: false

What is the purpose of Communication site

Communication site is choosen when requirements is for some large audience to broadcast news, articles, portal pages, reports, status updates etc with visually appealing by choosing blank or from templates.

We can share the site to eveyone or specific users.

https://support.microsoft.com/en-us/office/use-the-sharepoint-topic-showcase-and-blank-communication-site-templates-94a33429-e580-45c3-a090-5512a8070732

Question: Deploy tenant wide: package-solution.json

skipFeatureDeployment: true

Question: How to link the library with webpart?

After creating a library with funtions or methods we need to consume through webparts.

Then we will create a webpart, We need to make sure the prompt

"do you want to allow the tenant admin to deploy the solution.." - Yes

and in cmd prompt when we are in webpart path, we have to link with the library.

using npm link libraryname

<p>Calling the function resides in our library</p> <p>${myInstance.getCurrentDateTime()}</p>


Question: How do you package your solution?

In order to deploy in SharePoint completely, along with Javascript, CSS and other assets to be packaged with "--ship" option in the command.

For the purpose of completely deploy webpart in SharePoint, run the below commands.

gulp bundle --ship

gulp package-solution --ship


Question: How to make REST calls using SPFX?

Previously we use Javascript and JQuery for REST API calls.

Now in SPFX, we have predefined class called SPHttpClient.

HttpClient is parent class and SPHttpClient is sub class and used to perform REST API calls.

We use GET method to fetch the data.

URL string

SPHttpClientConfigation - used to set the default headers and version numbers.

ISPHttpClientOptions - which optional, used for optional parameters, for setting the web URL.

hence we import the required packages as below

import { SPHttpClient, SPHttpClientResponse, SPHttpClientConfiguration } from '@microsoft/sp-http'; 


Question: What is react life cycle

we see constructor method is get first called. We are passing our state and props interfaces as parameters to the constructor method.
super(props) is base class
this.state is speaking with our state interface.
Here, we have componentWillMount, componentDidMount and render methods.
componentWillMount method get called before the render method calls.
componentDidMount method get called after the render method calls.
(suppose, we have button click which should get called after render method, hence we specify our button click function in componentDidMount method.)
ComponentDidUpdate: 
when user changes input from webpart behaviour, which means by configuration of propertypane, when value changes by the user input. then in compnentDidMount, value is changed, but update should be hanppend only when we componentDidUpdate method calls.
It has properties holding, prevProp: prevState: prevContext
example:

Question: How to install Jquery 
npm install --save jquery
then Install jquery types
npm install --save @types/jquery

Question: what is pnp js
PnP js is introduced in spfx for making CRUD operations 
initially we need to install PnP js npm install sp-pnp-js --save
then import * as pnp from 'sp-pnp-js'
to add list item
pnp.sp.web.lists.getByTitle('YourListName').items.add({
//pass the json with list columns and values
"Title":"title value",
...
});
to read the list item (single)
pnp.sp.web.lists.getByTitle('YourListName').items.getById(id).get().then((item:any)=>{
document.getElementById("txtSoftwareTitle")["value"]=item.Title;
...
});
to update the list item
pnp.sp.web.lists.getByTitle('YourListName').items.getbyid(id).update({
//json to update
 "Title":softwaretitle,
...
});

to read all the list items
pnp.sp.web.lists.getByTitle('YourListName').items.get().then(items:any[])=>{
    items.forEach(function(item){
        html += `<tr>
        <td>${item.Id}</td> 
        <td>${item.Title}</td>
        <td>${item.SoftwareVendor}</td>
        <td>${item.SoftwareDescription}</td>
        <td>${item.SoftwareName}</td>
        <td>${item.SoftwareVersion}</td>
      </tr>`
    });
  html += `</table>`;
  const allitems : Element = this.domElement.querySelector("#spListData");
  allitems.innerHTML = html
}

to delete an item
pnp.sp.web.lists.getByTitle('SoftwareCatalog').items.getById(id).delete()

Question: How to make webpart full width support? 
In SP sites, We have team site and communication sites, where are modern sites supports full width webpart using spfx.
In our webpart solution go to manifest.json file, add property called,
"supportFullBreed":true
while adding webpart in sitepage, after click on plus icon, select full width layout.

Q. How do you refer webpart context in react component?
In main webpart.ts file, we have export default webpart name, this is our webpart, if we can import httpclient, httpClientresponse or spHttpClient and spHttpClientResponse from sp-http.
And then we can use this.context.httpClient or this.context.spHttpClient to refer the context in our webpart main ts file.
When comes to react component folder, we need to explicitly define the webpartcontext.
in props.ts file, we have to import WebPartContext from sp-webpartbase
import {WebPartContext} from '@microsoft/sp-webpart-base';

export interface IAnonymouseApiUsingReactComponentProps {
  description: string;
  apiURL: string;
  userID: string;
  context:WebPartContext
}
In Interface, context: WebPartContext.
-------------------------------------------------------------------------------
Question: SharePoint Host Apps
The Apps where the components are hosted in SharePoint only called SharePoint hosted apps.
SharePoint hosted apps are installed in SharePoint only, called "host web"
They have their resources hosted on their isolated subsite of a "host web" is called the "app web".
It is fully client side coding.
Can be developed using HTML, css, javascript, jquery, .NET, CSOM, Ajax Rest API, Angular JS.
Data sources: SharePOint online, SharePoint content data base.
Question: What is Provider Hosted Apps?
Provider hosted apps for SharePoint includes the components that are deployed and hosted out side of the SharePoint farm.
They are installed to the host web, but their remote components are hosted on the another server.
i.e App web for the provider hosted apps is completely a different server.
It is server side coding.
Any programming langauge can be used.
Datasource: Azure Storage, Content database, or any independent software vendors(ISV)

Question: What is event receivers?
Event receiver is a simple method, that is executed when a trigger action is occurred on SharePoint object.
two types 
Sync: Events are executed before the action is executed on the content database.
Async: Events are executed after the action is executed on the content database.
Event receivers can be create using VS.
It can be run very short period of time. It will not survive after server reboots.
Question: What is Timer job
Timer job is a task that is executed periodically in a SharePoint server. It provides us a task execution environment.
Question: How to over come rest api limit 5000 items?
after getting 1000 items, data.d.__next helps to get next set of items.
_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('list name')/items?$select=Id&$top=1000"
if (data.d.__next) {
                    url = data.d.__next;
                    GetRows();
                }
Question: What is Request Digest in REST API?
headers: {
“Accept”: “application/json; odata=verbose”,
“X-RequestDigest”: $(‘#__REQUESTDIGEST’).val()
}
request digest is a hidden field.
It is provides a client side token to prevent the posting databack to the server.
Request digest is a client side “token” to validate posts back to SharePoint to prevent attacks where the user might be tricked into posting data back to the server. The token is unique to a user and a site and is only valid for a (configurable) limited time.

Question: What is eTag in REST API?
Etag is a value in rest api, which is used for validation while many users accessing the form for submission, then in order to prevent the concurrency of accessing the same form by many users at a time and to make successful submission.
In restapi, for POST request, we see IF-Match request header.
Once we make GET request, we can see on etag value.
Now the data can be accessed by many users and they made update attempts same time to the form. we see concurrency issue.
With Etag value, we can check whether the valued do match each other by time the updates operation is performed. If the value matches the update will be performed

Nintex

Question: Flexi task?
We have "Assign to do task", which has two outcomes either approve or reject.
In Assign flexi task, we can create custom out comes.



Power Apps

DateDiff(Today(), DateValue("28/08/1991"))

In power apps lookup column in patch how do you do?

In patch method

lookupcolumn: {'@odata.type':"#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",

                        Id:3,

                        Value:"Complete"}

For people picker field

Patch(

    'Requests for Access',

    Defaults('Requests for Access'),

    {

        Title: "",

        Requester: {

            '@odata.type': "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedUser",

            Claims: "i:0#.f|membership|" & Lower(

                LookUp(

                    Office365Users.SearchUser(),

                    DisplayName = cbusername.Selected.DisplayName

                ).Mail

            ),

            Email: LookUp(

                Office365Users.SearchUser(),

                DisplayName = cbusername.Selected.DisplayName

            ).Mail,

            Picture: "",

            JobTitle: "",

            Department: "",

            DisplayName: cbusername.Selected.DisplayName

        }

    }

)

Refer: https://www.c-sharpcorner.com/article/powerapps-patch-fuction-with-complex-columns/ 

Power automate: split(outputs('Compose'),'sites/')[0]

Offline App capability:

Online- app fetches data from data source.

Offline- App fetches data from cache file using LoadData function

Online - App saves the data to data source and refresh the local cache.


Using timer, we will check whether app is online or not. 

If it is offline, the posted data will be save to the app cache by using SaveData method.

When ever it is online, this cache data will be saved to the data source.


Add rows dyanamically to  a gallery

Insert gallery - blank

add text input fields

1. Name, 2. Address

screen onvisible property:

collect(userdetailsLines, {lines:1});

gallery - source: userdetailsLines

add line button: 

Set(TotalLines, TotalLines+1);

Collect(userdetailsLines,{lines:TotalLines);

Remove icon:

Remove(userdetailsLines,ThisItem);

Reset button:

ClearCollect(userdetailsLines,{lines:1);

Submit Button:

ForAll(Gallery1.Allitems,

Collect(mysubmitgallery,{name:name.txt,address:address.txt);

);


Power Portals

Power Apps makers can now create a powerful new type of experience: external-facing websites that allow users outside their organizations to sign in with a wide variety of identities, create and view data in Microsoft Dataverse, or even browse content anonymously. The full capabilities of Dynamics 365 Portals, previously offered only as an add-on to customer engagement apps (Dynamics 365 Sales, Dynamics 365 Customer Service, Dynamics 365 Field Service, Dynamics 365 Marketing, and Dynamics 365 Project Service Automation), are now available standalone in Power Apps.

These capabilities feature a revamped end-to-end experience for makers to quickly create a website and customize it with pages, layout, and content. Makers can reuse page designs through templates, add forms and views to display key data from Dataverse, and publish to users.

Converting from trails to production global administrator and system administrator can do.

When we are converging portal from trail to prod, we have to make sure environment also should be in prod converted.

We can coverg existing license to capacity based license.

Dataverse starter portals are default studio template, page with title, page with child links

Templates in portals

1. Customer service portals

2. Partner portal

3. Employee service portal

4. Community portal

5. Portal from blank

To share the portal page to internal users,

First create a security role and assign user to the security role.

Make sure user has access to the environment.

Developer should have system administrator as recommended.

Liquid

Liquid is open source object langague allows dataverse table to loop in render data, or render table guid based we can show our login information or any other HTML snipped.

Question: Configure by code snippets

Leftside->Under Code snipped, we can inject eigther HTML or liquid object code.

Leftside->Under Web templates - Add the new code snippet created to the new web template

{% include 'snippet' snippet_name:'AccountData' %}

Leftside->On top we can see page template: Create new page template

Select newly created web template,

Now create new page, select blank page, under components right hand side, choose template name as page template we create.

Now our code snippet what ever we wrote will be render in the page.

Question: Dataverse how to anonymous access?

https://docs.microsoft.com/en-us/powerapps/maker/portals/configure/configure-portal-authentication

In power portal admin central, there is called "web roles" for setting permissions to the unauthenticated users.

Under "web roles", We can find "web page and web site" access control rules.

Here, Portal allows portal users with the choice of signin with external account based ASP.NET identity.

Though not recommended, portals also allows a local contact membership provider-based account for users to sign in.

Through email address, they can signin.

These are options for users to allow sigin options are Microsoft account, FB, LinkedIn, Twitter, Google and Local authentication with email.

Question: DataVerse:- Environment relation

Once environment is created, users from Azure AD are automatically added.

using security roles, providing permissions to the data and users

Question: diff types of security roles:

System administator 

System customizer

Environment maker

basic user

delegate

and custom security roles.

System adminstrator: CRUD, customizations, Security roles

System customizer: CRUD(Self), Customizations

Environment maker: Customizations

Basic User: CRUD(Self)

Delegate: Act on behalf of another user or impersonate.

Model Driven App

Model driven app, component focused approch to app development.

apps can distributed as a solution.

approch:

Modeling the business data,

define the business process,

compose the app

In order to create model driven app to a requirement, there will a busines process, which makes user journey easy and more focused to their work.

business process can be created setting->advanced customizations-> open solution explorer, select process->new

composing model driven app

we have site map(navigation puropose)

Dashboards, Business Process flows

Entity views(12)

eg:

Accounts: Forms(6), Views, Charts(2)

Activity: Forms, views, charts

While creating navigation site map, 

select site map designer->new subarea

To understand the model driven app components, The components and component properties that designers use to make up an app become the metadata.

To understand how each of these components relates to app design, they are sepeated in to data, UI, logic and visualization categories.

Data: 

table, relationship(1:N, N:1, N:N), Columns, Choice columns

UI: App, sitemap(navigation), Forms, views

Logic: BPF, 

Workflows(Automating, with out user interaction), 

Actions(process that let you manually invoke actions, including custom actions, directly from workflow)

Business rules(validation purpose)

Flow(power automate for notifications, collect data etc..)

Visualizations:

Charts, Dashboards,Power BI

There is advance model driven app making .

the solution explorer is a comphrehansive tool used for model-driven-app. It shows all components using navigation pane on the left side of the tool.

Forms:

Types of Model driven Forms:

Main forms: 

Forms provide main user interface for interacting with table data.

Quick create:

For updating tables, these forms provide a basic form optimized for creating new rows.

Quick view:

For updated tables, thse forms appear with in the main form to display additional data for a row that is referenced by a lookup column in the form.

Card: Used in views for Power Apps apps. Card forms are designed to present information in a compact format that is suitable for mobi.le devices.

In Main forms, In order to open the dialog as a popup or right hand side, there is javascript code to embed accordingly.

These dialogs are worked based on client API javascript code.

Apply custom business logic with business rules and flow in model driven apps:

Business rules:

It is basically a drag and drop interface.

creating rules that most commonly used rules.

example:

If you select this item ... The scope is set to..

Set column value

Clear column value

Set column requirement levels

show/hide columns

Enable/Disable columns

validate data and show error message,

create business recommendations based on business intelligence

Flow:

Automated flow: trigger by a event, one or more task etc..

Buttonflows:

Scheduled flow:

Business process flows:

Enter the data consitently and follow the same steps every time they work in an app.

Workflows and actions:

related to D365 classic dataverse which has workflows and actions.

Question: Sharing a Model-driven app using Power Apps:

Power apps use role-based security for sharing.

role based security is worked based on custom roles, which has to be created initially.

while creating custom roles, a table shows with check box to select and provide appropriately.

After all, My Apps->click on elipse-> click on share->select user-> manage roles->select custom role we created.


General Questions:

1. how to do group by in views for model driven apps?

Using editable grids users can do rich inline editing directly from views and sub grids they are using a webapp, tablet, phone

2. Can we share a canvas app with external busines partner and contractor:

Yes we can. Using azure ad b2b external collaboration for the tenant, guest user can be invited to use the app.

Vairables

Global variable and context variables.

Global variable - Set

Local variable - UpdateContext, Navigate

Collections - Collect, ClearCollect

Delegable functions:

Filter, Search, LookUp

StartsWith, EndsWith

Sort, SortByColumns 

Sum,Avg,Min

Non Delegable(C-based):

CountRows, Concat, Choices, Collect, ClearCollect, CountIf, RemoveIf, UpdateIf, GroupBy, Ungroup

Partial delegable:

AddColumns, ShowColumns, RenameColumns, DropColumns


Question: Working with containers?

Containers are building blocks of the repsonsive design.

There are two containers:

Horizontal container, Vertical container

x=0, y=0, width=Parent.Width, height=parent.height.

We can choose container inside a container.

example: I have added a vertical container in a screen.

Inside vertical container->add horizontal container.

We can adjust align property - vertical to strech to make full fill the vertical space.

Container has flexible width property - turn on

Question: Make App response layout In Containers.

Scale to fit

Lock aspect ratio

Lock orientation

When we choose screen as blank template, other templates are split screen, slidebar, header-mainsections-footer.

Question: In order to show more information in the app screen. 

Settings: Scale to fit turn off.

Then settings->

apps width property matches with designwidth,

Max(App.width, app.designwidth)

apps height property matches with designheight.

max(app.height, app.designheight).


Components

Design screen size: Max(App.Width, App.MinScreenWidth) 

Components in Powerapps are reusable building blocks for canvasapps. So that app makers are allowed to create custom components across the apps.

These components can be exported and imported to other apps to make use.

Header and Footer component, we can make use it in the entire app.

Standar look and feel.

A component consists of input properties that are capable of receiving values from the app.

Component also include the output properties that are capable of providing output values to the app.


Question: How to create Component in power app

New component -> and created MenuComponents

New custom property ->

Items

Input Type

Data Type: Table

Table({Item:"Home"}, {Item:"Admin"}, {Item:"About"}, {Item:"Help"});


We have to create an output property,  before that, I have added on vertical gallery in MenuComponents

Gallery1 - with only text label

Items: 

MenuComponent.Items

It will show list of Menu's


Now create an output property:

New custom property->

Selected

Output Type

Data Type: Text

click on created Selected property, click on advanced - > 

we observe Selected(Output)

Gallery1.Selected.Item 

Which means we are passing an output.

In our MenuComponent, since we already added on gallery control

Hence Gallery1.Selected.Item which ever is selected been an output from our output property named as selected.

Question: What is Scope in components?

In MenuComponent which we create, right hand side there is an option called "Access App Scope", we have to make it enable after created a component. 

It helps us to use our component with following accessibles

Global variables, Collections, Controls and components on the screen such as text input control,

Tabular data sources such as Dataverse tables.

If we are trying to import/export this component to other app, then it won't work.

Because, this Access App Scope enable feature only works for this app alone.

Question: How do you import and export a component.

We have components library to do this.

After creating component, elipse we can see import or export components. click on export components option.

In My Apps -> Components -> Import compoents

https://blog.cloudthat.com/top-25-microsoft-power-apps-consultant-interview-questions-and-answers/

Custom connector life cycle:

Build you API,

Describe your API and define the connector,

use your connector,

Share your connector(optional),

Certify your connector(optional)


1. Build your API: REST API that allows by logic apps, power automate, 

for public api's we can manage with azure api apps, azure web apps, azure functions


2. Secure your API:

using oAuth 2.0.

use Azure AD authentication for your API for azure portals which is more secure.


3. Describe your API and define the connector

describe or use your api via logicapps or power automate.

API supports

OpenAPI or Postman collection


Share and Certify,

Share means to use in organization level.

Ceritfy will be done review by microsoft.