Thursday, March 24, 2016

Understanding ASP.NET CORE


This is the course "Understanding ASP.NET Core" by Roland Gujit.
Those are my notes. It is not the entire course. 
If you are interested, please go on pluralsight.com and learn from there.

ASP.NET Core
     It is still in development, so many things may change. An example could be: ASP.NET 5 is now renamed as ASP.NET Core 1. Also, DNX (Dot Net Executable) is now integrated in DotNet CLI.

     ASP.NET 5 was built from scratch and it is significantly different with the rest of version.
     The dependency injection is now part of ASP.NET 5.

     ASP.NET 5 it is working only on VS 2015 or higher. At the time of this document, ASP.NET 5 is not included automatically with VS2015. So, you need to download the installer from http://get.asp.net . This will install ASP.NET 5 and also the templates in VS 2015.
     
     The new project structure is completely different by the previous versions. 
     You can find there:
      - global.json - this file contains information related to the new DNX (how to build and execute the solution). In this file exists a "sdk" tag what instructs the asp.net to use a particular version of DNX.
      - project.json - it is the file that contains the configurations and other settings for each project in the solution. 

     Packages
      - In ASP.NET 5 are used:
         a. NuGet - in order to manage packages on server side.
         b. Bower - in order to manage packages on client side.
         c. NPM    - in order to build tools and node.js on client/server side. Also here is Grunt.

      - When you'll install packages with Bower for example, the packages will be downloaded and shown in Dependencies folder.
      - But the files are not reachable to the site, as they are not in wwwroot folder. You need to minify and maybe boundling them.

      - In the new ASP.NET 5, there is no way to register and use bundles as it was...
      - In order to do that, you'll use task runners on node js. Now are used plugins to execute tasks. So bundles didn't make it in ASP.NET 5.
      - .csproj is gone. It was replaced by project.json and xproj (xproj is specific VS to be used for its operations)
     - DNX is using the project.json to get what it needs.

     Startup.cs
     - The global.asax file didn't make it in ASP.NET5. Now we have Startup.cs which contains a Main method what will be launch automatically (if exists) by ASP.NET 5. The Startup class it is just a simple class. Not implementing or deriving from anything.
      - Except Main, it might have two another methods: Configure and ConfigureServices.
      - When an application starts it is registering some classes in order to be automatically instantiated. Those classes are called services. And they are injected by an Dependency Injection service. Once registered, other types can ask the container for an instance of registered type. Also during registration you can specify the lifetime of that instance.
      - The lifetime of that registered object is managed by the container (types):
         a. Transient means a new instance is created every time when is asked for.
         b. Scoped means the instance will live until the web request is completely handled.
         c. Singleton means a single instance will be served for all.
      - This dependency service is right now part of ASP.NET 5 and it is invisibly created and filled with ASP.NET 5 services when the application starts. Anyway you still can use old dependency injector frameworks.
      - The concept of adding a service with DI is simple: write a class which implements whaterver interface you want. Add that interface in ConfigureServices with a command like: services.AddSingleton<Ixxxx, xxxx>(); which means when somebody is asking for that interface (Ixxxx) supply that class (xxxx).

     Those services can be injected in Controllers or even in views using @inject.

     The ASP.NET 5 uses also the idea of a pipeline. A request is coming from a browser and nothing will happen, nothing will be sent back.

     When a request is coming, first is catch by IIS (assuming that is the server). The IIS will delegate DNX in order to launch the application. The application will configure the pipeline adding so called middle services: Authorization, MVC, Static Files, etc and also the application will push the request through this configured pipeline. After finishing the pipeline, the request is physically sent back to the server.

      Until now, most of ASP.NET versions are based on System.Web DLL which is tied to IIS. In ASP.NET 5 this is no more there. Because started with version 1.0 it grown for a long period of time, so processing web requests with System.Web is not a solution on today's standards from processing time and memory usage point of view.

     Using the pipeline, you will plug only what you need, resulting to  a more efficient way to answer to the requests. That means also IIS is not required any more. So, it can be hoster by other web servers.
     IIS & IIS Express will still be supported for the beginning. But also there other options like: WebListener - a very light web server used for hosting, Kestrel - is another interesting web server because supports multiple operating systems.


     Pipeline

    When you add a middle ware in pipeline, then that one will be executed. In order to execute another one, the first one should call the second one, otherwise it returns and that's all.
    Instead to use app.Run in Configure method from Startup, you could use Use.
    Base example:

public void Configure (IApplicationBuilder app)   {      app.UseIISPlatformHandler(); // make sure using IIS      app.Use ( async ( context, next ) =>      {         await context.Response.WriteAsync("Hello !");         await next();      }
      app.Use ( async ( context ) =>      {         await context.Response.WriteAsync("Hello AGAIN!");      }   }
     The pipeline will give back control to the previous middle-ware component.

     ASP.NET can be seen as a next version of Katana (Katana is the Microsoft implementation of OWIN).

     WebForms - there will be no web forms in ASP.NET 5.

     MVC 6

     Services are objects that should be injected but first registered. MVC is also a service that should be registered in IoC container. Also it is required to configure a routing for MVC.
     In order to register MVC in ASP.NET you need to use AddMvc() method in ConfigureServices. After adding MVC service, it is required to add Mvc in pipeline.
     You need also to add StaticFileSupport service.
     You may use also a method like UseStatusCodePages() in order to show a friendly error when a page is not found. There are aslo some other methods in order to use this with a custom error page, etc.
     Web.config is not used anymore. It could be used only if you run under iis.
     The yellow error page is now a middleware.
     
     Environments
     
     In a professional development, you could have a development, testing and production servers. The type of the server may be controlled by environment variables. Those variables are staying usually in a file called: launchSettings.json.
     In Startup you could determine for example what environment is by using an MVC service which implements IHostingEnvironment.

     Unified Controllers

     MVC 5 (ASP.NET 4) has a clear distinction between MVC and WEB API. Web API was created using same model that MVC uses. The reason for what MVC and Web API were separately (even they are almost one to one map), it is that MVC is tied to System.Web.dll. Microsoft wanted to untie WEB API from System.Web.dll which gave to WEB API applications to be self hosted.
     Because ASP.NET 5 is not using System.Web.dll, there is no reason to have to sets. So WEB API and MVC are now together and the name Web API has been dropped.

     The new return is now IActionResult instead of ActionResult class. You can now create your ActionResult class, implementing IActionResult without being tied with the ActionResult base abstract class. There is also a benefit for unit testing.

     HTML helper tags
     In the previous version of MVC you could use:
       @Html.EditorFor ( m => m.Name)
     In the new ASP.NET 5 you can use:
       <input asp-for="Name"></input>
     Benefits: more HTML friendly approach. Also you can create your own taghelpers deriving from TagHelper instead to create an extension for Html class.
     There are few more new tags that are supporting the development. For this you need:
     a. Add the reference to the Microsoft.AspNet.Mvc.TagHelpers in the project.
     b. You need to make them visible everywhere: so you need to create a new partial view (eg: _ViewImport) in the root of the Views folder.
     c. Add the following code:
     @addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
     
     In the application, there is a tag called environment which is helping you to include that part of the code when the application has a specific variable environment. So you could load the full css and javascripts when is in development and minifyed versions when you are in production.
     Some tags:
     1. asp-href-include: it is used to add new css files. It can be used with wildcards.
     2. asp-src-include: it is used to add new js files. It can be used with wildcards.
     3. asp-append-version: it is used for images when you add an image, it computes the value based on the content of the image. So, if the image will be changed, it will be loaded and cached again.
     4. In C# 6 if you put $ in front of the string you can construct it with expressions.

     Configuration system
     The configuration system was reviewed. It is still using simple keyvalue pairs in order to keep the information.
     Until version ASP.NET 5 it is common to put settings in web.config or other xml files.
     After this version, web.config is gone. There are new configurations much more flexible like: in memory, JSON, XML, INI and environment variables.
     You could even extend sources by deriving from ConfigurationSource class. What was not possible previous.
     In ASP.NET 5 there is a new set of configuration classes in a different assembly: Microsoft.Extensions.Configuration. Also actual settings are decoupled by the setting system.
     In order to load a set of settings into a class, you need to add a json file with that information. After that you need in Startup to create an instance of ConfigurationBuilder where you should use AddJsonFile. You could add also optional files for different settings using for example an environment variable.
     After you need to call the Build command of that instance of ConfigurationBuilder.
     In order to pass data from json to the class, you should use  services.Configure<xxxx>(configBuilder) and pass it in constructor.

     The Traditional .NET 
     Since the beginning of .NET, things were similar. There is always some kind of Bootstraper which starts the .NET. 
     In the case of console app, this is the executable itself which is started by Windows. In the case of traditional ASP, this is the isapi.dll.
     The app written is compiled in an assembly which contains IL. On the machine IL is compiled in native code by JIT.
     JIT is contained in .NET itself in the part that is called CLR. The other part is named FCL or Framework Class Library. It contains all classes required by Windows Forms, WPF, etc. The advantage of this is the application will contain only what you wrote, not everything. 
     .NET Framework should be installed on the machine where you want to execute the application.
     The CLR is specific designed for Windows. It contains classes specific for Windows.

     Mono
     Mono is an opensource version of .net framework. And it is cross platforms. It is used heavily by Xamarin.

     NuGet
     Ideally, you don't need NuGet in order to run your application. But usually you need in order to download thirdparties from internet.
     Visual Studio has tooling to download, search and install nuget packages. Used to introduce new libraries and even frameworks.
     It is difficult to update, correct or create new versions of .NET in the old way. NuGet fixes this problem.

     .NET Core
     It contains:
         - CoreCLR - what is portable across all platforms
         - CoreFX - a set of classes what are common across platforms (classes like manipulating files, lists, etc. But not WPF for example).
     The entire CLR is distributed via NuGet.
     .NET core has:
         - a small footprint, lightweight
         - it is cloud optimized
         - no machine wide installation
         - it is an open source
     
    DNX
    The primary goal of it is to run the app on the designed framework.
    The command line it is called: DotNet Cli
    DNX runs the app. And DNX hosts the CLR instead of OS.
    DNX will look for Main method.

    Ngnix - is the production server for linux.



 
 

 




No comments:

Post a Comment