.NET Standard

Create a .NET Standard Library with Visual Studio 2017

It has been almost a year since I wrote this post on creating a .NET Standard Library which was before Visual Studio 2017 was released. This post is going to cover the same basic idea, but for the new tooling which has vastly simplified the process.

.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 from 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.

Create a .NET Standard Library

In Visual Studio click File > New > Project.

This will launch the New Project dialog. Find the .NET Standard templates and select Class Library.

Now that the library has been created right click on the project and go to properties. On the Application tab, there is an option to for Target framework which currently defaults to .NETStandard 1.4. Depending on your platform your library needs to support will decide which version of the .NET Standard you need to use.

See the chart on this page for help with picking a version of the standard. The lower the version of the standard you target the more platforms your library will run on, but keep in mind the lower the version the smaller the API surface that is available.

Wrapping up

This process is so much easier than it was in Visual Studio 2015. The tooling around .NET Core and .NET Standard has gotten so much better. This type of library is the future and I highly recommend using .NET Standard when you have the option over portable class libraries.

Create a .NET Standard Library with Visual Studio 2017 Read More »

Migration from ASP.NET Core 1.1.x to 2.0

On August 14th .NET Core 2.0 was released including corresponding versions of ASP.NET Core 2.0 and Entity Framework Core 2.0 which got with the finalization of .NET Standard 2.0. The links take you to the release notes for each item.

In this post, I will be covering taking the project used for the ASP.NET Basics series from 1.1.x to the 2.0 release. The starting point of the code can be found here. This post is only going to cover conversion of the Contacts project.

Installation

If you are a Visual Studio user make sure you have the latest version of Visual Studio 2017, which can be found here and at a minimum should be version 15.3.

Next, install the SDK for your operating system. The list of installs can be found here. For development, it is key that you install the SDK, not just the runtime. The following is a preview of what to expect on the download page.

Csproj

The csproj file of the project being upgraded is the best place to start the conversion. The TargetFramework needs to be changed to 2.0.

Before:
<TargetFramework>netcoreapp1.1</TargetFramework>

After:
<TargetFramework>netcoreapp2.0</TargetFramework>

Next, PackageTargetFallback changed to AssetTargetFallback.

Before:
<PackageTargetFallback>$(PackageTargetFallback);dotnet5.6;portable-net45+win8</PackageTargetFallback>

After:
<AssetTargetFallback>$(AssetTargetFallback);portable-net45+win8+wp8+wpa81</AssetTargetFallback>

There is a new Microsoft.AspNetCore.All package that bundles up what used to be a huge list of individual packages. Those individual packages still exist, but this new one wraps them and makes it much easier to get started. The following is the package list before and after.

Before:
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="1.1.1" />		
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="1.1.1" />		
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" />		
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />		
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.1" />		
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.1" />		
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />		
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />		
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" />		
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" />		
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.1" />		
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" />		
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.1" />		
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" />		
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.1" />		
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />		
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.1" />		
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />		
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.0" />		

After:
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />

Last change in this file is to change the DotNetCliToolReference versions to 2.0.0.

Before:
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.0" />
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />

After:
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />

Program.cs

Program.cs is another area that has been simplified by creating a default builder that does all the same things that were happening before but hide the details. Keep in mind the old version still works and is valid to use if you use case needs it.

Before:
public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

After:
public static void Main(string[] args)
{
    BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
           .UseStartup<Startup>()
           .Build();

Identity

The remaining changes I had to make were all related to Identity. In the Startup class’s Configure function the following change was needed.

Before:
app.UseIdentity();

After:
app.UseAuthentication();

Next, in the ManageLoginsViewModel class, the type of the OtherLogins property changed.

Before:
public IList<AuthenticationDescription> OtherLogins { get; set; }

After:
public IList<AuthenticationScheme> OtherLogins { get; set; }

The SignInManager dropped the GetExternalAuthenticationSchemes function in favor of GetExternalAuthenticationSchemesAsync. This caused changes in a couple of files. First, in the ManageController the following change was made.

Before:
var otherLogins = _signInManager
                  .GetExternalAuthenticationSchemes()
                  .Where(auth => userLogins
                                 .All(ul => auth.AuthenticationScheme != ul.LoginProvider))
                  .ToList();

After:
var otherLogins = (await _signInManager
                   .GetExternalAuthenticationSchemesAsync())
                  .Where(auth => userLogins
                                 .All(ul => auth.Name != ul.LoginProvider))
                  .ToList();

The second set of changes were in the Login.cshtml file. First the function change.

Before:
var loginProviders = SignInManager.GetExternalAuthenticationSchemes().ToList();

After:
var loginProviders = (await SignInManager.GetExternalAuthenticationSchemesAsync()).ToList();

Then the change to deal with the changed property names.

Before:
<button type="submit" class="btn btn-default" 
        name="provider" value="@provider.AuthenticationScheme" 
        title="Log in using your @provider.DisplayName account">
    @provider.AuthenticationScheme
</button>

After:
<button type="submit" class="btn btn-default" 
        name="provider" value="@provider.Name" 
        title="Log in using your @provider.DisplayName account">
    @provider.Name
</button>

Wrapping up

With the changes in the Contacts project now works on ASP.NET Core 2.0!  Make sure to check out Microsoft’s regular migration guide. as well as their identity migration guide. A full list of breaking changes for this release can be found here.

There is a lot more to explore with this new release and I have a lot of projects to update. Don’t worry I won’t be doing a blog post on all of them, but if I do hit any issues I will create a new post of update this one with the fixes. The finished code can be found here.

Migration from ASP.NET Core 1.1.x to 2.0 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 »