Cross-Origin Resource Sharing (CORS) in ASP.NET Core

Cross-Origin Resource Sharing (CORS) deals with sharing of restricted resources requested from outside the domain which made the request. Check out this Wikipedia article for a good over view of the subject.  If you read the post on Aurelia with an ASP.NET Core API then you might recall that cross-origin requests had to be enabled to allow the front end project to communicate with the API project.

When working on the post mentioned above I only spent enough time on the CORS options in ASP.NET Core to get the sample up and running. This post is going to expand on the path I used to get my sample working and explore some of the options ASP.NET Core offers. The official ASP.NET docs were very helpful in this exploration.

Starting point

In the API project the following was added in the Configure function of Startup in to allow any request regardless of headers, method or origin.

app.UseCors(builder =>
    {
        builder.AllowAnyHeader();
        builder.AllowAnyMethod();
        builder.AllowAnyOrigin();
    }
);

Limiting CORS

The above leaves the site wide open for cross-origin requests. Unless you have a need to allow any request it seems like a good idea to limit CORS. Keep in mind I am pretty new to the subject and my sure there are many nuances that will need to play into a live CORS strategy. For example the following limits CORS request to the two domains listed and only allows GET and POST.

app.UseCors(builder =>
    {
        builder.WithOrigins("http://google.com", "http://elanderson.net")
               .WithMethods("GET", "POST")
               .AllowAnyHeader();
    }
);

Note that origins are identified by scheme, host and port all being the same. For example all of the following would be considered different origins.

URLs with different origins
http://google.com
https://google.com
http://www.google.com
https://www.google.com
http://google.com:5000
https://google.com:5000
http://google.com:6000
https://google.com:6000
http://bing.com

Set CORS on a Controller or Action

MVC doesn’t force the whole site to use the same CORS settings. Just like with authorization CORS can be set by Controller or Action. To use this style of CORS ConfigureServices function of the Startup class needs to add CORS as a service and setup one or more policies. The name of the policy will be used with EnableCores attribute to specify where the policy is applied.

In ConfigureServices add app.AddCors which will allow additions of policies and make the available to controllers and actions. The following example adds an “AllowGoogle” CORS policy that allows http://google.com with any header and any method.

services.AddCors(options =>
{
    options.AddPolicy("AllowGoogle",
        builder => builder.WithOrigins("http://google.com")
                          .AllowAnyHeader()
                          .AllowAnyMethod());
});

Then to apply this policy to a controller or an action add the EnableCors attribute. The following example is applying “AllowGoogle” policy to the whole HomeController.

[EnableCors("AllowGoogle")]
public class HomeController : Controller

Now if you want to exempt the Index from the “AllowGoogle” CORS policy use the DisableCors attribute.

[DisableCors]
public IActionResult Index()

Wrapping up

I am sure the CORS subject goes much deeper than what I covered today, but I wanted to share what I have learned so far as it applies to ASP.NET Core. If you have more resources or have something to add please leave a comment.

Cross-Origin Resource Sharing (CORS) in ASP.NET Core Read More »

Visual Studio 2015 Team Explorer Fails to Undo Changes Using Git

At times I will make some quick changes to a project in Visual Studio to try something out knowing that I will undo the changes when done. Most of the time this works great with no problems, but a few times I am unable to get Visual Studio to undo the changes. Fist I am going to review the steps I normally use to undo and then I will cover the steps I use when files refuse to be undone. Just to be clear I am using Git base source control.

Normal undo changes

Normally when I am ready to undo a set of changes I open the Team Explorer window and select Changes from the drop down at the top of the window. Next I right click on the file, files, or directory I want to undo changes on and click Undo Changes.

undochanges

This show a message box asking for confirmation before undoing the changes. Click Yes to undo the changes.

undochangesyesnomessagebox

If all goes well the select files and/or directory will have reverted and no longer have any changes.

Undo failed now what?

If you undo didn’t clear the changes as expected now what? Well the best answer I have found is to open a command prompt and navigating to the directory that contains the file that needs to be undone and then run the following command. In this example the changes to gulpfile.babel.js  will be undone. This will work for both added and changed files.

git checkout gulpfile.babel.js

If you want to undo all the changes in a branch it takes a couple of commands. This first command will remove all changes to tracked files including staged files.

git reset --hard

Next if you have any files that were added (or not already tracked by Git) the following command will remove them.

git clean -f

Your repo will be back to its starting state as if it had just been cloned.

Caution

When using the above commands be careful as any changes will be gone and Git will have no record of them. For added files the file will be removed and again Git will have no record of the file. This mean these operations are permanent and should be used with a great deal of caution.

Visual Studio 2015 Team Explorer Fails to Undo Changes Using Git Read More »

Aurelia with ASP.NET Core: Host Aurelia from a Controller

This is the forth entry in a series using Aurelia and ASP.NET Core together. Each post builds on the previous and all the code is available on Github.

Part 1 – Add Aurelia to an ASP.NET Core Project
Part 2 – Aurelia with an ASP.NET Core API
Part 3 – Aurelia with an ASP.NET Core API: Modeling and Displaying Data in Aurelia
Part 4 – Aurelia with ASP.NET Core: Host Aurelia from a Controller (this post)
Github repo with the code for all of the parts with a release to go with each post

The goal

So far the Aurelia application in this series has existed outside of the the ASP.NET Core application. This post is going move the Aurelia application to be hosted by a MVC controller and a razor view. This would allow an existing application to slowly be ported to Aurelia or allow portions of an application to be replaced by Aurelia as it made sense, etc.

The controller

The controller isn’t going to be doing much other than returning a view that contains the entry point for the Aurelia application. This example will be using a new Aurelia  action on the HomeController.

public IActionResult Aurelia()
{
    return View();
}

The view

Next create a view in the Views/Home folder named Aurelia.cshtml to match the name of the action added to the HomeController above. Right click on the Home folder and select Add > New Item.

addnewitem

This will show the Add New Item dialog. Using the search in the upper right corner serach for MVC and select MVC View Page. Enter Aurelia.cshtml as the name and click Add.

Enter the following in the newly created file.

<div aurelia-app="main">
    <script src="/scripts/vendor-bundle.js" data-main="aurelia-bootstrapper"></script>
</div>

This code defines a div that will host an Aurelia application named main.

Add a link to the Aurelia application

Inside of the Views/Shared folder open _Layout.cshtml which is where the MVC application’s navigation bar is defined. Locate the navigation bar code and add a list item and link that points to the HomeController Aurelia action defined above. The following is the full navigation bar for the MVC application including the new link for Aurelia.

<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
        <li><a asp-area="" asp-controller="Home" asp-action="Aurelia">Aurelia</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>
</div>

Adjust Aurelia’s baseUrl

Finally inside the aurelia_project folder open aurelia.json and adjust the baseUrl property inside the targets section to look for the scripts folder to be up one directory. This is required now with the Aurelia application being hosted inside the HomeController which will cause the Aurelia application to look for its scripts in the Home/Scripts folder instead of the site’s main scripts folder. If you are going to have multiple Aurelia applications per MVC application then you may need to take a different path on this section.

Before:
"build": {
  "targets": [
    {
      "id": "aspnetcore",
      "displayName": "ASP.NET Core",
      "output": "wwwroot\\scripts",
      "baseUrl": "scripts"
    }
  ]

After:
"build": {
  "targets": [
    {
      "id": "aspnetcore",
      "displayName": "ASP.NET Core",
      "output": "wwwroot\\scripts",
      "baseUrl": "../scripts"
    }
  ]

Wrap up

Run the application and click the Aurelia link in the navigation bar and the Aurelia application from last week will run, but now it will still have the navigation bar from the MVC application showing. The index.html file located in the wwwroot folder that was previously used to host the Aurelia application can be deleted.

The code associated with this post can be found here.

Aurelia with ASP.NET Core: Host Aurelia from a Controller Read More »

Aurelia with an ASP.NET Core API: Modeling and Displaying Data in Aurelia

This is the third entry in a series using Aurelia and ASP.NET Core together. Each post builds on the previous and all the code is available on Github.

Part 1 – Add Aurelia to an ASP.NET Core Project
Part 2 – Aurelia with an ASP.NET Core API
Part 3 – Aurelia with an ASP.NET Core API: Modeling and Displaying Data in Aurelia (this post)
Github repo with the code for all of the parts with a release to go with each post

Starting point

Starting with the code from last weeks post we have a single solution with two projects. The Contacts project contains a basic razor UI for CRUD operations related to contact management as well as an API to provide that contact data to other applications.

The Aurelia project is a MVC application with Aurelia. At the moment the MVC and Aurelia applications don’t interact. In its current state the Aurelia application will connect to the Contacts API, download a list of contacts, and display the names of the contacts.

The goal

This post will cover taking the data from the Contacts API and mapping it to a JavaScript model class. Next the existing display of contacts will be removed and replaced with a contact list component.

Create a model

Create a contacts folder inside the src folder of the Aurelia project. Next add a contact.js file. This will be the model of a contact in the system. At the moment it only contains a constructor and a getAddress function. getAddress is just a demonstration of the model providing some functionality and not just being a data container.

export class Contact {
    constructor(data) {
        Object.assign(this, data);
    }

    getAddress() {
        return `${this.address} ${this.city}, ${this.state} ${this.postalCode}`;
    }
}

The Contact class ends up with all the properties of the data that was past to the constructor. In this case is all the properties from the Contact class in the Contact project. Coming from a mostly C# background the dynamic nature of JavaScript takes a little bit of getting used too.

 File naming an view/view model location

I hit a problem with how my files were named and Aurelia’s view/view model location strategy. I haven’t found a list of the conventions, but here is what I found playing around based on a view model named ContactList.

Filename Element Located
ContactList contact-list No
Contact-List contact-list No
Contact-List Contact-List No
contactlist contactlist No
contact-list contact-list Yes

Had the class name been Contactlist then the contactlist in the list above would have worked. For more information on how view are located check out this section of the Aurelia documentation.

Renaming for consistency

Based on research into why a view was not being located I am doing a bit of reorganizing in the project. All the contact related files are moving to a new contacts folder and the contactService.js is being renamed to contact-service.js. This is following the idea of organizing code by feature instead of type of file.

Update the Contact Service to use the new Contact class

In the contacts folder open the contact-service.js file. Next add an import for the Contact model class.

import { Contact } from './contact';

Next to the GetAll function add a line to convert the data to a Contact.

GetAll() {
   return this.http.fetch('')
        .then(response => response.json())
        .then(contacts => Array.from(contacts, c => new Contact(c)))
        .catch(error => console.log(error));
}

Here is the complete contact-service.js file.

import { HttpClient } from 'aurelia-fetch-client';
import { Contact } from './contact';

export class ContactService {
    static inject() { return [HttpClient] };

    constructor(http) {
        this.http = http;

        this.http.configure(config => {
            config
                .useStandardConfiguration()
                .withBaseUrl('https://localhost:13322/api/contactsApi/');
        });
    }

    GetAll() {
       return this.http.fetch('')
            .then(response => response.json())
            .then(contacts => Array.from(contacts, c => new Contact(c)))
            .catch(error => console.log(error));
    }
}

To verify the returned results are actually using the Contact model class change the call in App.js to use the getAddress function instead of just printing the contact names.

constructor(contactService) {
    this.message = 'Hello World!';
    contactService.GetAll()
        .then(result => {
            console.log(result);
            this.message = `Contact Results: 
                            ${result.map((contact) => contact.getAddress())}`;
        });
}

Run the application and it will print customer addresses. Note that the URL for the Aurelia application is http://localhost:37472/index.html.

Adding a contact list

Add two new files to the contacts folder for contact-list.html and contact-list.js which will result in the following structure.

contactrenames

The view model

contact-list.js is the view model for the contact list and will handle calling the ContactService to get a list of contacts to display. The contact service needs to be imported and injected via the constructor. Additionally the constructor is setting up an array that will be used to store the contacts after they are retrieved.

The call to the contact service is handled in the created function which is automatically called as part of Aurelia’s component lifecycle. For more information on the component lifecycle see the official documentation here. The following is the full definition of the ContactList view model class.

import { ContactService } from './contact-service';

export class ContactList {
    static inject() { return [ContactService] };

    constructor(contactService) {
        this.contactService = contactService;
        this.contacts = [];
    }

    created() {
        this.contactService.GetAll()
            .then(contacts => this.contacts = contacts);
    }
}

The view

contact-list.html is the view that Aurelia will map and use with contact-list.js. As before this view is going to be very basic to keep the noise down. The view is a template with an unordered list of contact names and their addresses.

<template>
    <ul>
        <li repeat.for="contact of contacts">
            <h4>${contact.name}</h4>
            <p>${contact.getAddress()}</p>
        </li>
    </ul>
</template>

The repeat.for tells Aurelia to output a list item for each contact found in the contacts property of the view model. ${contact.name} is a one way binding to the name property of the current contact. Also notice ${contact.getAddress()} which is one way binding the result of a function from the Contact model class.

Displaying a component

Now the component needs to be displayed. For simplicity the contact list will be shown directly from the main application view (app.html). The sample from last week will need to be cleared out before adding the contact list view. In the end the view should contain the following.

<template>
    <require from="./contacts/contact-list"></require>
    <h1>App</h1>
    <contact-list></contact-list>
</template>

require from is importing the contact list and then the contact-list tag determines where the contact list will show. Aurelia makes all components available in this manner. They just needs to be required in to be used as a tag.

Finally make sure to clear out app.js if using the sample from last week as retrieving contact list data has been moved to the contact list view model.

export class App {
}

When the application needs it the App class is where the application level router would go.

Wrap up

Aurelia is always a pleasant surprise after being away from it for awhile. After getting project setup and conventions down it is always pleasant to use. The documentation is very good for the most part. As you can tell from this post I had some trouble with conventions which is something I wish was covered better in the docs, and if it is and I just missed it please leave a comment.

The code associated with this post can be found here.

Aurelia with an ASP.NET Core API: Modeling and Displaying Data in Aurelia Read More »

Aurelia with an ASP.NET Core API

In last week’s post I covered creating a new ASP.NET Core project and then adding in Aurelia. The Aurelia application did nothing except output hello world. This week I am going to take an existing contacts API and the Aurelia project from last week use them together to make the Aurelia application display the name of the contacts from the API.

Part 1 – Add Aurelia to an ASP.NET Core Project
Part 2 – Aurelia with an ASP.NET Core API (This Post)
Part 3 – Aurelia with an ASP.NET Core API: Modeling and Displaying Data in Aurelia
Part 4 – Aurelia with ASP.NET Core: Host Aurelia from a Controller
Github repo with the code for all of the parts with a release to go with each post

Starting point overview

When you download a copy of the repo you will find an ASP.NET Core solution that contains two projects. The Aurelia project, obviously, contains the Aurelia application.

The Contacts project has a bit more going on. It has a set of razor views and a controllers to go with them that support standard CRUD operations, which at the moment is the best way to get contact information in the database. It also contains the ContactsApiController which will be the controller used to feed contacts to the Aurelia application.

Multiple startup projects in Visual Studio

In order to test this application both the Contacts and Aurelia projects to startup when the solution is run. Visual Studio provides an easy way to accomplish this. In the Solution Explorer window right click on the Solution and click Set StartUp Projects.

sestartup

This will launch the Solution Property Pages dialog. Looks for the Startup Project page under Common Properties.

multiplestartupprojects

Match the screenshot above by selecting the radio button for Multiple startup projects. Then using the arrows on the right to make sure that Contacts project will start first. Also set the Action on Contacts to be start without debugging since that project will just be feeding data and won’t need to be debugged at the moment.

Then on the Aurelia project set the Action to Start. Click OK and now both projects will start up when solution is run from Visual Studio.

Accessing Data from the API

In order to get data from the API we will need away to talk HTTP from Aurelia. Aurelia provides two libraries that provide this functionality which you can read about here. For this post I will be using Aurelia’s fetch client which based on the experimental Fetch API. The Fetch API isn’t supported by all browsers at point so if you need it there a polyfill can be found here.

Installing the Aurelia Fetch Client

If you started with the project from GitHub repo linked about then the fetch client will already be included in the projects dependencies, but if not I wanted to cover getting it installed. Using a command prompt run the following npm command in the project’s directory.

npm install aurelia-fetch-client -save

Alternately add the following line to the dependencies section of the project’s package.json file and when the file is saved Visual Studio will automatically restore the new package.

"aurelia-fetch-client": "^1.0.0"

The last step to making sure the fetch client available in the client application is to make sure it is included in the vendor-bundle.js that is created by the Aurelia CLI’s build process. To do this open the aurelia.json file found in the aurelia_project folder. In the bundles section look for the bundle named vendor-bundle.js and in its dependencies section add “aurelia-fetch-client”. The following an abbreviated example from my file to to make it clear where the new line should go.

"name": "vendor-bundle.js",
"prepend": [
  "node_modules/bluebird/js/browser/bluebird.core.js",
  "wwwroot\\scripts/require.js"
],
"dependencies": [
  "aurelia-binding",
  "aurelia-bootstrapper",
  "aurelia-dependency-injection",
  "aurelia-event-aggregator",
  "aurelia-fetch-client",

Create a client side service

It is important to not spread HTTP across the whole application and in order to achieve this goal it is a good idea to create a service that encapsulates the HTTP actions. For this example a contact service will be created that will handle all interactions with the ASP.NET Core API and the rest of the Aurelia application will just interact with the contact service.

To start create a services folder inside the src folder which contains the Aurelia client side application and added a new file to contain the new service called contactService.js.

nfcontactservice

The contact service will use the Aurelia fetch client to get all the contacts from the ASP.NET Core API. To do so it needs a constructor to allow injection and configuration of a HTTP client as well as a single function to get all the contacts. The following is the complete service.

import { HttpClient } from 'aurelia-fetch-client';

export class ContactService {
    static inject() { return [HttpClient] };

    constructor(http) {
        this.http = http;

        this.http.configure(config => {
            config
                .useStandardConfiguration()
                .withBaseUrl('https://localhost:13322/api/contactsApi/');
        });
    }

    GetAll() {
       return this.http.fetch('')
            .then(response => response.json())
            .catch(error => console.log(error));
    }
}

A future post will come back to this code and make it more robust, but this post is just about getting data for the Aurelia application so the service is being kept as simple as possible.

Using the Contact Service

Again to keep the code as simple as possible the contact servers will be utilized directly in existing the existing app.js file. The following is the class before any changes.

export class App {
  constructor() {
    this.message = 'Hello World!';
  }
}

The following is the class after the changes to import and inject the contact service via the constructor as well as using the contact service to download and show the name of each contact.

import { ContactService } from './services/contactService';

export class App {
    static inject() { return [ContactService] };

    constructor(contactService) {
        this.message = 'Hello World!';
        contactService.GetAll()
            .then(result => {
                this.message = `Contact Results: 
                                ${result.map((contact) => contact.name)}`;
            });
    }
}

Does it work?

At this point I used Visual Studio to launch both projects. In the Aurelia MVC application I navigated to http://localhost:37472/index.html which is the page that contains the Aurelia client application. Instead of being greeted by a list of contact names the application output “Hello World!”. That means that the Aurelia client application was running, but the contact service had failed for some reason. The console in the Chrome developer tools show the following error.

Fetch API cannot load http://localhost:13322/api/contactsApi/. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:37472’ is therefore not allowed access. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

The work around

Turns out that having two projects caused an issue I hadn’t considered. I now have to worry about cross-origin resource sharing. Not a topic that will be covered in this post. In order to work around this issues the Contacts project can be changed to added the following to the Configure function of the Startup class.

app.UseCors(builder =>
    {
        builder.AllowAnyHeader();
        builder.AllowAnyMethod();
        builder.AllowAnyOrigin();
    }
);

I am in no way saying that the above is the proper way to fix this issue. CORS is a subject I haven’t dug in to yet. The above is only meant to get this sample working. Please make sure to locate other resources on CORS for anything that is more than a demo.

Final thoughts

Running at this point will return the names of contacts as expected. Future posts will expand this application more. I want to get Angular 2 up as a new project in this same solution. When this solution has projects that contains the basics for MVC/razor, Aurelia and Angular 2 it will be in a good replacement the ASP.NET SPAs comparison reference application. Having each type of front end in a different project should make it easier to follow how each is set up. The code for today’s post can be found here.

Aurelia with an ASP.NET Core API Read More »

Create a .NET Standard Library for use with Full .NET Framework

Updated version for Visual Studio 2017 can be found here.

Recently I needed to create a library that would be shared between an UWP application and a Winforms application. My first thought was to create a portable class library with a profile that covered .NET 4.5.1 and Windows 10 which actually works out to be Profile44. At some point I was reminded of the new .NET Standard Library and decided that would be a better option.

.NET Standard Library

The .NET Standard Library specifies what .NET APIs are available based on the version of the .NET Standard Library being implemented. The following is a comparison to portable class libraries that really helped me understand the difference. This was pulled form the .NET Standard Library link above.

.NET Standard Library can be thought of as the next generation of Portable Class Libraries (PCL). The .NET Standard Library improves on the experience of creating portable libraries by curating a standard BCL and establishing greater uniformity across .NET runtimes as a result. A library that targets the .NET Standard Library is a PCL or a “.NET Standard-based PCL”. Existing PCLs are “profile-based PCLs”.

The .NET Standard Library and PCL profiles were created for similar purposes but also differ in key ways.

Similarities:

  • Defines APIs that can be used for binary code sharing.

Differences:

  • The .NET Standard Library is a curated set of APIs, while PCL profiles are defined by intersections of existing platforms.
  • The .NET Standard Library linearly versions, while PCL profiles do not.
  • PCL profiles represents Microsoft platforms while the .NET Standard Library is agnostic to platform.

.NET Standard Library Project Type?

Since I need to use my library in a winforms and UWP applications I need to create a csproj based library and not a xproj based library. This part of the process that took me the longest to figure out. Thankfully this Stack Overflow post helped clear up what is required. Basically if any of your projects need to use msbulid (which both winforms and UWP do) then your library should be csproj based.

Create a Portable Class Library

For csproj based .NET Standard library we must start with a Portable Class Library project type. To start click File > New Project which shows the New Project dialog.

nsnewproject

Locate the Class Library (Portable) type of project. Here I am using the C# version. Click OK. Next the Add Portable Class Library dialog will be shown.

nsaddpcl

Since this well be converted to use .NET Standard your selections don’t mean much here, but you will have to keep your target platforms when selecting which version of the .NET Standard your library will support. Click OK and the project will be created.

Convert a Portable Class Library to .NET Standard

Right click on your project and select properties. Alternately select the project in Solution Explorer and use the Project > [Project Name] Properties menu.

nsprojectpropertiesmenu

In project properties on the Library tab there is a link for Target .NET Platform Standard in the Targets section just below the Change button. Click the link.nsprojectpropertiesThis will show a warning message about saving changes and that the available APIs could change. Click yes to continue.

nstargetwarning

This will return you back to the library page of the project’s properties with the PCL related options replaced with a drop down used to select the version of the .NET Standard you want your library to target. I am going with version 1.2 based on where I need my library to run. Use the .NET Platform Support section of this page to help you decided on the proper version of the .NET Standard for your library.

nsselectversion

Save the project and it will now produce a .NET Standard library when built!

.NET CLI

It is hidden by default, but if you show all file you will see that the project now contains a project.json file which means the project can be used by the .NET CLI. Open a command prompt in the project directory. The following command can be used to build the project.

dotnet build

Or if you would like to create a Nuget package you can use the following.

dotnet pack

Inspecting the resulting dll in dotPeek

Just out of curiosity I wanted to see what showed when I opened up my .NET Standard library using a decompiler. I used dotPeek which is a free .NET decompiler created by JetBrains the company behind ReSharper.

As you can see in the following screenshot the platform shows as .Net Framework v4.6.1.

nsdotpeek46

Now here is a screenshot of the same library on a computer with an older version of .NET and it show a platform of .Net Framework v4.0.

nsdotpeek40

For some reason I was surprised by the fact the platform changed, but when I thought about it more I realized how else could it work because the library isn’t build to a specific platform. Seeing the platform change for the same library between two different machines really solidified how awesome the .NET Standard is.

Caution

As I said before I was hoping to use a .NET Standard library between a winform and UWP application. I did all the thing above and things were looking great. I added a project reference to my UWP application in Visual Studio 2015 with no trouble. Unfortunately the winforms application is stuck on Visual Studio 2013 (due to performance issue, 2015 is painfully slow with this solution) and Visual Studio 2013 doesn’t support this project type making a project reference impossible.

I could have gotten the library to work by adding it to the winforms solution as a Nuget reference, but for this project that was not a viable solution.

Create a .NET Standard Library for use with Full .NET Framework Read More »

Add Aurelia to an ASP.NET Core Project

In this post I am going to add a new project to the my existing ASP.NET Core Basics solution which can be found in this repository. The new project will be MVC 6  to which I will add in Aurelia. With both ASP.NET and Aurelia now being at RTM I thought this would be a good time to cover getting a new project setup.

Over time the ASP.NET Core Basics repo used in this post is going to be replacing my ASP.NET Core SPAs repo based on some feedback that having Aurelia and Angular 2 in the same project made it harder to see how each individual framework is setup.

Part 1 – Add Aurelia to an ASP.NET Core Project (This Post)
Part 2 – Aurelia with an ASP.NET Core API
Part 3 – Aurelia with an ASP.NET Core API: Modeling and Displaying Data in Aurelia
Part 4 – Aurelia with ASP.NET Core: Host Aurelia from a Controller
Github repo with the code for all of the parts with a release to go with each post

 Adding a new project to an existing solution

To add a new project to the existing solution right click on the solution and then click Add > New Project.

AddProjectExistingSolution

On the Add New Project dialog select ASP.NET Core Web Application (.NET Core), enter a name and then click OK.

AddNewProjectDialog

On the New ASP.NET Core Web Application (.NET Core) dialog select Web Application. This application doesn’t need authentication so leave it set to No Authentication. Finally click OK.

NewASPNetCoreWebApplication

After a few seconds the project creation will complete and the solution will contain two projects. The existing Contacts project that contains both a razor/normal implementation of a contacts list as well as an API implementation. The second project is the newly created Aurelia project.

SolutionWithTwoProjects

Changing the startup project

Notice in the screenshot above that the Contacts project is in bold. This means that the Contacts project is set as the startup project and it will be the project that starts when the application is run (F5 or Cntrl + F5). In this post we will just be working with the Aurelia project so we need to make it the startup project. To do this right click the Aurelia project and select Set as StartUp Project.

SetAsStartupProject

Now if you hit F5 the Aurelia project will run. Visual Studio provides a lot of flexibility around which projects start up. You can select a single, have which ever project you have to have select, or even multiple projects.  In a later post we will need both projects to start up and I will cover that when we have the need.

Install the Aurelia CLI

Make sure you have a minimum of NodeJs 4.x or above installed. If you need the installer it can be found here. After the install is complete open a command prompt and run the following command to install the Aurelia CLI.

npm install aurelia-cli -g

Add Aurelia to existing ASP.NET Core Project

In a command prompt navigate to the folder that contains the xproj file for the ASP.NET Core project created above. Now the Aurelia CLI can be used to setup a new Aurelia project at the current location using the following command.

au new --here

There will be a series of prompts the first of which is the selection of which platform to use. Select the option for ASP.NET Core (option 2). I used the defaults for most of the remaining prompts. The exception was for unit testing which I selected no on just to keep the project simpler not because I think testing is a bad idea.

When the Aurelia CLI finishes its file creation and dependency restore your project will contain the highlighted new files and folders.

auaddedfiels

Notice that I have a warning on Dependencies that something is not installed. There is a quirky issue with Visual Studio that Scott Hanselman has blogged about here. He goes in to a good bit of detail about what is going on as well as suggesting a work around. It has to do with npm and not being about to restore an optional package that isn’t meant for Windows machines.

gulp

The Aurelia CLI creates a set of tasks to help with building, transpiling the Aurelia part of the applications. I wrote a couple of posts over the couple few weeks dealing with converting a project to use glup as well as how to get gulp working with ES 2015.

I am going to cover the abbreviated version of those two post here. Add a new file called gulpfile.babel.js in the root of the project, where your project.json is located. The Aurelia CLI added all the needed items in the devDependencies section of package.json.

gulp no go

At this point I attempted to include the tasks under aurelia_project/tasks using require(‘require-dir’)(‘aurelia_project/tasks’);. This failed completely. I couldn’t get any of the items in the tasks folder to show up. I am not sure why this didn’t work. My best guess is that the tasks in the tasks folder are exporting gulp.series and not gulp.task. I just don’t know enough about gulp at this point to now how to fix/work around this or if what I am trying to do is just not the right way it should be used.

The gulp work around

I spent more time that I would have like working on getting gulp to pick up the items in the tasks folder, but I don’t want to have to run a CLI command every time I do a build to make sure all the Aurelia related files are up to date. As a work around I decided to add a gulp task to invoke the CLI command for me.

To start open package.json  and add the following to the devDependencies section which allows shell commands to be run from gulp.

"gulp-shell" :  "0.3.0"

Next in gulpfile.babel.js added the proper imports and created tasks for the CLI commands I wanted to run. In the case I am just showing the build command.

import gulp from 'gulp';
import shell from 'gulp-shell';

gulp.task('bulid', shell.task(['au build']));

Using the Task Runner Explorer this task can now be set to run after a build of the MVC project.

treafterbuild

This accomplishes what I wanted, but it feels like a hack. If anyone knows a better way please let me know.

It’s Alive!

At this point if you run the application it will go to the normal default home page that gets created by the Visual Studio template. For me that address is http://localhost:37472/. From there if you add index.html, the full address is http://localhost:37472/index.html, you will be invoking the Aurelia application.

At this point all you will see is “Hello World!”. Not that impressive I know, but it is a starting point that we will build on in future posts.

The associated code can be found here.

Add Aurelia to an ASP.NET Core Project Read More »

Unexpected token import with gulp

I have started to play with the release version of Aurelia. My current goal is to see what it takes to get going with Aurelia and ASP.NET Core now that both are RTM. I have hit a couple of road blocks that have ended up being new post of their own. For example this post that covers converting a new ASP.NET Core application to use gulp is one example. Today’s post is going to cover another issue I hit trying to use the gulp tasks created by the Aurelia CLI. There will not be anything Aurelia related in this post that will another post at a later date.

gulp setup

My gulpfile.js is nothing but a reference a directory of tasks. The full file looks like the following.

require('require-dir')('tasks');

Then I have a single task in tasks/exampleTask.js that consists of the following.

import gulp from 'gulp';

gulp.task('helloGulp', function(done){
 console.log('Hello Gulp!');
 done();
});

The error

With the above in place if you look at the task runner explorer you will see that Gulpfile.js shows a failed to load error instead of the helloGulp task.

gulpfailedtoload

As suggested by task runner explorer open the output window. There are many different things that use the output window so be sure and change show output from option to Task Runner Explorer. With that done you will be able to see why the task failed to load. The following is the error I am getting.

Failed to run "C:\ProjectDirectory\Gulpfile.js"...
cmd.exe /c gulp --tasks-simple
C:\ProjectDirectory\tasks\exampleTask.js:3
import gulp from 'gulp';
^^^^^^
SyntaxError: Unexpected token import
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:528:28)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.require (module.js:483:17)
    at require (internal/module.js:20:19)
    at requireDir (C:\ProjectDirectory\node_modules\require-dir\index.js:116:33)
    at Object.<anonymous> (C:\ProjectDirectory\gulpfile.js:1:85)

The fix

I did some googling and I found this post by Mark Goodyear on using ES6 (or ES 2015) with gulp. It turns out the tasks generated by the Aurelia CLI are using ES 2015 and in order to use ES 2015 with gulp there are a few steps that must be taken first. Mark does a great job explaining those steps, but I am going to include a summary from the Visual Studio perspective.

Verify the devDependencies section in package.json contains the following. require-dir is only required if your gulpfile or tasks are using it.

"devDependencies": {
  "gulp": "3.9.1",
  "babel-preset-es2015": "^6.9.0",
  "require-dir":  "^0.3.0" 
}

Next create a .babelrc file at the same level as the package.json file with the following contents.

{
  "presets": [ "es2015"]
}

Then rename gulpfile.js to gulpfile.babel.js.

Back in the Task Runner Explorer hit the refresh button in the top left of the window which should now load your list of tasks under Gulpfile.babel.js with no errors.

taskrunnerrefersh

 

Unexpected token import with gulp Read More »

Change from Bundle & Minifier to Gulp in Visual Studio

When ASP.NET Core 1.0 was released Microsoft switched gulp for Mads Kristensen‘s Bundler & Minifier. This post is going to cover taking a project that is using Bundler & Minifier and change it to use gulp instead. Don’t take this as problem with Bundler & Minifier I am just more familiar with gulp and didn’t mix in another new tool.

The extension

There is a Bundler & Minifier extension available that make the change to gulp super simple. You could do all this yourself, but the extension seems to be the fastest way to convert without having to worry about htting. Click the Tools > Extensions and Updates menu. Then in the Extensions and Update dialog on the left select Online. Next on the top right enter “bundler & minifier” in the search box. Then click the download button next to Bundler & Minifier and follow the prompt to install and then restart Visual Studio.

ExtensionBundlerMinifier

The conversion to gulp

Right click on your project’s bundleconfig.json (this is the file that is used to configure the default bundling and minification stuff) and select Bundler & Minifier > Convet To Gulp.

converttogulpmenu

This will show a warning dialog saying that the process will take a few minutes due to npm restores, etc. When the process is done you will now have a gulpfile.js file. The gulpfile.js file that is created will require bundleconfig.js in order to expose your existing tasks.

Required edit to bundleconfig.js

Since the generated gulpfile.js is using the existing tasks in bundleconfig.js all the comments must be removed from bundleconfig.js before gulp will work properly. This is due to comments not being valid json and the parser that gulp uses sees the json as being invalid. The following line exists in the generated gulpfile.js, but it is easy to miss so I wanted to call it out.

bundleconfig = require("./bundleconfig.json"); // make sure bundleconfig.json doesn't contain any comments

Wrapping up

package.json is the other file that got created during this process. If you are doing this manually don’t forget this file. I had tried this conversion manually once before and I am pretty sure this file is the reason I was not successful.

As I stated above I went the route of the extension so I wouldn’t miss anything and it worked out well. Now knowing what needs to be changed I could do it manually, but the extension works so well I recommend using it.

Thanks to Jon Galloway as I first saw this process at one of his talk at Code on the Beach.

Change from Bundle & Minifier to Gulp in Visual Studio Read More »

Add Git Ignore to existing Visual Studio Project

Last week I mentioned adding a .gitignore file to keep a configuration file from causing issues across machines. Visual Studio make it super easy to add, but the next time I made a change to the project the configuration file showed up in my changes again. Turns out that if Git is already tracking a file adding it to the ignore file will not do anything. I am going to walk through adding an ignore file and then cover the one of the processes that can be used to stop Git from tracking files that are in your ignore file.

Using Visual Studio to add a .gitignore file

Inside of Visual Studio open the Team Explorer window. If you don’t already have it open use the quick launch in the upper right hand side of the window to search for it. If it is not already on the Home page click the house icon in the top of the Team Explorer window.

TeamExplorerHome

Click the settings option.

TeamExplorerSettings

Then click Repository Settings.

TeamExplorerRepositorySettings

Now click the add link next to the Ignore File description. This will add the .gitignore file will all the defaults set for things that should be ignored. You could add the file manually, but then you would not get the nice set of default values. If you do decide to add the file manually this repo contains all the defaults that should be ignored for a project using .NET/Visual Studio.

Now that the file exists check it in.

Stop tracking files that should be ignored

To stop tracking the files in the ignore file open a command prompt and navigate to the directory that contains your solution file (.sln) and run the following commands.

git rm -r --cached . 
git add .
git commit -am "Remove ignored files"

That seemed to do the trick for me. The git commands I found here. If you click on that link you will see there are lots of options on which commands to use for this process. If the above doesn’t work for you one of the other answers should meet your needs.

In the future I will be making sure my ignore file exists first just to avoid any issues.

Add Git Ignore to existing Visual Studio Project Read More »