PnP Core SDK Documentation

repository·dev·Indexed 18 days ago

https://github.com/pnp/pnpcore

A unified, API-agnostic object model for interacting with Microsoft 365 workloads, specifically SharePoint Online and Teams. The SDK abstracts Microsoft Graph and SharePoint REST APIs to provide a consistent developer experience. It includes support for .NET dependency injection, various authentication providers via PnP.Core.Auth, and integration with Polyglot Notebooks and Azure Functions.

Tokens
175.9K
Snippets
481
Records
565
Agent score
62%

What's inside PnP Core SDK

  1. Overview of PnP Core SDK projects

    dev

    The PnP Core SDK is organized into several specialized projects within the PnP.Core.sln solution. Depending on your requirements, you may need to include specific libraries to extend the core functionality:

    • PnP.Core: The primary SDK codebase containing the core logic.
    • PnP.Core.Admin: An extension library providing administrative tasks and capabilities.
    • PnP.Core.Auth: A library of Authentication Providers that uses MSAL (Microsoft Authentication Library) for authentication logic.

    Note: The solution also contains test projects (PnP.Core.Test, PnP.Core.Admin.Test, and PnP.Core.Auth.Test) used for verifying the SDK's functionality.

  2. Available PnP Core Tools

    dev

    The pnpcore repository contains additional tools used for the creation and maintenance of the PnP Core SDK. These tools are located in the src/tools directory.

    ToolDescription
    PnP.Core.DomainModelGeneratorAssists with the initial generation of models.
    CodeCoverageContains PowerShell scripts to run test coverage reports for specific test projects (e.g., PnP.Core.Test) or individual test files (e.g., PnP.Core.Test\SharePoint\FilesTests.cs).
  3. Thread safety in PnP Core SDK

    dev

    The core classes of the PnP Core SDK are not thread-safe. You should avoid sharing these instances across multiple threads to prevent unexpected results and exceptions.

    Non-thread-safe components include:

    • PnPContext
    • Model classes (e.g., IWeb, ITeamChannel)
    • Model collection classes (e.g., IListCollection, ITeamChannelCollection)

    Important Note on Throttling: Parallelizing operations increases the number of requests made in a given time window, which may trigger SharePoint Online throttling. You can monitor throttling events via the PnP Core SDK EventHub.

  4. Understand the difference between SharePoint CSOM and PnP Core SDK

    dev

    While PnP Core SDK shares similarities with SharePoint CSOM, there are fundamental differences in how requests are executed and how data is loaded.

    Key differences include:

    • Execution Model: In CSOM, you must explicitly call ExecuteQuery() to send HTTP requests. In PnP Core SDK, most LoadAsync and UpdateAsync methods execute the HTTP request immediately. The exception is when using batching (LoadBatchAsync), where you must call ExecuteAsync().
    • Data Loading: In CSOM, you often load data into the context. In PnP Core SDK, LoadAsync methods are available directly on the SharePoint model objects. To load data into a variable, PnP Core SDK uses GetAsync or ToListAsync methods, which execute requests immediately.
    • Collections: PnP Core SDK allows you to apply LINQ filters directly to collections (e.g., .Where(...)), which are then translated into REST OData filters during execution.
  5. Compatibility and Runtime Support for PnP Core SDK

    dev

    PnP Core SDK is designed for modern .NET development and supports a wide range of runtimes and platforms:

    Supported Frameworks

    • .NET Standard 2.0: For backwards compatibility with .NET Framework 4.6.1+.
    • Modern .NET: Supports .NET 8.0, .NET 9.0, and .NET 10.0 (LTS).

    Supported Platforms and Workloads

    • Cross-platform: Windows, Linux, and macOS.
    • Backend: Azure Functions (v3/v4).
    • Web: ASP.NET Core and Blazor (Blazor WebAssembly support requires .NET 6.0 or later).
    • Mobile & Desktop: .NET MAUI (Windows, iOS, macOS, Android) and Windows Client (Windows Forms, WPF).

    Integration Pattern

    • The library is built with Dependency Injection (DI) as a first-class citizen, allowing it to be easily integrated into modern ASP.NET Core and other DI-based applications.
  6. Manage permission inheritance on securable objects

    dev

    In SharePoint, objects like IWeb, IList, and IListItem implement the ISecurableObject interface. By default, they inherit permissions from their parent. To provide unique permissions, you must break inheritance.

    Break permission inheritance

    Use BreakRoleInheritanceAsync(bool copyRoleAssignments, bool clearSubscopes):

    • copyRoleAssignments: If true, copies current permissions to the object so they can be edited. If false, no permissions are copied.
    • clearSubscopes: If true, existing custom permissions on child objects are dropped in favor of the current one. If false, existing custom permissions are preserved.

    Restore permission inheritance

    Use ResetRoleInheritanceAsync() to make the object inherit permissions from its parent again.

    var myList = await context.Web.Lists.GetByTitleAsync("mylist");
    
    // Break permission inheritance
    await myList.BreakRoleInheritanceAsync(false, true);
    
    // Reset permission inheritance
    await myList.ResetRoleInheritanceAsync();
  7. Understand the relationship between PnP Core SDK and PnP Framework

    dev

    It is important to distinguish between these two libraries when choosing your development path:

    • PnP Framework: A legacy .NET Framework-based library used in many production scenarios. It currently depends on PnP Core SDK.
    • PnP Core SDK: A new library designed for modern .NET development. It is intended to eventually replace PnP Framework as the primary library for Microsoft 365 workloads.

    Use PnP Core SDK for new projects targeting modern .NET (Core/5+) to ensure long-term compatibility and access to the unified object model.

  8. Understand the PnP Core SDK architecture and API usage

    dev

    The PnP Core SDK provides an API-agnostic object model. When you interact with models such as List, Team, or Web, the SDK automatically selects the most efficient underlying API to fulfill the request.

    API Priority Order:

    1. Microsoft Graph (v1.0): The preferred and recommended API used whenever possible.
    2. Microsoft Graph Beta: Used when specific features require beta endpoints.
    3. SharePoint REST: Used as a fallback when Microsoft Graph cannot provide the necessary data or consistency.
    4. CSOM (client.svc): Used in specific cases where other APIs are insufficient.

    This abstraction ensures a consistent development experience regardless of which underlying Microsoft service is being called.

  9. Choose the best approach for reading list items

    dev

    The PnP Core SDK provides different methods for reading list items based on your requirements for list size, filtering, and field depth. Use the following decision matrix to select an approach:

    RequirementsRecommended Approach
    Small lists (<= 100 items) and no filtering neededOption A: Use Get or Load methods via the Items property.
    Large lists (> 100 items) and no filtering neededOption B: Use implicit paging by iterating over the Items collection.
    Need to filter items or expand collections (e.g., RoleAssignments)Option C: Use LoadItemsByCamlQueryAsync with a CAML query.
    Need system properties (e.g., FileLeafRef) or detailed lookup propertiesOption D: Use LoadListDataAsStreamAsync with RenderListDataOptions.
  10. Implement a persistent token cache using IAuthenticationProvider

    dev

    The PnP Core SDK can be extended to implement a persistent cache, allowing the application to reuse access tokens across restarts without re-prompting the user for credentials. This is achieved by implementing a custom IAuthenticationProvider.

    In this pattern, MSAL tokens are cached locally after the initial authentication. Upon subsequent application restarts, the custom provider retrieves the cached token instead of triggering an interactive login flow.

    // Concept: Implement a custom IAuthenticationProvider to handle local token persistence
    // This allows the SDK to reuse tokens after application restart.
  11. Pin or reuse terms using term relations

    dev

    The SDK allows you to create links between terms using TermRelationType. This is useful for making terms available in different locations while controlling how children are managed.

    Pinning a Term (TermRelationType.Pin)

    Pinning creates linked copies of the term and its children at the destination. Crucially, children of a pinned term can only be created or edited at the source; changes made at the source will reflect everywhere the term is pinned.

    Reusing a Term (TermRelationType.Reuse)

    Reusing makes linked copies of the term and its children available at the destination. Unlike pinning, children for a reused term can be created anywhere it is used, but those children will exist only in the specific term set where they were created.

    To implement either, use the Relations.AddAsync method on the source term.

    // Pin termA in termSetB under termB
    await termA.Relations.AddAsync(TermRelationType.Pin, termSetB, termB);
    
    // Reuse termA in termSetB
    await termA.Relations.AddAsync(TermRelationType.Reuse, termSetB);