CommunityToolkit / CommunityToolkit/dotnet

[ObservableValidator] Crash on NativeAOT published app when using custom validator

Open
#810 2 comments 0 reactions 0 assignees View on GitHub
bug :bug:
Dominant language
C#
Stars
3.8k
Forks
400
PR merge metrics
No merged PRs in 30d

Description

### Describe the bug

If an app is published with NativeAOT active and it has custom validators, the app would crash when trying to validate the property. Debugging the NativeAOT app returns the error "The type `` does not contain a public property named ``."

### Regression

_No response_

### Steps to reproduce

```text
1. Create a new UI app that can be built with NativeAOT (for example, Avalonia).
2. Enable `PublishAot`

true

3. Create a UI that has a text box.
4. In the view model:

public sealed partial class MainWindowViewModel : ObservableValidator {

[ObservableProperty]
[IsValidPath(true)]
[NotifyDataErrorInfo]
string _sourceLocation;
}

6. Create a simple validator, like this:

public sealed class IsValidPathAttribute : ValidationAttribute
{
private readonly bool _isRequired;

public IsValidPathAttribute(bool required)
{
_isRequired = required;
}

public override bool IsValid(object value)
{
string potentialPath = value?.ToString();

if (!string.IsNullOrEmpty(potentialPath) || !string.IsNullOrWhiteSpace(potentialPath))
{
foreach (char invalidChar in Path.GetInvalidPathChars())
{
if (potentialPath.Contains(invalidChar))
{
ErrorMessage = "The path to the file shouldn't have invalid characters.";
return false;
}
}

if (!Directory.Exists(potentialPath) || !(Path.IsPathRooted(potentialPath) && !Path.GetPathRoot(potentialPath).Equals(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)))
{
ErrorMessage = "The path doesn't exist or isn't valid.";
return false;
}

return true;
}

if (_isRequired)
{
ErrorMessage = "This is required.";
}

return !_isRequired;
}
}

7. Bind the property to the text box and run.
8. Run the following command in the CLI (while pointing to the project's .csproj file):

dotnet publish -a x64 --self-contained

8 Run the published executable.
```

### Expected behavior

The app should run normally and do the proper validation.

### Screenshots

_No response_

### IDE and version

VS 2022

### IDE version

17.8.3

### Nuget packages

- [ ] CommunityToolkit.Common
- [ ] CommunityToolkit.Diagnostics
- [ ] CommunityToolkit.HighPerformance
- [X] CommunityToolkit.Mvvm (aka MVVM Toolkit)

### Nuget package version(s)

8.2.2

### Additional context

_No response_

### Help us help you

Yes, but only if others can assist

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.