Créer un site internet

Posts by fredericdietrich

Powerautomate Extract Data From Json Array

By On 31/03/2021

Powerautomate Extract Data From Json Array

 


{
	"fieldsMapping":[
		{
			"sourceFieldName": "Title2",
			"sourceFieldTypeAsString": "Text",
			"targetFieldName": "Title",
			"targetFieldTypeAsString": "Text"
		},
		 {
		  "sourceFieldName": "Title",
		  "sourceFieldTypeAsString": "Text",
		  "targetFieldName": "OtherTexteField",
		  "targetFieldTypeAsString": "Text"
		}
	]
}

Currentdata

items('Appliquer_à_chacun')?['sourceFieldName']

this command above will put sourceFieldName value in CurrentDataName variable

Datafromjsonarray

this command above will put sourceFieldName value in CurrentDataName variable

PowerAutomate Goodies

By On 31/03/2021

Power Automate goodies

 

Add a cont JSON to store urls and lists names for example

 


{
	"sourceUrl": "https://mySite/sites/DevSpFX/LRemy",
	"sourceListeName": "listeSource",
	"sourceListItemEntityTypeReq":"/_api/web/lists/getbytitle('listeSource')/?$select=ListItemEntityTypeFullName",
	"sourceListItemEntityTypeFullName":"null",
	"sourceListQuery":"/_api/Web/Lists/getbytitle('listeSource')/items?select=Title,myUser1,myChoice1,Title2",
	"targetUrl": "https://mySite/sites/DevSpFX/LRemy",
	"targetListItemEntityTypeReq":"/_api/web/lists/getbytitle('listTarget')/?$select=ListItemEntityTypeFullName",
	"targetListItemEntityTypeFullName":"null",
	"targetListeName": "listTarget",
	"targetListeRequest": "/_api/Web/Lists/getbytitle('listTarget')/items",
	"logListRequest": "/_api/Web/Lists/getbytitle('logs')/items",
	"fieldsMapping":[
		{
			"sourceFieldName": "Title2",
			"sourceFieldTypeAsString": "Text",
			"targetFieldName": "Title",
			"targetFieldTypeAsString": "Text"
		},
		 {
      "sourceFieldName": "Title",
      "sourceFieldTypeAsString": "Text",
      "targetFieldName": "OtherTexteField",
      "targetFieldTypeAsString": "Text"
    }
	]
}

Add a JSON analyser action (above json is juste an exemple)

Addjsonaction

 

Add your JSON in generate from sample, this will create an object that you can use later

Ehantillon 1

Then add your JSON datas (if you modify JSON structure, you must regenerate the sample)

Addcontentjson

Use you Const to get items

Addconstinaction

 

PowerShell Csom Batch Delete / delete all list items

By On 09/03/2021

Powershell CSOM clear list items / delete all items

 

 


clear
# Connect-PNPOnline -url $ProdWaveplaceURL -UseWebLogin -ErrorAction Stop
# Disconnect-PnPOnline

$listTitle = "testTaxo"
$list = Get-PnPList -Identity $listTitle -ThrowExceptionIfListNotFound


$ctx = Get-PnPContext
$page = $null
$pageNumber = 0;
$rowLimit = 100
$startDate = Get-Date
$deletedItemsCount = 0;

Do{
    $stringBuilder = New-Object System.Text.StringBuilder
 
    $stringBuilder.Append("<View scope='RecursiveAll'>") | Out-Null
    $stringBuilder.Append("<Query><Where></Where>")| Out-Null
    $stringBuilder.Append("<Orderby><Fieldref ascending='TRUE' name='ID'></Fieldref></Orderby>")| Out-Null
    $stringBuilder.Append("</Query>")| Out-Null
    $stringBuilder.Append("<Viewfields>")| Out-Null
    $stringBuilder.Append("<Fieldref name='ID' />")| Out-Null
    $stringBuilder.Append("</Viewfields>")| Out-Null
    $stringBuilder.Append("<Rowlimit paged='TRUE'>$($rowLimit)</Rowlimit>")| Out-Null
    $stringBuilder.Append("</View>")| Out-Null
    
    $spqQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
    $spqQuery.ViewXml = $stringBuilder.ToString();
    $spqQuery.ListItemCollectionPosition = $page


    $pageNumber ++;

    $spqQuery.ViewXml = $stringBuilder.ToString();
    $itemki=$list.GetItems($spqQuery); 
    $spqQuery.ListItemCollectionPosition = $itemki.ListItemCollectionPosition

    $ctx.Load($itemki)
    $ctx.ExecuteQuery();


    Write-Host "################## PAGE " $($page.PagingInfo) " #########################"
    Write-Host "processing query results. Recs: $($itemki.Count)"

    $Counter = $itemki.Count;
    if($itemki.Count -eq 0){
        exit 0
    }
    do{
        $itemki[$Counter - 1].DeleteObject()

        $Counter--
        $deletedItemsCount++
    }while($Counter -gt 0)
    Invoke-PnPQuery
    Write-Host "deletedItemsCount $($deletedItemsCount)"
    $page = $itemki.ListItemCollectionPosition
    $comp = $endDate - $startDate
    $endDate = Get-Date
    Write-Host "time to delete $($rowLimit) elements : Days '$($comp.Days)' Hours '$($comp.Hours)' Minutes '$($comp.Minutes)' Seconds '$($comp.Seconds)'"
 }   
 Until($page -eq $null) 

$comp = $endDate - $startDate
Write-Host "time to delete : Days '$($comp.Days)' Hours '$($comp.Hours)' Minutes '$($comp.Minutes)' Seconds '$($comp.Seconds)'"
In Nintex

Nintex 2016 Issue CodeTypeReferenceExpression

By On 08/02/2021

Nintex 2016 Issue CodeTypeReferenceExpression

 

SharePoint Foundation Workflow Infrastructure Unexpected RunWorkflow:

Microsoft.SharePoint.SPException: CompilerError Line="-1" Column="-1" Text="Type System.CodeDom.CodeBinaryOperatorExpression is not marked as authorized in the application configuration file.

 

Error saving from workflow export file.: Nintex.Workflow.NWSavingWorkflowException: Erreur lors de la publication du flux de travail  Text="Le type System.CodeDom.CodeTypeReferenceExpression n'est pas indiqué comme étant autorisé dans le fichier de configuration de l'application."

 

You should add below red line in each web.config form your farm except central admin

<authorizedType Assembly="System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System.CodeDom" TypeName="CodeTypeReferenceExpression" Authorized="True" />


<authorizedType Assembly="System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System.CodeDom" TypeName="CodeTypeReferenceExpression" Authorized="True" />
     </targetFx>
    </authorizedTypes>
    <authorizedRuleTypes>
      <targetFx version="v4.0">

--------------------------------

 

Nintex.Workflow.NWException: Erreur lors de la lecture du paramètre 'SMTPServerPort' depuis la base de données de configuration. Vérifiez que vos bases de données Nintex Workflow sont à jour.

 

Nintex.Workflow.NWException: Error reading 'SMTPServerPort' parameter from configuration database. Make sure your Nintex Workflow databases are up to date.

 

To solve this issue, i executed this command line in an powershell admin instance

NWAdmin.exe -o UpgradeDatabases "Server=[serverName];Database=[dbName];Trusted_Connection=True;" -isConfig

For update workflow and forms Nintex configuration databases

 

 

Export List Fields To Csv With Pnp Powershell

By On 21/01/2021

Export List Fields To Csv With Pnp Powershell

 


param($url="https://myTestSite", $listTitle="/Lists/aList")
clear

#connect to your site using windows identity manager
Connect-PnPOnline -Url "$($url)"  -Credentials 'myWindowsOrWebIdentity'

$list = Get-PnPList -Identity $listTitle -Includes Fields


function ExctractFieldsNoContentType()
{
    param($targetList)
    $targetList.Title
   
    $toExport = @()
    for($i = 0 ; $i -lt $targetList.Fields.Count ; $i++)
    {
        $field = $targetList.Fields[$i]
        
        #put in an object some field properties
        $aFieldToExport = New-Object -TypeName PSObject -Property @{

        'Title' = $field.Title
        'InternalName' = $field.InternalName
        'TypeAsString' = $field.TypeAsString
        'Hidden' = $field.Hidden
        'Group' = $field.Group
        'Required' = $field.Required
        'Description' = $field.Description

        }
        $toExport += $aFieldToExport
    }
    #export to csv
    $toExport | Export-Csv -Path "$($targetList.Title)_fields.csv" -Encodin:UTF8 -NoTypeInformation -Delimiter ";"

}

ExctractFieldsNoContentType -targetList $list
Disconnect-PnPOnline

manage identities in 

Identitymanager

Sharepoint Rest Caml Query

By On 06/01/2021

Use Sharepoint REST api to do a caml query

 


fdi.post = function(request, data, urlWeb, retFunction, expecedcode=200, odata="verbose"){
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo?&select=FormDigestValue";
	var xhr = new XMLHttpRequest();
	xhr.open('POST', url, true);
	xhr.setRequestHeader("Accept", "application/json; odata=nometadata");
	xhr.onload = function (data) {
		if (xhr.status === 200) {
			console.log(url + " : success");
			var d = JSON.parse(xhr.responseText);
            console.dir(d.FormDigestValue);

            var viewXml =  "<View>" +
                    "<Query>" +
                    "<Where></Where>" +
                    "</Query>" +
                    "</View>";
            
            var req = { "query" :{"__metadata": { "type": "SP.CamlQuery" }, "ViewXml": viewXml}};
            var xhrPOST = new XMLHttpRequest();
            var reqUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Catalogue Produits')/GetItems";
            debugger;
            xhrPOST.open('POST', reqUrl, true);
            xhrPOST.setRequestHeader("Accept", "application/json; odata=" + odata);
            xhrPOST.setRequestHeader("content-type", "application/json; odata=" + odata);
            xhrPOST.setRequestHeader("X-RequestDigest", d.FormDigestValue);

            console.log("onload");
            xhrPOST.onload = function () {
                
            console.log("onload ok");
                console.dir(JSON.parse(xhrPOST.responseText));
            }
            xhrPOST.send(JSON.stringify(req));
            console.log("sent");
		}
		else {
			console.log("error");
			console.log(xhr.status);
			console.dir(xhr);
			console.dir(xhr.responseText);			
		}
	};
    xhr.send();
};

SPLoaderError.loadComponentError

By On 09/12/2020

SPFX react sur Internet explorer : [SPLoaderError.loadComponentError]: There was a network problem. This may be a problem with a HTTPS certificate. Make sure you have the right certificate.

 

It's not always à certificate error, in my case, i use code below in a service,

 


import 'core-js/modules/es6.string.includes.js';//in my case this line should be commented to fix the isssue
import 'core-js/modules/es6.number.is-nan.js';
import 'core-js/es6/array';
import 'es6-map/implement';

when including "@types/es6-promise": "^3.3.0" i don't need anymore import 'core-js/modules/es6.string.includes.js

Sharepoint Online Missing Icons

By On 09/12/2020

Sharepoint missing icon on SPFX developpements

 

Some ican can be missing per exemple on :

SPFX missing icon as <i data-icon-name="Tag" class="ms-Button-icon icon-167" role="presentation" aria-hidden="true"></i> 

So you simply have to add this code below after yours imports

 


import { initializeIcons } from 'office-ui-fabric-react/lib/Icons';

initializeIcons();

 

Sharepoint Modern Update listItem

By On 09/12/2020

Update list in a modern site, getting formDigestValue


console.clear();
var dataToManage = {};
function getItemTypeForListName(listTitle, returnfct){
	var xhr = new XMLHttpRequest();
	var url = _spPageContextInfo.webAbsoluteUrl;
	if (url === "undefined") {
		console.log("_spPageContextInfo.webAbsoluteUrl undefined");
		url = "http://siteUrl";
	}
	
	xhr.open('GET', url + "/_api/web/lists/getbytitle('" + listTitle + "')/?$select=ListItemEntityTypeFullName");
	xhr.setRequestHeader("Accept", "application/json; odata=verbose");
	xhr.onload = function () {
		if (xhr.status === 200) {
			var kk = JSON.parse(xhr.responseText);
			console.dir(kk.d.ListItemEntityTypeFullName);
                        var returnValue = {};
			returnValue.ListItemEntityTypeFullName = kk.d.ListItemEntityTypeFullName;
			if(returnfct != null)
				returnfct(returnValue);
		}
		else {
			console.dir(xhr);
			alert('Request failed.  Returned status of ' + xhr.status);
		}
	};
	xhr.send();
}

//get FormDigestValue to do POST requests
function GetDisgestValue(returnFct){
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo";
	var xhr = new XMLHttpRequest();
	xhr.open('POST', url, true);
	xhr.setRequestHeader("Accept", "application/json; odata=verbose");
	xhr.setRequestHeader("content-type", "application/json; odata=verbose");
	xhr.onload = function (data) {
		if (xhr.status === 200) {
			console.log("success");
			var d = JSON.parse(xhr.responseText);
			console.dir(d.d.GetContextWebInformation.FormDigestValue);
			dataToManage.FormDigestValue = d.d.GetContextWebInformation.FormDigestValue;
			returnFct(d.d.GetContextWebInformation.FormDigestValue);
		}
		else {
			console.log("error");
			console.log(xhr.status);
			console.dir(xhr);
			console.dir(xhr.responseText);			
		}
	};
	xhr.send();
}

function UpdateListItem(){
	
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle" + 
	"('" + dataToManage.listName + "')/items("+dataToManage.itemId+")";
	
	var xhr = new XMLHttpRequest();
	xhr.open('POST', url, true);
	xhr.setRequestHeader("Accept", "application/json; odata=verbose");
	xhr.setRequestHeader("X-RequestDigest", dataToManage.FormDigestValue );
	xhr.setRequestHeader("content-type", "application/json; odata=verbose");
	xhr.setRequestHeader("X-HTTP-Method", "MERGE");
	xhr.setRequestHeader("If-Match", "*");
	
	xhr.onload = function () {
		if (xhr.status === 204) {
			console.log("success");
		}
		else {
			console.log("error");
			console.log(xhr.status);
			console.dir(xhr);
			console.dir(xhr.responseText);
			
		}
	};
	var str = JSON.stringify(dataToManage.item);
	xhr.send(str);
} 

function withDigestValue(formDigestValue){
	console.log("formDigestValue : " + formDigestValue);	
}

function getListDatas(data){
	console.log(data.ListItemEntityTypeFullName);
	dataToManage.listName = "aTest";//list title to update
	dataToManage.itemId = 1;//id of the item to update
	dataToManage.item = {
        "__metadata": { "type": data.ListItemEntityTypeFullName },
		"Title": "new title"//new fields values
    };
	GetDisgestValue(UpdateListItem);
}

getItemTypeForListName("atest", getListDatas);

In SQL

Sharepoint Caml Query

By On 08/09/2020

Basic CSOM caml query

 

<View>
    <Query>
        <Where>
            <Eq>
                <FieldRef Name='Matricule'/>
                <Value Type='Text'>90136794</Value>
            </Eq>
        </Where>

<OrderBy><FieldRef Name='ID' Ascending='True'/></OrderBy>
    </Query>
    <ViewFields>
        <FieldRef Name='Matricule' />
        <FieldRef Name='Email' />
    </ViewFields>
    <RowLimit>2</RowLimit>
</View>

 

Query Null Text fields or not

<Where>
    <IsNotNull>
        <FieldRef Name="Famille"/>
    </IsNotNull>
</Where>


<Where>
    <IsNull>
        <FieldRef Name="Famille"/>
    </IsNull>
</Where>

 

by ID

<Where>
    <Eq>
        <FieldRef Name='ID'/>
        <Value Type='Counter'>645</Value>
    </Eq>
</Where>

 

Get tasks by itemId (relatedItems in tasks list)

<Where>
    <Eq>
        <FieldRef Name='RelatedItems'/>
        <Value Type='RelatedItems'>""ItemId"":435,</Value>
    </Eq>
</Where>

 

boolean / Yes/No

<Eq><FieldRef Name='YourFieldName'/><Value Type='Boolean'>1</Value></Eq>

 

Comparators

<Eq> => equals

<Neq> => not equals

<Lt> => Less than

<Leq> => less or equal

<Gt> greater than

<Geq> greater or equal

<Contains>

<BeginsWith>

 

Errors

  • Sharepoint error Error in my cases
    One or more field types are not installed properly. Go to the list settings page to delete these fields. Fields in your query are not in list

    Cannot complete this action.

    Please try again.

    Syntax error in your query
       
       
       
       
       
       
       

     

SPFX React Tips

By On 02/09/2020

Override native css

 

:global(#spLeftNav) {  
  display: none;
} 
:global(.CanvasZone) {  
  max-width: 100%;
} 

Is member of

import 'core-js/modules/es6.string.includes.js';
import 'core-js/modules/es6.number.is-nan.js';
import 'core-js/es6/array';
import 'es6-map/implement';
import { sp,SPRest } from '@pnp/sp';
import { IWebPartContext } from '@microsoft/sp-webpart-base';
import * as React from 'react';

class PeopleService {
    private _context: IWebPartContext;
    private _localPnPSetup: SPRest;

    public constructor(webPartContext: IWebPartContext) {
        this._context = webPartContext;

        // To limit the payload size, we set odata=nometadata
        // We just need to get list items here
        // We use a local configuration to avoid conflicts with other Web Parts
        this._localPnPSetup = sp.configure({
            headers: {
                Accept: 'application/json; odata=nometadata',
            },
        }, this._context.pageContext.web.absoluteUrl);
    }

    public async isMemberOf(group: string): Promise{
        let groups = await this._localPnPSetup.web.currentUser.groups.get();
        let ret: boolean = false;
        
        groups.map(grp =>{
            if(grp.LoginName == group)
            ret =  true;
        });
        return ret;
    }

    public async isMemberOfanyGroup(groupNames: string[]): Promise{
        let groups = await this._localPnPSetup.web.currentUser.groups.get();
        let ret: boolean = false;
        groups.map(grp =>{
            groupNames.map(name =>{
                console.log("name : '" + name + "' grp : '" + grp.LoginName  + "'");
            if(grp.LoginName == name)
                ret = true;
            });
        });
        return ret;
    }

}
export default PeopleService;

Taxonomy, get tags, add tags

import { IWebPartContext } from '@microsoft/sp-webpart-base';
import { Session, ITermStore, ITermSet, ITermData, ITerm } from '@pnp/sp-taxonomy';

class TaxonomyService {
    private _context: IWebPartContext;
    
    public constructor(webPartContext: IWebPartContext) {
        this._context = webPartContext;
    }

    public async getTags() : Promise{
        
        console.log("Session");
        const taxonomy = new Session(this._context.pageContext.site.absoluteUrl);
        const store: any = taxonomy.termStores.getByName("Taxonomy_Wf8XzHaRobdAERjvvke+Tg==");
        let datas = await store.getTermSetById("c18ff3e6-e4a8-4dcb-85f5-51171f4bbc11").terms.select('Name', 'Id', 'Parent').get();
        
        let ret: string[] = [];
        for(let i = 0 ; i < datas.length ; i++)
            ret.push(datas[i]);

        return datas;
    }
    
    public async addNewTag(tag){
        
        const taxonomy = new Session(this._context.pageContext.site.absoluteUrl);
        const store: any = taxonomy.termStores.getByName("Taxonomy_Wf8XzHaRobdAERjvvke+Tg==");
        let datas = await store.getTermSetById("c18ff3e6-e4a8-4dcb-85f5-51171f4bbc11");
        const term: ITerm & ITermData = await datas.addTerm(tag, 1036, true);
    }
}
export default TaxonomyService;

CSOM Delete Items By Id Range

By On 02/09/2020

CSOM delete items by id range

Get items

public ListItemCollection GetItems(string listRelativUrl, string where, string orderBy, string viewFields, int rowlimit = 100)
{
    string xmlView = "";
    try
    {
        List lst = CurrentWeb.GetList(CurrentWeb.ServerRelativeUrl + listRelativUrl);

        StringBuilder vf = new StringBuilder();
        if (!string.IsNullOrEmpty(viewFields))
        {
            vf.Append("<ViewFields>");
            foreach (string fieldName in viewFields.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
            {
                vf.Append($"<FieldRef Name='{fieldName.Trim()}' />");
            }

            vf.Append("</ViewFields>");
        }

        CamlQuery camlQuery = new CamlQuery();
        camlQuery = new CamlQuery();
        Logger.LogInfo($"listRelativUrl {listRelativUrl} : <View><Query>{where}{orderBy}</Query>{vf.ToString()}<RowLimit>{rowlimit}</RowLimit></View>");
        xmlView = $"<View><Query>{where}{orderBy}</Query>{vf.ToString()}<RowLimit>{rowlimit}</RowLimit></View>";
        camlQuery.ViewXml = xmlView;

        ListItemCollection coll = lst.GetItems(camlQuery);
        SPContext.Load(coll);
        SPContext.ExecuteQuery();

        Logger.Log($"coll.Count : '{coll.Count}' : camlQuery.ViewXml {camlQuery.ViewXml}");

        return coll;
    }
    catch (ServerException ex1)
    {
        Logger.LogError($"Error ServerException Common.Sharepoint.SPTools.GetItems url '{_url}' login : '{_login}' " +
            $" listRelativUrl '{listRelativUrl}' where '{where}' orderBy '{orderBy}' rowlimit '{rowlimit}' xmlView : '{xmlView}' Exception '{ex1}'");
        throw;
    }
    catch (Exception ex)
    {
        Logger.LogError($"Error .Common.Sharepoint.SPTools.GetItems url '{_url}' login : '{_login}' " +
            $" listRelativUrl '{listRelativUrl}' where '{where}' orderBy '{orderBy}' rowlimit '{rowlimit}' xmlView : '{xmlView}' Exception '{ex}'");
        throw;
    }
}

delete items


public int DeleteItemByIdRange(string listRelativeUrl, int rowLimit, int from, int to = -1)
{
    int deleted = 0;
    try
    {
        string req = "";
        if (to == -1)
            req = $"<Where><Geq><FieldRef Name='ID'/><Value Type='Counter'>{from}</Value></Geq></Where>";
        else
        {
            if (from > to)
                throw new Exception($"DeleteItemByIdRange from should be < than to listRelativeUrl '{listRelativeUrl}' from '{from}' to '{to}'");
            req = $"<Where><And><Geq><FieldRef Name='ID' /><Value Type='Counter'>{from}</Value></Geq><Leq><FieldRef Name='ID' /><Value Type='Counter'>{to}</Value></Leq></And></Where>";
        }
        ListItemCollection coll = GetItems(listRelativeUrl, req, "", "ID", rowLimit);

        while (coll.Count > 0)
        {
            string id = coll[0].Id.ToString();
            coll[0].DeleteObject();
            this.ExecuteQuery($"DeleteItemByIdRange listRelativeUrl '{listRelativeUrl}' from '{from}' to '{to}' Id = '{id}'");
            deleted++;
        }
        return deleted;
    }
    catch (Exception ex)
    {
        Logger.LogError($"Error Sharepoint.SPTools.DeleteItemByIdRange from id '{from}' to id '{to}' url '{_url}' login : '{_login}'  Exception '{ex}'");
        throw;
    }
}

catch ServerException to get more details on CSOM exceptions

Invalid Client Query Exception

By On 07/07/2020

Microsoft.SharePoint.Client.InvalidClientQueryException A type named 'SP.Data' could not be resolved by the model. When a model is available, each type name must resolve to a valid type

 

get the correct ListItemEntityTypeFullName 

 

 




var xhr = new XMLHttpRequest();
var url = _spPageContextInfo.webAbsoluteUrl;
if (url === "undefined") {
    console.log("_spPageContextInfo.webAbsoluteUrl undefined");
    url = "http://siteUrl";
}
//xhr.open('GET', url +"/_api/web/Lists?$select=Id,Title,Hidden,ItemCount");
xhr.open('GET', url + "/_api/lists/getbytitle('Campaigns')?$select=ListItemEntityTypeFullName");
xhr.setRequestHeader("Accept", "application/json; odata=verbose");
xhr.onload = function () {
    if (xhr.status === 200) {
        var kk = JSON.parse(xhr.responseText);
        console.dir(kk);
    }
    else {
        console.dir(xhr);
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send();

Sharepoint Update Item With REST

By On 07/07/2020

Sharepoint update an item with REST no jquery

 


console.clear();
function UpdateListItem(listName){
    var listItemId=176;
    var itemType = "SP.Data.SurveysListItem";//GetItemTypeForListName(listName);
	//debugger;
    var item = {
        "__metadata": { "type": itemType },
		"LaunchReportingFlag": "0"
    };
	/*
		"Reporting": ""		
	
	*/
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items("+listItemId+")";
	var requestdigest = document.getElementById("__REQUESTDIGEST");
	var xhr = new XMLHttpRequest();
	xhr.open('POST', url, true);
	xhr.setRequestHeader("Accept", "application/json; odata=verbose");
	xhr.setRequestHeader("X-RequestDigest", requestdigest.value);
	xhr.setRequestHeader("content-type", "application/json; odata=verbose");
	xhr.setRequestHeader("X-HTTP-Method", "MERGE");
	xhr.setRequestHeader("If-Match", "*");
	
	xhr.onload = function () {
		if (xhr.status === 204) {
			console.log("success");
		}
		else {
			console.log("error");
			console.log(xhr.status);
			console.dir(xhr);
			console.dir(xhr.responseText);
			
		}
	};
	xhr.send(JSON.stringify(item));
}
 
UpdateListItem("Campaigns");


getItemTypeForListName


function getItemTypeForListName(listTitle){
	var xhr = new XMLHttpRequest();
	var url = _spPageContextInfo.webAbsoluteUrl;
	if (url === "undefined") {
		console.log("_spPageContextInfo.webAbsoluteUrl undefined");
		url = "http://siteUrl";
	}
	//xhr.open('GET', url +"/_api/web/Lists?$select=Id,Title,Hidden,ItemCount");
	xhr.open('GET', url + "/_api/web/lists/getbytitle('" + listTitle + "')/?$select=ListItemEntityTypeFullName");
	xhr.setRequestHeader("Accept", "application/json; odata=verbose");
	xhr.onload = function () {
		if (xhr.status === 200) {
			var kk = JSON.parse(xhr.responseText);
			console.dir(kk.d.ListItemEntityTypeFullName);
		}
		else {
			console.dir(xhr);
			alert('Request failed.  Returned status of ' + xhr.status);
		}
	};
	xhr.send();
}

Sharepoint REST query Search

By On 28/06/2020

use rest api to search items in sharepoint

var fdi = {};
fdi.search = function(url, query, target, selectProperties){
    var req = url + "/_api/search/query?querytext='" + query + "'&selectproperties='"+ selectProperties +"'&sortlist='LastModifiedTime:descending'&rowlimit=500";

    //&rowsperpage=0&rowlimit=5
    var xhr = new XMLHttpRequest();

    fdi.fdilog(req);
    xhr.open('GET', req);
    xhr.setRequestHeader("Accept", "application/json; odata=verbose");
    xhr.onload = function () {
        if (xhr.status === 200) {
            var kk = JSON.parse(xhr.responseText);
            fdi.lastQuery = req;
            fdi.lastResult = kk;

            fdi.fdilog(kk.d);
            //debugger;
            
            fdi.fdilog(kk.d.query.PrimaryQueryResult.RelevantResults.Table.Rows);//,TypeAsString,Title,Hidden,Required,Group
            fdi.fdilog("RowCount : " + kk.d.query.PrimaryQueryResult.RelevantResults.RowCount);
            fdi.fdilog("TotalRows : " + kk.d.query.PrimaryQueryResult.RelevantResults.TotalRows);
           var rows = kk.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
            var datas = [];
            var columns = selectProperties.split(",");
            for(var i = 0 ; i < rows.length ; i++){
                var tar = {};
                tar.rowNum = i;
                for(var j = 0 ; j < columns.length ; j++){
                        var found = false;
                    for(var k = 0 ; k < rows[i].Cells.results.length ; k++){
                        if(rows[i].Cells.results[k].Key == columns[j]){

                            found = true;
                            tar[columns[j]] = rows[i].Cells.results[k].Value;
                        }
                        if(!found)
                            tar[columns[j]] = "";
                    }
                }
                datas.push(tar);
//rows[i].Cells.results[1].Key
            }
            fdi.fdilog(datas);
            fdi.createTable("rowNum," + selectProperties, datas, target, "#EEEEEE");
        }
        else {
            fdi.fdilog(req);
            fdi.fdilog(xhr);
            alert('Request failed.  Returned status of ' + xhr.status);
        }
    };
    xhr.send();//send request
}

use as below

var reqvvv = "ContentTypeId:0x010056313CD55A8D274EB8FAF2CA0B228BCA00AAEACC42FC8BD24797DEF621447F7D00*";
var seletvvv = "Title,Path,RefinableString20,RefinableString23,RefinableString24,RefinableString25,RefinableDecimal02,RefinableDecimal03,RefinableDecimal04,LastModifiedTime,ListItemID";

fdi.search("https://aSite/sites/Dev", reqvvv, "fdiOutPut", seletvvv); 

 

Sharepointsearchapiquery

Display in a table


fdi.createTable = function( columns, datas, target, backGroundColor){
    if(fdi.isNullOrEmpty(target))
        return;
    
    // var targetDiv = document.getElementsByClassName("SPCanvas");
    // targetDiv[0];
    var targetDiv = document.getElementById(target);
    targetDiv.innerHTML = "";
	var tbl = document.createElement('table');
    var att = document.createAttribute("class");
    
    //var thead = document.createElement('thead');
    var tr1 = document.createElement('tr');
    
    var columnArray = columns.split(",");
    var att = null;
    for(var i = 0 ; i < columnArray.length ; i++){
        var th = document.createElement('th');
        fdi.fdidebuglog(columnArray[i]);
		th.innerText = columnArray[i];
        att = document.createAttribute("style");
        att.value = "border:1px solid #000;width:230px";
        th.setAttributeNode(att);
		tr1.appendChild(th);
    }
    tbl.appendChild(tr1);

    for(var j = 0 ; j < datas.length ; j++){
        var tr2 = document.createElement('tr');
        //background-color: #EEEEEE
        if(j % 2 == 0 && typeof(backGroundColor) !== "undefined"){
            att = document.createAttribute("style");
            att.value = "background-color:" + backGroundColor + ";";
            tr2.setAttributeNode(att);
        }
        for(var i = 0 ; i < columnArray.length ; i++){
            var td = document.createElement('td');
            td.innerText = datas[j][columnArray[i]];
            att = document.createAttribute("style");
            att.value = "border:1px solid #000;width:230px";
            td.setAttributeNode(att);
            tr2.appendChild(td);
        }        
        tbl.appendChild(tr2);
    }
    
    targetDiv.appendChild(tbl);
}

 

full script

SPFX pnp Taxonomy with internet explorer 11

By On 26/06/2020

SPFX webpart query Taxonomy / Term store with @pnp/sp-taxonomy on ie / internet explorer

 

Your package.json must contains at least :

"@pnp/polyfill-ie11": "1.0.0", 
"@pnp/sp": "1.2.7", 
"@pnp/sp-clientsvc": "^1.3.9", 
"@pnp/sp-taxonomy": "^1.3.9", 
"@types/es6-promise": "0.0.33"

 

In your service where you want to query Term store, you should import :

import 'core-js/modules/es6.string.includes.js';
import 'core-js/modules/es6.number.is-nan.js'; 
import 'core-js/es6/array'; 
import 'es6-map/implement'; 
import { Session } from '@pnp/sp-taxonomy'; 

 

Power Automate Flow Functions

By On 18/06/2020

Power plateform

Power automate flow

 

Functions

Check date is null

if(equals(triggerBody()?['myDate'], null),'[myDate is null]', formatDateTime(triggerBody()?['myDate'], 'dd/MM/yyyy'))

Power apps

Display view on query string value

If ( !IsBlank(Param("taskDisplay")) && Param("taskDisplay")="true"; Navigate(DevTasksView;ScreenTransition.Cover) )

set variable value (separator in english is , in french ;)

Set(CurrentToShow; "loppement") ;; Set(CurrentButton; "DEV")

Flow Get Item Send Mail

By On 10/06/2020

Microsoft Flow hot to get item by lookup and send a mail, with lookup details

Initialize variable

Initvars

Get lookup datas

Getitem 1

Extract approver datas


{
    "type": "object",
    "properties": {
        "@@odata.type": {
            "type": "string"
        },
        "Claims": {
            "type": "string"
        },
        "DisplayName": {
            "type": "string"
        },
        "Email": {
            "type": "string"
        }
    }
}

Extractdisplayname

Append datas to an array

Appendtoarray

Create an html table

Createhtml

Send the mail

Sendmail

In Tools

String Manipulations

By On 23/05/2020

String Manipultions

    • Input Text
    • Text Out
    • Separator
    •  
      Trim
       
      Set replacement is tab
       
      Set replacement is new line
  •  
    • join / concat lines
    • split
    • set Default Values
     
    • trim
    • remove last char
    • remove first char
     
    • Replace separator by tab or new line
    • remove last char
    • Get duplicates
     
    • stringify JSON
    • html encode
    • html decode
     
  •  
  •  
  • Url encoder

    • Input url
    • Output url
    • Actions
      • EncodeUrl
      •  
      •  
      •  
      •  
      • DecodeUrl
 
 

Sharegate Mon Plan De Migration

By On 21/05/2020

Les bonnes pratiques que j'ai pu identifier

 

  • Commencer par bien analyser le site à migrer
  • Controler le delta des features natives
  • Faire un pre-check avant de lancer la copie
    • Structure puis contenu
  • Décocher le maximum d'options en cas d'échec, puis les remettre de manière incrémental
  • Sharegatelinkcopyconfiguration
  • Sharegatelistcopyconfig
  • Migrer juste la structure d'une liste, puis vérifier que les formulaires New, Edit et View soient fonctionnels

Si l'on rencontre l'erreur suivante, Custom Scripting is disabled at destination and you do not have sufficient permissions to enable it. You must be Global admin (Tenant admin) in order to enable it. Some items might not be copied.  

et que vous avez coché "Required features"  Sharegaterequiredfeatures

Sharegate n'arrive pas à activer des features nécessaires pour la liste (procédure pour activer des features [liste des features SP2019 complète] )

  •