Posts by fredericdietrich
Connect Sharepoint With AppID Certificate
Connect to Sharepoint using app registration and certificate
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Graph;
using PnP.Core.Auth;
using PnP.Core.Auth.Services.Builder.Configuration;
using PnP.Core.Services;
using PnP.Core.Services.Builder.Configuration;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace HGH.Buisiness4
{
public class SPTools2 : IDisposable
{
private IHost _host;
public SPTools2()
{
}
public async Task Connect(string appId, string tenantId, string siteUrl, string thumbprint, StoreName storeName, StoreLocation storeLocation)
{
try
{
_host = Host.CreateDefaultBuilder()
.ConfigureServices((hostingContext, services) =>
{
// Add the PnP Core SDK library
services.AddPnPCore(options =>
{
options.Sites.Add("SiteToWorkWith", new PnPCoreSiteOptions
{
SiteUrl = siteUrl
});
});
services.AddPnPCoreAuthentication(
options =>
{
// Configure an Authentication Provider relying on Windows Credential Manager
options.Credentials.Configurations.Add("x509certificate",
new PnPCoreAuthenticationCredentialConfigurationOptions
{
ClientId = appId,
TenantId = tenantId,
X509Certificate = new PnPCoreAuthenticationX509CertificateOptions
{
StoreName = storeName,
StoreLocation = storeLocation,
Thumbprint = thumbprint
}
});
// Configure the default authentication provider
options.Credentials.DefaultConfiguration = "x509certificate";
// Map the site defined in AddPnPCore with the
// Authentication Provider configured in this action
options.Sites.Add("SiteToWorkWith",
new PnPCoreAuthenticationSiteOptions
{
AuthenticationProviderName = "x509certificate"
});
});
})
// Let the builder know we're running in a console
.UseConsoleLifetime()
// Add services to the container
.Build();
await _host.StartAsync();
}
catch (Exception ex)
{
Console.WriteLine($"ERROR SPTools2 appId {appId} siteUrl {siteUrl} thumbprint {thumbprint} {ex}");
throw new Exception($"ERROR SPTools2 appId {appId} siteUrl {siteUrl} thumbprint {thumbprint}", ex);
}
return 1;
}
public async Task LoadWeb()
{
try
{
// Optionally create a DI scope
using (var scope = _host.Services.CreateScope())
{
// Obtain a PnP Context factory
var pnpContextFactory = scope.ServiceProvider
.GetRequiredService();
// Use the PnP Context factory to get a PnPContext for the given configuration
using (var context = await pnpContextFactory.CreateAsync("SiteToWorkWith"))
{
// Retrieving web with lists and masterpageurl loaded ==> SharePoint REST query
var web = await context.Web.GetAsync(p => p.Title, p => p.Lists,
p => p.MasterUrl);
Console.WriteLine($"Web Title {web.Title} Loaded");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"ERROR LoadWeb{ex}");
throw new Exception($"ERROR LoadWeb ", ex);
}
return 1;
}
public void Dispose()
{
if (_host != null)
_host.Dispose();
}
}
}
PowerAutomate Add Folder
Powerautomate get folder by url
/_api/web/GetFolderByServerRelativeUrl('@{variables('WebserverRelativeUrl')}/@{variables('DoclibUrl')}/Fiche_@{variables('FicheId')}')
Verify status (exists = 200, does not exists = 404)
@{outputs('HttpGetFolder')['statusCode']}
Create folder
/_api/web/folders/add('@{variables('DoclibUrl')}/Fiche_@{variables('FicheId')}')
Powershell Import Export Fields
Write-Output 'Connexion Portail'
# Connect-PnPOnline -Url $siteUrl -Tenant $aadDomain -Thumbprint $certifThumbprint -ClientId $appId
function ExportFieldsToCsv {
Param(
[string]$listTitle,
[string]$csvFilename,
[boolean]$includeHidden = $false
)
#$list = Get-PnPList -Identity $list
if ([string]::IsNullOrEmpty($listTitle)) {
$fields = Get-PnPField
$aFieldToExports = @();
for ($i = 0 ; $i -lt $fields.Length ; $i++) {
$field = $fields[$i];
$aFieldToExport = New-Object -TypeName PSObject -Property @{
'Title' = $field.Title;
'InternalName' = $field.InternalName;
'Id' = $field.Id;
'TypeAsString' = $field.TypeAsString;
'Hidden' = $field.Hidden;
'StaticName' = $field.StaticName;
'Required' = $field.Required;
'Description' = $field.Description;
'TypeDisplayName' = $field.TypeDisplayName;
'Group' = $field.Group;
}
$aFieldToExports += $aFieldToExport
$aFieldToExports | Export-Csv -Path "$($csvFilename)" -Encodin:UTF8 -NoTypeInformation -Delimiter ";"
}
}
else {
<# Action when all if and elseif conditions are false #>
}
}
function ExportFieldsToXml {
Param(
[string]$listTitle,
[string]$xmlFilename,
[boolean]$includeHidden = $false
)
#$list = Get-PnPList -Identity $list
if ([string]::IsNullOrEmpty($listTitle)) {
$fields = Get-PnPField
$stringBuilder = New-Object System.Text.StringBuilder
$null = $stringBuilder.AppendLine("")
for ($i = 0 ; $i -lt $fields.Length ; $i++) {
$field = $fields[$i];
$null = $stringBuilder.AppendLine($field.SchemaXml);
}
$null = $stringBuilder.AppendLine("")
$stringBuilder.ToString() | Out-File -FilePath "$($xmlFilename)" -Encodin:UTF8 -Append
}
}
function ImportFields {
Param(
[string]$listTitle,
[string]$xmlFilePath,
[boolean]$includeHidden = $false
)
[XML]$xmlfile = Get-Content -Path $xmlFilePath -Encoding:UTF8
if ([string]::IsNullOrEmpty($listTitle)) {
foreach ($field in $xmlfile.fields.Field) {
Write-Host $field.Name
$exists = Get-PnPField -Identity $field.Name -ErrorAction:SilentlyContinue
if ($null -eq $exists) {
Write-Host "$($field.Name) is null"
Add-PnPFieldFromXml -FieldXml $field.OuterXml
Write-Host "$($field.Name) added"
}
else {
Write-Host "$($field.Name) exists"
}
}
}
else {
foreach ($field in $xmlfile.fields.Field) {
$siteField = Get-PnPField -Identity $field.Name -ErrorAction:SilentlyContinue
$listField = Get-PnPField -Identity $field.Name -List $listTitle -ErrorAction:SilentlyContinue
if ($null -eq $siteField -and $null -eq $listField) {
Write-Host "$($field.Name) is null"
Add-PnPFieldFromXml -FieldXml $field.OuterXml
Add-PnPField -List $listTitle -Field $field.Name
Write-Host "$($field.Name) added"
}
elseif($null -eq $listField){
Write-Host "$($field.Name) exists"
Add-PnPField -List $listTitle -Field $siteField.InternalName
Write-Host "$($field.Name) added to $($listTitle)"
}
}
}
}
PowerAutomate Try Catch
Try catch in power automate
{
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"startTime": {
"type": "string"
},
"endTime": {
"type": "string"
},
"trackingId": {
"type": "string"
},
"clientTrackingId": {
"type": "string"
},
"clientKeywords": {
"type": "array",
"items": {
"type": "string"
}
},
"code": {
"type": "string"
},
"status": {
"type": "string"
},
"error": {
"type": "object",
"properties": {
"code": {
"type": "string"
},
"message": {
"type": "string"
}
}
}
},
"required": [
"name",
"startTime",
"endTime",
"trackingId",
"clientTrackingId",
"clientKeywords",
"code",
"status",
"error"
]
}
}
{
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"type": {
"type": "string"
},
"location": {
"type": "string"
},
"tags": {
"type": "object",
"properties": {
"flowDisplayName": {
"type": "string"
},
"environmentName": {
"type": "string"
},
"logicAppName": {
"type": "string"
},
"environmentWorkflowId": {
"type": "string"
},
"xrmWorkflowId": {
"type": "string"
},
"environmentFlowSuspensionReason": {
"type": "string"
},
"sharingType": {
"type": "string"
}
}
},
"run": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"type": {
"type": "string"
}
}
}
}
}
concat('https://emea.flow.microsoft.com/manage/environments/', body('Analyser_JSON')?['tags']?['environmentName'], '/flows/', body('Analyser_JSON')?['name'], '/runs/', body('Analyser_JSON')?['run']?['name'])
a href="@{outputs('LinkToWfHisto')}">@{workflow()?['tags']?['flowDisplayName']} a
PowerAutomate Date Format
formatDateTime('2009-06-15T13:45:30', 'M/dd/yyyy h:mm tt') 6/15/2009 1:45 PM
formatDateTime('2009-06-15T13:45:30', 'dd/MM/yyyy') 15/06/2009
formatDateTime('2009-06-15T13:45:30', 'd/M/yyyy') 15/6/2009
formatDateTime('2009-12-15T13:45:30', 'dddd/MMMM/yyyy') Tuesday/December/2009
formatDateTime('2009-12-15T13:45:30', 'ddd/MMM/yyyy') Tue/Dec/2009
PowerApps Functions
PowerApps functions
Parse text to number
Filter('Workflow Tasks'; ID = Value(txtId.Text))
Add datas (listItem)
Patch(NewVoie;Defaults(NewVoie);{Num_x00e9_rovoie:"0"&LookUp(NewVoie;ID=1).Num_x00e9_rovoie}))
Update context, and forms datas
SubmitForm(FormBeneficiaires);;ResetForm(FormBeneficiaires);; NewForm(FormBeneficiaires);; UpdateContext({showPopup:false});
Navigate to another form
Navigate(Page_infos_enregistrements)
Get query string parameter and set a variable
Set(InitiativeId; Param("ID"))
Get a field from your datasource by ID
First(Filter(Initiatives; ID=1)).Nom
And Or Not
Or(And(Radio1.Selected.Value=4; !IsBlank(txtComment.Text));Radio1.Selected.Value<4)
Update Lookup Field
Patch(
ResultatAnalyses;
First(//here item to update
Filter(
ResultatAnalyses;
Affaire.Id = currentAffaire.ID And Analyse.Id = ThisItem.ID
)
);
{
Title: "notused";
Commentaires: txtGalComment.Text;
Gravite: Rating1.Value;
Affaire: {//lookup field name
Id: currentAffaire.ID;//id of lookup
Value: LookUp(
Affaires;//list who contains lookup value
ID = currentAffaire.ID;//id of lookup
currentAffaire.Title//title of lookup value
)
}
}
)
Patch Choice
TypeIntervention: {Value: dtvTypeIntervention.Selected.Value}
Execute automate with json
'My workflow'.Run(
JSON(
{
SolutionId: selectedSolution.ID,
ImageContent: UploadedImage14.Image
},
JSONFormat.IncludeBinaryData
)
);
Reg ex to get cleaned string
Clear(AttachmentsCollection);
ForAll(
RenameColumns(DataCardValue91.Attachments, "Name", "Name1"),
Collect(
AttachmentsCollection,
Name1
)
);Set(Title1, First(AttachmentsCollection).Value);Set(FileName1, Concat( Split(First(AttachmentsCollection).Value, "" ), If( IsMatch(Result, "([^A-Za-z0-9\.\-])" ), "",Result ) ))
Save Form
SubmitForm(Form1);;If(!IsBlankOrError( Form1.Error); Notify("Une erreur est survenue lors de la sauvegarde " & Form1.Error; NotificationType.Error);Notify("La savegarde a réussi";NotificationType.Information);;Set(currentElement; Form1.LastSubmit))
Sort columns
Set(Month, Distinct(SortByColumns(CurrentMonthMails, "Year", Ascending, "Month", Ascending), Month))
Set date
Set(StartDate, DateAdd(DateTimeValue( Day(Today) &"/"& Month(Today) &"/"& Year(Today) &" 00:00:00"), -30));
Sum
Sum(Filter(CurrentMonthMails, Month = ThisItem.Result ), uniqMails)
PowerAutomate Functions
Concat
concat(outputs('Compose'),'test')
Get user mail in REST results
items('Appliquer_à_chacun')?['MyUser']?['EMail']
Add 10 Days
addDays(utcNow(),10)
Get JSON data
body('parameterJSON')?['Relaunch1nbDays']
body('myGet')?['value']
Get variable value
variables('RelaunchDate1')
Check data is empty
if(empty(variables('userMail')), null, variables('userMail'))
Date formatting
formatDateTime(your-value, 'dd/MM/yyyy hh:mm tt')
image base64 to <img>
Get_file_content_using_path_2')['$content'] //the $ is important
<img class="logo" src="data:image/jpeg;base64, @{body('Get_file_content_using_path_2')['$content']}" alt="My Image" />
Json Formatting Edit Button
Add an edit button, in field json formatting
{
"$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
"elmType": "div",
"children": [
{
"elmType": "span",
"style": {
"padding-right": "8px"
},
"txtContent": "@currentField.title"
},
{
"elmType": "a",
"style": {
"text-decoration": "none"
},
"attributes": {
"iconName": "Edit",
"class": "sp-field-quickActions",
"target": "_blank",
"href": {
"operator": "+",
"operands": ["www.source=portal&screenColor=rgba%280%2C+176%2C+240%2C+1%29&skipAppMetadata=true&ID=",
"[$ID]"
]
}
}
}
]
}
Power Automate Check User Exists
/_api/web/ensureuser
content-type application/json; odata=verbose
{'logonName': '@{variables('userMailToCheck')}'}
@{outputs('Send_an_HTTP_request_to_SharePoint')['statusCode']}
How to resolve the 5000 item limit
var firstItems = listLocation.web.getList(listLocation.listUri).items.select("ID").top(1).orderBy("Id").get(); var lastItems = listLocation.web.getList(listLocation.listUri).items.select("ID").top(1).orderBy("Id", false).get(); if (firstItems.length === 1 && lastItems.length === 1) { const firstId: number = firstItems[0].ID; const lastId: number = lastItems[0].ID; let startId = firstId; let endId = firstId + 5000; do { let mySites: ISite[] = await listLocation.web.getList(listLocation.listUri).items .select("ID", "Title", "Url") .filter(`Id ge ${startId} and Id lt ${endId} and ProprietairesPeople/Id eq ${userId}`) .expand('ProprietairesPeople') .orderBy("Title") .top(5000) .getAll(); allMySites.push(...mySites); startId = startId + 5000; endId = endId + 5000; } while (endId < lastId); } return allMySites;
Add User To Group With Rest
Add User To Sharepoint Group With Rest
var fdi = fdi || {};
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 () {
if (xhr.status === 200) {
console.log(url + " : success");
var d = JSON.parse(xhr.responseText);
console.dir(d.FormDigestValue);
var viewXml = "" +
"" +
" " +
" " +
" ";
var req = { "query" :{"__metadata": { "type": "SP.CamlQuery" }, "ViewXml": viewXml}};
var xhrPOST = new XMLHttpRequest();
var reqUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(5)/users";
//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));
}
var metadata = {
__metadata: {
'type': 'SP.User'
},
LoginName: 'i:0#.f|membership|fred.ddiet@test.com'
}; JSON.stringify(metadata)
xhrPOST.send(JSON.stringify(metadata));
console.log("sent");
}
else {
console.log("error");
console.log(xhr.status);
console.dir(xhr);
console.dir(xhr.responseText);
}
};
xhr.send();
};
fdi.post();
PowerAutomate Add User To Group
Powerautomate add user to sharepoint group
Ajouter un utilisateur dans un groupe sharepoint en REST avec powerautomate
{"__metadata":{"type":"SP.User"},"LoginName":"i:0#.f|membership|@{variables('emailToAdd')}"}
{
"siteUrl": "https://vvvvvvvvvvvvvvv.com",
"Accept": "Accept",
"ApplicationJson": "application/json; odata=verbose",
"ContentType": "content-type"
}
Gulp Bundle Issue Cannot Read Property Id Of Undefined
Gulp bundle issue : Cannot read property 'id' of undefined
Gulp bundle issue : Field 'browser' doesn't contain a valid alias configuration
Gulp bundle issue : sub task errored after
Check that in your tsconfig.json, you've got this below :
"include": [
"src/**/*.ts", "src/**/*.tsx"
],
and not :
"include": [
"src/**/*.tsx"
],
PowerApps Build String To Link
Powerapps build your string to creae an html link
<div style="background-color:#000000;width:100%;"><code><a href="https://mySP.sharepoint.com/sites/DfSite/Lists/Initiatives/DispForm.aspx?ID="; InitiativeId; "" style="color:#FFFFFF;height:100px">";SelectedInitiative.Titre;"</a></code></div>
Powerautomate Caml Query
Powerautomate Caml Query
Powerautomate Add Comment To ListItem
Add comment to ListItem with powerautomate (http Sharepoint request)
PowerAutomate Update ListItem HTTP REST
Update a list item with http request with powerautomate
{
"Accept": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose",
"X-HTTP-Method": "MERGE",
"If-Match": "*"
}
Add WebPart On Modern Page PNP Powershell
Add custom WebPart On Modern Page Powershell
List your webpart with :
$page = Get-PnPPage -Identity "aTestDisp2.aspx"
$page.AvailablePageComponents() select your webpart by name or guid
param([string]$siteUrl="https://myyTenant.sharepoint.com/sites/muSite", [string]$pageName="aTestDisp2", [string]$webPartName="Test - Display Item") clear Connect-PnPOnline -Url $siteUrl -UseWebLogin #set your wenpart properties $wpProps = @{webUrl="https://myyTenantsharepoint.com/sites/
muSite" listId="b4d5f780-bd74-4cd5-b051-fed423e43125" field="Title" itemId="1"} #get the page $page = Get-PnPPage -Identity $pageName # get the target webpart $wp = $page.AvailablePageComponents() | Where-Object {$_.Name -eq $webPartName } if($wp -eq $null) { Write-Host "webpart '$($webPartName)' not found " -ForegroundColor:Red } #Add webpart with default user, to column 1 in section 1 Add-PnPPageWebPart -Page $pageName -Component $wp -Section 1 -Column 1 -WebPartProperties $wpProps
Disconnect-PnPOnline
You can check webpart properties, in result
Get Sharepoint List Items Count
Get Sharepoint list Items count
var xhr = new XMLHttpRequest();
console.clear();
var url = "https://mySiteUrl";
xhr.open('GET', url + "/_api/web/Lists/getbytitle('TheListName')?$select=ItemCount,Title");
xhr.setRequestHeader("Accept", "application/json; odata=verbose");
xhr.onload = function () {
if (xhr.status === 200) {
var kk = JSON.parse(xhr.responseText);
console.dir(kk.d.Title + " Item Count : " + kk.d.ItemCount);
}
else {
console.dir(xhr);
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
In your browser you must be your your site url, push key F12 paste above code in console, en push enter
fr
Power Automate Sharepoint Actions List
Power Automate Sharepoint Actions List