First talk retrospective

I made it through my first lightning talk at the May meeting of the Nashville .NET user group. If you want some background you can check out this post on my preparation for the talk.

This post is going to be mostly for me to look back on in the future in case I decided to attempt another talk, but I am sure if someone is a new speaking it could be a useful as well.

Retro

Overall the talk went OK. There was no huge epic failure, but it far from a good talk. I was extremely nervous which lead to me be locked to the podium and flying through the talk way faster than I should have. I am pretty soft spoken and didn’t project as much as I really needed to. As a result of that is my points weren’t as clear as I would have liked.

David Neal was right that the audience does want you to succeed. There were a couple of questions at the end of my talk which made me feel that my point wasn’t totally lost. I got feedback for some of the audience members and other speakers which I included in the previous paragraph. All the feedback was presented to me in a kind manner which I greatly appreciated.

The future

In the future, if I try speaking again I have a lot of things I can improve on. I know that sounds negative, but I am looking at it as an opportunity to grow. I now know that I will need more time during the prepping stage to practice out loud and in front of people.

I love technology and sharing what I learn with others. That is one of the reasons I write this blog every week. Speaking may or may not be part of the future way I get to share with other, but I am happy to now know it is something I can do. It would require a ton of work, but it is no longer something I can’t ever see myself doing.

First talk retrospective Read More »

Visual Studio 2017 Error: The project doesn’t know how to run the profile IIS Express

I have a couple of computers I work between for the samples I use on this blog and when switching to between of them I got the following error last week.

The project doesn’t know how to run the profile IIS Express.

I verified the project would still run on the other computer with no issues. I also verified that on the computer with the issues the project would still work using dotnet run from the command line still worked.

Next, I went to verify the project properties. Here I noticed a strange thing on the computer with the error the Debug tab of the project properties was missing a lot of setting. The following is a screen shot of the computer with the issues.

And here is the same tab on the same project, but from a different computer.

The cause

After more time that I would like to admit I was able to track down the issue. On the computer with the issue, I often work on projects that are very large which tend to slow down Visual Studio pretty bad. In an effort to speed things up a bit I when through and disabled all the extensions that I could including the Microsoft Azure App Service Tools. Turns out that disabling the previous extension caused the Microsft ASP.NET and Web Tools extension to be disabled as well (with no warning).

The solution

The only way I was able to get the project to work properly was to enable both the Microsft ASP.NET and Web Tools extension AND the Microsoft Azure App Service Tools extension. I am not sure why the Microsft ASP.NET and Web Tools extension need the Microsoft Azure App Service Tools extension but based on my experience they are related in some way.

Visual Studio 2017 Error: The project doesn’t know how to run the profile IIS Express Read More »

Setting Up Visual Studio Code for Debugging ASP.NET Core

Visual Studio Code is a cross-platform source code editor from Microsoft. Out of the box, Code’s language support includes JavaScript, TypeScript, and Node. Using Codes extension system support is available for almost any language you want to use including C#, F#, Elixir, SQL, Swift, and Java. As of this writing, there are 734 language extensions available.

I have been using VS Code since it was first released after Build in 2015, but I have only been using it as an editor never taking advantage of the Debugging capabilities it has available. In this post, I am going to walk through everything that is needed to get a new ASP.NET Core with an Angular front end to run via VS Code’s debugger.

Test application

The first thing I did was to create a new application using JavaScriptServices specifically for this post. For instructions on how to use JavaScriptServices to generate an application check out this post.

On Windows, after the application has been generated and you are in the application directory you can use the following command to open the directory in VS Code.

code .

I am sure there is something similar on Linux and Mac, but I don’t have the environments to try on.

VS Code Overview

When VS Code opens you will see a view close to the following.

The icons down the left side of the screen are for Explorer (shows currently open directory and files), Seach, Source Control (git support is built in), Debug, and Extensions.

Debug

The Debug tab will be our focus so click on it which will take you to the following view.

Using the gear with red circle select .NET Core as the environment for the project.

If you don’t see .NET Core listed click More… and click install for the C# option.

After selecting an environment VS Code will add a launch.json file to the project. This file defines what happens when the start button is clicked in the debugger. At this point clicking the start button to run the application using the debugger will result in an error that Could not find the preLaunchTask ‘build’.

Next, click the Configure Task Runner option and select .NET Core.

This will add a task.json file with a build command that the launch.json is looking for. At this point, I had to restart VS Code to get it to properly pick up the new files. This seems to be an issue that will be fixed with the next release of VS Code and can be tracked using this issue.

After restart and trying to run the debugger again I ran into the error Run ‘Debug: Download .NET Core Debugger’ in the Command Palette or open a .NET project directory to download the .NET Core Debugger.

I ended up having to uninstall and reinstall the C# extension and then opening a C# file to get the debugger to download. If you are having this problem make sure and open a C# file before going as far as reinstalling the C# extension.

Hitting run in the debugger now give the error launch: launch.json must be configured. Change ‘program’ to the path to the executable file that you would like to debug.

To fix this issue click Open launch.json and you will find two places with the following.

"program": "${workspaceRoot}/bin/Debug/<target-framework>/<project-name.dll>"

Change both places to point to the dll your application builds. In the case of my project named DebugTest the final version ended up being the following.

"program": "${workspaceRoot}/bin/Debug/netcoreapp1.1/DebugTest.dll"

Wrapping up

Debugging now works! Based on this post it would seem like debugging in VS Code is a big pain, but really after you get it set up once it just works. For new projects, you just have to let it add the

For new projects, you just have to let it add the launch.json and tasks.json and then set the path to your project’s assembly in launch.json. After that, you are ready to go.

I wait too long to figure this process out. I hope this helps you get started with debugging in VS Code.

Setting Up Visual Studio Code for Debugging ASP.NET Core Read More »

Identity Server: Introduction

In the SPA based sample applications, this blog has used so far user authentication has either been completely ignored in order to keep the examples simpler or the sites have used ASP.NET Core’s built in identity to encapsulate the whole SPA. In this post (or series of posts) I am going to share what I learn along the way of creating an Angular (2+) application that utilizes ASP.NET Core as its host/API/backend.

This post isn’t going to cover any code it is just going to be a lot of the information I gathered in the process of learning more about Identity Server.

Following are all the post in this series.

Identity Server: Introduction (this post)
Identity Server: Sample Exploration and Initial Project Setup
Identity Server: Interactive Login using MVC
Identity Server: From Implicit to Hybrid Flow
Identity Server: Using ASP.NET Core Identity
Identity Server: Using Entity Framework Core for Configuration Data
Identity Server: Usage from Angular

Identity Server

According to their docs IdentityServer4 is an OpenID Connect and OAuth 2.0 framework for ASP.NET Core which enables Authentication as a Service, Single Sign-on, API Access Control and a Federation Gateway.

Obviously, that covers a lot of scenarios. The two that I am interested in are Authentication as a Service and the API Access Control which has driven my research which means that the other aspects of IdentityServer4 will not be included.

Official Samples

The IdentityServer GitHub account has a samples repo that contains a ton of examples. I have found the quickstart area of the repo to be the most helpful when starting out.

Based on all the quickstarts samples it looks like a typical setup involves a minimum of three projects. One for the API, one for the client and one for Identity Server. As you go through the samples the number of projects increase, but that is because of a wider range of scenarios that the sample is trying to cover.

References for learning

Damienbod has a whole series of blog posts related to IdentityServer4 and code to go along with it which can be found here. As a side note if you are interested in ASP.NET Core and you aren’t following damienbo you should be he has a ton of great content.

Blog posts
Videos

Identity Server Alternatives

Identity Server isn’t the only way to go there is a number of Software as a Service options that cover a lot of same scenarios. The following are some examples.

Auth0 – Check out the .NET Core related blogs by Jerrie Pelser
Stormpath
Amazon Cognito

Wrapping up

Obviously, I didn’t get a lot covered on how to actually do something with IdentityServer, but I wanted to share my starting point. This is an area I am going to continue digging it to and sharing information about as I learn more.

If you have any resources in this area please leave a comment below.

Identity Server: Introduction Read More »

Preparing for my first talk

I will be doing an intro lightning talk on JavaScriptServices at the May meeting of the Nashville .NET user group. The meeting will be over by the time this post comes out, but I wanted to share my outlook on it before hand.

Background

This will be the first time I have done any sort of talk since the required speeches I did in grammar and high school. In college, all the required speaking was attached to some sort of group work in which I was happy to do some extra legwork if another group member was willing to do the presentation.

Based on what I have written so far I am sure you have picked up on the fact that speaking is terrifying to me. Although I have forced myself into more social situations in the last few years it has done nothing to alleviate my fear of speaking to a group of people.

Motivation

Trying speaking is something that has been in the back of my mind for a few years. Speaking is an area I have always shied away from, but over the last few years listening to people like Scott Hanselman, Cory House, Jeremy Clark and David Neal among others and their take on speaking/giving back to the community planted a seed that speaking is something I need to try at least once.

David Neal’s talk on Public Speaking without Barfing on Your Shoes was especially encouraging to me. Here is a recording of the talk from the last Nodevember.

Preparation

I decided on JavaScriptServices because it has provided a great amount of value to personally and I want more people to be aware of it. With the topic in hand, I moved on to making an outline of what I want to cover. Since this talk should max out at 10 minutes my initial outline ended up needing to be scaled back.

The next thing I did was to create a checklist of all the thing I need to do before the talk. The following is an example of where it stands at the moment.

  • Flesh out the outline
  • Add important items for each point in the outline
  • Create and test demo
  • Test demo offline
  • Create a couple of slides
  • Practice out loud

Of the above having to practice out loud is the one I dread the most. I am not sure what it is about hearing one’s own voice, but it is always disconcerting.

 Wrapping up

I am still in the prepping stages and ever day that the talk gets closer the more nervous I get. There is also a level of excitement to see if this could be something I enjoy. It would be fun to have a new way to share my enjoyment and lessons learned outside of this blog.

I will post an update here or a full new post after the talk with how I felt it went. I will also hopefully have the feedback of a few others as well.

Preparing for my first talk Read More »

Communication Issues

My wife recently had an interesting experience with her cell phone company and this experience reiterated to me the importance of communication. This post is going to cover some high-level issues I encounter regularly.

For a bit of background here is a description of out experience with the cell phone company. First level support was awesome. They were responsive, kind, and mostly knew what they were talking about. Our case ended up getting passes to second level support and this is where things went bad.

Under communication

This company’s second level support was a perfect example of under communication. It was impossible for us to communicate with a second level support person we had to just sit around and wait for them to email us. In fact, even a first level support person could actually talk to a second level support.

The response took days of sitting around and hoping that our issues haven’t fallen through the cracks. The lack of communication ended with use changing cell providers based on the level of under communication. Had we been able to get a status or be told where the issue stood things would have turned out different.

It doesn’t matter if you are dealing with your family, customers or coworkers make sure to communicate what you are doing, what your expectations, what issues you are facing, etc. by providing this information everyone will be on the same page and have good expectations of each other.

Noisy communication

This issue comes up when you are communicating, but the idea being communicated is lost due to an unfocused message. Make sure that each of your points is concise and to the point.

To extend the cell phone example above a noisy version of describing the problem would be describing to the support person how angry the issues is making you, why the weather make you angry, the problem with the cell service, the cool new trick your dog did yesterday.

In the above, the really important bit is the problem with your cell service and the rest of it distracts and obscures what the actual point of the communication.

Dishonest communication

Intentionally providing wrong information for me is the worst communication offense. Missing leading someone either through omission of facts or a full blown lie is a sure way for any process to break down. I feel people try and make the best choices they can, but when making choices based on false or missing information the results aren’t good.

Another big issue with dishonest communication is when someone finds out that you have been dishonest with them if changes all future interactions in a very negative way.

Wrapping up

I have only listed three communication issues here that I seem to deal with for the most, but there are tons of more issues. Take time to evaluate your day to day communication and make sure your communication isn’t unclear for some reason. Don’t let some of this issues cost you customer, employees or friends.

Communication Issues Read More »

Upgrading a JavaScript Services Application

As part of the ASP.NET Core Basics series of posts, JavaScript Services was used to create a couple of front end for a basic contacts API using Aurelia and Angular 2. Theses applications were created a few months ago and JavaScript Services has kept moving since then. This post is going to look at one strategy for taking an application created on an older version of JavaScript Services and update it to match the current version. This post will be following the upgrade of the Angular project from ASP.NET Core Basics repo with the starting point of the code being from this release.

The strategy

One of the considerations when doing this upgrade was getting the changes that happen on the ASP.NET Core side of the application and not just the JavaScript bits. In order to make sure that nothing was missed I decided to use JavaScript Services to generate a new application and use that to compare with the implementations in the existing application.

Create comparison application

This is going to assume JavaScript Services is already installed. If it isn’t this page has instructions or this post has sections that deal with creating a new application using JavaScript Services.

The update

Following is the files that changed during this update. This is also the list of files I would check anytime an upgrade needs to be done.

Angular.csproj
ClientApp/boot-client.ts
ClientApp/boot-server.ts
Program.cs
package.json
webpack.config.js
webpack.config.vendor.js

There were a fair amount of changes in the files listed above and instead of posting the code the differences can be found here. The previous diff didn’t contain the webpack.config files and those diffs can be found here and here.

After all the files have been updated make sure to run the following command from a command prompt in your project directory to make sure webpack has vendor related items regenerated.

webpack --config webpack.config.vendor.js

Wrapping up

This post is a lighter on the details that I do most of the time, but this type of upgrade would just have been a wall of code and not been overly useful and the commits on GitHub are a much better guide to what the upgrade looked like. My feeling is that over time the number of changes going forward may end up being smaller and easier to integrate.

Both the Aurelia and Angular projects have been upgraded and the final version of the code can be found here.

Upgrading a JavaScript Services Application Read More »

Entity Framework Core with SQLite Migration Limitations

This is part of what has turned into a series on Entity Framework Core with SQLite. The other parts can be found below.

Entity Framework Core with SQLite
Entity Framework Core Errors Using Add-Migration
Entity Framework Core with SQLite Scaffolding

The starting point of the code for this post can be found here.

Migration Limitations when using SQLite

SQLite’s ALTER TABLE is limited which in turn limits what Entity Framework Core can do via a migration. The official docs on the subject can be found here. These limitations are on the Entity Framework Team’s list of issues as an open enhancement and can be tracked here.

As long as you are just adding new tables or columns you would never notice the limitation, but if you have spelling problems like I do then the need to rename a column can be important. Thankfully things like ReSpeller (link is to the pro page, but a free version is available in ReSharpers extension manager) help with my spelling issues.

Unsupported example with a column rename

As an example of how to handle a migration that isn’t supported, we are going to rename the State property of the Contact class to Subregion.

Rename property on the model

Open the Contact class which can be found in the Models directory and make the following change.

Before:
public string State { get; set; }

After:
public string Subregion { get; set; }
Add a migration

With the property name change using the following command in the Package Manager Console to create a new migration.

Add-Migration RenameContactStateToSubregion -c ContactsDbContext

Which produces the following migration class.

public partial class RenameContactStateToSubregion : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.RenameColumn(
            name: "State",
            table: "Contacts",
            newName: "Subregion");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.RenameColumn(
            name: "Subregion",
            table: "Contacts",
            newName: "State");
    }
}
Error trying to apply the migration

As expected when an attempt to apply the above migration results in the following exception.

System.NotSupportedException: SQLite does not support this migration operation (‘RenameColumnOperation’). For more information, see http://go.microsoft.com/fwlink/?LinkId=723262.

Modify migration to manually rename the column

Searching for how to rename a column in SQLite will turn up a lot of results including this from the official docs and answers like this on StackOverflow. The gist of the how to do a rename is to create a new table with the desired schema, copy the data from the original table, drop the old table, and finally rename the new table to match the original name.

Now knowing the process the migration above can be modified to apply SQL directly instead of using Entity Framework Core to generate the SQL. This can be done by using the Sql function of the MigrationBuilder class. The following is the resulting migration.

public partial class RenameContactStateToSubregion : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql(
            @"PRAGMA foreign_keys = 0;

              CREATE TABLE Contacts_temp AS SELECT *
                                            FROM Contacts;
              
              DROP TABLE Contacts;
              
              CREATE TABLE Contacts (
                  Id         INTEGER NOT NULL
                                     CONSTRAINT PK_Contacts PRIMARY KEY AUTOINCREMENT,
                  Address    TEXT,
                  City       TEXT,
                  Email      TEXT,
                  Name       TEXT,
                  Phone      TEXT,
                  PostalCode TEXT,
                  Subregion  TEXT
              );
              
              INSERT INTO Contacts 
              (
                  Id,
                  Address,
                  City,
                  Email,
                  Name,
                  Phone,
                  PostalCode,
                  Subregion
              )
              SELECT Id,
                     Address,
                     City,
                     Email,
                     Name,
                     Phone,
                     PostalCode,
                     State
              FROM Contacts_temp;
              
              DROP TABLE Contacts_temp;
              
              PRAGMA foreign_keys = 1;");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
    }
}

You will notice that I didn’t bother doing the Down function, but the same idea would apply when trying to undo a migration. SQLiteStudio or similar tools can be used to generate the SQL above if SQL isn’t something you want to deal with.

Fix other references to the renamed field

This isn’t really the topic of this post, but I wanted to throw in a reminder that after a rename like this there are places that will need to be updated that the tooling may not have picked up. For example, make sure all your views are using the new column as well as any bind statements in your controllers.

Wrapping up

The first time I hit the need to rename a column and it resulted in an exception it was extremely frustrating. Over time as I learned what the tooling around SQLite provides it has become less of an issue. I look forward to seeing what the Entity Framework team does in the future around this issue. The finished code can be found here.

Entity Framework Core with SQLite Migration Limitations Read More »

Entity Framework Core with SQLite Scaffolding

This is the third in what is turning into a series of post about using SQLite with Entity Framework Core. This post is going to cover adding a migration, scaffolding a controller and related views, and a few things that are harder to do using SQLite. The following are the first two post.

Entity Framework Core with SQLite
Entity Framework Core Errors Using Add-Migration

Adding Model, DbContext, Controller, and Views

If you have any experience with Entity Framework Core or have read any of my past entries on the subject this section is going to repeat some of the same information, but I am including it so someone who is looking for a full example will have it.

Model

In the Models folder add a Contact class similar the following.

public class Contact
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string PostalCode { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
}
DbContext

In the Data folder add a ContactsDbContext that inherits from DbContext. The following is an example that auto applies migrations to a database, if you don’t need that functionality it can be dropped out.

public sealed class ContactsDbContext : DbContext
{
    private static bool _created;

    public DbSet<Contact> Contacts { get; set; }

    public ContactsDbContext(DbContextOptions<ContactsDbContext> options)
        : base(options)
    {
        if (_created) return;
        Database.Migrate();
        _created = true;
    }
}

Now that the application has a model and a related DbContext the following can be used to add a migration that will create a Contacts in the SQLite database. Run from the Package Manager console.

Add-Migration AddContacts -Context ContactsDbContext

Add-Migration is a Powershell command to add a migration (surprise!), AddContacts is the name of the migration and -Context ContactsDbContext is an argument that lets the command know which DbConext to use. The Context is only needed if your application has more than one DbContext.

Controller and Views

With the above complete Visual Studio provides some tooling that makes it very fast to create a controller with views for listing, adding, editing, and deleting items. To begin right-click on the Controllers folder and select Add > New Scaffolded Item.

Select the MVC Controller with views, using Entity Framework option and click Add.

On the next dialog use the drop downs to select a model class and a data context class. Then verify the controller name and click add.

When the process completes the following items will have been added to your project.

Controllers
 - ContactsController.cs
Views
 - Contacts
   - Create.cshtml
   - Delete.cshtml
   - Details.cshtml
   - Edit.cshtml
   - Index.cshtml
Add to nav bar

To add a link to the new section of the app to the nav bar open the _Layout.cshtml in the Views/Shared/ directory. The following is the section of the file that needs to be changed to add an item to the nav bar.

<ul class="nav navbar-nav">
    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
    <li><a asp-area="" asp-controller="Contacts" asp-action="Index">Contacts</a></li>
    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
</ul>

Specifically, the following line was added to provide access to the contact list page.

<li><a asp-area="" asp-controller="Contacts" asp-action="Index">Contacts</a></li>

Wrapping up

With the above, the application will be runnable. The code for this post can be found here. The next post in this series will cover the limitations of migrations when using SQLite with Entity Framework Core.

 

Entity Framework Core with SQLite Scaffolding Read More »

Entity Framework Core Errors Using Add-Migration

I started off trying to expand my sample from last week’s post and hit some issues when trying to add a migration for a new DbContext.

The Setup

I added the following DbContext that only has one DbSet and auto applies migrations in the constructor.

using EfSqlite.Models;
using Microsoft.EntityFrameworkCore;

public sealed class ContactsDbContext : DbContext
{
    private static bool _created;

    public DbSet<Contact> Contacts { get; set; }

    public ContactsDbContext(DbContextOptions<ContactsDbContext> options)
        : base(options)
    {
        if (_created) return;
        Database.Migrate();
        _created = true;
    }
}

The command

Using Visual Studio’s Package Manager Console I ran the following command.

Add-Migration AddContacts -Context ContactsDbContext
Error 1 – No parameterless constructor

The above command resulted in the following error.

No parameterless constructor was found on ‘ContactsDbContext’. Either add a parameterless constructor to ‘ContactsDbContext’ or add an implementation of ‘IDbContextFactory<ContactsDbContext>’ in the same assembly as ‘ContactsDbContext’.

I read the first sentence and added a parameterless constructor to ContactsDbContext. I did think it was strange that a parameterless constructor wasn’t required the other contexts I had written in the past, but the error said to add a parameterless constructor so that is what I did.

Error 2 – System.InvalidOperationException: No database provider has been configured for this DbContext

Now having a parameterless constructor I ran the Add-Migration command again and was greeted with the following error.

System.InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.

The second error forced me to step back and think more about what the problem was as it didn’t have an action I could take as the first sentence, which is, of course, my fault for not fully digesting what the error was saying.

The fix

The bit I was missing was the fact that I hadn’t added the following to the ConfigureServices function of the project’s Startup class.

services.AddDbContext<ContactsDbContext>(options =>
    options.UseSqlite(Configuration.GetConnectionString("Sqlite")));

With the above added I removed the parameterless constructor from ContactsDbContext and was able to successfully run the add migration command again.

Wrapping up

The moral of the story is to actually read the full error message before running off and trying to fix the problem. The second error message saying “using AddDbContext on the application service provider” is what triggered me to head in the right direction.

This was also a good reminder that tools like the ones used by Add-Migration can/do compile the project they are being used on in order to have enough context to perform their tasks.

Entity Framework Core Errors Using Add-Migration Read More »