Tag Archives: web development

Exploring .NET Core 3.0 and the Future of C# with ASP .NET Core

By Shahed C on December 8, 2018

This is the tenth of a new series of posts on ASP .NET Core. In this post, we’ll explore what’s to come in .NET Core 3.0 and C# 8.0, and what’s new with ASP .NET Core. This post is also included in Matthew Groves‘ 2018 C# Advent Calendar, in the Dec 8 slot.

ASPNETCoreLogo-300x267

WARNING: Be prepared for a lot of information and tons of links to get even more information. 🙂 

In This Article:

Microsoft Connect(); 2018

msft-connect-2018

This past week has given us many exciting announcements and releases from Microsoft Connect(); 2018. This includes the releases of .NET Core 2.2 (with ASP .NET Core 2.2), .NET Core 3.0 Preview 1 and Visual Studio 2019 Preview 1.

You can catch up on what you missed at the following URLs:

What to Expect in .NET Core 3.0

.NET Core 3.0 brings us a slew of new features, notably support for Windows desktop apps (WinForms, WPF) on .NET Core. This will allow “side by side” versions of .NET Core for your desktop apps as opposed to “in-place” framework installations.

Well, how about ASP .NET Core 3.0? Well, during Connect(); 2018, Scott Hunter pointed out that ASP .NET Core 2.2 was also released at the same time as .NET Core 3.0 preview 1. He added that ASP .NET Core 3.0 (preview) within  .NET Core 3.0 (preview) currently has “the exact same ASP .NET Core 2.2 bits” and “so, there’s no benefit to move to 3 yet… won’t be till…. sometime next year [2019]”.

Skip to 8:43 in the following video:


What to Expect in ASP .NET Core 3.0

Here are a few things you can expect in ASP .NET Core 3.0, whenever it comes out next year:

  • Newtonsoft’s Json.NET will be removed from the shared framework
  • EF Core will be shipped separately as pure NuGet packages
  • ASP .NET Core 3.0 will only run on the cross-platform .NET Core 3.0
  • ASP .NET Core 3.0 will NOT run on the Windows-only .NET Framework
  • Note that some new C# 8.0 features will only be coming to .NET Core 3.0

You can get more information on ASP .NET Core 3.0 from an Oct 2018 announcement:

Some additional things you should know about Blazor, the cool kid on the block:

From Daniel Roth (Oct 2018): “We are now working towards shipping Razor Components and the editing in .NET Core 3.0,”… “This includes integrating Razor Components into ASP.NET Core so that it can be used from MVC. We expect to have a preview of this support early next year after the ASP.NET Core 2.2 release has wrapped up.

What’s New in ASP .NET Core 2.2 Right Now

So what’s new in ASP .NET Core 2.2 right now? First of all, you can work with ASP .NET Core 2.2 in the latest version of Visual Studio 2017 or VS Code with the .NET Core 2.2 SDK. There are many cool new features, notably:

  • New Health Checks API
  • Improved Open API (Swagger) Integration
  • Client-side template updates (Bootstrap 4, Angular 6)
  • SignalR Java Client
  • HTTP/2 Server Support (Preview)
  • Improved perf: IIS throughput, MVC model validation + routing, HTTP Client

You can read the full announcement here:

You can get also a recap of the API improvements and Health Checks API in this video from Connect:


Health Checks

From the aforementioned Github repo, here is a code snippet for the new Health Checks feature:

public void ConfigureServices(IServiceCollection services)
{
   ...
   services.AddHealthChecks()
      .AddDbContextCheck<PlacesContext>();
   ...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   ... 
   app.UseHealthChecks("/ready");
   ...
}

In the above snippet, the call to AddHealthChecks() followed by AddDbContextCheck() ensures that the data connection is healthy before determining that the application is healthy. The route /ready can be accessed in a browser or externally to determine the health of the application.

Open API (Swagger)

Features for using Open API (Swagger) with ASP .NET Core was already included in ASP .NET Core 2.1 and has further improved with ASP .NET Core 2.2. As before, you can use community-driven projects such as NSwag and Swashbuckle.AspNetCore to visualize Open API documents for your API.

Benefits include:

  • interactive documentation
  • client SDK generation
  • API discoverability

So what’s new in 2.2? We now have Microsoft.AspNetCore.Mvc.Api.Analyzers, which work with [APIController]-decorated controllers introduced in 2.1, and also builds on API conventions. With this package added to a new Web API project, my .csproj project file looks like this:

<Project Sdk="Microsoft.NET.Sdk.Web"> 
<PropertyGroup>
 <TargetFramework>netcoreapp2.2</TargetFramework>
 <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
 </PropertyGroup> 
<ItemGroup>
 <PackageReference Include="Microsoft.AspNetCore.App" />
 <PackageReference Include="Microsoft.AspNetCore.Mvc.Api.Analyzers" Version="2.2.0" />
 <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
 </ItemGroup> 
</Project>

So what do these new analyzers do? One example can be explained by starting with the code snippet below:

 // GET api/values/5
 [HttpGet("{id}")]
 [ProducesResponseType(200)]
 public ActionResult<string> Get(int? id)
 {
    if (id == null)
    {
       return NotFound();
    }
    return "value";
 }

In this simple Get method in my API Controller, it returns an HTTP 200 (Success!) Status Code when everything is going well, which is indicated by [ProducesResponsesType(200)]. But if the id value is null, it returns NotFound(). In this case, the analyzer can automatically guide you to add the proper attribute for a HTTP 400 (Not Found) Status Code as well.

See this illustrated in the GIF below:

API Analyzer Example

API Analyzer Example

Here is the end result:

 // GET api/values/5
 [HttpGet("{id}")]
 [ProducesResponseType(200)]
 [ProducesResponseType(StatusCodes.Status404NotFound)]
 [ProducesDefaultResponseType]
 public ActionResult<string> Get(int? id)
 {
    if (id == null)
    {
       return NotFound();
    }
    return "value";
 }

If you use common API Conventions, you can make your life even easier by using Conventions. Conventions can be applied via attributes in 3 different ways: at the assembly level, at the controller level and at the method level, each deeper level superseding the attribute at the higher level. These can then be superseded by ProducesResponseType applied at an action level.

Three examples are shown below:

At the assembly level:

[assembly: ApiConventionType(typeof(DefaultApiConventions))]

At the controller level, e.g. ItemsController

[ApiConventionType(typeof(DefaultApiConventions))]
[ApiController]
[Route("/api/[controller]")]
public class ItemsController : ControllerBase
{
   ...
}

At the method level, e.g. PutItem()

// PUT: api/items/5
[ApiConventionMethod(typeof(DefaultApiConventions), nameof(DefaultApiConventions.Put))]
[HttpPut("{id}")]
public async Task<ActionResult<Item>> PutItem(long id, Item item)
{
   ...
}

For more information, check out the official announcement from August 2018:

What’s New in EF Core 2.2 & 3.0

EF Core 2.2 includes some new features and a ton of bug fixes. New features include:

  • Spatial data support: used to represent the physical location and shape of objects
  • Collections of owned entities: extends the ability to model ownership to 1-to-many associations, going beyond 1-to-1 associations (previously added in 2.0)
  • Query tags: allows you to annotate a LINQ query with a string of text that appears as comments in generated SQL output (which may be captured in logs)

EF Core 3.0 will bring several new features:

  • LINQ improvements
  • Cosmos DB support
  • C# 8.0 support
  • Reverse engineering database views into query types
  • Property bag entities
  • EF 6.3 on .NET Core

These are all explained in detail in the official announcement:

What to Expect in C# 8.0

From one of the C# 8.0 announcements“The current plan is that C# 8.0 will ship at the same time as .NET Core 3.0. However, the features will start to come alive with the previews of Visual Studio 2019”.

Here are some new features you can expect in C #8.0:

  • Nullable Reference Types: get a friendly warning if you try to assign non-nullable reference types to null. This setting can be toggled, to assist in future projects and also provide warnings in existing projects. In other words, C# 8.0 allows you to express “nullable intent”.
string myString = null; // Friendly Warning!
string? myString = null; // This is ok
  • IAsyncEnumerable<T> for consumption of async streams: It is essentially an asynchronous version of IEnumerable<T>, allowing you to await foreach over the items in an async stream.
async IAsyncEnumerable<int> GetBigResultsAsync()
{
   await foreach (var result in GetResultsAsync())
   {
      if (result > SomeValue) yield return result; 
   }
}
  • Ranges and Indices: A new Index type and a .. (two dots) range feature bring in the ability to easily slice through subsets of ranges of values. You may have missed such a feature in C# if you’ve worked with Python to manipulate your data.
// for an array of ints
int[] myArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Index index1 = 3; // 0-index, number 3, counted from beginning
Index index2 = ^4; // 4th item from end, counting backwards 

Console.WriteLine($"{myArray[index1]}, {myArray[index2]}"); // "3, 6" 

var mySlice = myArray[index1..index2]; // { 3, 4, 5 } not including end 

When I used the above code in Visual Studio 2019 Preview 1, I had to update my .csproj to use C# 8.0. Take a look at the example below:

<Project Sdk="Microsoft.NET.Sdk"> 
<PropertyGroup>
 <OutputType>Exe</OutputType>
 <TargetFramework>netcoreapp3.0</TargetFramework>
 <LangVersion>8.0</LangVersion>
 </PropertyGroup> 
</Project>
  • Default implementations of interface members: this gives you the ability to add a real implementation of an interface member that will be used by any class that implements the interface but doesn’t explicitly define the member in its class. Existing classes will automatically get this implementation.
interface ILogger
{
   // method 1 defined in interface 
   void Log(LogLevel level, string message);
   
   /// method 2 can be added to interface, even after class was created
   void Log(Exception ex) => Log(LogLevel.Error, ex.ToString()); 
} 

class ConsoleLogger : ILogger
{
   // method 1, explicitly implemented in class   
   public void Log(LogLevel level, string message) { ... }
  
   // method 2, Log(Exception) gets default implementation
}

You can get more information on C# 8.0 features at:

References, Docs & Tutorials

New/Updated Downloads:

.NET Core 3 and ASP .NET Core 3.0 References:

ASP .NET Core 2.2 Tutorials, Samples and Docs:

Open API (Swagger) References 

ASP .NET Core 3.0

C# 8.0 Tutorials, Samples and Docs:

References for Microsoft Connect(); (Dec 4, 2018)

Your First Razor UI Library with ASP .NET Core

By Shahed C on December 2, 2018

This is the ninth of a new series of posts on ASP .NET Core. In this post, we’ll learn about Razor Class Libraries to build reusable UI for your web app. This post is also included in Matthew Groves‘ 2018 C# Advent Calendar, in the Dec 2 slot.

ASPNETCoreLogo-300x267

Introduction to Razor Class Libraries

From an earlier post on Pages in ASP .NET Core, we’ve seen various of ways of creating web pages with or without controllers, views and models to support each of your pages. If you’re an experienced developer, you already know how to reuse server-side code in class libraries.

Starting with ASP .NET Core 2.1, you can now “package your Razor views and pages (.cshtml files) along with your controllers, page models, and data models in reusable class libraries that can be packaged and shared. Apps can then include pre-built UI components by referencing these packages and customize the UI by overriding specific views and pages.”

Better yet, ASP .NET Core Identity is now available as a Razor Class Library, and can be scaffolded into your web application with just the pieces you need.

Before You Begin

Before you begin, take a look at the sample code project on GitHub:

Web GameConsoles on GitHub: https://github.com/shahedc/GameConsoles

Open the GameConsoles.sln file to load the 2 projects included with the solution:

  • Web App project (Set as StartUp Project)
  • Razor UI Class Library project (contains shared UI for reuse)

Steps to Create in Visual Studio 2017

Create Class Library project, add reusable UI: 

  1. Click File | New | Project
  2. Select ASP .NET Core Web Application, click OK
  3. Select Razor Class Library under ASP .NET Core 2.1

VS2017-Project-RazorClassLibrary

Add partial views under /Pages/Shared/

  • /Pages/Shared/_Header.cshtml
  • /Pages/Shared/_Footer.cshtml
  1. Create folder structure /Pages/Shared/
  2. Add new Razor View _Header.cshtml to Shared subfolder
  3. Add new Razor View _Footer.cshtml to Shared subfolder

Reference for adding new folders and views: https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-view?view=aspnetcore-2.1

Contents of _Header.cshtml:

<h3>_Header.cshtml partial view.</h3>

<p>/Pages/Shared/_Header.cshtml</p>

<a href="/">Home</a>

Contents of _Footer.cshtml:

<h3>_Footer.cshtml partial view.</h3>

<p>/Pages/Shared/_Footer.cshtml</p>

Source: <a href="https://en.wikipedia.org/wiki/List_of_home_video_game_consoles">https://en.wikipedia.org/wiki/List_of_home_video_game_consoles</a>

Continue reading

Watching for File Changes in ASP .NET Core

By Shahed C on November 26, 2018

This is the eighth of a new series of posts on ASP .NET Core. In this post, we’ll learn how to use the .NET CLI file watcher tool during development and debugging.

ASPNETCoreLogo-300x267

Before You Begin

Before you begin, take a look at the sample code project on GitHub:

Web AspNetCoreWatcher on GitHub: https://github.com/shahedc/AspNetCoreWatcher

Specifically, look at the history of CalcController to see how the Sum() method has been updated to accept doubles and not just ints, when summing up two numbers.

Debugging while Running

Initially, we have a Sum() method that looks like this:

 [Route("[action]")]
 public ActionResult<string> Sum(
    [FromQuery(Name = "num1")] int num1,
    [FromQuery(Name = "num2")] int num2)
 {
    var sum = (num1 + num2).ToString();
    return $"The sum of numbers {num1} and {num2} is {sum}.";
 }

We can run the web app from the command line using dotnet run:

> dotnet run

This allows us to access the Web API via a web browser to add 2 numbers, e.g. 3 and 4 for num1 and num2.

https://localhost:5001/api/calc/Sum?num1=3&num2=4

SumInts

However, we get an error if we try to pass in numbers with decimal points, e.g. 3 and 4.4 for num1 and num2.

https://localhost:5001/api/calc/Sum?num1=3&num2=4.4

SumDoublesError

Continue reading

EF Core Migrations in ASP .NET Core

By Shahed C on November 15, 2018

This is the seventh of a new series of posts on ASP .NET Core. In this post, we’ll be looking at the use of EF Core Migrations for your ASP .NET Core web apps. (Normally, I would publish these blog posts on a weekend to allow developers to read it the following week. However, it’s Thanksgiving next week in the US, so I’m publishing this one a few days earlier.) 

ASPNETCoreLogo-300x267

Entity Framework Core

Entity Framework is Microsoft’s ORM (Object-Relational Mapper) and EF Core is a lightweight, cross-platform version of EF, useful for ASP .NET Core web app developers. This article isn’t going to try and convince you of the benefits of using an ORM. If you’re reading this article, hopefully you’ll already recognize the value of using an ORM for your web app.

Instead, we’ll be focusing on EF Core Migrations for taking control of your database. By using migrations, you’ll be able to add and manipulate database objects, define relationships between entities and help developers and server environments stay in sync with specific versions of your database schema.

EFCore-diagrams

Continue reading

NetLearner – ASP .NET Core Internet Learning Helper

By Shahed C on November 11, 2018

This is the sixth of a new series of posts on ASP .NET Core. This week, we’ll be looking  at NetLearner, a new ASP.NET Core Web app to organize online learning resources.

ASPNETCoreLogo-300x267

NetLearner: What is it?

NetLearner is an ASP .NET Core web app to allow any user to consolidate multiple learning resources all under one umbrella.

NetLearner-logo

Some Background: As I’ve been doing a lot of R&D on ASP .NET Core, I found myself keeping track of blog posts, podcasts, YouTube videos, Twitch streams, Pluralsight tutorials, ebooks across Amazon, Safari Books Online, and so much more. I’ve been using Notepad, OneNote, browser bookmarks, Twitter lists, emails to myself, Google/Word docs and so much more just to keep track of URLs, notes and progress. I’m building this new app for myself to organize my learning plans, but also open-sourcing it and deploying it to allow others to use it too.

Web NetLearner on GitHub: https://github.com/shahedc/NetLearner

The name implies 2 things: the app’s source code will be a real-world example for people learning .NET (specifically ASP .NET Core 2.1 and beyond), and the tool itself will help people learn any topic from various resources across the Internet.

What can you expect in 2019?

  1. Use the web app’s source code to learn all about ASP .NET Core 2.1+ and beyond.
  2. Add links to various learning resources: books, articles, blogs, conference sessions, podcasts, online workshops, videos and livestreams.
  3. View embedded content where appropriate, e.g. videos
  4. See contents of RSS feed where appropriate, e.g. blogs with RSS
  5. Discover what others have added to their NetLearner lists, via suggestions of what’s popular.
  6. Follow content creators with links to their social media accounts.
  7. Deploy your own instance instantly to your own Azure account.
  8. Build lists to learn anything and share with others.

Stay tuned for more information!