Adding an Admin Panel to a .NET Core web app with CoreAdmin

I’ve published version 1.0.0 of a new open source package and a corresponding nuget package – CoreAdmin.

CoreAdmin adds a nice set of CRUD screens to your .NET Core web app in one line of code!

Adding CoreAdmin to your app

Given a typical Startup.cs file, you will have a ConfigureServices method. You need to add the line services.AddCoreAdmin() somewhere near the bottom (at least after you register your Entity Framework DbContexts).

Then when you visit your site with /coreadmin on the end of the URL, you’ll see this:

On the left you can see your database tables (these are the DBSets in your DbContexts). Click one and you get:

From here you can Create new entities, Delete and Edit them. Full searching, sorting, filtering etc are also supported.

There are a few limitations on data types and primary keys (for example, entities with composite primary keys are not supported for editing or deletion yet) but this should be sufficient for basic quick and dirty editing of entities.

How to get it

CoreAdmin on Github

CoreAdmin on NuGet

Simply install the nuget package “CoreAdmin” and you are good to go!  

Or watch a demo!

Here is a YouTube Style video demo.

Add An Admin Panel to a .NET Core App in 2 Minutes!
Watch this video on YouTube.

EF Core Migrations – creating Indexes Online depending on SQL Server edition

I recently hit the classic case of trying to add Indexes to a large table. Whilst Entity Framework Core supports creating Indexes online during migrations, not all versions of SQL Server support this.

In the case that your migration contains the code:

 migrationBuilder.CreateIndex(
                 name: "IX_TableName_ColumnName",
                 table: "TableName",
                 column: "ColumnName").Annotation("SqlServer:Online", true);

This will fail hard on SQL Server Express, which you are likely using for development locally, with the error message “Online index operations can only be performed in Enterprise edition of SQL Server.”. Online index operations are available in Enterprise or luckily in my case, Azure SQL.

Whilst there is not a “feature flag” to detect the support of Online index creation, you can execute the following query to detect the edition of SQL Server your app is running on.

SELECT SERVERPROPERTY(‘EngineEdition’)

Which returns 3 for Enterprise edition or 5 for SQL Azure (full list here).

EF Core has removed the ability to easily execute scalar queries so you’ll need a small extension method:

public static class SqlQueryExtensions
    {
        public static T ExecuteScalar<T>(this DbContext context, string rawSql,
         params object[] parameters)
        {
            var conn = context.Database.GetDbConnection();
            using (var command = conn.CreateCommand())
            {
                command.CommandText = rawSql;
                if (parameters != null)
                    foreach (var p in parameters)
                        command.Parameters.Add(p);
                conn.Open();
                return (T) command.ExecuteScalar();
            }
        }

 

And then you can set a public static property on your migration before calling DbContext.Migrate():

var dbEngineVersion = dbContext.ExecuteScalar<int>("SELECT SERVERPROPERTY('EngineEdition')");
MyMigrationName.UseOnlineIndexCreation = dbEngineVersion == 3 || dbEngineVersion == 5;
dbContext.Database.Migrate();


public partial class MyMigrationName : Migration
{
    public static bool UseOnlineIndexCreation { get; set; }

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        if (UseOnlineIndexCreation)
        {
            migrationBuilder.CreateIndex(
             name: "IX_TableName_ColumnName",
             table: "TableName",
             column: "ColumnName").Annotation("SqlServer:Online", true);
        }
        else
        {
            migrationBuilder.CreateIndex(
             name: "IX_TableName_ColumnName",
             table: "TableName",
             column: "ColumnName");
            }

        }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropIndex(
            name: "IX_TableName_ColumnName",
            table: "AuditTrail");
    }
}

Now your Index will be created Online on editions of SQL Server that support it.

 

Missing StoreKey PFX certificates when building a Visual Studio 2019 UWP project

I came across an interesting issue updating my UWP app to Visual Studio 2019 and a new Azure DevOps pipeline. “Associate with Store” no longer adds password-less PFX files named *TemporaryKey.pfx and *StoreKey.pfx to your project to sign your store submissions – instead in VS2019 it now adds the certificates to your local user store only.

Which means when it comes to build, you get errors like

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\AppxPackage\Microsoft.AppXPackage.Targets(4353,5): Error APPX0102: A certificate with thumbprint '' that is specified in the project cannot be found in the certificate store. Please specify a valid thumbprint in the project file.
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\AppxPackage\Microsoft.AppXPackage.Targets(4353,5): Error APPX0107: The certificate specified is not valid for signing. For more information about valid certificates, see http://go.microsoft.com/fwlink/?LinkID=241478.

For comparison:

Above: Visual Studio 2017

Above: Visual Studio 2019 – notice the options to select from file and create test certificate are no longer.

To fix this for Azure Devops, you’ll need to install the PFX private key on every build. Follow these steps:

  • On the Choose Certificate window (shown above) choose View Full Certificate
  • On the second tab, choose “Copy to file…” to start the export to PFX process
  • Export the private key to a password protected PFX file
  • Add the PFX file to your project directory, like where it used to be in VS 2017
  • Update your .csproj file, adding a <PackageCertificateKeyFile> element containing the filename alongside <PackageCertificateThumbprint>
  • Add your PFX to source control making sure it is not ignored
  • In Azure Devops Pipelines, you’ll need a quick Powershell build step to add the certificate to the local user store:
  • Make sure that the WorkingDirectory option is set to the folder with the PFX file (alongside the .csproj) file.

That Powershell script in full:

$pfxpath = 'MySigningKey.pfx'
$password = 'supersecretpassword'

Add-Type -AssemblyName System.Security
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($pfxpath, $password, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"PersistKeySet")
$store = new-object system.security.cryptography.X509Certificates.X509Store -argumentlist "MY", CurrentUser
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]"ReadWrite")
$store.Add($cert)
$store.Close()

Now when your app is built, the private signing key will be loaded from the local machine store.

A note on security

The above is a quick and dirty way of getting this working – adding a PFX file to your source code repository is not best practice and you shouldn’t do this if you can help it. This is probably why Microsoft changed this behaviour in VS2019. An improvement on this could be to use the Secure Files feature of Azure DevOps to securely hold the PFX file until the build templates have a decent way of handing this scenario.