NullReferenceException at DriveItemRequestBuilderExtensions.ItemWithPath (packaged WinUI 3 app)
Describe the bug
This code throws NullReferenceException in a packaged WinUI 3 app (so maybe something related to Native AOT):
var driveItem = _graphServiceClient.Drives[driveId].Items[itemId].ItemWithPath(relativePath).GetAsync();
Crash:
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Graph.DriveItemRequestBuilderExtensions.ItemWithPath(DriveItemItemRequestBuilder, String)
Expected behavior
No crash
How to reproduce
- Create a WinUI 3 app
- Add some code to call
ItemWithPath, for example:var driveItem = _graphServiceClient.Drives[driveId].Items[itemId].ItemWithPath(relativePath).GetAsync(); - Add to .csproj:
<GenerateAppxPackageOnBuild>true</GenerateAppxPackageOnBuild> - Start debugging (release build)
SDK Version
5.77.0
Latest version known to work for scenario above?
No response
Known Workarounds
Do not use .ItemWithPath, for example:
private async Task<DriveItem> GetItemAsync(string relativePath)
{
// Normalize the path to use forward slashes
relativePath = relativePath.Replace('\\', '/');
var pathParts = relativePath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var currentItem = await GraphServiceClient
.Drives[DriveId]
.Items[Id]
.GetAsync().ConfigureAwait(false);
foreach (var part in pathParts)
{
var children = await GraphServiceClient
.Drives[DriveId]
.Items[currentItem.Id]
.Children
.GetAsync().ConfigureAwait(false);
currentItem = children.Value
.FirstOrDefault(item => item.Name.Equals(part, StringComparison.OrdinalIgnoreCase));
if (currentItem == null)
{
throw new FileNotFoundException($"Item '{part}' not found in the path.");
}
}
return currentItem;
}
Debug output
No response
Configuration
- WIndows 11
- arm64
Other information
I added some logging and noticed that in this code the variable field will be null which is not correct (it has a valid value in a debug build):
https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/main/src/Microsoft.Graph/Extensions/DriveItemRequestBuilderExtensions.cs#L95
I see there also these build warnings:
Assembly 'Microsoft.Kiota.Serialization.Json' produced trim warnings. For more information see https://aka.ms/il2104
Assembly 'Microsoft.Graph' produced trim warnings. For more information see https://aka.ms/il2104
Any info about this? I've got the same NRE, as well as the same build warnings in my UWP .NET 9 app.
I did some digging and found that the issue lies in the DriveItemRequestBuilderExtensions class, which is unsafe for Trimming (but no warning is generated when building the library, for some reason).
As a workaround, I've found that adding the following DynamicDependency where ItemWithPath() is used fixes the NullReferenceException with Native AOT :
[DynamicDependency(DynamicallyAccessedMemberTypes.NonPublicFields, typeof(BaseRequestBuilder))]