SharepointCode
use code to add in sharepoint
Csom Context Sharepoint ClientContext
By fredericdietrich On 23/05/2023
c# Connect to Sharepoint with ClientContext appId and certificat ThumbPrint
using Microsoft.Identity.Client;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace MY.PNP.Powershell.EXT.CSOM
{
public class CsomContext : IDisposable
{
public ClientContext _clientContext;
public ClientRuntimeContext _context;
private async Task GetAccessToken(string tenantName, string clientId, string thumbprint)
{
var certificate = GetCert(thumbprint);
var authority = $"https://login.microsoftonline.com/{tenantName}.onmicrosoft.com/";
var azureApp = ConfidentialClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.WithCertificate(certificate)
.Build();
var scopes = new string[] { $"https://{tenantName}.sharepoint.com/.default" };
var authResult = await azureApp.AcquireTokenForClient(scopes).ExecuteAsync();
return authResult.AccessToken;
}
public async Task CallClientObjectModel(string tenantName, string url, string clientId, string thumbprint)
{
var token = await GetAccessToken(tenantName, clientId, thumbprint);
var siteUrl = url;//;$"https://{tenantName}.sharepoint.com";
var context = new ClientContext(siteUrl);
context.ExecutingWebRequest += (s, e) =>
{
e.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + token;
};
var web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine(web.Title);
Console.WriteLine(web.Url);
_context = web.Context;
_clientContext = context;
}
private X509Certificate2 GetCert(string thumbprint)
{
X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = certStore.Certificates.Find(
X509FindType.FindByThumbprint,
// Replace below with your cert's thumbprint
thumbprint,
false);
X509Certificate2 cert = null;
// Get the first cert with the thumbprint
if (certCollection.Count > 0)
{
cert = certCollection[0];
// Use certificate
Console.WriteLine(cert.FriendlyName);
}
certStore.Close();
return cert;
}
public void Dispose()
{
if (_context != null)
_context.Dispose();
if (_clientContext != null)
_clientContext.Dispose();
}
}
}
Connect Sharepoint With AppID Certificate
By fredericdietrich On 21/03/2023
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();
}
}
}
By fredericdietrich 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
Sharepoint Add SPFolder To SPList By Code
By fredericdietrich On 28/09/2018
use code below to add a folder in your SPList or SPFolderCollection
SPFolder rollupFolderNAme = styleLib.RootFolder.SubFolders.Cast<SPFolder>().FirstOrDefault(o => o.Name == "new folder");
if (rollupFolderNAme == null)
{
SPFolder newFolder = styleLib.RootFolder.SubFolders.Add("new folder");
newFolder.Update();
}