There was an error running the selected code generator in .Net Core 5

I’m working on a new .Net Core 5 web app with user authentication and Identity Server 4 where I need to customize some of the Identity account pages (Login, Register, Forgot Password, etc). Out of the box these pages are built into .Net Core and Identity Server 4 so there’s nothing you need to do to use them. However, if you want to customize any of the account pages you’ll need to scaffold the source of those pages into your project.

In the latest version of Visual Studio 2019 – (Version 16.8.4 as of today) you are able to do this by right clicking the project and selected “Add –> New Scaffolded Item” for all .Net Core projects below version 5 without any issues. But if you are trying to scaffold Identity in .Net Core 5 from Visual Studio then you might run into this error:

“There was an error running the selected code generator: ‘Package restored failed. Rolling back package changes for ‘Your App’.”

A way around this is error I found was to use the dotnet CLI outside of Visual Studio. Follow these steps to scaffold the full Identity pages into your .Net Core 5 app.

  1. Close Visual Studio
  2. Open a command prompt and change directories to the project where you want to create the scaffolded items.
  3. Run the following command updating MyApp.Models.ApplicationDbContext to your own DbContext: dotnet aspnet-codegenerator identity -dc MyApp.Models.ApplicationDbContext

That should fix the “There was an error running the selected code generator” issue. You can also pass a set of parameters into the dotnet aspnet-codegenerator app if you only want to scaffold a certain number of files versus all Identity files.

Why I Write Unit Tests

In computer programming, unit testing is a software testing method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures, are tested to determine whether they are fit for use — wikipedia

Unit tests, who needs em? We all do. There are a lot of resources online that will tell you why unit testing is important or why writing unit tests before building implementations is a good idea. But I’m here to tell you how unit tests can save you a massive production headache.

A while back, a coworker pushed code to production that consumed and parsed large .csv files uploaded by users. The code looped through the file then parsed and mapped each record to the associated record in the model. The model contained a few bool fields that were populated by executing the C# Boolean.TryParse method against the text field to convert the string from the file to bool. If the TryParse method returned false then the value in the csv file must have been falsy, and vice versa for true. The record was applied to the model and saved to the database.

As it turned out, our code didn’t work as expected which caused a major problem. For bool fields users would upload either a 1 or 0. 1 being true and 0 being false. Because the source was a csv file all values were imported as strings. Therefore, before applying the values to our model, we must convert the string representation to the appropriate type within the model.

Here’s an example of the code, the Parse method below takes a string argument named parsable, does a Boolean.TryParse against parsable and returns the newly converted value.

	
	public static Main(){
	    var trueFalse = Parse("1");
	}
	
	public bool Parse(string parsable)
	{
		 bool flag;
		 bool result = Boolean.TryParse(parsable, out flag);
         return flag;
	}

From looking at the method and without knowing how C# Boolean.TryParse converts the string argument “1” to bool you’d think that this method returns true, not false. But in reality the above method returns false. Even though 1 generally equals true in most contexts, if passed in as a string the result is false, not true.

If we would have had proper unit tests set up we would have written a unit test that looks something like this:

[TestMethod]
public void Parse_BooleanTryParseString__ReturnsFalse()
{
    string stringToParse = "1";
    bool expected = true;
    bool actual = Parse(stringToParse);

    Assert.AreEqual(expected, actual);
}

The above unit test would have failed and we’d have found the problem, fixed it and been on our way. Unfortunately for us, we didn’t have a unit test for the above Parse method and QA didn’t catch the issue during their testing. The code eventually made its way to production, users start uploading files against the new code and yadda, yadda, yadda…we end up with a lot false values that should be true.

I've made a huge mistake

The good news is we were able to recover the lost data. But the recovery process took a few days and a lot of manual work which set us back on our timeline, not to mention created a garbage truck full of unwanted stress while we scrambled to recover the data and explain to our stakeholders that we’d made a huge mistake.

The takeaway my team and I had from this experience is how valuable a unit test can be. Unit tests are not just a key part of the testing process, but they’ve proven to be invaluable in making sure the code you write is actually doing what you think it’s doing.

Convert A Generic List To CSV File In C#

This is an example of how to convert a generic list to a dynamic downloadable .csv file using C#, the CsvHelper library and the FileStreamResult.

Download the repo and run the full project solution from Github

In this example a request comes into the controller, we create a generic list of type ListItem, created a memory stream and using the CsvWriter library  return a dynamic .csv file to the browser.

Step 1: Create the generic list class
This class will hold our generic list items. This can be whatever data you need.

public class ListItem
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Step 2: Create the MVC action to return the CSV file
This action method creates the generic list, writes it to memory with help from the CsvHelper library and returns the FileStreamResult back to the browser.

//Action Method for your controller
[HttpPost]
public ActionResult ConvertToCSV()
{
    //Create the test list
    var list = new List<ListItem>()
    {
        new ListItem(){Id = 1, Name = "Jerry"},
        new ListItem(){Id = 2, Name="George"},
        new ListItem(){Id = 3, Name="Kramer"},
        new ListItem(){Id = 4, Name = "Elaine"}
     };

    byte[] result;
    using (var memoryStream = new MemoryStream())
    {
        using (var streamWriter = new StreamWriter(memoryStream))
        {
            using (var csvWriter = new CsvWriter(streamWriter))
            {
                csvWriter.WriteRecords(list);
                streamWriter.Flush();
                result = memoryStream.ToArray();
            }
         }
     }

     return new FileStreamResult(new MemoryStream(result), "text/csv") { FileDownloadName = "filename.csv" };
}

h/t to this StackOverflow post

Download the repo and run the full project solution from Github