.NET Core

Unable to start process dotnet.exe

This morning I did a sync of a repo using of Visual Studio and then tried to run a web application I was going start working when I got this error:

Unable to start process C:\Program Files\dotnet\dotnet.exe. The web server request failed with status code 500, Internal Server Error. The full response has been written to C:\Users\ericl\AppData\Local\Temp\HttpFailure_11-01-57.html.

As directed by the error message I opened up the referenced html file. The file stated the requested page cannot be access because the related configuration data for the page is invalid. Along with the path to the configuration file. Here is a screen shot of the rendered file.

50019

I checked the config file referenced in the error message and I saw nothing wrong. It is the default generated file with no changes.

Since this project ran fine on another computer the day before I thought I would search for my profile name on from the other computer on the one having issues. This led me to the .vs/config folder found at the solution level of my application which contained the applicationhost.config file.

The solution

applicationhost.config has a lot of information in it, but the section I needed to change was under the sites tag. The physical path was set to the directory where the project was located on my other computer. I changed the path to match the path on my current computer and all worked fine. Not sure why this path isn’t relative one it exists within the solution. This is the line that I needed to change.

<virtualDirectory path="/" physicalPath="C:\Users\ericl\Source\Repos\ASP.NET Core Contacts\Contacts\src\Contacts" />

As an alternative it also works to close Visual Studio delete the whole .vs folder and reopen the project in Visual Studio. This causes the config file to regenerated with the proper values.

Looks like the .vs folder is in the default .gitignore file, but my project was missing the ignore file.

Unable to start process dotnet.exe Read More »

ASP.NET Core Basics: API Controller

This week’s post is going to cover the creation of an API controller. The starting point for this post is based on this post from last week and the starting state of the code can be found here.

Scaffolding

Using the same Contact model class from last week’s post Entity Framework Core’s scaffolding can be used to generate an API controller for us with all the read and write actions already written. To begin in the Solution Explorer window right click on the Controllers folder and select Add > New Scaffolded Item.

AddNewScaffoldedItemMenu

On the Add Scaffold dialog select API Controller with actions, using Entity Framework. This option will create an API controller with read and write actions based on a model.

AddScaffoldApi

On the Add Controller dialog for the model class select the Contact class, for the data context class select the existing ContactsContext. Finally enter the controller name you would like to use. I am using ContactsApiController since the MVC controller from last week’s post is already named ContactsController.

AddApiControllerDialog

Click add and the scaffolding process will create a ContactsApiController in the Controllers folder. With that the project now contains a fully functional contacts API that will handle gets, puts, posts and deletes with zero code changes.

Test with Postman

Postman is a great tool that I always use when developing an API that allows me to exercise all the functions of the API before any clients have been built. I know you can do some of the same things using a browser, but Postman was built for this type of usage and it shows. Postman is free and you can grab it from here as a Chrome app or they have app versions available here.

After installing the application and running it you will see something like the following.

PostmanBlank

It is best to have some data available for testing so in the case of this application I recommend using the UI added in last weeks post to add a couple of contacts.

Now that some data is available it is time to test the GetContact function on the ContactsApiController. If you run the application it should open in a browser from which you can copy the URL, or right click on the project select properties then on the Debug tab copy the URL from the App URL field.

ProjectProperties

Paste the base URL in the URL box in Postman and then add on the route for the endpoint you are wanting to test. In this case I want to test the the GetContact function on the ContactsApiController so I will be using the a URL of http://localhost:13322/api/contactsapi. Next make sure contact application is running and then click the send button in Postman. The application should respond and the results of the API call will be displayed on the body tab of Postman.

PostmanGetContacts

Postman can be used to try out pretty much all aspects of the API that an application has. For example if you wanted to test out the PostContact then in Postman click the down arrow next to Get and select Post. Next select the upper body tab (in the request area) and the click the raw radio button. Then to the right of the radio buttons hit the down arrow and select JSON (application/json) and then it the large text box you can enter the JSON that will be sent to the server when you click the send button. The following is an example of a post request.

PostmanPostContact

Wrapping Up

This application now has a fully functional API and we have covered how test it using Postman.

The next step would be to create some sort of client to actually utilized the API such as an Aurelia or Angular 2 application.

The code for this post can be found here.

ASP.NET Core Basics: API Controller Read More »

ASP.NET Core Basics: MVC Controller with Entity Framework Core

Last week’s post covered the installation and creation of a new project in ASP.NET Core. This week I will be expanding that existing project to create a basic contact list which will use Entity Framework Core and its scaffolding capabilities to generate the needed files from a model class. This code from last week is being used as a starting point for this post.

Add a Model

To start off I need a class to represent the information for a single contact. In the default setup the proper place to store this type of class is in the Models folder. To add a new class from the Solution Explorer window right click on the Models folder and select Add > Class menu option.

AddClassMenu

This menu choice will bring up the Add New Item dialog defaulted to adding a new class. Enter the name as Contact.cs and click Add.

AddNewItemDialogContact

The following is my resulting Contact after adding the properties of a contact that this application is going to use.

namespace Contacts.Models
{
    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; }
    }
}

Scaffolding

Now that the application knows what a Contact looks like we can take advantage of a feature of Entity Framework Core called scaffolding. Scaffolding can be sued to create a number of different setups based on a model, but in this case it I am using it to generate a MVC Controller with views, using Entity Framework which will result in a controller, DbContext and associated MVC razor views being created.

In the Solution Explorer window right click on the Controllers folder and select Add > New Scaffolded Item.

AddNewScaffoldedItemMenu

On the Add Scaffold dialog select MVC Controller with views, using Entity Framework. This is the only option that will create views. Now click the Add button.

AddScaffoldDialog

The Add Controller dialog will be shown next. First select the model that should be the base of the scaffolding operation which is the Contact class for this project. For the data context class option I used the plus (+) button to add a new one since this project doesn’t have an existing data context that I want to use.

AddControllerDialog

After clicking add and letting the process finish the Controllers folder will now contain a ContactsController and in the Models folder there will be ContactsContext. I always move the newly created context out of the Models folder and into the Data folder to match the location used for the ApplicationDbContext.

Entity Framework Migration

Now that the application has a contact model and DbContext it is time to create an entity framework migration which is the mechanism entity framework uses to create and/or migrate a database to match the changes made in the models of an application. Migrations can be added within Visual Studio via the Package Manager Console or from a command prompt using the .NET CLI. I am going to walk through both, but keep in mind you only need to use one.

Package Manager Console

To open the Package Manager Console use the View > Other Windows > Package Manager Console menu. Which show a window that looks like the following.

PackageManagerConsole

To add a migration use run the Add-Migration Init-Contacts -Context ContactsContext command. The Package Manager Console is using powershell so Add-Migration is a command that take a parameter that is the name of the migration which is Init-Contacts in this case. -Context ContactsContext is required in this application because it contains more than one DbContext and the command has to know which DbContext it is working with.

.NET CLI

Open a command prompt and navigate to your project’s directory and then run the dotnet ef migrations add Init-Contacts –context ContactsContext command. This is does exactly the same thing as the Package Manager Console above with just slightly different syntax.

Regardless of which version is used you will see a new Migrations folder added to the root of the project that contains a snapshot of the models referenced by the relevant DbContext as well as a migration file named by using a time stamp plus the migration name.

Automatic Database Migration

In the early stages of a project (or always if it meets your need) it is nice to automatically apply migrations instead of having to do so manually using the package manager console or the .NET CLI. One way to accomplish this is to add a static flag to the constructor of the DbContext in question and if that flag is false then use Database.Migrate() to apply any migrations that the database is missing. Here is an example using my ContatsContext class with the flag named _created.

public sealed class ContactsContext : DbContext
{
    private static bool _created;
    public DbSet<Contact> Contact { get; set; }
    public ContactsContext(DbContextOptions<ContactsContext> options)
        : base(options)
    {
        if (_created) return;
        Database.Migrate();
        _created = true;
    }
}

Add Navigation

At this point you could type in a URL that would take you to the index action of the new ContactsController, but it would be much more useful to add a link to the sites navigation bar to provide an easy way to access the new functionality. The code for the navigation bar can be found in _Layout.cshtml which is located in the Views > Shared folder.

The navigation bar is defined using an unordered list with a class of “nav navbar-nav”. Add a new link to the unorderd list labeled Contact List. This new link needs to point to the index action of ContactsController. ASP.NET Core provides some tag helpers to assist in building links to controller actions. Using the asp-controller and specify “Contacts” as the controller which will resolve to the ContactsController and then use asp-action set to “Index” to point to the index action.

<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">Contact List</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>

Wrapping Up

Now when the application is run there will be a link for Contact List at the top that will trigger actions in the new controller and backing database table.

Next week I play to take this same project and add a web API end point to it and show how that end point can be verified using Postman.

The code that goes with the post can be found here.

ASP.NET Core Basics: MVC Controller with Entity Framework Core Read More »