Archive for category Error

The pesky “There is already an object named ‘Audit’ in the database” error

Yes, we’ve all been there. We are happily adding a new model to be added to our Entity Framework-based application and “BAM!!!”, we get that error. It caused much weeping and gnashing of teeth.

I’m a simple man with simple needs, such as getting my application working. In my case, this error happened early on in the lifecycle of my project. I had my initial migration, and then a second migration, and during the “Update-Database” statement of the second migration was when I received this message.

My solution was the comment-out the entire “Up” method of the initial migration:

        protected override void Up(MigrationBuilder migrationBuilder)
        {
            //migrationBuilder.CreateTable(
            //    name: "Coaster",
            //    columns: table => new
            //    {
            //        Id = table.Column<int>(type: "int", nullable: false)
            //            .Annotation("SqlServer:Identity", "1, 1"),
            //        Name = table.Column<string>(type: "nvarchar(max)", nullable: false)
            //    },
            //    constraints: table =>
            //    {
            //        table.PrimaryKey("PK_Coaster", x => x.Id);
            //    });
         }

Perhaps a blunt force approach. But then again, it worked.

Leave a comment

Error in “razor.g.cs” file

After building my project I was seeing errors reported in the MainLayout.razor.g.cs file. This file didn’t even exist, but it was giving me errors. And there were no further helpful messages in the “Errors” tab in Visual Studio.

Cutting to the chase, the problem was there was an error in the MainLayout.razor file, but the compiler wasn’t telling me in a straightforward manner. But when I opened the MainLayout.razor page, I did see the red squiggles and was able to resolve it. So when you see a file in a “g.cs” file, open the razor page to which it is referring.

Leave a comment

Error: Cannot provide a value for property ‘TokenAcquisitionService’

While converting my Blazor server application from our existing authentication scheme to use Microsoft Authentication Services using Azure Active Directory, and I ran into this error:

Error: System.InvalidOperationException: Cannot provide a value for property 'TokenAcquisitionService' on type 'BlazorCoasterApp.Pages.FetchData'. There is no registered service of type 'Microsoft.Identity.Web.ITokenAcquisition'.

To figure out what was missing, I found a tutorial on the Microsoft site. There is a lot of good information in that tutorial, but for fixing my error, there were two lines that were a huge help. The first downloaded the MS Identity templates:

dotnet new install Microsoft.Identity.Web.ProjectTemplates

The second was using the dotnet command to generate the application:

dotnet new blazorserver --auth SingleOrg --calls-graph -o {APP NAME} --client-id "{CLIENT ID}" --tenant-id "{TENANT ID}" --domain "{DOMAIN}" -f net7.0

This blog post isn’t about the complete process of creating an Azure AD application and all the fun that comes with setting it up, but another MS tutorial provides great information on how to do that.

After creating the application, I went through my Blazor app to find the differences between the application that was created by the tutorial and the one I did on my own. The first was that I didn’t have the Microsoft.Identity.Web.MicrosoftGraph NuGet package installed.

The second problem involved some missing lines in the Program.cs file. I am showing part of my file, and the bolded lines are the ones that were missing:

var builder = WebApplication.CreateBuilder(args);

var initialScopes = builder.Configuration[“DownstreamApi:Scopes”]?.Split(‘ ‘);

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection(“AzureAd”))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(builder.Configuration.GetSection(“DownstreamApi”))
.AddInMemoryTokenCaches();
builder.Services.AddControllersWithViews()
.AddMicrosoftIdentityUI();

builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy
options.FallbackPolicy = options.DefaultPolicy;
});

So if you are having problems getting the identity services to work, I recommend creating a new application using the method above and seeing what the differences are.

Leave a comment

Cannot convert void to EventCallback in Blazor

I had created a simple method in a Razor page in my Blazor app – nothing fancy:

private void DownloadFile(string fileName)
{
    // Do something awesome
}

This method was to be called when a button was clicked. Again, not too fancy:

<input type="button" value="Download" @onclick="DownloadFile(document.Key)" />

But this little method wasn’t like by Visual Studio, giving me the error “Argument 2: cannot convert from ‘void’ to ‘Microsoft.AspNetCore.Components.EventCallback’

To fix this, I used the inline method syntax, and this called the method without complaint:

input type="button" value="Download" @onclick="(() => DownloadFile(document.Key))" class="btn btn-primary" />

Leave a comment

Unable to connect to web server ‘IIS Express’

If you have found this post it is because you are, at this very moment, irritated. For me, this errors happens about every week or two. I primarily work with .NET Core application and it seems to happen to me more than the old .NET Framework stuff, but maybe it’s my perception.

There are three solutions I have found:

  1. Reboot. Yes, this works, but it is a productivity killer
  2. Delete the applicationhost.config file found in the .vs\config folder. I have found this solution to be hit or miss. For me, this usually doesn’t work
  3. Delete the launchSettings.json file in the Solution Name\Project Name\Properties folder. This is the solution that consistently works for me

Good luck with your connection frustration. Beer helps for me – your mileage may vary.

Leave a comment

DbContext not properly caching in .NET Core / Blazor

I ran into an issue with a seemingly simple Entity Framework Core add / update method. This code allowed the user to either add or update a new Activity, and it simply updated the database:

        public void UpdateActivity(Activity activity)
        {
            var activities = _context.Activities.Where(a => a.Name == activity.Name).FirstOrDefault();

            if (activities != null)
            {
                return null;
            }

            if (activity == null)
            {
                _context.Activities.Add(activity);
            }
            else
            {
                _context.Activities.Update(activity);
            }

            _context.SaveChanges();
        }

The problem came at the line that retrieved the Activities from the context:

var activities = _context.Activities.Where(a => a.Name == activity.Name).FirstOrDefault();

When updating an existing object, the query would return a matching record for a name that I knew did not exist in the database. I had run into something similiar on another .NET Core Blazor project where the context was not properly updating the records in memory and to solve the issue there, I created a new DbContext and continued on with the query:

            DbContextOptions<CoasterDbContext> options = new DbContextOptions<CoasterDbContext>();
            var optionsBuilder = new DbContextOptionsBuilder<CoasterDbContext>();
            optionsBuilder.UseSqlServer(_configuration.GetConnectionString("CoasterConnection"));
            var _context = new CoasterDbContext(optionsBuilder.Options);

Though it worked in another project, in this case, it didn’t work – I ran into a ID tracking issue.

To get this solved, I had to use the EF Entry().Reload() method. Of course, this will reload the entity passed into it, so I saved the new name of the Activity before reloading it. I then check to see if there are any existing records with the name I saved into a variable.

        public Activity UpdateActivity(Activity activity)
        {
            string activityName = activity.Name;
            _context.Entry(activity).Reload();

            var activities = _context.Activities.AsAsyncEnumerable().Where(a => a.Name == activityName).FirstOrDefaultAsync().Result;

            if (activities != null)
            {
                return null;
            }

            ...
        }

This hack worked, though I’m not sure why other projects do the same type of operation and work as expected.

Leave a comment

MudBlazor.MudListItem has the same key value

While working with the MudAutomplete control, I was pulling records from the database and I encountered this error:

More than one sibling of component 'MudBlazor.MudListItem' has the same key value, 'Millennium Force'. Key values must be unique.

This seems fairly straight-forward, but not quite. The key values were unique. However, the values displayed (i.e. the text) also had to be unique. So I had data like this:

ID     Name
1      Millennium Force
2      Gemini
3      Mine Ride
4      Millennium Force

I had two unique records with the same name, and if you are working with legacy data, this type of thing can happen. You may not be able to disregard one of the records because perhaps you have other data that references either one of those records.

My solution was to append the ID to the name of the ID to the name, making the name unique. This allowed the MudAutocomplete to display the records and tells the user that the records are different and what their ID is. If your data set has fields that would be better as differentiating the (such as “Park Name”), then append that value instead.

coasters.Add(new KeyValuePair<int, string>(int.Parse(reader[0].ToString()), $"{reader[1].ToString()} ({reader[0].ToString()})"));

Leave a comment

JS interop: The JSON value could not be converted to System.Boolean

I was attempting to use a JavaScript alert method in my Blazor with this amazing code:

        if (String.IsNullOrEmpty(coaster.Name))
        {
            await JsRuntime.InvokeAsync<bool>("alert", "Your coaster needs a name.");
            return;
        }

This simple bit of code was returning the error “An exception occurred executing JS interop: The JSON value could not be converted to System.Boolean”.

Luckily, this was a simple thing to fix. Instead of using a bool type in the InvolkeAsync call, instead use an object:

            await JsRuntime.InvokeAsync<object>("alert", "Your coaster needs a name.");

That should fix your problem.

Leave a comment

COULD NOT LOAD FILE OR ASSEMBLY ‘DOTNETNUKE.HTTPMODULES’

After deploying an application to production, I received the message:

COULD NOT LOAD FILE OR ASSEMBLY 'DOTNETNUKE.HTTPMODULES' OR ONE OF ITS DEPENDENCIES.

sMy web.config did not reference any DotNetNuke libraries.

To solve this, I had to open the IIS application, then go to the “Modules” section:

I then sorted the results by “Code” (one of the columns in that screen) and found all references that started with DotNetNuke or DNN. After removing them, all was well.

Leave a comment

Context doesn’t build properly after EDMX file update

I needed to update an EDMX file in a data project (Coaster.Data), adding a new table from the database. This worked fine – I just right clicked on the EDMX file workspace and added my table as normal. However, after attempting to build the data project, none of the DbSet properties were showing up, so all projects that depended on Coaster.Data were failing because properties they referenced were no longer there. For example, the following code would complain that “Park” didn’t exist:

var result = from coaster in context.Park.Where(p => p.Name == "Cedar Point");

It turns out the context class was blown away for some reason and not populated. In the Coaster.Data project, under the Coaster.tt file, I had the context class Coaster.cs. This is the class that held the list of DbSet properties:

This file was empty, devoid of all properties that made it useful – this was all I saw in there was:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

Not useful. So I went back into source control and repopulated the DbSet properties that I need:

namespace Coaster.Data
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class CoasterEntities : DbContext
    {
        public CoasterEntities()
            : base("name=CoasterEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Park> Parks { get; set; }
        public virtual DbSet<Company> Companies { get; set; }
    }
}

Project built properly again.

Leave a comment