Home > Enterprise >  Visual Studio 2022 v17.2.4 - Weird exceptions in .NET Blazor Server
Visual Studio 2022 v17.2.4 - Weird exceptions in .NET Blazor Server

Time:06-18

I have a .NET 6 Blazor Server application I have been working on for a while. Last night when I closed Visual Studio it updated to the latest version (17.2.4 at this time). When I came back to said project the following day and try to compile the project I get a bunch of weird errors (previously I had none):

Error CS0116 A namespace cannot directly contain members such as fields, methods or statements D:\Repositories\MyWebApp\MyWebApp.Web\Microsoft.NET.Sdk.Razor.SourceGenerators\Microsoft.NET.Sdk.Razor.SourceGenerators.RazorSourceGenerator\Pages_Sample_razor.g.cs 356

Error CS0246 The type or namespace name 'await' could not be found (are you missing a using directive or an assembly reference?) SuggestionApp.Web D:\Repositories\MyWebApp\MyWebApp.Web\Pages\Sample.razor 67

Error CS8802 Only one compilation unit can have top-level statements. SuggestionApp.Web D:\Repositories\MyWebApp\MyWebApp.Web\Pages\Sample.razor 89

The application worked perfectly the day before, but now I get 20 of these errors. I have not touched anything in the auto-generated files, nor did I make any changes to the blazor component in question Sample.razor.

I tried cleaning up the solution, I tried creating a different file none of my attempts worked.

My guess is that the issue is somehow caused by the VS update even though there was nothing about blazor in the release notes. Am I the only one with this issue or is there a fix to this sort of problem that I am not aware of?

CodePudding user response:

Have you checked the build output? Most often it will hint which file [indicates FAILED] to stare at until something becomes obvious. Takes me back to my PHP days...

Just my two cents but when I've run into this it's because I either accidentally added or am missing a character [ { , } , < , > , ; ...] in the markup or elsewhere, especially when it's the razor.g.cs files complaining.

As others have suggested, cleaning the solution or deleting the \bin and \obj can folders help.

CodePudding user response:

The reason I was getting all these weird errors mentioned above is because blazor interpreted the indentation incorrectly. Here is the file that threw all the exception Sample.razor

@page "/sample"
@inject ICategoryData categoryData
@inject IStatusData statusData
@inject IUserData userData
@inject ISuggestionData suggestionData

<h3>Sample Data</h3>

@if (categoriesCreated)
{
    <h4>Categories have been created</h4>
}
else
{
    <button  @onclick="CreateCategories">Create 
Categories</button>
}

@if(statusesCreated)
{
    <h4>Statuses have been created</h4>
}
else
{
    <button  @onclick="CreateStatuses">Create 
Statuses</button>
}

<button  @onclick="GenerateSampleData">Generate 
Sample Data</button>

@code {
private bool categoriesCreated = false;
private bool statusesCreated = false;

private async Task GenerateSampleData()
{
    UserModel user = new()
    {
        FirstName = "Florin",
        LastName = "Zamfir",
        EmailAddress = "[email protected]",
        DisplayName = "TestUser",
        ObjectIdentifier = "test"
    };

    await userData.CreateUser(user);

    var foundUser = await userData.GetUserFromAuthentication("test");
    var categories = await categoryData.GetAllCategories();
    var statuses = await statusData.GetAllStatuses();

    HashSet<string> votes = new();

    votes.Add("1");
    votes.Add("2");
    votes.Add("3");
    votes.Add("4");     
    
    SuggestionModel suggestion = new()
    {
        Author = new BasicUserModel(foundUser),
        Category = categories[0],
        Suggestion = "Our First Suggetion",
        SuggestionStatus = statuses[1],
        UserVotes = votes,
        Description = "This is a suggestion created by the sample data 
generation method",
        ApprovedForRelease = true
    };

// For some reason blazor interpreted this as the end of the code block 
// hence the weird errors like "Type or namespace 'await' cannot be found"

    await suggestionData.CreateSuggestion(suggestion);

    suggestion = new()
    {
        Author = new BasicUserModel(foundUser),
        Category = categories[0],
        Suggestion = "Our Second Suggetion",
        SuggestionStatus = statuses[2],
        Description = "This is a suggestion created by the sample data 
generation method",
        ApprovedForRelease = true
    };

    await suggestionData.CreateSuggestion(suggestion);

    suggestion = new()
    {
        Author = new BasicUserModel(foundUser),
        Category = categories[1],
        Suggestion = "Our Third Suggetion",
        SuggestionStatus = statuses[3],
        Description = "This is a suggestion created by the sample data 
generation method",
        ApprovedForRelease = true
    };

    await suggestionData.CreateSuggestion(suggestion);

    suggestion = new()
    {
        Author = new BasicUserModel(foundUser),
        Category = categories[2],
        Suggestion = "Our Fourth Suggetion",
        SuggestionStatus = statuses[1],
        Description = "This is a suggestion created by the sample data 
generation method",
        ApprovedForRelease = true
    };

    await suggestionData.CreateSuggestion(suggestion);
}

private async Task CreateCategories()
{
    var categories = await categoryData.GetAllCategories();

    if (categories?.Count > 0) return;

    CategoryModel cat = new()
    {
        CategoryName = "Bug",
        CategoryDescription = "Report a bug"
    };

    await categoryData.CreateCategory(cat);

    cat = new()
    {
        CategoryName = "Feature",
        CategoryDescription = "Suggest a feature"
    };

    await categoryData.CreateCategory(cat);

    categoriesCreated = true;
}

private async Task CreateStatuses()
{
    var statuses = await statusData.GetAllStatuses();

    if (statuses?.Count > 0) return;

    StatusModel stat = new()
    {
        StatusName = "Completed",
        StatusDescription = ""
    };

    await statusData.CreateStatus(stat);

    stat = new()
    {
        StatusName = "Watching",
        StatusDescription = ""
    };

    await statusData.CreateStatus(stat);
    
    stat = new()
    {
        StatusName = "Upcoming",
        StatusDescription = ""
    };

    await statusData.CreateStatus(stat);

    stat = new()
    {
        StatusName = "Dismissed",
        StatusDescription = ""
    };

    await statusData.CreateStatus(stat);

    statusesCreated = true;
}

In the GenerateSampleData() method at the point where I put the comment in the code blazor interpreted that as being the end of the code block. At design time it did not show any errors. Once I try to compile it, it figures out that something is not right and throws all the exceptions.

I literally tried everything to fix it and in the end rewriting the method did the trick. I am surprised that replacing the file altogether didn't work even after deleting the \obj and \bin folders. I guess I will have to report this bug to Microsoft.

  • Related