ASP.NET Core- Zero to Hero

By | March 1, 2017

In this article, we will cover the below topics,

  • What is .Net Core
  • Unified Model
  • New Feature
  • Project Layout
  • Tag Helpers in ASP.NET Core
  • Dependency injection into views
  • View Components
  • Setup Entity Framework
  • Logging in ASP.NET Core
  • Support for Grunt
  • Support for Gulp
  • Support for Bower
  • CURD operation Demo

 

What is ASP.NET Core?

ASP.NET Core is a new open-source and cross-platform framework for building modern cloud based internet connected applications, such as web apps, IoT apps and mobile backends.

It was architected to provide an optimized development framework for apps that are deployed to the cloud or run on-premises.

It consists of modular components with minimal overhead, so you retain flexibility while constructing your solutions. ASP.NET Core is open source at GitHub.

It is unified programming model , which combines MVC,WEB API and WEB PAGE into one framework know as MVC6 or ASP CORE  MVC .

 

 

Unified Model

As we know In earlier versions of MVC, MVC controllers were different from Web API controllers. Where An MVC controller need to inherit from System.Web.MVC.Controller base class and Web API controller need to inherit from  System.Web.Http.ApiController base class.

In MVC 6, there is only one Controller base class for both MVC and Web API controllers which is the Microsoft.AspNet.Mvc.Controller  .
As we know web pages and MVC both are used to build UI applications and both can use HTML Helpers for creating UI functionality, but the implementation of the HTML Helpers is entirely different for both.
For web pages HTML helpers are defined in System.Web.WebPages.Html  namespace
in System.Web.WebPages assembly. while for MVC HTML helpers are defined
in System.Web.Mvc namespace in the System.Web.Mvc assembly
In MVC 6 , Microsoft.AspNetCore.Html namespace is used to provide html helpers.

 

New Features

  • Open source and available on GitHub
  • Platform Independent (can build and run on Windows, Mac and Linux)
  • Built-in dependency injection.
  • Built on .NET Core, which supports true side-by-side app versioning
  • Ships entirely as NuGet packages
  • New tooling that simplifies modern web development
  • New light-weight and modular HTTP request pipeline
  • Ability to host on IIS or self-host in your own process
  • It supports the cloud based environment based configuration.
  • Earlier we used the System.Web DLL which has been removed from ASP.NET Core

 

Project Layout

project.json :

The project.json file replaces packages.config in UWP, ASP.NET 5, and .NET desktop projects (WPF and WinForms) as a means to maintain the list of packages used in a project. (For .NET Core, refer to  NET Core Tools – project.json).

 

launchSettings.json :
This file contains the settings related to the application launch.
This file holds the project specific settings associated with each debug profile like Development, Staging, Production etc. You can also define different settings for different debugging profiles.

 

Startup.cs :
The startup class is helpful to define the request handling pipeline and configure the Services required by the app.

appsettings.json :
This is a JSON file which contain configuration details or static values like “ConnectionStrings”.
This file is not available in an empty template. Thus, we can add through “Ctrl + Shift + A ” or “Add -> New Item – Type JSON in search area -> Select ASP.NET Configuration File ”

Web.config :
In the previous versions, everything is handled by Web.Config but in ASP.NET Core,we don’t know about Web configure file and the only purpose it gives the instruction to iis for what should be done and it receives the http request.

 

Tag Helpers in ASP.NET Core

ASP.NET Core MVC introduces a new feature called Tag Helpers. It improves the readability of your Razor views that generate HTML forms.

Here is how we would generate an HTML input for the UserName property using an HTML Helper and a Tag Helper.

<!--Create an input for UserName using Html Helper-->
@Html.EditorFor(l => l.UserName)
<!--Create an input for UserName using Tag Helper-->
<input asp-for="UserName" />

 

How to enable Tag Helpers

The MVC Tag Helpers are located in the Microsoft.AspNet.Mvc.TagHelpers package so you will need to add a reference to that in your project.json file. Once you have added the reference, you can enable tag helpers in all your views by adding the following code to GlobalImports.cshtml.

@addTagHelper “*, Microsoft.AspNet.Mvc.TagHelpers”

 

Dependency injection

ASP.NET 5 provides a built-in DI abstraction that is available in a consistent way throughout the entire web stack. You can access services at startup, in middleware, in filters, in controllers, in model binding and virtually any part of the pipeline where you want to use your services. ASP.NET 5 includes a minimalistic DI container to bootstrap the system, but you can easily replace the default container with your container of choice (Autofac, Ninject, etc). It has support for the following types of lifetimes for configured services (injected dependencies).

Singleton: A single shared instance throughout your application’s lifetime. Only created once.
Scoped: Shared within a single request (or Service Scope).
Transient: Created on every request for the service.

 

Dependency injection into views

ASP.NET Core supports dependency injection into views. This can be useful for view-specific services, such as localization or data required only for populating view elements. You should try to maintain separation of concerns between your controllers and views. Most of the data your views display should be passed in from the controller.

You can inject a service into a view using the @inject directive. You can think of @inject as adding a property to your view, and populating the property using DI.

The syntax for @inject: @inject <type> <name>

 

View Components

New to ASP.NET Core MVC, view components are similar to partial views, but they are much more powerful. View components don’t use model binding, and only depend on the data you provide when calling into it. A view component:

  • Renders a chunk rather than a whole response
  • Includes the same separation-of-concerns and testability benefits found between a controller and view
  • Can have parameters and business logic
  • Is typically invoked from a layout page View Components are intended anywhere you have reusable rendering logic that is too complex for a partial view, such as:
  • Dynamic navigation menus
  • Tag cloud (where it queries the database).

Setup Entity Framework

To use EF Core, First we need to install necessary packages for database provider.so install the following packages via Nuget (Tools ‣ NuGet Package Manager ‣ Package Manager Console).

Run Install-Package Microsoft.EntityFrameworkCore.SqlServer
Run Install-Package Microsoft.EntityFrameworkCore.Tools –Pre
Run Install-Package Microsoft.EntityFrameworkCore.Design
Run Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

Open project.json
Locate the tools section and add the Microsoft.EntityFrameworkCore.Tools.DotNet package.

 

Run the following command to create a model from the existing database. If you receive an error stating the term ‘Scaffold-DbContext’ is not recognized as the name of a cmdlet, then close and reopen Visual Studio.

Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Test1;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/DB

As below image.

 

Register your context with dependency injection
The concept of dependency injection is central to ASP.NET Core. Services (such as Test1Context) are registered with dependency injection during application startup. Components that require these services (such as your MVC controllers) are then provided these services via constructor parameters or properties.

Now Remove inline context configuration file.

Open Models\DB\Test1Context.cs
Delete the following lines of code as below image below.

 

Now add that connection string in ConfigureServices() method  and register it as service also in Startup.cs file as below.

var con = @"Data Source=(localdb)\mssqllocaldb;Initial Catalog=Test1;Integrated Security=True;";

services.AddDbContext<Test1Context>(options => options.UseSqlServer(con));

 

Logging in ASP.NET Core

ASP.NET Core supports a logging API that works with a variety of logging providers. Built-in providers let you send logs to one or more destinations, and you can plug in a third-party logging framework.

ASP.NET Core dependency injection (DI) provides the ILoggerFactory instance. The AddConsole and AddDebug extension methods are defined in the Microsoft.Extensions.Logging.Console and Microsoft.Extensions.Logging.Debug packages. Each extension method calls the ILoggerFactory.AddProvider method, passing in an instance of the provider .

I am using Serilog liabrary for writing logs in a text file by installing from nuget or adding below line in project.json file.

"Serilog.Extensions.Logging.File": "1.0.0"

Example: modify the configure method in Startup.cs file

 

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
loggerFactory.AddFile("Log/error_{Date}.txt");

app.UseApplicationInsightsRequestTelemetry();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseApplicationInsightsExceptionTelemetry();

}

 

Grunt

Grunt is a JavaScript task runner that automates script minification, TypeScript compilation, code quality “lint” tools, CSS pre-processors, and just about any repetitive chore that needs doing to support client development. Grunt is fully supported in Visual Studio, though the ASP.NET project templates use Gulp by default. There are some following packages:

  • grunt: The Grunt task runner package.
  • grunt-contrib-clean: A plugin that removes files or directories.
  • grunt-contrib-jshint: A plugin that reviews JavaScript code quality.
  • grunt-contrib-concat: A plugin that joins files into a single file.
  • grunt-contrib-uglify: A plugin that minifies JavaScript to reduce size.
  • grunt-contrib-watch: A plugin that watches file activity.

Gulp

Gulp is a JavaScript-based streaming build toolkit for client-side code. It is commonly used to stream client-side files through a series of processes when a specific event is triggered in a build environment. Some advantages of using Gulp include the automation of common development tasks, the simplification of repetitive tasks, and a decrease in overall development time. For instance, Gulp can be used to automate bundling and minification or the cleansing of a development environment before a new build.

 

Bower

As in the NPM, Bower is a tool that manages packages too, but now it’s packages such as jQuery, Angular and others clients that we use in our projects. In this moment comes a question: Why use Bower since Nuget does that? When I saw Bower I also had this question. But when I went to research I understood the reason. Bower is the bigger client package manager and when a developer develops a new library it is stored in Bower and not in Nuget, because it is only to .Net. For this reason, Microsoft decides to bet on Bower and uses it in the development. Already with Nuget, it continues, but just to the library of the back end as Identity, MVC and many others packages that there are and that work only to .Net.

Visual Studio developers are already familiar with NuGet, so why not use NuGet instead of Bower? Mainly because Bower already has a rich ecosystem with over 34,000 packages in play; and, it integrates well with the Gulp and Grunt task runners.

Client-side packages are listed in the bower.json file. The ASP.NET Core project template pre-configures bower.json with jQuery, jQuery validation, and Bootstrap.

 

Here i have uploaded  a demo project with all examples and CURD operation in github, so you can download

Download Source Code

Like it? Share it
  • Honey Singh

    Thanks…it is very useful for me…great explaination