docs: start milestone v2.2 Report Branding & User Directory

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Dev
2026-04-08 10:35:27 +02:00
parent fd442f3b4c
commit 8447e78db9
513 changed files with 6496 additions and 946 deletions

View File

@@ -1,581 +1,443 @@
# Architecture Research
# Architecture Patterns
**Domain:** C#/WPF SharePoint Online Administration Desktop Tool
**Researched:** 2026-04-02
**Confidence:** HIGH
## Standard Architecture
### System Overview
```
┌─────────────────────────────────────────────────────────────────────┐
│ PRESENTATION LAYER │
│ ┌──────────────┐ ┌─────────────────────────────────────────────┐ │
│ │ MainWindow │ │ Feature Views (XAML) │ │
│ │ Shell.xaml │ │ Permissions │ Storage │ Search │ Templates │ │
│ │ │ │ Duplicates │ Bulk │ Reports │ Settings │ │
│ └──────┬───────┘ └──────────────────────┬────────────────────┘ │
│ │ DataContext binding │ DataContext binding │
├─────────┴─────────────────────────────────┴────────────────────────┤
│ VIEWMODEL LAYER │
│ ┌─────────────┐ ┌──────────────────────────────────────────────┐ │
│ │ MainWindow │ │ Feature ViewModels │ │
│ │ ViewModel │ │ PermissionsVM │ StorageVM │ SearchVM │ │
│ │ (nav/shell)│ │ TemplatesVM │ BulkOpsVM │ DuplicatesVM │ │
│ └──────┬──────┘ └───────────────────────┬──────────────────────┘ │
│ │ ICommand, ObservableProperty │ AsyncRelayCommand │
├─────────┴─────────────────────────────────┴────────────────────────┤
│ SERVICE LAYER │
│ ┌────────────────┐ ┌─────────────────┐ ┌──────────────────────┐ │
│ │ AuthService │ │ SharePoint │ │ Cross-Cutting │ │
│ │ SessionManager │ │ Feature Services │ │ Services │ │
│ │ TenantSession │ │ PermissionsService│ │ ReportExportService │ │
│ │ │ │ StorageService │ │ LocalizationService │ │
│ │ │ │ SearchService │ │ DialogService │ │
│ │ │ │ TemplateService │ │ SettingsService │ │
│ └────────┬───────┘ └────────┬────────┘ └──────────────────────┘ │
│ │ ClientContext │ IProgress<T>, CancellationToken │
├───────────┴────────────────────┴────────────────────────────────────┤
│ INFRASTRUCTURE / INTEGRATION LAYER │
│ ┌──────────────────┐ ┌───────────────────┐ ┌──────────────────┐ │
│ │ PnP Framework │ │ Microsoft Graph │ │ Local Storage │ │
│ │ AuthManager │ │ GraphServiceClient │ │ JSON Files │ │
│ │ ClientContext │ │ (Graph operations) │ │ Profiles │ │
│ │ (CSOM ops) │ │ │ │ Templates │ │
│ └──────────────────┘ └───────────────────┘ └──────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘
```
### Component Responsibilities
| Component | Responsibility | Typical Implementation |
|-----------|----------------|------------------------|
| MainWindow Shell | Tab navigation, tenant selector, app chrome, log panel | XAML with TabControl or navigation frame |
| Feature Views | User input forms, result grids, progress indicators | UserControl XAML, zero code-behind |
| Feature ViewModels | Commands, observable state, orchestrates services | ObservableObject subclass, AsyncRelayCommand |
| AuthService / SessionManager | Multi-tenant session lifecycle, token cache, active tenant state | Singleton, MSAL token cache per tenant |
| TenantSession | Per-tenant PnP ClientContext + auth token | Immutable record, created by AuthService |
| SharePoint Feature Services | Domain logic that calls PnP Framework or Graph | Stateless class, injectable, cancellable |
| ReportExportService | HTML/CSV generation from result models | Stateless, template-based string builder |
| LocalizationService | Key-based EN/FR translation, dynamic language switch | Singleton, loads lang/*.json, INotifyPropertyChanged |
| SettingsService | Read/write JSON settings, profiles, templates | Singleton, file I/O wrapped in async |
| DialogService | Open files, show message boxes, pick folders | Interface + WPF implementation, testable |
**Domain:** C#/WPF MVVM desktop app — SharePoint Online MSP admin tool
**Feature scope:** Report branding (MSP/client logos in HTML) + User directory browse mode
**Researched:** 2026-04-08
**Confidence:** HIGH — based on direct codebase inspection, not assumptions
---
## Recommended Project Structure
## Existing Architecture (Baseline)
```
SharepointToolbox/
├── App.xaml # Application entry, DI container bootstrap
├── App.xaml.cs # Host builder, service registration
├── Core/ # Domain models — no WPF dependencies
│ ├── Models/
├── PermissionEntry.cs
│ ├── StorageMetrics.cs
│ ├── SiteTemplate.cs
│ │ ├── TenantProfile.cs
│ │ └── SearchResult.cs
│ ├── Interfaces/
├── IAuthService.cs
│ │ ├── IPermissionsService.cs
│ │ ├── IStorageService.cs
│ ├── ISearchService.cs
├── ITemplateService.cs
│ ├── IBulkOpsService.cs
├── IDuplicateService.cs
│ ├── IReportExportService.cs
│ │ ├── ISettingsService.cs
│ │ ├── ILocalizationService.cs
│ └── IDialogService.cs
│ └── Exceptions/
│ ├── SharePointConnectionException.cs
│ └── AuthenticationException.cs
├── Services/ # Business logic + infrastructure
│ ├── Auth/
│ │ ├── AuthService.cs # PnP AuthenticationManager wrapper
│ │ ├── SessionManager.cs # Multi-tenant session store
│ │ └── TenantSession.cs # Per-tenant PnP ClientContext holder
│ ├── SharePoint/
│ │ ├── PermissionsService.cs # Recursive permission scanning
│ │ ├── StorageService.cs # Storage metric traversal
│ │ ├── SearchService.cs # KQL-based search via PnP/Graph
│ │ ├── TemplateService.cs # Capture & apply site templates
│ │ ├── DuplicateService.cs # File/folder duplicate detection
│ │ └── BulkOpsService.cs # Transfer, site creation, member add
│ ├── Reporting/
│ │ ├── HtmlReportService.cs # Self-contained HTML + JS reports
│ │ └── CsvExportService.cs # CSV export
│ ├── LocalizationService.cs # EN/FR key-value translations
│ ├── SettingsService.cs # JSON profiles, templates, settings
│ └── DialogService.cs # WPF dialog abstractions
├── ViewModels/ # WPF-aware but UI-framework-agnostic
│ ├── MainWindowViewModel.cs # Shell nav, tenant switcher, log
│ ├── Permissions/
│ │ └── PermissionsViewModel.cs
│ ├── Storage/
│ │ └── StorageViewModel.cs
│ ├── Search/
│ │ └── SearchViewModel.cs
│ ├── Templates/
│ │ └── TemplatesViewModel.cs
│ ├── Duplicates/
│ │ └── DuplicatesViewModel.cs
│ ├── BulkOps/
│ │ └── BulkOpsViewModel.cs
│ └── Settings/
│ └── SettingsViewModel.cs
├── Views/ # XAML — no business logic
│ ├── MainWindow.xaml
│ ├── Permissions/
│ │ └── PermissionsView.xaml
│ ├── Storage/
│ │ └── StorageView.xaml
│ ├── Search/
│ │ └── SearchView.xaml
│ ├── Templates/
│ │ └── TemplatesView.xaml
│ ├── Duplicates/
│ │ └── DuplicatesView.xaml
│ ├── BulkOps/
│ │ └── BulkOpsView.xaml
│ └── Settings/
│ └── SettingsView.xaml
├── Controls/ # Reusable WPF controls
│ ├── TenantSelectorControl.xaml
│ ├── LogPanelControl.xaml
│ ├── ProgressOverlayControl.xaml
│ └── StorageChartControl.xaml # LiveCharts2 wrapper
├── Converters/ # IValueConverter implementations
│ ├── BytesToStringConverter.cs
│ ├── BoolToVisibilityConverter.cs
│ └── PermissionColorConverter.cs
├── Resources/ # Styles, brushes, theme
│ ├── Styles.xaml
│ └── Colors.xaml
├── Lang/ # Language files
│ ├── en.json
│ └── fr.json
└── Infrastructure/
└── Behaviors/ # XAML attached behaviors (no code-behind workaround)
└── ScrollToBottomBehavior.cs
Core/
Models/ — TenantProfile, AppSettings, domain records (all POCOs/records)
Messages/ — WeakReferenceMessenger value message types
Helpers/ — Static utility classes
Infrastructure/
Auth/ — MsalClientFactory, GraphClientFactory (MSAL PCA per-tenant + Graph SDK bridge)
Persistence/ — ProfileRepository, SettingsRepository, TemplateRepository (JSON, atomic write-then-replace)
Logging/ — LogPanelSink (Serilog sink to in-app RichTextBox)
Services/
Export/ — Concrete HTML/CSV export services per domain (no interface, consumed directly)
*.cs — Domain services with IXxx interfaces
ViewModels/
FeatureViewModelBase.cs — Abstract base: RunCommand, CancelCommand, ProgressValue, StatusMessage,
GlobalSites, WeakReferenceMessenger registration
MainWindowViewModel.cs — Toolbar: tenant picker, Connect, global site picker, broadcasts TenantSwitchedMessage
Tabs/ — One ViewModel per tab, all extend FeatureViewModelBase
ProfileManagementViewModel.cs — Profile CRUD dialog VM
Views/
Dialogs/ — ProfileManagementDialog, SitePickerDialog, ConfirmBulkOperationDialog, FolderBrowserDialog
Tabs/ — One UserControl per tab (XAML + code-behind)
App.xaml.cs — Generic Host IServiceCollection DI registration for all layers
```
### Structure Rationale
### Key Patterns Already Established
- **Core/**: Pure C# — no WPF references. Interfaces here make services testable. Models are plain data classes.
- **Services/**: All domain logic and I/O. Injected via constructor DI. No static state.
- **ViewModels/**: Mirror the feature structure. Depend on service interfaces, never on concrete implementations.
- **Views/**: XAML-only. No logic. `DataContext` set by DI or ViewModelLocator pattern at startup.
- **Controls/**: Reusable UI widgets that encapsulate chart, log, and progress concerns.
| Pattern | How It Works |
|---------|-------------|
| Tenant switching | `MainWindowViewModel.OnSelectedProfileChanged` broadcasts `TenantSwitchedMessage` via `WeakReferenceMessenger`; each tab VM overrides `OnTenantSwitched(profile)` |
| Global site propagation | `GlobalSitesChangedMessage` received in `FeatureViewModelBase.OnGlobalSitesReceived` |
| HTML export | Concrete service class (e.g. `UserAccessHtmlExportService`), `BuildHtml(entries)` returns a string, `WriteAsync(entries, path, ct)` writes it. No interface. Pure data-in, HTML-out. |
| JSON persistence | Repository pattern: constructor takes `string filePath`, atomic write via `.tmp` + round-trip JSON validation before `File.Move`, `SemaphoreSlim` write lock. |
| DI registration | All in `App.xaml.cs RegisterServices()`. Export services and ViewModels are `AddTransient`; shared infrastructure is `AddSingleton`. |
| Dialog factory | View code-behind sets `ViewModel.OpenXxxDialog = () => new XxxDialog(...)` — keeps dialogs out of ViewModel layer |
| People-picker search | `IGraphUserSearchService.SearchUsersAsync(clientId, query, maxResults, ct)` calls Graph `/users?$filter=startsWith(...)` with `ConsistencyLevel: eventual` |
| Test constructor | `UserAccessAuditViewModel` has a `internal` 3-param constructor without export services — test pattern to replicate for new injections |
---
## Architectural Patterns
## Feature 1: Report Branding (MSP/Client Logos in HTML Reports)
### Pattern 1: ObservableObject + AsyncRelayCommand (CommunityToolkit.Mvvm)
### What It Needs
**What:** Use `ObservableObject` as base class for all ViewModels. Use `[ObservableProperty]` source-gen attribute for bindable properties. Use `AsyncRelayCommand` (with `CancellationToken`) for all SharePoint operations.
- **MSP logo** — one global image, shown in every HTML report from every tenant
- **Client logo** — one image per tenant, shown in reports for that tenant only
- **Storage** — base64-encoded strings in JSON (no separate image files — preserves atomic save semantics and single-data-folder design)
- **Embedding** — `data:image/...;base64,...` `<img>` tag injected into the HTML header (maintains self-contained HTML invariant — zero external file references)
- **User action** — file picker → read bytes → detect MIME type → convert to base64 → store in JSON → preview in UI
**When to use:** All ViewModels. This is the standard pattern for .NET 8 + WPF.
### New Components (create from scratch)
**Trade-offs:** Source generators require C# 10+. Generated partial class syntax is unfamiliar at first but eliminates 80% of boilerplate.
**Example:**
**`Core/Models/BrandingSettings.cs`**
```csharp
public partial class PermissionsViewModel : ObservableObject
public class BrandingSettings
{
private readonly IPermissionsService _permissionsService;
public string? MspLogoBase64 { get; set; }
public string? MspLogoMimeType { get; set; } // "image/png", "image/jpeg", etc.
}
```
Belongs in Core/Models alongside AppSettings. Kept separate — branding may grow independently of general app settings.
[ObservableProperty]
private bool _isRunning;
**`Core/Models/ReportBranding.cs`**
```csharp
public record ReportBranding(
string? MspLogoBase64,
string? MspLogoMimeType,
string? ClientLogoBase64,
string? ClientLogoMimeType);
```
Lightweight data transfer record assembled at export time from BrandingSettings + current TenantProfile. Not persisted directly — constructed on demand.
[ObservableProperty]
private string _statusMessage = string.Empty;
**`Infrastructure/Persistence/BrandingRepository.cs`**
Same pattern as `SettingsRepository`: constructor takes `string filePath`, atomic write-then-replace, `SemaphoreSlim` write lock. File: `%AppData%\SharepointToolbox\branding.json`.
[ObservableProperty]
private ObservableCollection<PermissionEntry> _results = new();
**`Services/BrandingService.cs`**
```csharp
public class BrandingService
{
public Task<BrandingSettings> GetBrandingAsync();
public Task SetMspLogoAsync(string filePath); // reads file, detects MIME, converts to base64, saves
public Task ClearMspLogoAsync();
}
```
Thin orchestration, same pattern as `SettingsService`. MSP logo only — client logo is managed via `ProfileService` (it belongs to `TenantProfile`).
public IAsyncRelayCommand RunReportCommand { get; }
### Modified Components
public PermissionsViewModel(IPermissionsService permissionsService)
{
_permissionsService = permissionsService;
RunReportCommand = new AsyncRelayCommand(RunReportAsync, allowConcurrentExecutions: false);
}
**`Core/Models/TenantProfile.cs`** — Add two nullable string properties:
```csharp
public string? ClientLogoBase64 { get; set; }
public string? ClientLogoMimeType { get; set; }
```
This is backward-compatible. `ProfileRepository` uses `JsonSerializer` with `PropertyNameCaseInsensitive: true` — missing JSON fields deserialize to null without error. Existing `profiles.json` files continue to load correctly.
private async Task RunReportAsync(CancellationToken cancellationToken)
{
IsRunning = true;
StatusMessage = "Scanning permissions...";
try
{
var results = await _permissionsService.ScanAsync(
SiteUrl, cancellationToken,
new Progress<string>(msg => StatusMessage = msg));
Results = new ObservableCollection<PermissionEntry>(results);
}
finally { IsRunning = false; }
}
**All HTML export services** — Add `ReportBranding? branding = null` optional parameter to every `BuildHtml()` overload. When non-null and at least one logo is present, inject a branding header div between `<body>` open and `<h1>`:
```html
<div class="brand-header" style="display:flex;align-items:center;gap:16px;padding:16px 24px 0;">
<!-- only rendered if logo present -->
<img src="data:{mimeType};base64,{base64}" style="max-height:60px;max-width:200px;" alt="MSP" />
<img src="data:{mimeType};base64,{base64}" style="max-height:60px;max-width:200px;" alt="Client" />
</div>
```
When `branding` is null (existing callers) the block is omitted entirely. No behavior change for callers that do not pass branding.
Affected services (all in `Services/Export/`):
- `HtmlExportService` (two `BuildHtml` overloads — `PermissionEntry` and `SimplifiedPermissionEntry`)
- `UserAccessHtmlExportService`
- `StorageHtmlExportService` (two `BuildHtml` overloads — with and without `FileTypeMetric`)
- `SearchHtmlExportService`
- `DuplicatesHtmlExportService`
**ViewModels that call HTML export** — All `ExportHtmlAsync` methods need to resolve branding before calling the export service. The ViewModel calls `BrandingService.GetBrandingAsync()` and reads `_currentProfile.ClientLogoBase64` to assemble a `ReportBranding`, then passes it to `BuildHtml`.
Affected ViewModels: `PermissionsViewModel`, `UserAccessAuditViewModel`, `StorageViewModel`, `SearchViewModel`, `DuplicatesViewModel`. Each gets `BrandingService` injected via constructor.
**`ViewModels/Tabs/SettingsViewModel.cs`** — Add MSP logo management:
```csharp
[ObservableProperty] private string? _mspLogoPreviewBase64;
public RelayCommand BrowseMspLogoCommand { get; }
public RelayCommand ClearMspLogoCommand { get; }
```
On browse: open `OpenFileDialog` (filter: PNG, JPG, GIF) → call `BrandingService.SetMspLogoAsync(path)` → reload and refresh `MspLogoPreviewBase64`.
**`Views/Tabs/SettingsView.xaml`** — Add a "Report Branding — MSP Logo" section:
- `<Image>` bound to `MspLogoPreviewBase64` via a base64-to-BitmapSource converter
- "Browse Logo" button → `BrowseMspLogoCommand`
- "Clear" button → `ClearMspLogoCommand`
- Note label: "Applies to all reports"
**Client logo placement:** Client logo belongs to a `TenantProfile`, not to global settings. The natural place to manage it is `ProfileManagementDialog` (already handles profile CRUD). Add logo fields there rather than in SettingsView.
**`ViewModels/ProfileManagementViewModel.cs`** — Add client logo management per profile:
```csharp
[ObservableProperty] private string? _clientLogoPreviewBase64;
public RelayCommand BrowseClientLogoCommand { get; }
public RelayCommand ClearClientLogoCommand { get; }
```
On browse: read image bytes → base64 → set on the being-edited `TenantProfile` object before saving. Uses `ProfileService.AddProfileAsync` / rename pipeline that already exists.
**`Views/Dialogs/ProfileManagementDialog.xaml`** — Add client logo fields to the add/edit profile form (same pattern as SettingsView branding section).
### Data Flow: Report Branding
```
User picks MSP logo (SettingsView "Browse Logo" button)
→ SettingsViewModel.BrowseMspLogoCommand
→ OpenFileDialog in View code-behind or VM (follow existing BrowseFolder pattern)
→ BrandingService.SetMspLogoAsync(path)
→ File.ReadAllBytesAsync → Convert.ToBase64String
→ detect MIME from extension (.png → image/png, .jpg/.jpeg → image/jpeg, .gif → image/gif)
→ BrandingRepository.SaveAsync(BrandingSettings)
→ ViewModel refreshes MspLogoPreviewBase64
User runs export (e.g. ExportHtmlCommand in UserAccessAuditViewModel)
→ BrandingService.GetBrandingAsync() → BrandingSettings
→ reads _currentProfile.ClientLogoBase64, _currentProfile.ClientLogoMimeType
→ new ReportBranding(mspBase64, mspMime, clientBase64, clientMime)
→ UserAccessHtmlExportService.BuildHtml(entries, branding)
→ injects <img> data URIs in header when base64 is non-null
→ writes HTML file
```
---
## Feature 2: User Directory Browse Mode
### What It Needs
The existing `UserAccessAuditView` has a people-picker: search box → Graph API `startsWith` filter → autocomplete dropdown → add to `SelectedUsers`. Directory browse mode is an alternative to the search box: show a paginated, filterable list of all tenant users, allow multi-select, bulk-add to `SelectedUsers`.
This is purely additive. The underlying audit logic (`IUserAccessAuditService`, `RunOperationAsync`, `SelectedUsers` collection, export commands) is completely unchanged.
### New Components (create from scratch)
**`Core/Models/PagedUserResult.cs`**
```csharp
public record PagedUserResult(
IReadOnlyList<GraphUserResult> Users,
string? NextPageToken); // null = last page
```
**`Services/IGraphUserDirectoryService.cs`**
```csharp
public interface IGraphUserDirectoryService
{
Task<PagedUserResult> GetUsersPageAsync(
string clientId,
string? filter = null,
string? pageToken = null,
int pageSize = 100,
CancellationToken ct = default);
}
```
### Pattern 2: Multi-Tenant Session Manager
**`Services/GraphUserDirectoryService.cs`**
Reuses `GraphClientFactory` (already injected elsewhere). Calls `graphClient.Users.GetAsync()` without the `startsWith` constraint used in search — uses `$top=100` with cursor-based paging via Graph's `@odata.nextLink`. Returns `PagedUserResult` so callers control pagination. Uses `ConsistencyLevel: eventual` + `$count=true` (same as existing search service).
**What:** A singleton `SessionManager` holds a dictionary of `TenantSession` objects keyed by tenant URL. When the user selects a tenant profile, the session is reused if still valid (MSAL token cache handles token refresh). No re-authentication unless the token is expired and silent refresh fails.
### Modified Components
**When to use:** Every SharePoint service operation resolves `IAuthService.GetSessionAsync(tenantUrl)` before calling PnP Framework.
**`ViewModels/Tabs/UserAccessAuditViewModel.cs`** — Add browse mode state:
**Trade-offs:** MSAL token cache must be persisted across app restarts for seamless reconnect. For interactive login, MSAL `PublicClientApplicationBuilder` with `WithParentActivityOrWindow` is required on Windows to avoid a blank browser window.
**Example:**
```csharp
public class SessionManager
{
private readonly ConcurrentDictionary<string, TenantSession> _sessions = new();
[ObservableProperty] private bool _isBrowseModeActive;
[ObservableProperty] private ObservableCollection<GraphUserResult> _directoryUsers = new();
[ObservableProperty] private string _directoryFilter = string.Empty;
[ObservableProperty] private bool _isLoadingDirectory;
[ObservableProperty] private bool _hasMoreDirectoryPages;
public async Task<TenantSession> GetOrCreateSessionAsync(
TenantProfile profile, CancellationToken ct)
{
if (_sessions.TryGetValue(profile.TenantUrl, out var session)
&& !session.IsExpired)
return session;
private string? _directoryNextPageToken;
var authManager = new PnP.Framework.AuthenticationManager(
profile.ClientId,
openBrowserCallback: url => Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }));
var ctx = await authManager.GetContextAsync(profile.TenantUrl);
var newSession = new TenantSession(profile, ctx, authManager);
_sessions[profile.TenantUrl] = newSession;
return newSession;
}
}
public IAsyncRelayCommand LoadDirectoryCommand { get; }
public IAsyncRelayCommand LoadMoreDirectoryCommand { get; }
public RelayCommand<IList<GraphUserResult>> AddDirectoryUsersCommand { get; }
```
### Pattern 3: IProgress\<T\> + CancellationToken for All Long Operations
`partial void OnIsBrowseModeActiveChanged(bool value)` → when `value == true`, fire `LoadDirectoryCommand` to populate page 1.
**What:** Every service method that calls SharePoint accepts `IProgress<OperationProgress>` and `CancellationToken`. The ViewModel creates `Progress<T>` (which marshals callbacks to the UI thread automatically) and `CancellationTokenSource`.
`partial void OnDirectoryFilterChanged(string value)` → debounce 300ms (same pattern as `OnSearchQueryChanged`), re-fire `LoadDirectoryCommand` with new filter, clear `_directoryNextPageToken`.
**When to use:** All SharePoint service methods. This replaces the PowerShell runspace + timer polling pattern from the existing app.
The `IGraphUserDirectoryService` is added to the constructor. The internal test constructor (currently 3 params) gets a 4-param overload adding the directory service with a null-safe default, or a new explicit test constructor.
**Trade-offs:** `Progress<T>` captures SynchronizationContext on creation — must be created on the UI thread (i.e., inside the ViewModel, not inside the service).
**Example:**
**`App.xaml.cs RegisterServices()`** — Add:
```csharp
// In ViewModel (UI thread context):
var cts = new CancellationTokenSource();
CancelCommand = new RelayCommand(() => cts.Cancel());
var progress = new Progress<OperationProgress>(p => StatusMessage = p.Message);
// In Service (any thread):
public async Task<IList<PermissionEntry>> ScanAsync(
string siteUrl,
CancellationToken ct,
IProgress<OperationProgress> progress)
{
progress.Report(new OperationProgress("Connecting..."));
using var ctx = await _sessionManager.GetOrCreateSessionAsync(..., ct);
// ... recursive scanning ...
ct.ThrowIfCancellationRequested();
progress.Report(new OperationProgress($"Found {results.Count} entries"));
return results;
}
services.AddTransient<IGraphUserDirectoryService, GraphUserDirectoryService>();
```
The `UserAccessAuditViewModel` transient registration picks up the new injection automatically (DI resolves by type).
### Pattern 4: Messenger for Cross-ViewModel Events
**`UserAccessAuditViewModel.OnTenantSwitched`** — Also clear `DirectoryUsers`, reset `_directoryNextPageToken`, `HasMoreDirectoryPages`, `IsLoadingDirectory`.
**What:** Use `CommunityToolkit.Mvvm.Messaging.WeakReferenceMessenger` for decoupled communication between ViewModels (e.g., "tenant switched" notifies all feature VMs to reset state, "log entry added" updates the log panel ViewModel).
**`Views/Tabs/UserAccessAuditView.xaml`** — Add to the top of the left panel:
- Mode toggle: two `RadioButton`s or `ToggleButton`s bound to `IsBrowseModeActive`
- "Search" panel: existing `GroupBox` shown when `IsBrowseModeActive == false`
- "Browse" panel: new `GroupBox` shown when `IsBrowseModeActive == true`, containing:
- Filter `TextBox` bound to `DirectoryFilter`
- `ListView` with `SelectionMode="Extended"` bound to `DirectoryUsers`, `SelectionChanged` handler in code-behind
- "Add Selected" `Button``AddDirectoryUsersCommand`
- "Load more" `Button` shown when `HasMoreDirectoryPages == true``LoadMoreDirectoryCommand`
- Loading indicator (existing `IsSearching` pattern, but for `IsLoadingDirectory`)
- Show/hide panels via `DataTrigger` on `IsBrowseModeActive`
**When to use:** When two ViewModels need to communicate without direct reference (shell ↔ feature VMs, service callbacks ↔ log panel).
**`Views/Tabs/UserAccessAuditView.xaml.cs`** — Add `SelectionChanged` handler to pass `ListView.SelectedItems` (as `IList<GraphUserResult>`) to `AddDirectoryUsersCommand`. Follow the existing `SearchResultsListBox_SelectionChanged` pattern.
**Trade-offs:** Weak references mean recipients must be alive (held by DI container). Don't use for per-request data passing — use method return values for that.
### Data Flow: Directory Browse Mode
### Pattern 5: Dependency Injection via Microsoft.Extensions.Hosting
```
User clicks "Browse" mode toggle
→ IsBrowseModeActive = true
→ OnIsBrowseModeActiveChanged fires LoadDirectoryCommand
→ GraphUserDirectoryService.GetUsersPageAsync(clientId, filter: null, pageToken: null, 100, ct)
→ Graph GET /users?$select=displayName,userPrincipalName,mail&$top=100&$orderby=displayName
→ returns PagedUserResult { Users = [...100 items], NextPageToken = "..." }
→ DirectoryUsers = new collection of returned users
→ HasMoreDirectoryPages = (NextPageToken != null)
→ _directoryNextPageToken = returned token
**What:** Bootstrap the app with `Host.CreateDefaultBuilder()` in `App.xaml.cs`. Register all services, ViewModels, and the main window in the DI container. Use constructor injection everywhere — no service locator anti-pattern.
User types in DirectoryFilter
→ debounce 300ms
→ LoadDirectoryCommand re-fires with filter
→ DirectoryUsers replaced with filtered page 1
**Example:**
```csharp
// App.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
_host = Host.CreateDefaultBuilder()
.ConfigureServices(services =>
{
// Core services (singletons)
services.AddSingleton<ISettingsService, SettingsService>();
services.AddSingleton<ILocalizationService, LocalizationService>();
services.AddSingleton<SessionManager>();
services.AddSingleton<IAuthService, AuthService>();
services.AddSingleton<IDialogService, DialogService>();
User selects users in ListView + clicks "Add Selected"
→ AddDirectoryUsersCommand(selectedItems)
→ for each: if not already in SelectedUsers by UPN → SelectedUsers.Add(user)
// Feature services (transient — no shared state)
services.AddTransient<IPermissionsService, PermissionsService>();
services.AddTransient<IStorageService, StorageService>();
services.AddTransient<ISearchService, SearchService>();
// ViewModels
services.AddTransient<MainWindowViewModel>();
services.AddTransient<PermissionsViewModel>();
services.AddTransient<StorageViewModel>();
// Views
services.AddSingleton<MainWindow>();
})
.Build();
_host.Start();
var mainWindow = _host.Services.GetRequiredService<MainWindow>();
mainWindow.DataContext = _host.Services.GetRequiredService<MainWindowViewModel>();
mainWindow.Show();
}
User clicks "Load more"
→ LoadMoreDirectoryCommand
→ GetUsersPageAsync(clientId, currentFilter, _directoryNextPageToken, 100, ct)
→ DirectoryUsers items appended (not replaced)
→ _directoryNextPageToken updated
```
---
## Data Flow
## Component Boundary Summary
### SharePoint Operation Request Flow
### New Components (create)
```
User clicks "Run" button
View command binding triggers AsyncRelayCommand.ExecuteAsync()
ViewModel validates inputs → creates CancellationTokenSource + Progress<T>
ViewModel calls IFeatureService.ScanAsync(params, ct, progress)
Service calls SessionManager.GetOrCreateSessionAsync(profile, ct)
SessionManager checks cache → reuses token or triggers interactive login
Service executes PnP Framework / Graph SDK calls (async, awaited)
Service reports incremental progress → Progress<T>.Report() → UI thread
Service returns result collection to ViewModel
ViewModel updates ObservableCollection → WPF binding refreshes DataGrid
ViewModel sets IsRunning = false → progress overlay hides
```
| Component | Layer | Type | Purpose |
|-----------|-------|------|---------|
| `BrandingSettings` | Core/Models | class | MSP logo storage (base64 + MIME type) |
| `ReportBranding` | Core/Models | record | Data passed to `BuildHtml` overloads at export time |
| `BrandingRepository` | Infrastructure/Persistence | class | JSON load/save for `BrandingSettings` |
| `BrandingService` | Services | class | Orchestrates logo file read / MIME detect / base64 convert / save |
| `PagedUserResult` | Core/Models | record | Page of `GraphUserResult` items + next-page token |
| `IGraphUserDirectoryService` | Services | interface | Contract for paginated tenant user enumeration |
| `GraphUserDirectoryService` | Services | class | Graph API user listing with cursor pagination |
### Authentication & Session Flow
Total new files: 7
```
User selects tenant profile from dropdown
MainWindowViewModel calls SessionManager.SetActiveProfile(profile)
SessionManager publishes TenantChangedMessage via WeakReferenceMessenger
All feature ViewModels receive message → reset their state/results
On first operation: SessionManager.GetOrCreateSessionAsync()
[Cache hit: token valid] → return existing ClientContext immediately
[Cache miss / expired] → PnP AuthManager.GetContextAsync()
MSAL silent token refresh attempt
[Silent fails] → open browser for interactive login
User authenticates → token cached by MSAL
ClientContext returned to caller
```
### Modified Components (extend)
### Report Export Flow
| Component | Change | Risk |
|-----------|--------|------|
| `TenantProfile` | + 2 nullable logo props | LOW — JSON backward-compatible |
| `HtmlExportService` | + optional `ReportBranding?` on 2 overloads | LOW — optional param, existing callers unaffected |
| `UserAccessHtmlExportService` | + optional `ReportBranding?` | LOW |
| `StorageHtmlExportService` | + optional `ReportBranding?` on 2 overloads | LOW |
| `SearchHtmlExportService` | + optional `ReportBranding?` | LOW |
| `DuplicatesHtmlExportService` | + optional `ReportBranding?` | LOW |
| `PermissionsViewModel` | + inject `BrandingService`, use in ExportHtmlAsync | LOW |
| `UserAccessAuditViewModel` | + inject `BrandingService` + `IGraphUserDirectoryService`, browse mode state/commands | MEDIUM |
| `StorageViewModel` | + inject `BrandingService`, use in ExportHtmlAsync | LOW |
| `SearchViewModel` | + inject `BrandingService`, use in ExportHtmlAsync | LOW |
| `DuplicatesViewModel` | + inject `BrandingService`, use in ExportHtmlAsync | LOW |
| `SettingsViewModel` | + inject `BrandingService`, MSP logo commands + preview property | LOW |
| `ProfileManagementViewModel` | + client logo browse/preview/clear | LOW |
| `SettingsView.xaml` | + branding section with logo preview + buttons | LOW |
| `ProfileManagementDialog.xaml` | + client logo fields | LOW |
| `UserAccessAuditView.xaml` | + mode toggle + browse panel in left column | MEDIUM |
| `App.xaml.cs RegisterServices()` | + 3 new registrations | LOW |
```
Service returns List<TModel> to ViewModel
User clicks "Export CSV" or "Export HTML"
ViewModel calls IReportExportService.ExportAsync(results, format, outputPath)
ReportExportService generates file (string building, no blocking I/O on UI thread)
ViewModel calls IDialogService.OpenFile(outputPath) to auto-open result
```
### State Management
```
AppState (DI-managed singletons):
SessionManager → active profile, tenant sessions dict
SettingsService → user prefs, data folder, profiles list
LocalizationService → current language, translation dict
Per-Operation State (ViewModel-local):
ObservableCollection<T> → bound to DataGrid
CancellationTokenSource → cancel button binding
IsRunning (bool) → progress overlay binding
StatusMessage (string) → progress label binding
```
Total modified files: 17
---
## Component Boundaries
## Build Order (Dependency-Aware)
### What Communicates With What
The two features are independent of each other. Phases can run in parallel if worked by two developers; solo they should follow top-to-bottom order.
| Boundary | Communication Method | Direction | Notes |
|----------|---------------------|-----------|-------|
| View ↔ ViewModel | WPF data binding (two-way for inputs, one-way for results) | Both | No code-behind |
| ViewModel ↔ Service | Constructor-injected interface, async method call | VM → Service | Services return Task\<T\> |
| ViewModel ↔ ViewModel | WeakReferenceMessenger messages | Broadcast | Tenant switch, log events |
| Service ↔ SessionManager | `GetOrCreateSessionAsync()` | Service → SessionMgr | Every SharePoint call |
| SessionManager ↔ PnP Framework | `AuthenticationManager.GetContextAsync()` | SessionMgr → PnP | On cache miss only |
| Service ↔ Graph SDK | `GraphServiceClient` method calls | Service → Graph | For Graph-only operations |
| SettingsService ↔ FileSystem | `System.Text.Json` + `File.ReadAllText/WriteAllText` | Both | Async I/O |
| LocalizationService ↔ Views | XAML binding to translated string properties | Service → View | Via singleton binding |
### Phase A — Data Models (no dependencies)
1. `Core/Models/BrandingSettings.cs` (new)
2. `Core/Models/ReportBranding.cs` (new)
3. `Core/Models/PagedUserResult.cs` (new)
4. `Core/Models/TenantProfile.cs` — add nullable logo props (modification)
### What Must NOT Cross Boundaries
All files are POCOs/records. Unit-testable in isolation. No risk.
- Views must not call services directly — all via ViewModel commands
- Services must not reference any WPF types (`System.Windows.*`) — use `IProgress<T>` for UI feedback
- ViewModels must not instantiate `ClientContext` or `AuthenticationManager` directly — only via `IAuthService`
- SessionManager is the only class that holds `ClientContext` objects — services receive them per-operation
### Phase B — Persistence + Service Layer
5. `Infrastructure/Persistence/BrandingRepository.cs` (new) — depends on BrandingSettings
6. `Services/BrandingService.cs` (new) — depends on BrandingRepository
7. `Services/IGraphUserDirectoryService.cs` (new) — depends on PagedUserResult
8. `Services/GraphUserDirectoryService.cs` (new) — depends on GraphClientFactory (already exists)
Unit tests for BrandingService (mock repository) and GraphUserDirectoryService (mock Graph client) can be written at this phase.
### Phase C — HTML Export Service Extensions
9. All 5 `Services/Export/*HtmlExportService.cs` modifications — add optional `ReportBranding?` param
These are independent of each other. Tests: verify that passing `null` branding produces identical HTML to current output (regression), and that passing a branding record injects the expected `<img>` tags.
### Phase D — ViewModel Integration (branding)
10. `SettingsViewModel.cs` — add MSP logo commands + preview
11. `ProfileManagementViewModel.cs` — add client logo commands + preview
12. `PermissionsViewModel.cs` — add BrandingService injection, use in ExportHtmlAsync
13. `StorageViewModel.cs` — same
14. `SearchViewModel.cs` — same
15. `DuplicatesViewModel.cs` — same
16. `App.xaml.cs` — register BrandingRepository, BrandingService
Steps 12-15 follow an identical pattern and can be batched together.
### Phase E — ViewModel Integration (directory browse)
17. `UserAccessAuditViewModel.cs` — add IGraphUserDirectoryService injection, browse mode state/commands
Note: UserAccessAuditViewModel also gets BrandingService at this phase (from Phase D pattern). Do both together to avoid touching the constructor twice.
### Phase F — View Layer (branding UI)
18. `SettingsView.xaml` — add MSP branding section
19. `ProfileManagementDialog.xaml` — add client logo fields
Requires a base64-to-BitmapSource `IValueConverter` (add to `Views/Converters/`). This is a common WPF pattern — implement once, reuse in both views.
### Phase G — View Layer (directory browse UI)
20. `UserAccessAuditView.xaml` — add mode toggle + browse panel
21. `UserAccessAuditView.xaml.cs` — add SelectionChanged handler for directory ListView
This is the highest-risk UI change: the left panel is being restructured. Do this last, after all ViewModel behavior is proven by unit tests.
---
## Build Order (Dependency Graph)
## Anti-Patterns to Avoid
The following reflects the order components can be built because later items depend on earlier ones:
### Storing Logo Images as Separate Files
**Why bad:** Breaks the single-data-folder design. Reports become non-self-contained if they reference external paths. Atomic save semantics break.
**Instead:** Base64-encode into JSON. Logo thumbnails are typically 10-200KB. Base64 overhead (~33%) is negligible.
```
Phase 1: Foundation
└── Core/Models/* (no dependencies)
└── Core/Interfaces/* (no dependencies)
└── Core/Exceptions/* (no dependencies)
### Adding an `IHtmlExportService` Interface Just for Branding
**Why bad:** The existing pattern is 5 concrete classes with no interfaces, consumed directly by ViewModels. Adding an interface for a parameter change creates ceremony without value.
**Instead:** Add `ReportBranding? branding = null` as optional parameter. Existing callers compile unchanged.
Phase 2: Infrastructure Services
└── SettingsService (depends on Core models)
└── LocalizationService (depends on lang files)
└── DialogService (depends on WPF — implement last in phase)
└── AuthService / SessionManager (depends on PnP Framework NuGet)
### Loading All Tenant Users at Once
**Why bad:** Enterprise tenants regularly have 20,000-100,000 users. A full load blocks the UI for 30+ seconds and allocates hundreds of MB.
**Instead:** `PagedUserResult` pattern — page 1 on mode toggle, "Load more" button, server-side filter applied to DirectoryFilter text.
Phase 3: Feature Services (depend on Auth + Core)
└── PermissionsService
└── StorageService
└── SearchService
└── TemplateService
└── DuplicateService
└── BulkOpsService
### Async in ViewModel Constructor
**Why bad:** DI constructs ViewModels synchronously on the UI thread. Async work in constructors requires fire-and-forget which loses exceptions.
**Instead:** `partial void OnIsBrowseModeActiveChanged` fires `LoadDirectoryCommand` when browse mode activates. Constructor only wires up commands and state.
Phase 4: Reporting (depends on Feature Services output models)
└── HtmlReportService
└── CsvExportService
### Client Logo in `AppSettings` or `BrandingSettings`
**Why bad:** Client logos are per-tenant. `AppSettings` and `BrandingSettings` are global. Mixing them makes per-profile deletion awkward and serialization structure unclear.
**Instead:** `ClientLogoBase64` + `ClientLogoMimeType` directly on `TenantProfile` (serialized in `profiles.json`). MSP logo goes in `branding.json` via `BrandingRepository`.
Phase 5: ViewModels (depend on service interfaces)
└── MainWindowViewModel (shell, nav, tenant selector)
└── Feature ViewModels (Permissions, Storage, Search, Templates, Duplicates, BulkOps)
└── SettingsViewModel
Phase 6: Views + App Bootstrap (depend on ViewModels + DI)
└── XAML Views (bind to ViewModels)
└── Controls (TenantSelector, LogPanel, Charts)
└── App.xaml.cs DI container wiring
```
### Changing `BuildHtml` Signatures to Required Parameters
**Why bad:** All 5 HTML export services currently have callers without branding. Making the parameter required is a breaking change forcing simultaneous updates across 5 VMs.
**Instead:** `ReportBranding? branding = null` is optional. Inject only where branding is desired. Existing call sites remain unchanged.
---
## Scaling Considerations
## Scalability Considerations
This is a local desktop tool with a single user. "Scaling" means handling larger SharePoint tenants, not more users.
| Concern | Approach |
|---------|----------|
| Large site collections (1000+ sites) | Async streaming with early cancellation; paginated PnP calls; virtual DataGrid |
| Deep permission hierarchies | Configurable scan depth; user can limit scope to top-level only |
| Large file search results | Server-side KQL filtering first, client-side regex only as secondary pass |
| Multiple simultaneous operations | Each ViewModel has its own CancellationTokenSource; operations are isolated |
| Session token expiry during long scan | MSAL silent refresh + retry on 401; surface error to user if re-auth needed |
---
## Anti-Patterns
### Anti-Pattern 1: `Dispatcher.Invoke` in Services
**What people do:** Call `Application.Current.Dispatcher.Invoke()` inside service classes to update UI state.
**Why it's wrong:** Couples service layer to WPF, makes services untestable, causes deadlocks if called from wrong thread.
**Do this instead:** Service accepts `IProgress<T>` parameter. `Progress<T>` marshals to UI thread automatically via the captured SynchronizationContext.
### Anti-Pattern 2: Giant "God ViewModel"
**What people do:** Create one MainViewModel with all feature logic, mirroring the monolithic PowerShell script.
**Why it's wrong:** Replicates the exact problem being solved. Hard to navigate, hard to test, merge conflicts on every change.
**Do this instead:** One ViewModel per feature tab. MainWindowViewModel owns only shell navigation, active tenant, and log state.
### Anti-Pattern 3: Storing ClientContext as a Long-Lived Static
**What people do:** Cache `ClientContext` in a static field for reuse.
**Why it's wrong:** `ClientContext` is not thread-safe and has an auth token that expires. Static makes it impossible to manage per-tenant.
**Do this instead:** `SessionManager` manages ClientContext lifetime. Services request a context per operation. PnP Framework handles token refresh.
### Anti-Pattern 4: Blocking Async on Sync Context
**What people do:** Call `.Result` or `.Wait()` on Tasks inside WPF event handlers to avoid `async void`.
**Why it's wrong:** Deadlocks the WPF SynchronizationContext. The UI freezes permanently.
**Do this instead:** Use `async void` only for top-level event handlers (acceptable in WPF), or bind all user actions to `AsyncRelayCommand`.
### Anti-Pattern 5: Silent Catch Blocks (porting the existing bug)
**What people do:** Wrap PnP calls in `catch {}` or `catch { /* ignore */ }` to prevent crashes.
**Why it's wrong:** The existing PowerShell app has 38 such blocks — they produce silent failures, missing data, and phantom "success" states.
**Do this instead:** Catch specific exceptions (`SharePointException`, `MicrosoftIdentityException`). Log with full stack trace via `ILogger`. Surface user-visible error message via ViewModel's `ErrorMessage` property.
---
## Integration Points
### External Services
| Service | Integration Pattern | Library | Notes |
|---------|---------------------|---------|-------|
| SharePoint Online (CSOM) | PnP Framework `ClientContext` | `PnP.Framework` NuGet | Use for permissions, storage, templates, bulk ops |
| SharePoint Search | PnP Framework `SearchRequest` | `PnP.Framework` NuGet | KQL queries; paginated |
| Microsoft Graph | `GraphServiceClient` | `Microsoft.Graph` NuGet | Use for user/group lookups, Teams data |
| Azure AD / MSAL | `PublicClientApplication` via PnP `AuthenticationManager` | Built into `PnP.Framework` | Interactive browser login; token cache callback |
| WPF Charts | `LiveCharts2` or `OxyPlot.Wpf` | NuGet | Storage metrics visualization; LiveCharts2 preferred for richer WPF binding |
### Internal Boundaries
| Boundary | Communication | Notes |
|----------|---------------|-------|
| SessionManager ↔ Feature Services | `TenantSession` passed per operation | Services do not store sessions |
| LocalizationService ↔ XAML | Singleton bound via `StaticResource`; properties fire `INotifyPropertyChanged` on language switch | All UI text goes through this |
| ReportExportService ↔ ViewModels | Called after operation completes; returns file path | Self-contained HTML with embedded JS/CSS |
| SettingsService ↔ all singletons | Read at startup; written on change | JSON format must match existing `Sharepoint_Settings.json` schema for migration |
| Concern | Impact | Mitigation |
|---------|--------|------------|
| Logo storage size in JSON | PNG logos base64-encoded: 10-200KB per logo. `profiles.json` grows by at most that per tenant | Acceptable — config files, not bulk data |
| HTML report file size | +2-10KB per logo (base64 inline) | Negligible — reports are already 100-500KB |
| Directory browse load time | 100-user pages from Graph: ~200-500ms per page | Loading indicator, pagination. Acceptable UX. |
| Large tenants (50k+ users) | Full load would take minutes and exceed memory budgets | Pagination via `PagedUserResult` prevents this entirely |
| ViewModel constructor overhead | BrandingService adds one lazy JSON read at first export | Not at construction — no startup impact |
---
## Sources
- [Introduction to MVVM Toolkit - Microsoft Learn](https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/) — HIGH confidence
- [AsyncRelayCommand - CommunityToolkit](https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/asyncrelaycommand) — HIGH confidence
- [PnP Framework AuthenticationManager API](https://pnp.github.io/pnpframework/api/PnP.Framework.AuthenticationManager.html) — HIGH confidence
- [PnP Framework Getting Started](https://pnp.github.io/pnpframework/using-the-framework/readme.html) — HIGH confidence
- [Acquire and cache tokens with MSAL - Microsoft Learn](https://learn.microsoft.com/en-us/entra/identity-platform/msal-acquire-cache-tokens) — HIGH confidence
- [WPF Development Best Practices 2024 - MESCIUS](https://medium.com/mesciusinc/wpf-development-best-practices-for-2024-9e5062c71350) — MEDIUM confidence
- [Modern WPF Development: MVVM and Prism - Einfochips](https://www.einfochips.com/blog/modern-wpf-development-leveraging-mvvm-and-prism-for-enterprise-app/) — MEDIUM confidence
- [Async Programming Patterns for MVVM - Microsoft Learn](https://learn.microsoft.com/en-us/archive/msdn-magazine/2014/april/async-programming-patterns-for-asynchronous-mvvm-applications-commands) — HIGH confidence
All findings are based on direct inspection of the codebase at `C:/Users/dev/Documents/projets/Sharepoint/SharepointToolbox/`. No external research needed — this is an integration architecture document for a known codebase.
---
*Architecture research for: C#/WPF SharePoint Online administration desktop tool*
*Researched: 2026-04-02*
Key files examined:
- `Core/Models/TenantProfile.cs`, `AppSettings.cs`
- `Infrastructure/Persistence/ProfileRepository.cs`, `SettingsRepository.cs`
- `Infrastructure/Auth/GraphClientFactory.cs`
- `Services/SettingsService.cs`, `ProfileService.cs`
- `Services/GraphUserSearchService.cs`, `IGraphUserSearchService.cs`
- `Services/Export/HtmlExportService.cs`, `UserAccessHtmlExportService.cs`, `StorageHtmlExportService.cs`
- `ViewModels/FeatureViewModelBase.cs`, `MainWindowViewModel.cs`
- `ViewModels/Tabs/UserAccessAuditViewModel.cs`, `SettingsViewModel.cs`
- `Views/Tabs/UserAccessAuditView.xaml`, `SettingsView.xaml`
- `App.xaml.cs`

View File

@@ -1,192 +1,211 @@
# Feature Research
# Feature Landscape
**Domain:** SharePoint Online administration and auditing desktop tool (MSP / IT admin)
**Researched:** 2026-04-02
**Confidence:** MEDIUM (competitive landscape from web sources; no Context7 for SaaS tools; Microsoft docs HIGH confidence)
**Domain:** MSP IT admin desktop tool — SharePoint audit report branding + user directory browse
**Milestone:** v2.2 — Report Branding & User Directory
**Researched:** 2026-04-08
**Overall confidence:** HIGH (verified via official Graph API docs + direct codebase inspection)
## Feature Landscape
---
### Table Stakes (Users Expect These)
## Scope Boundary
Features that IT admins and MSPs assume exist in any SharePoint admin tool. Missing these makes the product feel broken or incomplete.
This file covers only the two net-new features in v2.2:
1. HTML report branding (MSP logo + client logo per tenant)
2. User directory browse mode in the user access audit tab
Everything else is already shipped. Dependencies on existing code are called out explicitly.
---
## Feature 1: HTML Report Branding
### Table Stakes
Features an MSP admin expects without being asked. If missing, the reports feel unfinished and
unprofessional to hand to a client.
| Feature | Why Expected | Complexity | Notes |
|---------|--------------|------------|-------|
| Permissions report (site-level) | Every audit tool has this; admins must prove who has access where | MEDIUM | Must show owners, members, guests, external users, and broken inheritance |
| Export to CSV | Standard workflow — admins paste into tickets, compliance reports, Excel | LOW | Already in current app; keep for all reports |
| Multi-site permissions scan | Admins manage dozens of sites; per-site-only scan is unusable at scale | HIGH | Requires batching Graph API calls; throttling management needed |
| Storage metrics per site | Native M365 admin center only shows tenant-level; per-site is expected | MEDIUM | Already in current app; retain and improve |
| Interactive login / Azure AD OAuth | No client secret storage expected; browser-based auth is the norm | MEDIUM | Already implemented; new version adds session caching |
| Site template management | Re-using structure across client sites is a core MSP workflow | MEDIUM | Already in current app; port to C# |
| File search across sites | Finding content across a tenant is a day-1 admin task | MEDIUM | Already in current app; Graph driveItem search |
| Bulk operations (user add/remove, site creation) | Manual one-by-one is unacceptable at MSP scale | HIGH | Already in current app; async required to avoid UI freeze |
| Error reporting (not silent failures) | Admins need to know when scans fail partially | LOW | Current app has 38 silent catch blocks — critical fix |
| Localization (EN + FR) | Already exists; removing it would break existing users | LOW | Key-based translation system already in place |
| Export to interactive HTML | Shareable reports without requiring recipients to have the tool | MEDIUM | Already in current app; retain embedded JS for sorting/filtering |
| MSP global logo in report header | Every white-label MSP tool shows the MSP's own brand on deliverables | Low | Single image stored in AppSettings or a dedicated branding settings section |
| Client (per-tenant) logo in report header | MSP reports are client-facing; client should see their own logo next to the MSP's | Medium | Stored in TenantProfile; 2 sources: import from file or pull from tenant |
| Logo renders in self-contained HTML (no external URL) | Reports are often emailed or archived; external URLs break offline | Low | Base64-encode and embed as `data:image/...;base64,...` inline in `<img src=` |
| Logo graceful absence (no logo configured = no broken image) | Admins will run the tool before configuring logos | Trivial | Conditional render — omit the `<img>` block entirely when no logo is set |
| Consistent placement across all HTML export types | App already ships 5+ HTML exporters; logos must appear in all of them | Medium | Extract a shared header-builder method or inject a branding context into each export service |
### Differentiators (Competitive Advantage)
### Differentiators
Features that are not universally provided, or are done poorly by competitors, where this tool can create genuine advantage.
Features not expected by default, but add meaningful value once table stakes are covered.
| Feature | Value Proposition | Complexity | Notes |
|---------|-------------------|------------|-------|
| Multi-tenant session caching | MSPs switch between 10-30 client tenants daily; re-auth per client wastes 2-3 min each | HIGH | Token cache per tenant profile; MSAL token cache serialization; core MSP differentiator |
| User access export across selected sites | "Show me everything User X can access across these 15 sites" — native M365 can't do this for arbitrary site subsets | HIGH | Requires enumerating group memberships, direct assignments, and inherited access across n sites; high Graph API volume |
| Simplified permissions view (plain language) | Compliance reports today require admins to translate "Contribute" to "can edit files" — untrained staff can't read them | MEDIUM | Jargon-free labels, summary counts, color coding; configurable detail level |
| Storage graph by file type (pie + bar toggle) | Native admin center shows totals only; file-type breakdown identifies what's consuming quota (videos, backups, etc.) | MEDIUM | Requires Graph driveItem enumeration with file extension grouping; recharts-style WPF chart control |
| Duplicate file detection | Reduces storage waste; no native Microsoft tool provides this simply | HIGH | Hash-based (SHA256/MD5) or name+size matching; large tenant = Graph throttling challenge |
| Folder structure provisioning | Create standardized folder trees on new sites from a template — critical for MSPs onboarding clients | MEDIUM | Already in current app; differentiating because competitors (ShareGate) don't focus on this |
| Offline profile / tenant registry | Store tenant URLs, display names, notes locally — instant context switching without re-entering URLs | LOW | JSON-backed, local only — simple but missing from all SaaS tools by design |
| Operation progress and cancellation | SaaS tools run jobs server-side; desktop tool must show real-time progress and allow cancel mid-scan | MEDIUM | CancellationToken throughout async operations; progress reporting via IProgress<T> |
| Auto-pull client logo from Microsoft Entra tenant branding | Zero-config for tenants that already have a banner logo set in Entra ID | Medium | Graph API: `GET /organization/{id}/branding/localizations/default/bannerLogo` returns raw image bytes. Least-privileged scope is `User.Read` (delegated, already in use). Returns empty body or 404 when not configured — must handle gracefully. |
| Report timestamp and tenant display name in header | Contextualizes archived reports without needing to inspect the filename | Low | TenantProfile.TenantUrl already available; display name derivable from domain |
### Anti-Features (Commonly Requested, Often Problematic)
### Anti-Features
Features that seem valuable but create disproportionate complexity, maintenance burden, or scope creep for this tool's purpose.
Do not build these. They add scope without proportionate MSP value.
| Feature | Why Requested | Why Problematic | Alternative |
|---------|---------------|-----------------|-------------|
| Permission change alerts / real-time monitoring | Admins want to know when permissions change | Requires persistent background service, webhook registration in Azure, certificate lifecycle management — turns a desktop tool into a service | Run scheduled audit scans manually or via Windows Task Scheduler; export diffs between runs |
| Automated remediation (auto-revoke permissions) | "Fix it for me" saves time | One wrong rule destroys access for a client's entire org; liability risk; requires undo capability and audit trail that equals a full compliance system | Surface recommendations, let admin click to apply one at a time |
| SQLite or database storage | Faster queries on large datasets | Adds install dependency, schema migration complexity, and breaks the "single EXE" distribution model | JSON with chunked loading; lazy evaluation; paginated display |
| Cloud sync / shared tenant registry | Team of admins sharing tenant configs | Requires auth system, conflict resolution, server infrastructure — out of scope for local tool | Export/import JSON profiles; share config files manually |
| AI-powered governance recommendations | Microsoft is adding this to native admin center (SharePoint Admin Agent, Copilot-licensed) | Requires Copilot license, Graph calls with high latency, and competes directly with Microsoft's own roadmap | Focus on raw data accuracy and export quality; let Microsoft handle AI summaries |
| Cross-platform (Mac/Linux) support | Some admins use Macs | WPF is Windows-only; rewrite to MAUI/Avalonia is a full project — not justified for current user base | Confirmed out of scope in PROJECT.md |
| Version history management / rollback | Admins sometimes need to see version bloat | Version management is a deep separate problem; Graph API pagination for versions is complex and slow at scale | Surface version storage totals in storage metrics; flag libraries with high version counts |
| SharePoint content migration | Admins ask to move content between tenants or sites | Migration is a fully separate product category (ShareGate, AvePoint); competing here is a multi-year investment | Refer to ShareGate or native SharePoint migration for content moves |
| Anti-Feature | Why Avoid | What to Do Instead |
|--------------|-----------|-------------------|
| Color theme / CSS customization per tenant | Complexity explodes per-tenant CSS is a design system problem, not an admin tool feature | Stick to a single professional neutral theme; logo is sufficient branding |
| PDF export with embedded logo | PDF generation requires a third-party library (iTextSharp, QuestPDF, etc.) adding binary size to the 200 MB EXE | Document in release notes that users can print-to-PDF from browser |
| Animated or SVG logo support | MIME handling complexity; SVG in data-URIs introduces XSS risk | Support PNG/JPG/GIF only; reject SVG at import time |
| Logo URL field (hotlinked) | Reports break when URL becomes unavailable; creates external dependency for a local-first tool | Force file import with base64 embedding |
## Feature Dependencies
### Feature Dependencies
```
Multi-tenant session caching
└──requires──> Tenant profile registry (JSON-backed)
└──required by──> All features (auth gate)
User access export across selected sites
└──requires──> Multi-site permissions scan
└──requires──> Multi-tenant session caching
Simplified permissions view
└──enhances──> Permissions report (site-level)
└──enhances──> User access export across selected sites
Storage graph by file type
└──requires──> Storage metrics per site
└──requires──> Graph driveItem enumeration (file extension data)
Duplicate file detection
└──requires──> File search across sites (file enumeration infrastructure)
└──conflicts──> Automated remediation (deletion without undo = data loss risk)
Bulk operations
└──requires──> Operation progress and cancellation
└──requires──> Error reporting (not silent failures)
Export (CSV / HTML)
└──enhances──> All report features
└──required by──> Compliance audit workflows
Folder structure provisioning
└──requires──> Site template management
AppSettings + MspLogoBase64 (string?, nullable)
TenantProfile + ClientLogoBase64 (string?, nullable)
+ ClientLogoSource (enum: None | Imported | AutoPulled)
Shared branding helper → called by HtmlExportService, UserAccessHtmlExportService,
StorageHtmlExportService, DuplicatesHtmlExportService,
SearchHtmlExportService
Auto-pull code path → Graph API call via existing GraphClientFactory
Logo import UI → WPF OpenFileDialog -> File.ReadAllBytes -> Convert.ToBase64String
-> stored in profile JSON via existing ProfileRepository
```
### Dependency Notes
**Key existing code note:** All 5+ HTML export services currently build their `<body>` independently
with no shared header. Branding requires one of:
- (a) a `ReportBrandingContext` record passed into each exporter's `BuildHtml` method, or
- (b) a `HtmlReportHeaderBuilder` static/injectable helper all exporters call.
- **Multi-tenant session caching requires Tenant profile registry:** Without a registry of tenant URLs and display names, the session cache has nothing to key against. The tenant profile JSON must exist before any feature can authenticate.
- **User access export requires multi-site permissions scan:** The "all accesses for user X" feature is essentially a filtered multi-site permissions scan. The scanning infrastructure must exist first.
- **Simplified permissions view enhances reports:** This is a presentation layer on top of raw permissions data — it cannot exist without the underlying data model.
- **Storage graph by file type requires Graph driveItem enumeration:** The native Graph storage reports do not include file type breakdown. This requires enumerating files with their extensions, which is a heavier Graph operation than summary-only calls.
- **Duplicate detection requires file enumeration infrastructure:** The file search feature already enumerates files; duplicate detection reuses that path but adds hash computation or name+size matching on top.
- **Bulk operations require cancellation support:** Long-running bulk operations that cannot be cancelled will freeze or force-kill the app. CancellationToken must be threaded through before bulk ops are exposed to users.
- **Duplicate detection conflicts with automated remediation:** Surfacing duplicates is safe; auto-deleting them without undo is not. Keep these concerns separate.
Option (b) is lower risk — it does not change method signatures that existing unit tests already call.
## MVP Definition
### Complexity Assessment
### Launch With (v1)
| Sub-task | Complexity | Reason |
|----------|------------|--------|
| AppSettings + TenantProfile model field additions | Low | Trivial nullable-string fields; JSON serialization already in place |
| Settings UI: MSP logo upload + preview | Low | WPF OpenFileDialog + BitmapImage from base64, standard pattern |
| ProfileManagementDialog: client logo upload per tenant | Low | Same pattern as MSP logo |
| Shared HTML header builder with logo injection | Low-Medium | One helper; replaces duplicated header HTML in 5 exporters |
| Auto-pull from Entra `bannerLogo` endpoint | Medium | Async Graph call; must handle 404, empty stream, no branding configured |
| Localization keys EN/FR for new labels | Low | ~6-10 new keys; 220+ already managed |
Minimum viable product — sufficient to replace the existing PowerShell tool completely.
---
- [ ] Tenant profile registry with multi-tenant session caching — without this, no feature works
- [ ] Permissions report (site-level) with CSV + HTML export — core audit use case
- [ ] Storage metrics per site — currently used daily
- [ ] File search across sites — currently used daily
- [ ] Bulk operations (member add, site creation, transfer) with progress + cancel — currently used; async required
- [ ] Site template management — core MSP provisioning workflow
- [ ] Folder structure provisioning — paired with templates
- [ ] Duplicate file detection — currently used for storage cleanup
- [ ] Error reporting (no silent failures) — current app's biggest reliability issue
- [ ] Localization (EN/FR) — existing users depend on this
## Feature 2: User Directory Browse Mode
### Add After Validation (v1.x)
### Table Stakes
Features to add once core parity is confirmed working.
Features an admin expects when a "browse all users" mode is offered alongside the existing search.
- [ ] User access export across selected sites — new feature; high value for MSP audits; add once multi-site scan is stable
- [ ] Simplified permissions view (plain language) — presentation enhancement; add after raw data model is solid
- [ ] Storage graph by file type (pie + bar toggle) — visualization enhancement on top of existing storage metrics
| Feature | Why Expected | Complexity | Notes |
|---------|--------------|------------|-------|
| Full directory listing (all member users, paginated) | Browse implies seeing everyone, not just name-search hits | Medium | Graph `GET /users` with `$top=100`, follow `@odata.nextLink` until null. Max page size is 999 but 100 pages give better progress feedback |
| Searchable/filterable within the loaded list | Once loaded, admins filter locally without re-querying | Low | In-memory filter on DisplayName, UPN, Mail — same pattern used in PermissionsView DataGrid |
| Sortable columns (Name, UPN) | Standard expectation for any directory table | Low | WPF DataGrid column sorting, already used in other tabs |
| Select user from list to run access audit | The whole point — browse replaces the people-picker for users the admin cannot spell | Low | Bind selected item; reuse the existing IUserAccessAuditService pipeline unchanged |
| Loading indicator with progress count | Large tenants (5k+ users) take several seconds to page through | Low | Existing OperationProgress pattern; show "Loaded X users..." counter |
| Toggle between Browse mode and Search (people-picker) mode | Search is faster for known users; browse is for discovery | Low | RadioButton or ToggleButton in the tab toolbar; visibility-toggle two panels |
### Future Consideration (v2+)
### Differentiators
Features to defer until product-market fit is established.
| Feature | Value Proposition | Complexity | Notes |
|---------|-------------------|------------|-------|
| Filter by account type (member vs guest) | MSPs care about guest proliferation; helps scope audit targets | Low | Graph returns `userType` field; add a toggle filter. Include in `$select` |
| Department / Job Title columns | Helps identify the right user in large tenants with common names | Low-Medium | Include `department`, `jobTitle` in `$select`; optional columns in DataGrid |
| Session-scoped directory cache | Avoids re-fetching full tenant list on every tab visit | Medium | Store list in ViewModel or session-scoped service; invalidate on TenantSwitchedMessage |
- [ ] Scheduled scan runs via Windows Task Scheduler integration — requires stable CLI/headless mode first
- [ ] Permission comparison between two points in time (diff report) — useful for compliance but requires snapshot storage
- [ ] Export to XLSX (full Excel format, not just CSV) — requested but not critical; CSV opens in Excel adequately
### Anti-Features
## Feature Prioritization Matrix
| Anti-Feature | Why Avoid | What to Do Instead |
|--------------|-----------|-------------------|
| Eager load on tab open | Large tenants (10k+ users) block UI and risk Graph throttling on every tab navigation | Lazy-load on explicit "Load Directory" button click; show a clear affordance |
| Delta query / incremental sync | Delta queries are for maintaining a local replica over time; wrong pattern for a one-time audit session | Single paginated GET per session; add a Refresh button |
| Multi-user bulk select for simultaneous audit | The audit pipeline is per-user by design; multi-user requires a fundamentally different results model | Out of scope; single-user selection only |
| Export the user directory to CSV | That is an identity reporting feature (AdminDroid et al.), not an access audit feature | Out of scope for this milestone |
| Show disabled accounts by default | Disabled users do not have active SharePoint access; pollutes the list for audit purposes | Default `$filter=accountEnabled eq true`; optionally expose a toggle |
| Feature | User Value | Implementation Cost | Priority |
|---------|------------|---------------------|----------|
| Tenant profile registry + session caching | HIGH | MEDIUM | P1 |
| Permissions report (site-level) | HIGH | MEDIUM | P1 |
| Storage metrics per site | HIGH | MEDIUM | P1 |
| File search across sites | HIGH | MEDIUM | P1 |
| Bulk operations with progress/cancel | HIGH | HIGH | P1 |
| Error reporting (no silent failures) | HIGH | LOW | P1 |
| Site template management | HIGH | MEDIUM | P1 |
| Folder structure provisioning | MEDIUM | MEDIUM | P1 |
| Duplicate file detection | MEDIUM | HIGH | P1 |
| Localization (EN/FR) | MEDIUM | LOW | P1 |
| User access export across selected sites | HIGH | HIGH | P2 |
| Simplified permissions view | HIGH | MEDIUM | P2 |
| Storage graph by file type | MEDIUM | MEDIUM | P2 |
| Permission diff / snapshot comparison | MEDIUM | HIGH | P3 |
| XLSX export | LOW | LOW | P3 |
| Scheduled scans (headless/CLI) | LOW | HIGH | P3 |
### Feature Dependencies
**Priority key:**
- P1: Must have for v1 launch (parity with existing PowerShell tool)
- P2: Should have — add after v1 validated; new features from PROJECT.md active requirements
- P3: Nice to have, future consideration
```
New IGraphDirectoryService + GraphDirectoryService
→ GET /users?$select=displayName,userPrincipalName,mail,jobTitle,department,userType
&$filter=accountEnabled eq true
&$top=100
→ Follow @odata.nextLink in a loop until null
→ Uses existing GraphClientFactory (DI, unchanged)
## Competitor Feature Analysis
UserAccessAuditViewModel additions:
+ IsBrowseMode (bool property, toggle)
+ DirectoryUsers (ObservableCollection<GraphUserResult> or new DirectoryUserEntry model)
+ DirectoryFilterText (string, filters in-memory)
+ LoadDirectoryCommand (async, cancellable)
+ IsDirectoryLoading (bool)
+ SelectedDirectoryUser → feeds into existing audit execution path
| Feature | ShareGate | ManageEngine SharePoint Manager Plus | AdminDroid | Our Approach |
|---------|-----------|---------------------------------------|------------|--------------|
| Permissions matrix report | Yes — visual matrix, CSV export | Yes — granular permission level reports | Yes — site users/groups report | Yes — with plain-language layer on top |
| Multi-tenant management | Yes — SaaS, per-tenant login | Yes — web-based | Yes — cloud SaaS | Yes — local session cache, instant switch, offline profiles |
| Storage reporting | Basic | Basic tenant-level | Basic | Enhanced — file-type breakdown, pie/bar toggle |
| Duplicate detection | No | No | No | Yes — differentiator |
| Folder structure provisioning | No | No | No | Yes — differentiator |
| Site templates | Migration focus | No | No | Yes — admin provisioning focus |
| Bulk operations | Yes — migration-focused | Limited | No | Yes — admin-operations focus (not migration) |
| User access export (cross-site) | Partial — site-by-site | Partial | Partial | Yes — arbitrary site subset, single export |
| Plain language permissions | No | No | No | Yes — differentiator for untrained users |
| Local desktop app (no SaaS) | No — cloud | No — cloud | No — cloud | Yes — core constraint and privacy advantage |
| Offline / no internet needed | No | No | No | Yes (after auth token cached) |
| Price | ~$6K/year | Subscription | Subscription | Tool cost (one-time dev, distributed free or licensed) |
TenantSwitchedMessage handler in ViewModel: clear DirectoryUsers, reset IsBrowseMode
UserAccessAuditView.xaml:
+ Toolbar toggle (Search | Browse)
+ Visibility-collapsed people-picker panel when in browse mode
+ New DataGrid panel for browse mode
```
**Key existing code note:** `GraphUserSearchService` does filtered search only (`startsWith` filter +
`ConsistencyLevel: eventual`). Directory listing is a different call pattern — no filter, plain
pagination without `ConsistencyLevel`. A separate `GraphDirectoryService` is cleaner than extending
the existing service; search and browse have different cancellation and retry needs.
### Complexity Assessment
| Sub-task | Complexity | Reason |
|----------|------------|--------|
| IGraphDirectoryService + GraphDirectoryService (pagination loop) | Low-Medium | Standard Graph paging; same GraphClientFactory in DI |
| ViewModel additions (browse toggle, load command, filter, loading state) | Medium | New async command with progress, cancellation on tenant switch |
| View XAML: toggle + browse DataGrid panel | Medium | Visibility-toggle two panels; DataGrid column definitions |
| In-memory filter + column sort | Low | DataGrid pattern already used in PermissionsView |
| Loading indicator integration | Low | OperationProgress + IsLoading used by every tab |
| Localization keys EN/FR | Low | ~8-12 new keys |
| Unit tests for GraphDirectoryService | Low | Same mock pattern as GraphUserSearchService tests |
| Unit tests for ViewModel browse mode | Medium | Async load command, pagination mock, filter behavior |
---
## Cross-Feature Dependencies
Both features touch the same data models. Changes must be coordinated:
```
TenantProfile model — gains fields for branding (ClientLogoBase64, ClientLogoSource)
AppSettings model — gains MspLogoBase64
ProfileRepository — serializes/deserializes new TenantProfile fields (JSON, backward-compat)
SettingsRepository — serializes/deserializes new AppSettings field
GraphClientFactory — used by both features (no changes needed)
TenantSwitchedMessage — consumed by UserAccessAuditViewModel to clear directory cache
```
Neither feature requires new NuGet packages. The Graph SDK, MSAL, and System.Text.Json are
already present. No new binary dependencies means no EXE size increase.
---
## MVP Recommendation
Build in this order, each independently releasable:
1. **MSP logo in HTML reports** — highest visible impact, lowest complexity. AppSettings field + Settings UI upload + shared header builder.
2. **Client logo in HTML reports (import from file)** — completes the co-branding pattern. TenantProfile field + ProfileManagementDialog upload UI.
3. **User directory browse (load + select + filter)** — core browse UX. Toggle, paginated load, in-memory filter, pipe into existing audit.
4. **Auto-pull client logo from Entra branding** — differentiator, zero-config polish. Build after manual import works so the fallback path is proven.
5. **Directory: guest filter + department/jobTitle columns** — low-effort differentiators; add after core browse is stable.
Defer to a later milestone:
- Directory session caching across tab switches — a Refresh button is sufficient for v2.2.
- Logo on CSV exports — CSV has no image support; not applicable.
---
## Sources
- [ShareGate SharePoint audit tool feature page](https://sharegate.com/sharepoint-audit-tool) — MEDIUM confidence (marketing page)
- [ManageEngine SharePoint Manager Plus permissions auditing](https://www.manageengine.com/sharepoint-management-reporting/sharepoint-permission-auditing-tool.html) — MEDIUM confidence
- [Microsoft Data access governance reports — site permissions for users](https://learn.microsoft.com/en-us/sharepoint/data-access-governance-site-permissions-users-report) — HIGH confidence
- [Microsoft SharePoint Advanced Management overview](https://learn.microsoft.com/en-us/sharepoint/advanced-management) — HIGH confidence
- [sprobot.io: 9 must-have features for SharePoint storage reporting](https://www.sprobot.io/blog/how-to-choose-the-right-sharepoint-storage-reporting-tool-9-must-have-features) — MEDIUM confidence
- [AdminDroid SharePoint Online auditing](https://admindroid.com/microsoft-365-sharepoint-online-auditing) — MEDIUM confidence
- [CIAOPS: Best ways to monitor and audit permissions across SharePoint M365](https://blog.ciaops.com/2025/04/27/best-ways-to-monitor-and-audit-permissions-across-a-sharepoint-environment-in-microsoft-365/) — MEDIUM confidence
- [ShareGate: How to generate a SharePoint user permissions report](https://sharegate.com/blog/build-the-perfect-sharepoint-permissions-report) — MEDIUM confidence
- [Microsoft SharePoint storage reports admin center](https://learn.microsoft.com/en-us/microsoft-365/admin/activity-reports/sharepoint-storage-reports?view=o365-worldwide) — HIGH confidence
---
*Feature research for: SharePoint Online administration/auditing desktop tool (C#/WPF, MSP/IT admin)*
*Researched: 2026-04-02*
- Graph API List Users (v1.0 official): https://learn.microsoft.com/en-us/graph/api/user-list?view=graph-rest-1.0 — HIGH confidence
- Graph API Get organizationalBranding (v1.0 official): https://learn.microsoft.com/en-us/graph/api/organizationalbranding-get?view=graph-rest-1.0 — HIGH confidence
- Graph API bannerLogo stream: `GET /organization/{id}/branding/localizations/default/bannerLogo` — HIGH confidence (verified in official docs)
- Graph pagination concepts: https://learn.microsoft.com/en-us/graph/paging — HIGH confidence
- ControlMap co-branding (MSP + client logo pattern): https://help.controlmap.io/hc/en-us/articles/24174398424347 — MEDIUM confidence
- ManageEngine ServiceDesk Plus MSP per-account branding: https://www.manageengine.com/products/service-desk-msp/rebrand.html — MEDIUM confidence
- SolarWinds MSP report customization: http://allthings.solarwindsmsp.com/2013/06/customize-your-branding-on-client.html — MEDIUM confidence
- Direct codebase inspection: HtmlExportService.cs, GraphUserSearchService.cs, AppSettings.cs, TenantProfile.cs — HIGH confidence

View File

@@ -381,3 +381,422 @@ File I/O is not inherently thread-safe. `System.Text.Json`'s `JsonSerializer.Ser
*Pitfalls research for: C#/WPF SharePoint Online administration desktop tool (PowerShell-to-C# rewrite)*
*Researched: 2026-04-02*
---
---
# v2.2 Pitfalls: Report Branding & User Directory
**Milestone:** v2.2 — HTML report branding (MSP/client logos) + user directory browse mode
**Researched:** 2026-04-08
**Confidence:** HIGH for logo handling and Graph pagination (multiple authoritative sources); MEDIUM for print CSS specifics (verified via MDN/W3C but browser rendering varies)
These pitfalls are specific to adding logo branding to the existing HTML export services and replacing the people-picker search with a full directory browse mode. They complement the v1.0 foundation pitfalls above.
---
## Critical Pitfalls (v2.2)
### Pitfall v2.2-1: Base64 Logo Encoding Bloats Every Report File
**What goes wrong:**
The five existing HTML export services (`HtmlExportService`, `UserAccessHtmlExportService`, `StorageHtmlExportService`, `SearchHtmlExportService`, `DuplicatesHtmlExportService`) are self-contained by design — no external dependencies. The natural instinct is to embed logos as inline `data:image/...;base64,...` strings in the `<style>` or `<img src>` tag of every report. This works, but base64 encoding inflates image size by ~33%. A 200 KB PNG logo becomes 267 KB of base64 text, inlined into every single exported HTML file. An MSP generating 10 reports per client per month accumulates significant bloat per file, and the logo data is re-read, re-encoded, and re-concatenated into the `StringBuilder` on every export call.
The secondary problem is that `StringBuilder.AppendLine` with a very long base64 string (a 500 KB logo becomes ~667 KB of text) causes a single string allocation of that size per report, wasted immediately after the file is written.
**Why it happens:**
The "self-contained HTML" design goal (no external files) is correct for portability. Developers apply it literally and embed every image inline. They test with a small 20 KB PNG and never notice. Production logos from clients are often 300600 KB originals.
**Consequences:**
- Report files 300700 KB larger than necessary — not catastrophic, but noticeable when opening in a browser.
- Logo bytes are re-allocated in memory on every export call — fine for occasional use, wasteful in batch scenarios.
- If the same logo is stored in `AppSettings` or `TenantProfile` as a raw file path, it is read from disk and re-encoded on every export. File I/O error at export time if the path is invalid.
**Prevention:**
1. Enforce a file size limit at import time: reject logos > 512 KB. Display a warning in the settings UI. This keeps base64 strings under ~700 KB worst case.
2. Cache the base64 string. Store it in the `AppSettings`/`TenantProfile` model as the pre-encoded base64 string (not the original file path), so it is computed once on import and reused on every export. `TenantProfile` and `AppSettings` already serialize to JSON — base64 strings serialize cleanly.
3. Enforce image dimensions in the import UI: warn if the image is wider than 800 px and suggest the user downscale. A 200×60 px logo at 72 dpi is sufficient for an HTML report header.
4. When reading from the JSON-persisted base64 string, do not re-decode and re-encode. Inject it directly into the `<img src="data:image/png;base64,{cachedBase64}">` tag.
**Detection:**
- Export a report and check the generated HTML file size. If it is > 100 KB before any data rows are added, the logo is too large.
- Profile `BuildHtml` with a 500 KB logo attached — memory allocation spike is visible in the .NET diagnostic tools.
**Phase to address:** Logo import/settings phase. The size validation and pre-encoding strategy must be established before any export service is modified to accept logo parameters. If the export services are modified first with raw file-path injection, every caller must be updated again later.
---
### Pitfall v2.2-2: Graph API Full Directory Listing Requires Explicit Pagination — 999-User Hard Cap Per Page
**What goes wrong:**
The existing `GraphUserSearchService` uses `$filter` with `startsWith` and `$top=10` — a narrow search, not a full listing. The new user directory browse mode needs to fetch all users in a tenant. Graph API `GET /users` returns a maximum of 999 users per page (not 1000 — the valid range for `$top` is 1999). Without explicit pagination using `@odata.nextLink`, the call silently returns at most 999 users regardless of tenant size. A 5 000-user tenant appears to have 999 users in the directory with no error or indication of truncation.
**Why it happens:**
Developers see `$top=999` and assume a single call returns everything for "normal" tenants. The Graph SDK's `.GetAsync()` call returns a `UserCollectionResponse` with a `Value` list and an `OdataNextLink` property. If `OdataNextLink` is not checked, pagination stops after the first page. The existing `SearchUsersAsync` intentionally returns only 10 results — the pagination concern was never encountered there.
**Consequences:**
- The directory browse mode silently shows fewer users than the tenant contains.
- An MSP auditing a 3 000-user client tenant sees only 999 users with no warning.
- Guest/service accounts in the first 999 may appear; those after page 1 are invisible.
**Prevention:**
Use the Graph SDK's `PageIterator<User, UserCollectionResponse>` for all full directory fetches. This is the Graph SDK's built-in mechanism for transparent pagination:
```csharp
var users = new List<User>();
var response = await graphClient.Users.GetAsync(config =>
{
config.QueryParameters.Select = new[] { "displayName", "userPrincipalName", "mail", "userType" };
config.QueryParameters.Top = 999;
config.QueryParameters.Orderby = new[] { "displayName" };
}, ct);
var pageIterator = PageIterator<User, UserCollectionResponse>.CreatePageIterator(
graphClient,
response,
user => { users.Add(user); return true; },
request => { request.Headers.Add("ConsistencyLevel", "eventual"); return request; });
await pageIterator.IterateAsync(ct);
```
Always pass `CancellationToken` through the iterator. For tenants with 10 000+ users, this will make multiple sequential API calls — surface progress to the user ("Loading directory... X users loaded").
**Detection:**
- Request `$count=true` with `ConsistencyLevel: eventual` on the first page call. Compare the returned `@odata.count` to the number of items received after full iteration. If they differ, pagination was incomplete.
- Test against a tenant with > 1 000 users before shipping the directory browse feature.
**Phase to address:** User directory browse implementation phase. The interface `IGraphUserSearchService` will need a new method `GetAllUsersAsync` alongside the existing `SearchUsersAsync` — do not collapse them.
---
### Pitfall v2.2-3: Graph API Directory Listing Returns Guest, Service, and Disabled Accounts Without Filtering
**What goes wrong:**
`GET /users` returns all user objects in the tenant: active members, disabled accounts, B2B guest users (`userType eq 'Guest'`), on-premises sync accounts, and service/bot accounts. In an MSP context, a client's SharePoint tenant may have dozens of guest users from external collaborators and several service accounts (e.g., `sharepoint@clientdomain.com`, `MicrosoftTeams@clientdomain.com`). If the directory browse mode shows all 3 000 raw entries, admins spend time scrolling past noise to find real staff.
Filtering on `userType` helps for guests but there is no clean Graph filter for "service accounts" — it is a convention, not a Graph property. There is also no Graph filter for disabled accounts from the basic `$filter` syntax without `ConsistencyLevel: eventual`.
**Why it happens:**
The people-picker search in v1.1 is text-driven — the user types a name, noise is naturally excluded. A browse mode showing all users removes that implicit filter and exposes the raw directory.
**Consequences:**
- Directory appears larger and noisier than expected for MSP clients.
- Admin selects the wrong account (service account instead of user) and runs an audit that returns no meaningful results.
- Guest accounts from previous collaborations appear as valid targets.
**Prevention:**
Apply a default filter in the directory listing that excludes obvious non-staff entries, while allowing the user to toggle the filter off:
- Default: `$filter=accountEnabled eq true and userType eq 'Member'` — this excludes guests and disabled accounts. Requires no `ConsistencyLevel` header (supported in standard filter mode).
- Provide a checkbox in the directory browse UI: "Include guest accounts" that adds `or userType eq 'Guest'` to the filter.
- For service account noise: apply a client-side secondary filter that hides entries where `displayName` contains common service patterns (`SharePoint`, `Teams`, `No Reply`, `Admin`) — this is a heuristic and should be opt-in, not default.
Note: filtering `accountEnabled eq true` in the `$filter` parameter without `ConsistencyLevel: eventual` works on the v1.0 `/users` endpoint. Verify before release.
**Detection:**
- Count the raw user total vs. the filtered total for a test tenant. If they differ by more than 20%, the default filter is catching real users — review the filter logic.
**Phase to address:** User directory browse implementation phase, before the UI is built. The filter strategy must be baked into the service interface so the ViewModel does not need to know about it.
---
### Pitfall v2.2-4: Full Directory Load Hangs the UI Without Progress Feedback
**What goes wrong:**
Fetching 3 000 users with page iteration takes 38 seconds depending on tenant size and Graph latency. The existing people-picker search is a debounced 500 ms call that returns quickly. The directory browse "Load All" operation is fundamentally different in character. Without progress feedback, the user sees a frozen list and either waits or clicks the button again (triggering a second concurrent load).
The existing `IsBusy` / `IsRunning` pattern on `AsyncRelayCommand` will disable the button, but there is no count feedback in the existing ViewModel pattern for this case.
**Why it happens:**
Developers implement the API call first, wire it to a button, and test with a 50-user dev tenant where it returns in < 500 ms. The latency problem is only discovered when testing against a real client.
**Consequences:**
- On first use with a large tenant, the admin thinks the feature is broken and restarts the app.
- If the command is not properly guarded, double-clicks trigger two concurrent Graph requests populating the same `ObservableCollection`.
**Prevention:**
- Add a `DirectoryLoadStatus` observable property: `"Loading... X users"` updated via `IProgress<int>` inside the `PageIterator` callback.
- Use `BindingOperations.EnableCollectionSynchronization` on the users `ObservableCollection` so items can be streamed in as each page arrives rather than waiting for full iteration.
- The `AsyncRelayCommand` `CanExecute` must return `false` while loading is in progress (the toolkit does this automatically when `IsRunning` is true — verify it is wired).
- Add a cancellation button that is enabled during the load, using the same `CancellationToken` passed to `PageIterator.IterateAsync`.
**Detection:**
- Test with a mock that simulates 10 pages of 999 users each, adding a 200 ms delay between pages. The UI should show incrementing count feedback throughout.
**Phase to address:** User directory browse ViewModel phase.
---
### Pitfall v2.2-5: Logo File Format Validation Is Skipped, Causing Broken Images in Reports
**What goes wrong:**
The `OpenFileDialog` filter (`*.png;*.jpg;*.jpeg`) prevents selecting a `.exe` file, but it does not validate that the selected file is actually a valid image. A user may select a file that was renamed with a `.png` extension but is actually a PDF, a corrupted download, or an SVG (which is XML text, not a binary image format). When the file is read and base64-encoded, the string is valid base64, but the browser renders a broken image icon in the HTML report.
WPF's `BitmapImage` will throw an exception on corrupt or unsupported binary files. SVG files loaded as a `BitmapImage` throw because SVG is not a WPF-native raster format.
A second failure mode: `BitmapImage` throws `NotSupportedException` or `FileFormatException` for EXIF-corrupt JPEGs. This is a known .NET issue where WPF's BitmapImage is strict about EXIF metadata validity.
**Why it happens:**
The file picker filter is treated as sufficient validation. EXIF corruption is not anticipated because it is invisible to casual inspection.
**Consequences:**
- Report is generated successfully from the app's perspective, but every page has a broken image icon where the logo should appear.
- The user does not see the error until they open the HTML file.
- EXIF-corrupt JPEG from a phone camera or scanner is a realistic scenario in an MSP workflow.
**Prevention:**
After file selection and before storing the path or encoding:
1. Load the file as a `BitmapImage` in a `try/catch`. If it throws, reject the file and show a user-friendly error: "The selected file could not be read as an image. Please select a valid PNG or JPEG file."
2. Check `BitmapImage.PixelWidth` and `PixelHeight` after load — a 0×0 image is invalid.
3. For EXIF-corrupt JPEGs: `BitmapCreateOptions.IgnoreColorProfile` and `BitmapCacheOption.OnLoad` reduce (but do not eliminate) EXIF-related exceptions. Wrap the load in a retry with these options if the initial load fails.
4. Do not accept SVG files. The file filter should explicitly include only `*.png;*.jpg;*.jpeg;*.bmp;*.gif`. SVG requires a third-party library (e.g., SharpVectors) to rasterize — out of scope for this milestone.
5. After successful load, verify the resulting base64 string decodes back to a valid image (round-trip check) before persisting to JSON.
**Detection:**
- Unit test: attempt to load a `.txt` file renamed to `.png` and a known EXIF-corrupt JPEG. Verify both are rejected with a user-visible error, not a silent crash.
**Phase to address:** Logo import/settings phase. Validation must be in place before the logo path or base64 is persisted.
---
### Pitfall v2.2-6: Logo Path Stored in JSON Settings Becomes Stale After EXE Redistribution
**What goes wrong:**
The simplest implementation of logo storage is to persist the file path (`C:\Users\admin\logos\msp-logo.png`) in `AppSettings` JSON. This works on the machine where the logo was imported. When the tool is redistributed to another MSP technician (or when the admin reinstalls Windows), the path no longer exists. The export service reads the path, the file is missing, and the logo is silently omitted from new reports — or worse, throws an unhandled `FileNotFoundException`.
**Why it happens:**
Path storage is the simplest approach. Base64 storage feels "heavy." The problem is only discovered when a colleague opens the tool on their own machine.
**Consequences:**
- Client-branded reports stop including the logo without any warning.
- The user does not know the logo is missing until a client complains about the unbranded report.
- The `AppSettings.DataFolder` pattern is already established in the codebase — the team may assume all assets follow the same pattern, but logos are user-supplied files, not app-generated data.
**Prevention:**
Store logos as base64 strings directly in `AppSettings` and `TenantProfile` JSON, not as file paths. The import action reads the file once, encodes it, stores the string, and the original file path is discarded after import. This makes the settings file fully portable across machines.
The concern about JSON file size is valid but manageable: a 512 KB PNG becomes ~700 KB of base64, which increases the settings JSON file by that amount. For a tool that already ships as a 200 MB EXE, a 1 MB settings file is acceptable. Document this design decision explicitly.
Alternative if file-path storage is preferred: copy the logo file into a `logos/` subdirectory of `AppSettings.DataFolder` at import time (use a stable filename like `msp-logo.png`), store only the relative path in JSON, and resolve it relative to `DataFolder` at export time. This is portable as long as the DataFolder travels with the settings.
**Detection:**
- After importing a logo, manually edit `AppSettings.json` and verify the logo data is stored correctly.
- Move the settings JSON to a different machine and verify a report is generated with the logo intact.
**Phase to address:** Logo import/settings phase. The storage strategy must be decided and implemented before any export service accepts logo data.
---
## Moderate Pitfalls (v2.2)
### Pitfall v2.2-7: Logo Breaks HTML Report Print Layout
**What goes wrong:**
The existing HTML export services produce print-friendly reports (flat tables, no JavaScript required for static reading). Adding a logo `<img>` tag to the report header introduces two print layout risks:
1. **Logo too large:** An `<img>` without explicit CSS constraints stretches to its natural pixel size. A 1200×400 px banner image pushes the stats cards and table off the first page, breaking the expected report layout.
2. **Image not printed:** Some users open HTML reports and use "Print to PDF." Browsers' print stylesheets apply `@media print` rules. By default, most browsers print background images but not inline `<img>` elements with `display:none` — this is usually not a problem, but logos inside `<div>` containers with `overflow:hidden` or certain CSS transforms may be clipped or omitted in print rendering.
**Why it happens:**
Logo sizing is set by the designer in the settings UI but the reports are opened in diverse browsers (Chrome, Edge, Firefox) with varying print margin defaults. The logo is tested visually on-screen but not in a print preview.
**Prevention:**
- Constrain all logo `<img>` elements with explicit CSS: `max-height: 60px; max-width: 200px; object-fit: contain;`. This prevents the image from overflowing its container regardless of the original image dimensions.
- Add a `@media print` block in the report's inline CSS that keeps the logo visible and appropriately sized: `@media print { .report-logo { max-height: 48px; max-width: 160px; } }`.
- Use `break-inside: avoid` on the header `<div>` containing both logos and the report title so a page break never splits the header from the first stat card.
- Test "Print to PDF" in Edge (Chromium) before shipping — it is the most common browser for MSP tools on Windows.
**Detection:**
- Open a generated report in Edge, use Ctrl+P, check print preview. Verify the logo appears on page 1 and the table is not pushed to page 2 by an oversized image.
**Phase to address:** HTML report template phase when logo injection is added to `BuildHtml`.
---
### Pitfall v2.2-8: ConsistencyLevel Header Amplifies Graph Throttling for Directory Listing
**What goes wrong:**
The existing `GraphUserSearchService` already uses `ConsistencyLevel: eventual` with `$count=true` for its `startsWith` filter query. This is required for the advanced filter syntax. However, applying `ConsistencyLevel: eventual` to a full directory listing with `$top=999` and `$orderby=displayName` forces Graph to route requests through a consistency-checked path rather than a lightweight read cache. Microsoft documentation confirms this increases the cost of each request against throttling limits.
For a tenant with 10 000 users (11 pages of 999), firing 11 consecutive requests with `ConsistencyLevel: eventual` is significantly more expensive than 11 standard read requests. Under sustained MSP use (multiple tenants audited back-to-back), this can trigger per-app throttling (HTTP 429) after 23 directory loads in quick succession.
**Why it happens:**
`ConsistencyLevel: eventual` is already in the existing service and developers copy it to the new `GetAllUsersAsync` method because it was needed for `$count` support.
**Prevention:**
For `GetAllUsersAsync`, evaluate whether `ConsistencyLevel: eventual` is actually needed:
- `$orderby=displayName` on `/users` does **not** require `ConsistencyLevel: eventual` — standard `$orderby` on `displayName` is supported without it.
- `$count=true` does require `ConsistencyLevel: eventual`. If user count is needed for progress feedback, request it only on the first page, then use the returned `@odata.count` value without adding the header to subsequent page requests. The `PageIterator` does not automatically carry the header to next-link requests — verify this behaviour.
- If `ConsistencyLevel: eventual` is not needed for the primary listing, omit it from `GetAllUsersAsync`. Use it only when `$search` or `$count` are required.
**Detection:**
- Load the full directory for two different tenants back-to-back. Check for HTTP 429 responses in the Serilog output. If throttling occurs within the first two loads, `ConsistencyLevel` overhead is the likely cause.
**Phase to address:** User directory browse service implementation phase.
---
### Pitfall v2.2-9: WPF ListView with 5 000+ Users Freezes Without UI Virtualization
**What goes wrong:**
A WPF `ListView` or `DataGrid` bound to an `ObservableCollection<DirectoryUser>` with 5 000 items renders all 5 000 item containers on first bind if UI virtualization is disabled or inadvertently defeated. This causes a 510 second freeze when the directory loads and ~200 MB of additional memory for the rendered rows, even though only ~20 rows are visible in the viewport.
Virtualization is defeated by any of these common mistakes:
- The `ListView` is inside a `ScrollViewer` that wraps both the list and other content (`ScrollViewer.CanContentScroll=False` is the kill switch).
- The `ItemsPanel` is overridden with a non-virtualizing panel (`StackPanel` instead of `VirtualizingStackPanel`).
- Items are added one-by-one to the `ObservableCollection` (each addition fires a `CollectionChanged` notification, causing incremental layout passes — 5 000 separate layout passes are expensive).
**Why it happens:**
The existing people-picker `SearchResults` collection has at most 10 items — virtualization was never needed and its absence was never noticed. The directory browse `ObservableCollection` is a different scale.
**Prevention:**
- Use a `ListView` with its default `VirtualizingStackPanel` (do not override `ItemsPanel`).
- Set `VirtualizingPanel.IsVirtualizing="True"`, `VirtualizingPanel.VirtualizationMode="Recycling"`, and `ScrollViewer.CanContentScroll="True"` explicitly — do not rely on defaults being correct after a XAML edit.
- Never add items to the collection one-by-one from the background thread. Use `BindingOperations.EnableCollectionSynchronization` and assign `new ObservableCollection<T>(loadedList)` in one operation after all pages have been fetched, or batch-swap when each page arrives.
- For 5 000+ items, add a search-filter input above the directory list that filters the bound `ICollectionView` — this reduces the rendered item count to a navigable size without requiring the user to scroll 5 000 rows.
**Detection:**
- Load a 3 000-user directory into the ListView. Open Windows Task Manager. The WPF process should not spike above 300 MB during list rendering. Scroll should be smooth (60 fps) with recycling enabled.
**Phase to address:** User directory browse View/XAML phase.
---
### Pitfall v2.2-10: Dual Logo Injection Requires Coordinated Changes Across All Five HTML Export Services
**What goes wrong:**
There are five independent `HtmlExportService`-style classes, each with its own `BuildHtml` method that builds the full HTML document from scratch using `StringBuilder`. Adding logo support means changing all five methods. If logos are added to only two or three services (the ones the developer remembers), the other reports ship without branding. The inconsistency is subtle — the tool "works," but branded exports alternate with unbranded exports depending on which tab generated the report.
**Why it happens:**
Each export service was written independently and shares no base class. There is no shared "HTML report header" component that all services delegate to. Each service owns its complete `<!DOCTYPE html>` block.
**Consequences:**
- Permissions report is branded; duplicates report is not.
- Client notices inconsistency and questions the tool's reliability.
- Future changes to the report header (adding a timestamp, changing the color scheme) must be applied to all five files separately.
**Prevention:**
Before adding logo injection to any service, extract a shared `HtmlReportHeader` helper method (or a small `HtmlReportBuilder` base class/utility) that generates the `<head>`, `<style>`, and branded header `<div>` consistently. All five services call this shared method with a `BrandingOptions` parameter (MSP logo base64, client logo base64, report title). This is a refactoring prerequisite — not optional if branding consistency is required.
The refactoring is low-risk: the CSS blocks in all five services are nearly identical (confirmed by reading the code), so consolidation is straightforward.
**Detection:**
- After branding is implemented, export one report from each of the five export services. Open all five in a browser side by side and verify logos appear in all five.
**Phase to address:** HTML report template refactoring phase — this must be done before logo injection, not after.
---
## Minor Pitfalls (v2.2)
### Pitfall v2.2-11: `User.Read.All` Permission Scope May Not Be Granted for Full Directory Listing
**What goes wrong:**
The existing `SearchUsersAsync` uses `startsWith` filter queries that work with `User.ReadBasic.All` (the least-privileged scope for user listing). Full directory browse with all user properties may require `User.Read.All`, depending on which properties are selected. If the Azure AD app registration used by MSP clients only has `User.ReadBasic.All` consented (which is sufficient for the v1.1 people-picker), the `GetAllUsersAsync` call may silently return partial data or throw a 403.
`User.ReadBasic.All` returns only: `displayName`, `givenName`, `id`, `mail`, `photo`, `securityIdentifier`, `surname`, `userPrincipalName`. Requesting `accountEnabled` or `userType` (needed for filtering out guests/disabled accounts per Pitfall v2.2-3) requires `User.Read.All`.
**Prevention:**
- Define the exact `$select` fields needed for the directory browse feature and verify each field is accessible under `User.ReadBasic.All` before assuming `User.Read.All` is required.
- If `User.Read.All` is required, update the app registration documentation and display a clear message in the tool if the required permission is missing (catch the 403 and surface it as "Insufficient permissions — User.Read.All is required for directory browse mode").
- Add `User.Read.All` to the requested scopes in `MsalClientFactory` alongside existing scopes.
**Detection:**
- Test the directory browse against a tenant where the app registration has only `User.ReadBasic.All` consented. Verify the error message is user-readable, not a raw `ServiceException`.
**Phase to address:** User directory browse service interface phase.
---
### Pitfall v2.2-12: Logo Preview in Settings UI Holds a File Lock
**What goes wrong:**
When showing a logo preview in the WPF settings UI using `BitmapImage` with a file URI (`new BitmapImage(new Uri(filePath))`), WPF may hold a read lock on the file until the `BitmapImage` is garbage collected. If the user then tries to re-import a different logo (which involves overwriting the same file), the file write fails with a sharing violation. This is a known WPF `BitmapImage` quirk.
**Prevention:**
Load logo previews with `BitmapCacheOption.OnLoad` and set `UriSource` then call `EndInit()`:
```csharp
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(filePath);
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
bitmap.Freeze(); // Makes it immutable and thread-safe; also releases the file handle
```
`Freeze()` is the critical call — it forces the image to be fully decoded into memory and releases the file handle immediately, preventing file locks.
**Detection:**
- Import a logo, then immediately try to overwrite the source file using Windows Explorer. Without `Freeze()`, the file is locked. With `Freeze()`, the overwrite succeeds.
**Phase to address:** Settings UI / logo import phase.
---
## Phase-Specific Warnings (v2.2)
| Phase Topic | Likely Pitfall | Mitigation |
|-------------|---------------|------------|
| Logo import + settings persistence | Base64 bloat (v2.2-1) + path staleness (v2.2-6) | Store pre-encoded base64 in JSON; enforce 512 KB import limit |
| Logo import + settings persistence | Invalid/corrupt image file (v2.2-5) | Validate via `BitmapImage` load before persisting; `Freeze()` to release handle (v2.2-12) |
| HTML report template refactoring | Inconsistent branding across 5 services (v2.2-10) | Extract shared header builder before touching any service |
| HTML report template | Print layout broken by oversized logo (v2.2-7) | Add `max-height/max-width` CSS and `@media print` block |
| Graph directory service | Silent truncation at 999 users (v2.2-2) | Use `PageIterator`; request `$count` on first page for progress |
| Graph directory service | Guest/service account noise (v2.2-3) | Default filter `accountEnabled eq true and userType eq 'Member'`; UI toggle for guests |
| Graph directory service | Throttling from ConsistencyLevel header (v2.2-8) | Omit `ConsistencyLevel: eventual` from standard listing; use only when `$search` or `$count` required |
| Graph directory service | Missing permission scope (v2.2-11) | Verify `User.Read.All` vs. `User.ReadBasic.All` against required fields; update app registration docs |
| Directory browse ViewModel | UI freeze during load (v2.2-4) | Stream pages via `IProgress<int>`; cancellable `AsyncRelayCommand` |
| Directory browse View (XAML) | ListView freeze with 5 000+ items (v2.2-9) | Explicit virtualization settings; batch `ObservableCollection` assignment; filter input |
---
## v2.2 Integration Gotchas
| Integration | Common Mistake | Correct Approach |
|-------------|----------------|------------------|
| Logo base64 in `AppSettings` JSON | Store file path; re-encode on every export | Store pre-encoded base64 string at import time; inject directly into `<img src>` |
| `BitmapImage` logo preview | Default `BitmapImage` constructor holds file lock | Use `BeginInit/EndInit` with `BitmapCacheOption.OnLoad` and call `Freeze()` |
| Graph `GetAllUsersAsync` | Single `GetAsync` call; no pagination | Always use `PageIterator<User, UserCollectionResponse>` |
| Graph `$top` parameter | `$top=1000` — invalid; silently rounds down | Maximum valid value is `999` |
| Graph directory filter | No filter — returns all account types | Default: `accountEnabled eq true and userType eq 'Member'` |
| `ConsistencyLevel: eventual` | Applied to all Graph requests by habit | Required only for `$search`, `$filter` with non-standard operators, and `$count` |
| HTML export services | Logo injected in only the modified services | Extract shared header builder; all five services use it |
| WPF ListView with large user list | No virtualization settings, items added one-by-one | Explicit `VirtualizingPanel` settings; assign `new ObservableCollection<T>(list)` once |
---
## v2.2 "Looks Done But Isn't" Checklist
- [ ] **Logo size limit enforced:** Import a 600 KB PNG. Verify the UI rejects it with a clear message and does not silently accept it.
- [ ] **Corrupt image rejected:** Rename a `.txt` file to `.png` and attempt to import. Verify rejection with user-friendly error.
- [ ] **Logo portability:** Import a logo on machine A, copy the settings JSON to machine B (without the original file), generate a report. Verify the logo appears.
- [ ] **All five report types branded:** Export one report from each of the five HTML export services. Open all five in a browser and verify logos appear in all.
- [ ] **Print layout intact:** Open each branded report type in Edge, Ctrl+P, print preview. Verify logo appears on page 1 and table is not displaced.
- [ ] **Directory listing complete (large tenant):** Connect to a tenant with > 1 000 users. Load the full directory. Verify user count matches the Azure AD count shown in the Azure portal.
- [ ] **Directory load cancellation:** Start a directory load and click Cancel before it completes. Verify the list shows partial results or is cleared, no crash, and the button re-enables.
- [ ] **Guest account filter:** Verify guests are excluded by default. Verify the "Include guests" toggle adds them back.
- [ ] **ListView performance:** Load 3 000 users into the directory list. Verify scroll is smooth and memory use is reasonable (< 400 MB total).
- [ ] **FR locale for new UI strings:** All logo import labels, error messages, and directory browse UI strings must have FR translations. Verify no untranslated keys appear when FR is active.
---
## v2.2 Sources
- Microsoft Learn: List users (Graph v1.0) — https://learn.microsoft.com/en-us/graph/api/user-list?view=graph-rest-1.0
- Microsoft Learn: Graph API throttling guidance — https://learn.microsoft.com/en-us/graph/throttling
- Microsoft Learn: Graph API service-specific throttling limits — https://learn.microsoft.com/en-us/graph/throttling-limits
- Microsoft Learn: Graph SDK paging / PageIterator — https://learn.microsoft.com/en-us/graph/sdks/paging
- Microsoft Learn: Graph permissions — User.ReadBasic.All vs User.Read.All — https://learn.microsoft.com/en-us/graph/permissions-reference
- Rick Strahl's Web Log: Working around the WPF ImageSource Blues (2024) — https://weblog.west-wind.com/posts/2024/Jan/03/Working-around-the-WPF-ImageSource-Blues
- Rick Strahl's Web Log: HTML to PDF Generation using the WebView2 Control (2024) — https://weblog.west-wind.com/posts/2024/Mar/26/Html-to-PDF-Generation-using-the-WebView2-Control
- MDN Web Docs: CSS Printing — https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Printing
- Microsoft Learn: BitmapImage / BitmapCacheOption — https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.imaging.bitmapcacheoption
- Microsoft Learn: Optimize WPF control performance (virtualization) — https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/optimizing-performance-controls
- Microsoft Q&A: WPF BitmapImage complains about EXIF corrupt metadata — https://learn.microsoft.com/en-us/answers/questions/1457132/wpf-bitmapimage-complains-about-exif-corrupt-metad
- Microsoft Q&A: What is the suggested way for filtering non-human accounts from /users — https://learn.microsoft.com/en-us/answers/questions/280526/what-is-the-suggested-34way34-or-best-options-for.html
- DebugBear: Page Speed — Avoid Large Base64 data URLs — https://www.debugbear.com/blog/base64-data-urls-html-css
- Graph API — how to avoid throttling (Tech Community) — https://techcommunity.microsoft.com/blog/fasttrackforazureblog/graph-api-integration-for-saas-developers/4038603
- Existing codebase: `UserAccessHtmlExportService.cs`, `HtmlExportService.cs`, `GraphUserSearchService.cs` (reviewed 2026-04-08)
---
*v2.2 pitfalls appended: 2026-04-08*

View File

@@ -1,204 +1,275 @@
# Stack Research
# Technology Stack
**Domain:** C#/WPF desktop administration tool for SharePoint Online (multi-tenant MSP)
**Researched:** 2026-04-02
**Confidence:** HIGH (core framework choices), MEDIUM (charting library)
**Project:** SharePoint Toolbox v2
**Researched:** 2026-04-08 (updated for v2.2 milestone)
---
## Recommended Stack
## v2.2 Stack Additions
### Core Technologies
| Technology | Version | Purpose | Why Recommended |
|------------|---------|---------|-----------------|
| .NET 10 LTS | 10.x | Target runtime | Released November 2025, LTS until November 2028 — the current LTS. Avoid .NET 8 (ends November 2026) and .NET 9 STS (ended May 2026). WPF support is first-class and actively improved in .NET 10. |
| WPF (.NET 10) | built-in | UI framework | Windows-only per project constraint. Modern MVVM data binding, richer styling than WinForms. The existing codebase uses WinForms; WPF is the correct upgrade path for richer UI. |
| C# 13 | built-in with .NET 10 | Language | Current language version shipping with .NET 10 SDK. |
### SharePoint / Microsoft 365 API
| Library | Version | Purpose | Why Recommended |
|---------|---------|---------|-----------------|
| PnP.Framework | 1.18.0 | SharePoint CSOM extensions, provisioning engine, site templates, permissions | Directly replaces PnP.PowerShell patterns the existing app uses. Contains PnP Provisioning Engine needed for site templates feature. Targets .NET Standard 2.0 so runs on .NET 10 via compatibility. This is the correct choice for a CSOM-heavy migration — use PnP.Core SDK only when starting greenfield with Graph-first design. |
| Microsoft.Graph | 5.103.0 | Microsoft Graph API access (Teams, Groups, users across tenants) | Required for Teams site management, user enumeration across tenants. Complements PnP.Framework which is CSOM-first. Use Graph SDK for Graph-native operations; use PnP.Framework for SharePoint-specific provisioning. |
**Note on PnP.Core SDK vs PnP.Framework:** PnP Core SDK is the modern Graph-first replacement for PnP Framework, but PnP Framework is the right choice here because: (1) this is a migration from PnP.PowerShell which is CSOM-based, (2) the PnP Provisioning Engine for site templates lives in PnP.Framework, not PnP Core SDK, (3) the existing feature set maps directly to PnP.Framework's extension methods.
### Authentication
| Library | Version | Purpose | Why Recommended |
|---------|---------|---------|-----------------|
| Microsoft.Identity.Client (MSAL.NET) | 4.83.1 | Azure AD interactive browser login, token acquisition | The underlying auth library used by both PnP.Framework and Microsoft.Graph SDK. Use directly for multi-tenant session management. |
| Microsoft.Identity.Client.Extensions.Msal | 4.83.3 | Token cache persistence to disk | Required for multi-tenant session caching — serializes the MSAL token cache to encrypted local storage so users don't re-authenticate on each app launch or tenant switch. PnP.Framework 1.18.0 already depends on this (>= 4.70.2). |
| Microsoft.Identity.Client.Desktop | 4.82.1 | Windows-native broker support (WAM) | Enables Windows Authentication Manager integration for WPF apps. Provides system-level SSO. Add `.WithWindowsBroker()` to the PublicClientApplicationBuilder. |
**Multi-tenant session caching pattern:** Create one `PublicClientApplication` per tenant, serialize each tenant's token cache separately using `MsalCacheHelper` from Extensions.Msal. Store serialized caches in `%AppData%\SharepointToolbox\tokens\{tenantId}.bin`. PnP.Framework's `AuthenticationManager.CreateWithInteractiveLogin()` accepts a custom MSAL app instance — wire the cached app here.
### MVVM Infrastructure
| Library | Version | Purpose | Why Recommended |
|---------|---------|---------|-----------------|
| CommunityToolkit.Mvvm | 8.4.2 | MVVM base classes, source-generated commands and properties, messaging | Microsoft-maintained, ships with .NET Community Toolkit. Source generators eliminate 90% of MVVM boilerplate. `[ObservableProperty]`, `[RelayCommand]`, `[INotifyPropertyChanged]` attributes generate all property change plumbing at compile time. The standard choice for WPF/MVVM in 2025-2026. |
| Microsoft.Extensions.Hosting | 10.x | Generic Host for DI, configuration, lifetime management | Provides `IServiceCollection` DI container, `IConfiguration`, and structured app startup/shutdown lifecycle in WPF. Avoids manual service locator patterns. Wire WPF `Application.Startup` into the host lifetime. |
| Microsoft.Extensions.DependencyInjection | 10.x | DI container | Included with Hosting. Register ViewModels, services, and repositories as scoped/singleton/transient services. |
### Logging
| Library | Version | Purpose | Why Recommended |
|---------|---------|---------|-----------------|
| Serilog | 4.3.1 | Structured logging | Industry standard for .NET desktop apps. Structured log events (not just strings) make post-mortem debugging of the existing app's 38 silent catch blocks tractable. File sink for persistent logs, debug sink for development. |
| Serilog.Extensions.Logging | 10.0.0 | Bridge Serilog into ILogger<T> | Allows injecting `ILogger<T>` everywhere while Serilog handles the actual output. One configuration point. |
| Serilog.Sinks.File | latest | Write logs to rolling files | `%AppData%\SharepointToolbox\logs\log-.txt` with daily rolling. Essential for diagnosing auth and SharePoint API failures in the field. |
### Data Serialization
| Library | Version | Purpose | Why Recommended |
|---------|---------|---------|-----------------|
| System.Text.Json | built-in .NET 10 | JSON read/write for profiles, settings, templates | Built into .NET, no NuGet dependency, faster and less memory-hungry than Newtonsoft.Json. Sufficient for the simple config/profile/template structures this app needs. The existing PowerShell app uses JSON — `System.Text.Json` with source generators enables AOT-safe deserialization, important for self-contained EXE size. |
**Why not Newtonsoft.Json:** Slower, adds ~500KB to the EXE, no AOT support. Only justified when you need LINQ-to-JSON or highly polymorphic deserialization — neither of which applies here.
### Data Visualization (Charts)
| Library | Version | Purpose | Why Recommended |
|---------|---------|---------|-----------------|
| ScottPlot.WPF | 5.1.57 | Pie and bar charts for storage metrics | Stable, actively maintained (weekly releases), MIT licensed, no paid tier. Supports pie, bar, and all chart types needed. Renders via SkiaSharp — fast even for large datasets. LiveCharts2 is still RC for WPF (2.0.0-rc6.1 as of April 2026) and introduces unnecessary risk. OxyPlot is mature but lacks interactive features and has poor performance on large datasets. ScottPlot 5.x is the stable choice. |
### Report Generation
| Library | Version | Purpose | Why Recommended |
|---------|---------|---------|-----------------|
| CsvHelper | latest stable | CSV export | Industry standard for .NET CSV serialization. Handles encoding, quoting, header generation. Replaces manual string concatenation. |
| No HTML library needed | — | HTML reports | Generate HTML reports via `StringBuilder` or T4/Scriban text templates with embedded JS (Chart.js or DataTables). Self-contained HTML files require no server. Keep it simple — a `ReportBuilder` service class is sufficient. |
### Localization
| Library | Version | Purpose | Why Recommended |
|---------|---------|---------|-----------------|
| .NET Resource files (.resx) | built-in | EN/FR localization | ResX is the standard WPF localization approach for a two-language desktop app. Compile-time safety, strong tooling in Visual Studio, no runtime switching complexity. The existing app uses a key-based translation system — ResX maps directly. Use `Properties/Resources.en.resx` and `Properties/Resources.fr.resx`. Runtime language switching (if needed later) is achievable via `Thread.CurrentThread.CurrentUICulture`. |
### Distribution
| Tool | Version | Purpose | Why Recommended |
|------|---------|---------|-----------------|
| `dotnet publish` with PublishSingleFile + SelfContained | .NET 10 SDK | Single self-contained EXE | Built-in SDK feature. Set `<PublishSingleFile>true</PublishSingleFile>`, `<SelfContained>true</SelfContained>`, `<RuntimeIdentifier>win-x64</RuntimeIdentifier>`. No third-party tool needed. Expected output size: ~150-200MB (runtime + SkiaSharp from ScottPlot). |
This section covers only the NEW capability needs for v2.2 (Report Branding + User Directory). The full existing stack is documented in the section below. The short answer: **no new NuGet packages are needed for either feature.**
---
## Project File Configuration
### Feature 1: HTML Report Branding (Logo Embedding)
```xml
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<!-- Distribution -->
<PublishSingleFile>true</PublishSingleFile>
<SelfContained>true</SelfContained>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<!-- Trim carefully — MSAL and PnP use reflection -->
<PublishTrimmed>false</PublishTrimmed>
</PropertyGroup>
**Requirement:** Embed MSP logo (global) and client logo (per-tenant) into the self-contained HTML reports that already exist.
#### Approach: Base64 data URI — BCL only
The existing HTML export services (`HtmlExportService`, `UserAccessHtmlExportService`, etc.) produce fully self-contained HTML files using `StringBuilder` with all CSS and JS inlined. Logo images follow the same pattern: convert image bytes to a Base64 string and embed as an HTML `<img>` data URI.
```csharp
// In a LogoEmbedHelper or directly in each export service:
byte[] bytes = await File.ReadAllBytesAsync(logoFilePath, ct);
string mime = Path.GetExtension(logoFilePath).ToLowerInvariant() switch
{
".png" => "image/png",
".jpg" => "image/jpeg",
".jpeg" => "image/jpeg",
".gif" => "image/gif",
".svg" => "image/svg+xml",
".webp" => "image/webp",
_ => "image/png"
};
string dataUri = $"data:{mime};base64,{Convert.ToBase64String(bytes)}";
// In HTML: <img src="{dataUri}" alt="Logo" style="height:48px;" />
```
**Note on trimming:** Do NOT enable `PublishTrimmed` with PnP.Framework or MSAL.NET. Both libraries use reflection internally and are not trim-safe. The EXE will be larger (~150-200MB) but reliable. Trimming would require extensive `[DynamicDependency]` annotations and is not worth the effort.
**Why this approach:**
- Zero new dependencies. `File.ReadAllBytesAsync`, `Convert.ToBase64String`, and `Path.GetExtension` are all BCL.
- The existing "no external dependencies" constraint on HTML reports is preserved.
- Self-contained EXE constraint is preserved — no logo file paths can break because the bytes are embedded in the HTML at export time.
- Base64 increases image size by ~33% but logos are small (< 50 KB typical); the impact on HTML file size is negligible.
---
**Logo storage strategy — store file path, embed at export time:**
## Installation (NuGet Package References)
Store the logo file path (not the base64) in `AppSettings` (global MSP logo) and `TenantProfile` (per-client logo). At export time, the export service reads the file and embeds it. This keeps JSON settings files small and lets the user swap logos without re-entering settings.
```xml
<!-- SharePoint / Graph API -->
<PackageReference Include="PnP.Framework" Version="1.18.0" />
<PackageReference Include="Microsoft.Graph" Version="5.103.0" />
- `AppSettings.MspLogoPath: string?` — path to MSP logo file
- `TenantProfile.ClientLogoPath: string?` — path to client logo file for this tenant
<!-- Authentication -->
<PackageReference Include="Microsoft.Identity.Client" Version="4.83.1" />
<PackageReference Include="Microsoft.Identity.Client.Extensions.Msal" Version="4.83.3" />
<PackageReference Include="Microsoft.Identity.Client.Desktop" Version="4.82.1" />
The settings UI uses WPF `OpenFileDialog` (already used in multiple ViewModels) to browse for image files — filter to `*.png;*.jpg;*.jpeg;*.gif;*.svg`.
<!-- MVVM + DI -->
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.0" />
**Logo preview in WPF UI:** Use `BitmapImage` (built into `System.Windows.Media.Imaging`, already in scope for any WPF project). Bind a WPF `Image` control's `Source` to a `BitmapImage` loaded from the file path.
<!-- Logging -->
<PackageReference Include="Serilog" Version="4.3.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="10.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
```csharp
// In ViewModel — logo preview
[ObservableProperty]
private BitmapImage? _mspLogoPreview;
<!-- Charts -->
<PackageReference Include="ScottPlot.WPF" Version="5.1.57" />
<!-- CSV Export -->
<PackageReference Include="CsvHelper" Version="33.0.1" />
partial void OnMspLogoPathChanged(string? value)
{
if (string.IsNullOrWhiteSpace(value) || !File.Exists(value))
{
MspLogoPreview = null;
return;
}
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri(value, UriKind.Absolute);
bmp.CacheOption = BitmapCacheOption.OnLoad; // close file handle immediately
bmp.EndInit();
MspLogoPreview = bmp;
}
```
---
## Alternatives Considered
| Category | Recommended | Alternative | Why Not |
|----------|-------------|-------------|---------|
| .NET version | .NET 10 LTS | .NET 8 LTS | .NET 8 support ends November 2026 — too soon for a new project to start on |
| .NET version | .NET 10 LTS | .NET 9 STS | .NET 9 ended May 2026 — already past EOL at time of writing |
| SharePoint API | PnP.Framework | PnP Core SDK | PnP Core SDK is Graph-first and not yet feature-complete for CSOM-heavy provisioning operations. Wrong choice for a migration from PnP.PowerShell patterns. |
| MVVM toolkit | CommunityToolkit.Mvvm | Prism | Prism adds module/region/navigation complexity appropriate for large enterprise apps. This is a focused admin tool — CommunityToolkit.Mvvm is leaner and Microsoft-maintained. |
| Charts | ScottPlot.WPF | LiveCharts2 | LiveCharts2 WPF package is still RC (2.0.0-rc6.1). Unstable API surface is inappropriate for production. |
| Charts | ScottPlot.WPF | OxyPlot | OxyPlot has poor performance on large datasets and limited interactivity. Low activity/maintenance compared to ScottPlot 5. |
| JSON | System.Text.Json | Newtonsoft.Json | Newtonsoft.Json adds ~500KB to EXE, is slower, and has no AOT support. Not needed for simple config structures. |
| Localization | ResX (.resx files) | WPF ResourceDictionary XAML | ResourceDictionary localization is more complex, harder to maintain with tooling, and overkill for a two-language app. ResX provides compile-time safety. |
| HTML reports | T4/StringBuilder | Razor / Blazor Hybrid | A dedicated template engine adds a dependency for what is a one-time file generation task. StringBuilder or Scriban (lightweight) is sufficient. |
| Logging | Serilog | Microsoft.Extensions.Logging (built-in) | Built-in logging lacks file sinks and structured event support without additional providers. Serilog is de facto standard for desktop .NET apps. |
**No new library needed:** `BitmapImage` lives in the WPF `PresentationCore` assembly, which is already a transitive dependency of any `<UseWPF>true</UseWPF>` project.
---
## What NOT to Use
### Feature 2: User Directory Browse Mode (Graph API)
| Avoid | Why | Use Instead |
|-------|-----|-------------|
| LiveCharts2 WPF | Still in RC (2.0.0-rc6.1 as of April 2026) — unstable API, potential breaking changes before 2.0 GA | ScottPlot.WPF 5.1.57 (stable, weekly releases) |
| PnP Core SDK (as primary SharePoint lib) | Graph-first design doesn't match the CSOM-heavy provisioning/permissions operations being migrated. The PnP Provisioning Engine is only in PnP.Framework | PnP.Framework 1.18.0 |
| Prism Framework | Overengineered for this use case. Adds module system, region navigation complexity that doesn't match a single-window admin tool | CommunityToolkit.Mvvm 8.4.2 |
| PublishTrimmed=true | PnP.Framework and MSAL.NET use reflection and are not trim-safe. Trimming causes runtime crashes | Keep trimming disabled; accept larger EXE |
| .NET 8 as target | EOL November 2026 — a new project started now should not immediately be on a near-EOL runtime | .NET 10 LTS (supported until November 2028) |
| SQLite / LiteDB | Out of scope per project constraints. JSON is sufficient for profiles, settings, templates. | System.Text.Json with file-based storage |
| DeviceLogin / client secrets for auth | Per project memory note: MSP workflow requires interactive login, never DeviceLogin for PnP registration | MSAL interactive browser login via `WithInteractiveBrowser()` |
| WinForms | The existing app is WinForms. The rewrite targets WPF explicitly for MVVM data binding and richer styling | WPF |
**Requirement:** In the User Access Audit tab, add a "Browse" mode alternative to the people-picker search. Shows a paginated list of all users in the tenant — no search query, just the full directory — allowing the admin to pick users by scrolling/filtering locally.
#### Graph API endpoint: GET /users (no filter)
The existing `GraphUserSearchService` calls `GET /users?$filter=startsWith(...)` with `ConsistencyLevel: eventual`. Full directory listing removes the `$filter` and uses `$select` for the fields needed.
**Minimum required fields for directory browse:**
```
displayName, userPrincipalName, mail, jobTitle, department, userType, accountEnabled
```
- `userType`: distinguish `"Member"` from `"Guest"` — useful for MSP admin context
- `accountEnabled`: allow filtering out disabled accounts
- `jobTitle` / `department`: helps admin identify the right user in large directories
**Permissions required (confirmed from Microsoft Learn):**
| Scope type | Minimum permission |
|---|---|
| Delegated (work/school) | `User.Read.All` |
The existing auth uses `https://graph.microsoft.com/.default` which resolves to whatever scopes the Azure AD app registration has consented. If the MSP's app has `User.Read.All` consented (required for the existing people-picker to work), no new permission is needed — `GET /users` without `$filter` uses the same `User.Read.All` scope.
**Pagination — PageIterator pattern:**
`GET /users` returns a default page size of 100 with a maximum of 999 via `$top`. For tenants with hundreds or thousands of users, pagination via `@odata.nextLink` is mandatory.
The `Microsoft.Graph` 5.x SDK (already installed at 5.74.0) includes `PageIterator<TEntity, TCollectionResponse>` in `Microsoft.Graph.Core`. No version upgrade required.
```csharp
// In a new IGraphUserDirectoryService / GraphUserDirectoryService:
var firstPage = await graphClient.Users.GetAsync(config =>
{
config.QueryParameters.Select = new[]
{
"displayName", "userPrincipalName", "mail",
"jobTitle", "department", "userType", "accountEnabled"
};
config.QueryParameters.Top = 999; // max page size
config.QueryParameters.Orderby = new[] { "displayName" };
config.Headers.Add("ConsistencyLevel", "eventual");
config.QueryParameters.Count = true; // required for $orderby with eventual
}, ct);
var allUsers = new List<DirectoryUserResult>();
var pageIterator = PageIterator<User, UserCollectionResponse>.CreatePageIterator(
graphClient,
firstPage,
user =>
{
if (user.AccountEnabled == true) // optionally skip disabled
allUsers.Add(new DirectoryUserResult(
user.DisplayName ?? user.UserPrincipalName ?? string.Empty,
user.UserPrincipalName ?? string.Empty,
user.Mail,
user.JobTitle,
user.Department,
user.UserType == "Guest"));
return true; // continue iteration
});
await pageIterator.IterateAsync(ct);
```
**Why PageIterator over manual nextLink loop:**
The Graph SDK's `PageIterator` correctly handles the `DirectoryPageTokenNotFoundException` pitfall — it uses the token from the last successful non-retry response for the next page request. Manual loops using `withUrl(nextLink)` are susceptible to this error if any retry occurs mid-iteration. The SDK pattern is the documented recommendation (Microsoft Learn, updated 2025-08-06).
**Performance consideration — large tenants:**
A tenant with 5,000 users fetching `$top=999` requires 5 API round-trips. At ~300-500 ms per call, this is 1.52.5 seconds total. This is acceptable for a browse-on-demand operation with a loading indicator. Do NOT load the directory automatically on tab open — require an explicit "Load Directory" button click.
**Local filtering after load:**
Once the full directory is in memory (as an `ObservableCollection<DirectoryUserResult>`), use `ICollectionView` with a `Filter` predicate for instant local text-filter — the same pattern already used in the `PermissionsViewModel` and `StorageViewModel`. No server round-trips needed for filtering once the list is loaded. This is already in-process for the existing ViewModels and requires no new library.
**New model record:**
```csharp
// Core/Models/DirectoryUserResult.cs — or extend GraphUserResult
public record DirectoryUserResult(
string DisplayName,
string UserPrincipalName,
string? Mail,
string? JobTitle,
string? Department,
bool IsGuest);
```
**New service interface:**
```csharp
// Services/IGraphUserDirectoryService.cs
public interface IGraphUserDirectoryService
{
Task<IReadOnlyList<DirectoryUserResult>> GetAllUsersAsync(
string clientId,
bool includeGuests = true,
bool includeDisabled = false,
CancellationToken ct = default);
}
```
The implementation follows the same `GraphClientFactory` + `GraphServiceClient` pattern as `GraphUserSearchService`. Wire it in DI alongside the existing search service.
---
## Version Compatibility Notes
## No New NuGet Packages Required
| Concern | Detail |
|---------|--------|
| PnP.Framework on .NET 10 | PnP.Framework targets .NET Standard 2.0, .NET 8.0, .NET 9.0. It runs on .NET 10 via .NET Standard 2.0 compatibility. No explicit .NET 10 TFM yet (as of April 2026), but the .NET Standard 2.0 path is stable. |
| MSAL version pinning | PnP.Framework 1.18.0 requires `Microsoft.Identity.Client.Extensions.Msal >= 4.70.2`. Installing 4.83.3 satisfies this constraint. Pin to 4.83.x to avoid drift. |
| Microsoft.Graph SDK major version | Use 5.x only. The 4.x to 5.x upgrade introduced Kiota-generated code with significant breaking changes. Do not mix 4.x and 5.x packages. |
| CommunityToolkit.Mvvm source generators | 8.4.2 introduces partial properties support requiring C# 13 / .NET 9+ SDK. On .NET 10 this is fully supported. |
| ScottPlot.WPF + SkiaSharp | ScottPlot 5.x bundles SkiaSharp. Ensure no version conflict if SkiaSharp is pulled in by another dependency. ScottPlot.WPF 5.1.57 bundles SkiaSharp 2.88.x. |
| Feature | What's needed | How provided |
|---|---|---|
| Logo file → Base64 data URI | `Convert.ToBase64String`, `File.ReadAllBytesAsync` | BCL (.NET 10) |
| Logo preview in WPF settings | `BitmapImage`, `Image` control | WPF / PresentationCore |
| Logo file picker | `OpenFileDialog` | WPF / Microsoft.Win32 |
| Store logo path in settings | `AppSettings.MspLogoPath`, `TenantProfile.ClientLogoPath` | Extend existing models |
| User directory listing | `graphClient.Users.GetAsync()` + `PageIterator` | Microsoft.Graph 5.74.0 (already installed) |
| Local filtering of directory list | `ICollectionView.Filter` | WPF / System.Windows.Data |
**Do NOT add:**
- Any HTML template engine (Razor, Scriban, Handlebars) — `StringBuilder` is sufficient for logo injection
- Any image processing library (ImageSharp, SkiaSharp standalone, Magick.NET) — no image transformation is needed, only raw bytes → Base64
- Any new Graph SDK packages — `Microsoft.Graph` 5.74.0 already includes `PageIterator`
---
## Impact on Existing Services
### HTML Export Services
Each existing export service (`HtmlExportService`, `UserAccessHtmlExportService`, `StorageHtmlExportService`, `DuplicatesHtmlExportService`, `SearchHtmlExportService`) needs a logo injection point. Two options:
**Option A (recommended): `ReportBrandingContext` parameter**
Introduce a small record carrying resolved logo data URIs. Export services accept it as an optional parameter; when null, no logo header is rendered. This keeps the services testable without file I/O.
```csharp
public record ReportBrandingContext(
string? MspLogoDataUri, // "data:image/png;base64,..." or null
string? ClientLogoDataUri, // "data:image/png;base64,..." or null
string? MspName,
string? ClientName);
```
A `ReportBrandingService` converts file paths to data URIs. ViewModels call it before invoking the export service.
**Option B: Inject branding directly into all BuildHtml signatures**
Less clean — modifies every export service signature and every call site.
Option A is preferred: it isolates file I/O from HTML generation and keeps existing tests passing without changes.
### UserAccessAuditViewModel
Add a `BrowseMode` boolean property (bound to a RadioButton or ToggleButton). When `true`, show the directory list panel instead of the people-picker search box. The `IGraphUserDirectoryService` is injected alongside the existing `IGraphUserSearchService`.
---
## Existing Stack (Unchanged)
The full stack as validated through v1.1:
| Technology | Version | Purpose |
|---|---|---|
| .NET 10 | 10.x | Target runtime (LTS until Nov 2028) |
| WPF | built-in | UI framework |
| C# 13 | built-in | Language |
| PnP.Framework | 1.18.0 | SharePoint CSOM, provisioning engine |
| Microsoft.Graph | 5.74.0 | Graph API (users, Teams, Groups) |
| Microsoft.Identity.Client (MSAL) | 4.83.3 | Multi-tenant auth, token acquisition |
| Microsoft.Identity.Client.Extensions.Msal | 4.83.3 | Token cache persistence |
| Microsoft.Identity.Client.Broker | 4.82.1 | Windows broker (WAM) |
| CommunityToolkit.Mvvm | 8.4.2 | MVVM base classes, source generators |
| Microsoft.Extensions.Hosting | 10.0.0 | DI container, app lifetime |
| LiveCharts2 (SkiaSharpView.WPF) | 2.0.0-rc5.4 | Storage charts (in use, stable enough) |
| Serilog | 4.3.1 | Structured logging |
| Serilog.Extensions.Hosting | 10.0.0 | ILogger<T> bridge |
| Serilog.Sinks.File | 7.0.0 | Rolling file output |
| CsvHelper | 33.1.0 | CSV export |
| System.Text.Json | built-in | JSON settings/profiles/templates |
| xUnit | 2.9.3 | Unit tests |
| Moq | 4.20.72 | Test mocking |
---
## Sources
- NuGet: https://www.nuget.org/packages/PnP.Framework/version 1.18.0 confirmed, .NET targets confirmed
- NuGet: https://www.nuget.org/packages/Microsoft.Graph/ — version 5.103.0 confirmed
- NuGet: https://www.nuget.org/packages/microsoft.identity.client — version 4.83.1 confirmed
- NuGet: https://www.nuget.org/packages/Microsoft.Identity.Client.Extensions.Msal/ — version 4.83.3 confirmed
- NuGet: https://www.nuget.org/packages/CommunityToolkit.Mvvm/ — version 8.4.2 confirmed
- NuGet: https://www.nuget.org/packages/ScottPlot.WPF — version 5.1.57 (stable), 5.1.58 (latest as of March 2026)
- NuGet: https://www.nuget.org/packages/serilog/ — version 4.3.1 confirmed
- Microsoft Learn: https://learn.microsoft.com/en-us/dotnet/core/deploying/single-file/overview — PublishSingleFile guidance, .NET 8+ SelfContained behavior change
- .NET Blog: https://devblogs.microsoft.com/dotnet/announcing-dotnet-10/ — .NET 10 LTS November 2025 GA
- .NET Support Policy: https://dotnet.microsoft.com/en-us/platform/support/policy/dotnet-core — LTS lifecycle dates
- PnP Framework GitHub: https://github.com/pnp/pnpframework — .NET targets, auth patterns
- PnP Framework vs Core comparison: https://github.com/pnp/pnpframework/issues/620 — authoritative guidance on which library to use
- MSAL token cache: https://learn.microsoft.com/en-us/entra/msal/dotnet/how-to/token-cache-serialization — cache serialization patterns
- CommunityToolkit 8.4 announcement: https://devblogs.microsoft.com/dotnet/announcing-the-dotnet-community-toolkit-840/ — partial properties, .NET 10 support
---
*Stack research for: SharePoint Online administration desktop tool (C#/WPF)*
*Researched: 2026-04-02*
- Microsoft Learn — List users (Graph v1.0): https://learn.microsoft.com/en-us/graph/api/user-list?view=graph-rest-1.0permissions, $top max 999, $orderby with ConsistencyLevel, default fields (HIGH confidence, updated 2025-07-23)
- Microsoft Learn — Page through a collection (Graph SDKs): https://learn.microsoft.com/en-us/graph/sdks/paging — PageIterator C# pattern, DirectoryPageTokenNotFoundException warning (HIGH confidence, updated 2025-08-06)
- Microsoft Learn — Get organizationalBranding: https://learn.microsoft.com/en-us/graph/api/organizationalbranding-get?view=graph-rest-1.0 — branding stream retrieval via localizations/default/bannerLogo (HIGH confidence, updated 2025-11-08) — note: tenant branding pull is optional/future, not required for v2.2 which relies on user-supplied logo files
- .NET Perls / BCL docs — Convert.ToBase64String + data URI pattern: confirmed BCL, no library needed (HIGH confidence)
- Existing codebase inspection: GraphClientFactory.cs, GraphUserSearchService.cs, HtmlExportService.cs, UserAccessHtmlExportService.cs, TenantProfile.cs, AppSettings.cs — confirmed exact integration points