Prep NET Framework & Core

  1. Explain how the .NET Framework compiles code?
    ASP.NET must first parse and compile the code of your Web application into one or more assemblies (also known as .exe or dll files). When the code is compiled, it is translated into a language-independent and CPU-independent representation called Microsoft Intermediate Language (MSIL). At run time, the CLR software loads and translates MSIL into CPU-specific instructions for the processor on the computer running the application, effectively managing error handling, memory management, security, and more (simulating a hardware environment).
  2. Describe the .NET Framework.
    Developed by Microsoft in 2002 and primarily ran on Microsoft machines, it is a combination of numerous class libraries (called Framework Class Libraries) which provide language inter-operability including C#, VB, J#, and others. Programs written against the .NET Framework are executed in a software environment (as opposed to a hardware environment) named the Common Language Runtime (CLR) which is a virtual machine providing security, memory management, exception handling and more.

    The two components FCL and CLR comprise the .NET Framework.
  3. What happens when a .NET application is first ran?
    When an application is first launched, the .NET Framework compiles the CIL code into executable code using its just-in-time compiler, and caches the executable program. Due to caching, the application launches faster for subsequent launches, although the first launch is slower.
  4. What is .NET core? Explain.
    .NET Core is a cross-platform (Linux, Windows, Mac) and open-source (anyone has access to source code) software framework similar to .NET Framework and designed to eliminate the bloated .NET Framework of the past by creating portable class libraries that are lighter, faster, and smaller. Its targets are desktop users of Windows products, but also of Mac iOS machines, phone devices (Android), and more.

    So, what is .NET Core again? It is a modular framework accessible across platforms because it is a refactored set of base class libraries (CoreFX Jump ) and Runtime (CoreCLR Jump ). Along with that you can also have your own out-of-band libraries. This is also a key characteristic of .NET Core where you may choose the package you need to deploy with your app. This means that your apps can be deployed and run in isolation and machine-wide versions of the full .NET Framework do not cause a hindrance in the running of your apps.
  5. What's the difference between ASP.NET Core and ASP.NET?
    ASP.NET Core is a complete framework rewrite of classic ASP.NET 4.6 into a much smaller and more modular design. The old CLR and FCL libraries and tools are now replaced by CoreCLR and CoreFX. Besides being open-sourced and cross-platform independent, it is notable to show that when designing ASP.NET applications, one has to do so using a Windows box...and delivering it to IIS to display the web pages for web viewing. ASP.NET Core eliminates this need, meaning I can also BUILD on a MAC, deploy using a Linux box, and run the application on an Android Phone. Very Nice!!
  6. What are 6 or more common components of the .NET framework?
    • Common Language Runtime (CLR)
    • Framework Class Libraries (base: System)
    • Windows Forms
    • ASP.NET
    • ADO.NET
    • Windows Communication Foundation
    • LINQ
  7. The .NET Framework allows you to build 3 types of applications. What are they?
    • Windows Form Applications
    • Web Applications
    • Web Services
  8. What is middleware? What are some common middleware calls?
    A component class that gets executed on every Http request in Core applications, getting configured in the StartUp.cs file of the Configure() method, and which forms a pipeline wherein each middleware component add or modifies the http request and optionally passes control to the next middleware component, performing these same steps in reverse using the Http response.

    All middleware components begin with "Use" and perform jobs we want the entire application to provide such as UseAuthentication(), UseAuthorization(), UseEndPoints(), and the custom UseMiddleware() method which can allow things such as custom logging and other items we'd like to include in middleware.
  9. Dependency Injection is common in .NET Core applications and is generally configured as a services in the ConfigureServices() method of the Startup.cs class. What are the lifetime of these services for each of our configurable types and what are their characteristics?
    Singleton: Only a single instance is created and that instance remains for the lifetime of the application (ie, logger), regardless of new instance requests of the service or Http requests. 

    Scoped: We use the same service instance for each request, so while a single user may use that single instance, other users would get their own instance, yet, every new request from the same user would create a new instance.

    Transient: Every instance and every request results in a brand new instance being created.
  10. How would you choose to use Singleton, Transient, or Scoped service types?
    Singleton is common when we want something to last the lifetime of the application, for example, configuration files, database connection string, application state, logging service or security services. We don't need to keep creating these services because they will be widely used and loading their information is a lot of overhead for something that may be used on every page of the application (security, logging) or nearly every page (configuration, app settings).

    Scoped is common when we have just a little information we'd like to keep between requests (pages) such as state management between pages or inside a grid. 

    Transient is only used when we don't care about any state management between requests whatsoever, like an API request wherein we don't care about our next request or what is going outside of this one request, because state management isn't saved in API calls so we wouldn't bother to keep this information stored in memory, rather, every request is like the first.
  11. An application contains a simple controller which houses a counter with 3 objects. The UI creates an instance of our service as does the controller. A single button that increments the number of objects in the controller would produce what results if the service was implemented using Singleton, Scoped, and Transient? Explain why.
    Singleton: 3, 4, 5, 6, 7. That is, we would start with showing 3 and then each press of the button (request) would increment our value by 1, regardless that the UI and controller both request to increment, we would only see an increment of 1 each time.

    Scope: 3, 4, 4, 4, 4. We'd start with 3 displayed, then we hit the button we increment by 1 (controller), it gets sent to the UI but not incremented (same instance in same request), the button is pressed again, the controller is treated as a new request (3) whereas the UI still says (4), the controller is incremented to 4 and then passed again to UI which again displays 4, and keeps doing this over and over.

    Transient: 3, 3, 3, 3. Each request is brand new and even the UI doesn't increment further as each instance is started anew.
  12. In pseudocode and plain words, explain how you would error handling and the redirecting to error pages work in .NET applications.
    1. Development and Production can be toggled against the ASPNETCORE_ENVIRONMENT json variable in launchSettings.json file.

    2. In Configure() method of Startup.cs, we toggle between both environments using the env.IsDevelopment() property. In development, we would use app.UseDeveloperExceptionPage() and in production, we would use two methods: app.UseStatusCodePagesWithRedirects("/Error/{0}") for 404 and similar errors or app.UseExceptionHandler("/Error") for uncaught 500 errors.

    3. Outside of here, we use basic controller/action/view methods to obtain and handle the error (ie, logging, database), and then pass the error to the view to display to the user while also limiting what the user would see for security reasons.
  13. What would the typical error handling page controller and action methods look like in a .NET application?
    1. We'd use DI to inject database and logger capabilities.

    2. We'd import System.Diagnostic and Microsoft.AspNetCore.Diagnostics API's into the page.

    3. We would have one action method which handles PageNotFound (404) and other controlled errors. It's header would be:

    • [Route("Error/{statuscode}")]
    • public IActionResult HttpStatusCodeHandler(int statusCode)

    4. We would have on action method which handles all uncaught exceptions (500 errors). Its method would look like:

    • [Route("Error")]
    • [AllowAnonymous]
    • public IActionResult Error()

    5. Both would likely persist the error information to the database or to the logger.
  14. What are the two method calls to get error information about the calling procedure such as error message, path, query string, stack trace and more?

    What other common information should be obtained?
    1. HttpContext.Features.Get<IStatusCodeReExecuteFeature>();

    which can get us query string information or original path requested information.

    2. HttpContext.Features.Get<IExceptionHandlerPathFeature>();

    which can provide us with error message, path, error, inner exception, stack trace, etc.

    3. User information using User.Identity.Name, timestamp can be obtained when inserting into database as a default, and of course, we can say type of error code (HttpContext.Response.StatusCode) and error page and line number where the error occured (StackTrace).
  15. What's the important security vulnerability and why we handle errors?
    Handling errors means to handle an unforeseen error gracefully such that we do not show secure information--therefore, we handle them by logging them to a file, in system errors, or even to the database but we would never show this information to the user.
  16. How do we use logging to log errors throughout the application.
    Using DI, we inject ILogger to a private variable on our error page, inject this with the ErrorModel type through the constructor, and then finally log our custom message to the logger through the LogError() method.

    For example:

    private readonly ILogger<ErrorModel> _logger;

    • public ErrorModel(ILogger<ErrorModel> logger)
    • {
    • _logger = logger;
    • }

    _logger.LogError($"An error occured {ex.Message}");
  17. What is logging and how is it done in Core?
    Core does not provide out-of-the-box file logging, but does offer several providers which handle different ways of logging Information, Warnings, Errors, and more. In the appSettings.json file, a "Logging" object exists with a LogLevel object which can be set for different targets and how each should be handled.

    • Below is list of providers
    • .AddConsole(); // to web browser console or command line (display only)
    • .AddDebug();  // to debug output window
    • .AddEventSourceLogger(); // to windows event source 
    • .AddEventLog();
    • .AddApplicationInsights

    • Below is list of levels (in prod, we use 3+)
    • Trace = 0, Debug = 1, Information = 2, Warning = 3, Error = 4, Critical = 5, and None = 6.

    • Below is list of log method calls
    • LogTrace(), LogDebug(), LogInformation(), LogWarning(), LogError(), LogCritical(), and LogNone().
  18. How is Serilog logging handled? Who is a competitor?
    You install a package called Serilog.Extensions.Logging.File into your application and then use DI to inject ILoggerFactory loggerFactory in the Configure file. We add a single line which is the file we'd like updated within a Log folder of our application "loggerFactory.AddFile("Logs/Amazon.txt");" and we are done, all logs would then be logged to the Amazon.txt file with a date value, each day a new log is created.

    Serilog is great for ease of use and getting up and running quickly, but the biggest logger package is probably NLog since it can be used in web.config, database, files, and more.
  19. What is the Core project file used for? How about launchSettings.json? How about appSettings.json?
    (a) *.cproj

    (b) launchSettings.json

    (c) appSettings.json:
  20. What is middleware?
  21. How do we send data to the view? What is a strongly typed view?
  22. How is routing handled?
  23. How do we add client-side validation to a Core application in relation to entity framework data annotations?
  24. What are tokens? How are they used (use examples)?
    Tokens are generated and validated in ASP.NET Core for use for things like email validation, password reset, or 3rd party logon capabilities using token authentication. The app begins by adding the service under *.addAuthentication() with various options followed by the *.UseAuthentication() method in middleware section, thereby allowing the token to be passed/validated prior to executing the API.

    Using an API, it is also commonly known as an access token/bearer token for Http requests wherein the API header is inspected, and a valid token is found, the request is allowed, toherwise, a 401 Unauthorized response is generated.

    • Examples:
    • var token = await userManager.GenerateEmailConfirmationTokenAsyc(user);
    • var token = await userManager.GeneratePasswordResetTokenAsync(user);
  25. What is JWT and how is it handled?
    Json Web Token is an open standard the defines how the token and its properties are sent to an .NET API in 3 different parts (header, payload, signature):

    "JWT": {      "ValidAudience": "http://localhost:4200",      "ValidIssuer": "http://localhost:61955",      "Secret": "ByYM000OLlMQG6VVVp1OH7Xzyr7gHuw1qvUC5dcGt3SNM"    }
Card Set
Prep NET Framework & Core
Questions on .NET Framework related to the technologies and its benefits..