.Net Core Tutorial - ASP.NET Core Tutorial - .Net Tutorial



.Net Core Introduction

  • .Net Core is the latest general purpose development platform maintained by Microsoft and it works across different platforms.
  • .Net has been redesigned in a way that makes flexible, fast and modern.
  • All in open source, .Net core happens to be one of the major contributions by Microsoft. Developers can now build Android, iOS, Linux, Mac, and Windows applications with .NET.

Characteristics of .Net Core

.Net

Open-Source

  • .NET Core is an open-source implementation, using Apache 2 licenses and MIT.
  • .NET Core is available on GitHub and it is a Foundation project.
  • As an open-source project, it promotes an active and engaged community, it promotes a more transparent development process.

Cross-Platform

  • In .Net Core application implemented can be run and its code can be reused regardless of your platform target.
  • It currently supports three main operating systems (OS) which is Windows, Linux and Mac OS.

Flexible Deployment

  • There are two types of deployments for .NET Core applications they are Framework-dependent deployment and Self-Contained deployment.
  • Our app depends on a system-wide version of .NET Core on which our app and third-party dependencies are installed, with framework-dependent deployment.
  • The .NET Core version used to build your application is also deployed along with your app and third-party dependencies and can run side-by-side with other versions, with self-contained deployment.

Command-line Tools

  • At the command line all products scenarios can be exercised.

Compatible

  • .NET Core is compatible with Xamarin, Mono and .NET Framework, via the .NET Standard Library.

Modular

  • .NET Core is made available as smaller feature-centric packages and it is released through NuGet in smaller assembly packages.
  • .NET Framework is one large assembly which contains most of the core functionalities.
  • The modular approach enables the developers to optimize their app by including just those NuGet packages which they need in their app.

.NET Core Platform

.Net

.Net Runtime

  • It provides assembly loading, native interop, type system, a garbage collector and other basic services.

Fundamental Libraries

  • A set of framework libraries, which provide fundamental utilities, primitive data types and app composition types.

SDK & Compiler

  • A set of SDK tools and language compilers which enables the base developer experience, available in the .NET Core SDK.

.Net app host

  • It is used to launch .NET Core apps and provides an assembly loading policy and launches the app.
  • It selects the runtime and hosts the runtime and same host is also used to launch SDK tools in much the same way.

.Net Core Numerics

  • .NET Core supports the standard numeric integral and floating-point primitives and also supports the Big Integer, Complex, SIMD.
.Net

Integral Types

  • .NET Core supports both signed and unsigned integers of different ranges from one byte to eight bytes in length.
  • Each integral type supports a standard set of comparison, equality, explicit conversion, implicit conversion and arithmetic operators.
  • Here all integers are value types.
.Net

Floating-point types

  • .NET Core includes three primitive floating-point types, they are double, single and decimal.
  • Each integral type supports a standard set of comparison, equality, explicit conversion, implicit conversion and arithmetic operators.
  • As well as its own set of methods for performing some additional mathematical operations, Decimal structure has its own methods, Decimal.GetBits and Decimal.Decimal(Int32()), for working with a decimal value's individual bits.
.Net

BigInteger

  • BigInteger is an integral type with no upper or lower bound.
  • BigInteger is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds.
  • In this the methods of the BigInteger type is closely parallel to those of the other integral types.

Complex

  • Complex type represents a complex number in which a number with a real number part and an imaginary number part.
  • It supports a standard set of comparison, equality, explicit conversion, and implicit conversion, arithmetic operators, as well as mathematical, algebraic, and trigonometric methods.

SIMD

  • SIMD otherwise known as Single Instruction Multiple Data.
  • For .Net Core Numerics namespace includes a set of SIMD-enabled vector types.
  • SIMD allows some operations to be parallelized at the hardware level, which results in huge performance improvements in scientific, mathematical and graphics apps that perform computations over vectors.

.NET Core - Garbage Collection

.Net
  • The concept of Garbage collection which is one of most important features of the .NET managed code platform.
  • The garbage collector (GC) manages the allocation, release of memory and serves as an automatic memory manager.
  • We don’t need to know how to manage he lifetime of the objects that use that memory or to allocate and release memory.
  • An allocation is made any time you declare an object with a “new” keyword or a value type is boxed and they are typically very fast.
  • The GC must collect and dispose of garbage memory to make memory available for new allocations, when there isn’t enough memory to allocate an object.
  • We don’t need to free memory manually while developing your application.
  • It also provides memory safety by making sure that an object cannot use the content of another object.
  • The GC Collect method is called in almost all cases, we do not have to call this method, because the garbage collector runs continuously.

.NET Core - Code Execution

.Net
  • We will understand the execution process of .NET Core and compare it with the .NET Framework.
  • The managed code execution process includes the following steps, they are:
    • Choosing a compiler
    • Compiling your code MSIL
    • Compiling MSIL to native code
    • Running code

Choosing a Compiler

  • The runtime supports a wide variety of data types and language features, so it is a multi-language execution environment.
  • We must use one or more language compilers that target the runtime, to obtain the benefits provided by the common language runtime.

Compiling your code to MSIL

  • Compiling is used to translates your source code into Microsoft Intermediate Language (MSIL) and generates the required metadata.
  • Metadata describes the types in your code, including the definition of each type the signature of each types the members that your code references and at execution time other data that the runtime uses.
  • The runtime extracts and locates the metadata from the file as well as from framework class libraries (FCL) as needed during execution.

Compiling MSIL to Native Code

  • A just in time compiler translates the MSIL into native code, at execution time.
  • Code must pass a verification process that examines the MSIL and metadata to find out whether the code can be determined to be type safe, during this compilation.

Running Code

  • The common language runtime provides the infrastructure that enables the execution to take place and during execution services that can be used.
  • Managed code receives services such as interoperability, security and garbage collection with unmanaged code, cross-language debugging support, and enhanced deployment and versioning support, during execution.

.NET Core Code Execution Process

.Net
  • Like we have Roslyn for C# and VB, in .Net core now we have a new series of compilers.
  • We can also make use of the new F# 4.1 compiler if we want to use F# with .NET Core.
  • .Net core don’t have a framework class library (FCL), so a different set of libraries are used and we now have CoreFx.
  • In .Net core CoreFx is the reimplementation of the class libraries.
  • In .Net core we have a new run time known as CoreCLR and leverages a JIT Compiler.

.NET Core - Package References

  • We will discuss how to add packages in our .NET Core application and how to find a specific package.
  • Let us now go to the source code of .NET Core.
.Net
  • Open the src folder, in CoreFx.
.Net
  • We will see the whole list of folders that correspond to different packages, let search for Json.
.Net
  • There is another way to find our package, we all are known probably various types if we are familiar with .NET Framework, but the assembling of packages in .NET Core is totally different and we won’t know where that packages in.
  • If we know the type, you can search to reverse package search by using - https://packagesearch.azurewebsites.net/
.Net
  • Here we can enter any type of package to find.
  • After, this site will scan NuGet and find the relevant packages for us.
  • Let us search for DataContractJson.
  • .Net

    .NET Core – Configuration

    .Net
    • In Solution Explorer, we will see the Startup.cs file.
    • If we have worked with previous versions of ASP.NET Core, we will probably expect to see a global.asax file, which was one place where you could write codes to execute during startup of a web application.
    • We will also expect to see a web.config file containing all the configuration parameters your application needed to execute.
    • These files are gone and instead of configuration and startup code are loaded from Startup.cs, at ASP.NET Core.
    • There is a Startup class inside the file and in that class, we can configure our application and even configure our configuration sources.

    Sample Code

    //Startup.cs file

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Threading.Tasks; 
    
    using Microsoft.AspNetCore.Builder; 
    using Microsoft.AspNetCore.Hosting; 
    using Microsoft.AspNetCore.Http; 
    
    using Microsoft.Extensions.DependencyInjection; 
    using Microsoft.Extensions.Logging;  
    
    namespace FirstAppDemo { 
       public class Startup { 
          // This method gets called by the runtime.
          // Use this method to add services to the container. 
          // For more information on how to configure your application, 
          // visit http://go.microsoft.com/fwlink/?LinkID=398940 
          public void ConfigureServices(IServiceCollection services) { 
          }  
          
          // This method gets called by the runtime. Use this method to configure 
          // the HTTP request pipeline.
          public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
             ILoggerFactory loggerFactory) { 
             loggerFactory.AddConsole();  
             
             if (env.IsDevelopment()) { 
                app.UseDeveloperExceptionPage(); 
             }  
             app.Run(async (context) => { 
                await context.Response.WriteAsync("Hello World!"); 
             }); 
          } 
       } 
    }
    
    • There are two methods where most of our work will take place, in startup class.
    • The Configure method of the class is where we build our HTTP processing pipeline.
    • This defines how our application responds to requests and it can only say Hello World! Then, if we want the application to behave differently, we will need to change the pipeline around by adding additional code in this Configure method.
    • This other component might load that text from a JSON file or a database or a web service, it doesn't matter where exactly it is.
    .Net
    • In the Solution Explorer, right-click on our project node and select Add → New Item.
    • Call this file AppSettings.json and click on the Add button as in the above screenshot.
    .Net
    • We can also have our program read the text from the file instead of having the Hello World! String in Startup.cs and add the following code in AppSettings.json file.
    {
         "message": "Hello, World! this message is from configuration file..."
    }

    Sample Code

    using Microsoft.AspNet.Builder; 
    using Microsoft.AspNet.Hosting; 
    using Microsoft.AspNet.Http; 
    
    using Microsoft.Extensions.DependencyInjection; 
    using Microsoft.Extensions.Configuration;  
    
    namespace FirstAppDemo { 
       public class Startup { 
          public Startup() { 
             var builder = new ConfigurationBuilder()   
                .AddJsonFile("AppSettings.json"); 
             Configuration = builder.Build(); 
          }  
          public IConfiguration Configuration { get; set; }  
          
          // This method gets called by the runtime. 
          // Use this method to add services to the container. 
          // For more information on how to configure your application, 
          // visit http://go.microsoft.com/fwlink/?LinkID=398940 
          public void ConfigureServices(IServiceCollection services) { 
          }  
          
          // This method gets called by the runtime.  
          // Use this method to configure the HTTP request pipeline. 
          public void Configure(IApplicationBuilder app) {
             app.UseIISPlatformHandler();  
             app.Run(async (context) => { 
                var msg = Configuration["message"]; 
                await context.Response.WriteAsync(msg); 
             });  
          }  
            
          // Entry point for the application. 
          public static void Main(string[] args) =7gt; WebApplication.Run<Startup>(args); 
       } 
    }

    Output

    .Net

    .NET Core – Exceptions

    • In Asp.Net Core app when errors occur, we can handle them in a variety of ways.
    • Let us go to app.Run and see how the application behaves if we just throw an exception every time we hit this piece of middleware, to simulate an error.

    Sample Code

    using Microsoft.AspNet.Builder; 
    using Microsoft.AspNet.Hosting; 
    using Microsoft.AspNet.Http; 
    
    using Microsoft.Extensions.DependencyInjection; 
    using Microsoft.Extensions.Configuration;  
    
    namespace FirstAppDemo { 
       public class Startup { 
          public Startup() { 
             var builder = new ConfigurationBuilder() 
                .AddJsonFile("AppSettings.json"); 
             Configuration = builder.Build(); 
          }  
          public IConfiguration Configuration { get; set; }  
            
          // This method gets called by the runtime. 
          // Use this method to add services to the container. 
          // For more information on how to configure your application, 
          // visit http://go.microsoft.com/fwlink/?LinkID=398940 
          public void ConfigureServices(IServiceCollection services) { 
          }  
          
          // This method gets called by the runtime. 
          // Use this method to configure the HTTP request pipeline.
          public void Configure(IApplicationBuilder app) { 
             app.UseIISPlatformHandler();  
             app.UseRuntimeInfoPage();  
             
             app.Run(async (context) => { 
                throw new System.Exception("Throw Exception"); 
                var msg = Configuration["message"]; 
                await context.Response.WriteAsync(msg); 
             });  
          }  
            
          // Entry point for the application. 
          public static void Main(string[] args) => WebApplication.Run<Startup>(args); 
       }   
    } 

    Output

    • It will throw an exception with a very generic message then, save Startup.cs page and run your application.
    .Net
    • We just add another piece of middleware, which is the UseDeveloperExceptionPage.

    Sample Code

    // This method gets called by the runtime.  
    // Use this method to configure the HTTP request pipeline. 
    public void Configure(IApplicationBuilder app) { 
       app.UseIISPlatformHandler();  
       app.UseDeveloperExceptionPage(); 
       app.UseRuntimeInfoPage();  
       
       app.Run(async (context) => { 
          throw new System.Exception("Throw Exception"); 
          var msg = Configuration["message"]; 
          await context.Response.WriteAsync(msg); 
       });  
    }
    

    Output

    .Net

    Related Searches to .Net Core Tutorial - ASP.NET Core Tutorial - .Net Tutorial