Thursday, 15 November 2018

Angular Development Best Practices

In this article, we are going to show what we consider to be the best practices in Angular while develop the client side project in this framework. During the development process it is really easy to forget about some rules or recommendations in Angular, so having the reference to look at from time to time is a good way to refresh memory.
Without further ado, let’s dive right into it.
In this blog post, we are going to go through the following sections:

Angular CLI

We would always recommend using the Angular CLI tool while working with the Angular project.
Why is that?
Well, it will increase our productivity for sure. Angular CLI has its own set of commands for creating the Angular project, creating components, modules, services etc…
Not only that we are creating our components faster with Angular CLI, but it will reference those components into their own modules and will comply to the naming convention as well, so we don’t have to worry about it.
We can use a basic set of commands to generate our components but every command has its own options. For example, if we want to generate component we would type:
It is going to generate 4 files for us. The component file, html file, css file and the spec file. The last one is for testing purposes. If we don’t want to have that last one created we can just add the flag: --spec false. By doing this Angular CLI will not generate the spec file at all. This is just one of the options.
We may find more about Angular CLI on https://github.com/angular/angular-cli

Files and Folders in Angular Project

Let’s see how to name our files and classes and how to organize the folder structure in an Angular project.

File Naming

While creating our files, we should pay attention to the file names. Names should be consistent with the same pattern in which we mention the file’s feature first and then the type, dot separated.
For example home.component.ts or home.component.html or auth.service.ts …
If we want to add more descriptive names to our files we should use a dash(-) to separate the words in the name: menu-admin-user.component.ts…

Class Names

When we add names to our classes, we should use upper camel case style with the added suffix that represents the type of our file:

Folder Structure

Our files should reside in the folders named by the feature they represent. This is very important because we can easily identify which business logic we have implemented in those files inside our descriptive folders:
Folder structure - Angular Best Practices

Angular Coding Practices

In this part, we are going to explain how to organize components in a single file and what are the benefits of using interfaces, immutability and writing clean and small functions.

Single Responsibility Principle

It is very important not to create more than one component, service, directive… inside a single file. Every file should be responsible for a single functionality. By doing this, we are keeping our files clean, readable and maintainable.

Using Interfaces

If we want to create a contract for our class we should always use interfaces. By using them we can force the class to implement functions and properties declared inside the interface. Let’s take for example OnInit interface and its implementation:
Using interfaces is a perfect way of describing our object literals. If our object is of an interface type, it is obligated to implement all of the interface’s properties. We shouldn’t name our interfaces with the starting capital I letter as we do in some programming languages.
The TypeScript will show an error if an object doesn’t contain all of the interface’s properties, and light up intellisense for us while populating that object:
Interface not implemented Angular Best Practices
Interface-intellisense Angular Best Practice
We can specify optional properties, by using the question mark (?) inside an interface as well. We don’t need to populate those properties inside an object:

Using Immutability

Objects and arrays are the reference types in javascript. If we want to copy them into another object or an array and to modify them, the best practice is to do that in an immutable way.
By modifying reference types immutably, we are preserving the original objects and arrays and modifying only their copies.
The easiest way to modify objects and arrays immutably is by using the es6 spread operator (…) :
We are deep copying the user object and then just overriding the name property.
Let’s take a look at how to use the spread operator with arrays:
Now if we remove or modify any of the numbers from the newNumbers array, the original array is going to be preserved with all of its values.

Small Functions and Access Modifiers

Whenever we create our functions to execute some business logic, we should keep them small and clean. Small functions are easier to test and reuse. Furthermore, it is much easier to understand and maintain functions with fewer lines of codes. If we notice that our function is becoming too crowded it is a time to create a new one.
It is very important to distinguish the functions and properties that we are going to use only in our components from those that we are going to call from our template file. Those properties and functions, which we are going to reference from the template should always have the public access modifier. The private ones will be visible to the HTML template as well, but it is not a good practice due to AoT compilation failure.

Constructor Usage

We should use the constructor method to setup Dependency Injection for our services and that is pretty much it. We shouldn’t be doing any work inside it, especially fetching the data from the server. For this type of actions, we have the lifecycle hooks in Angular.
Even though we can use the service injection inside the constructor:
The much better and the recommended way is:

Safe Navigation Operator (?) in HTML Template

To be on the safe side we should always use the safe navigation operator while accessing a property from an object in a component’s template. If the object is null and we try to access a property, we are going to get an exception. But if we use the save navigation (?) operator, the template will ignore the null value and will access the property once the object is not the null anymore.

Module Organization and Lazy Loading

Modules are very important in an Angular project, so let’s talk about that and lazy loading and shared modal features.

Multi Modules in Application

Even though an Angular application is going to work just fine if we create just one module, the recommendation is to split our application into multi-modules. There are a lot of advantages to this approach. The project structure is better organized, it is more maintainable, readable and reusable and we are able to use the lazy-loading feature.

Routing Module

The best practice for Angular application is to use a separate routing module for the router:
And then to register this new routing module in our app module:

Lazy Loading

If we have a multi-modular application, implementing a lazy loading feature is recommended. The great advantage of a lazy loading approach is that we can load our resources on demand and not all at once. This helps us in decreasing the startup time. Modules that we are loading in a lazy manner will be loaded as soon as a user navigates to their routes.
Let’s show how to set up lazy loading in our module:
In this code example, the HomeComponent is loading eagerly but the OwnerModule and all the components registered in that module are loading in a lazy manner.
If you want to learn more about the lazy loading feature you may read our blog post about lazy loading.

Shared module

If we have components, directives or pipes in our project, which we want to share through the entire project, the best way to do that is to register them inside the shared module file. Then, we need to register the shared module inside the app module. It is important not to register services, that we want to use globally,  in a shared module. We should register such services inside its own feature module or in the app module.
But, if we need any service registered inside a shared module, the best way is to provide it through the static forRoot() method that returns the ModuleWithProviders interface:
Now, we can register this shared module in our app module with the following syntax: SharedModule.forRoot().
It is also important to export our components, directives, and pipes that we register in the shared module:

Components, Decorators, Directives, and Lifecycle

Let’s explain how to structure the files in ou components and why to use directives and lifecycle hooks.

Component’s Files Separation

While creating our components, it is very important to separate the component, template and styling logic into the separate files. Even though we have the possibility to keep all of it inside the component file this is not a good idea.
So, we shouldn’t be doing something like this:
Instead, we should separate styles and HTML in their own files and import them:

Reusable Components and Decorators

Creating reusable components is one of the best techniques we can use while developing our project. We can reuse those types of components inside any parent component and pass the data through the @Input decorator. Those components can emit events by using the @Output decorator and EventEmmiter class. Here is an example of the @Input and @Output decorators in action:
To learn more about decorators in angular and how to use them to create reusable components, you may read Child components, @Input, @Output Decorators.

Code Simplicity in Components

To keep our components readable and easy maintainable we should write a clean code inside them. We should limit the logic in the component to satisfy the template needs and nothing more. No additional complicated business logic is required. If we need additional logic, we should extract it into a service. That way our component remains clean and the extra code could be reused in other components. Furthermore, the logic inside a service can be easily tested and it hides an implementation of the component, thus making a component more readable.

Using Directives

Whenever we have a situation where multiple HTML elements have the same behavior (for example: when we hover over the element it receives the blue color), we should consider using attribute directives. We shouldn’t repeat the hover logic every time we need it on some HTML element. A much better way would be to create directive and then just reuse it on the particular element.
Directive creation is quite simple:
We need to register this directive in a required module and to call it in HTML template file:

Using Lifecycle Hooks

Lifecycle hooks play a very important part of Angular development. We should use them whenever we have an opportunity to. For example, if we need to fetch some data from a database as soon as our component is instantiated, we should use ngOnInit() lifecycle hook and not the constructor.
If we have some logic inside child components and we want to execute that logic as soon as decorator parameters are modified, we can use ngOnChanges() lifecycle hook.
If we need to clean up some resources as soon as our component is destroyed, we should use ngOnDestroy()lifecycle hook.
Even though we don’t have to implement interfaces to use the lifecycle hooks, we are better off implementing them.
So don’t do something like this:
Instead, implement it like this:

Services

Let’s talk a bit more about services, how to use them, why to use them and how to provide them.

Service Usage

Services provide a great way to connect two unrelated components. To configure services for this, the best way is to register them is as a singleton. Furthermore, services are a great way to extract the code from our components, thus making components more readable and maintainable. We may use a service to extract the code related to the component in which that service is provided or to share reusable code with that service between different components.

Single Responsibility

Services in Angular should be implemented with the single responsibility principle in mind. Service shouldn’t be responsible for multiple actions or features. Just the opposite. As soon as we notice that our service starts to exceed the singular purpose, we should create another service.
Just a simple example.
If we want to send the HTTP requests, we should create a service as a centralized place for that kind of actions. But we shouldn’t handle errors inside the same service. We should create another one for that error handling.
By creating services to concur to the single responsibility principle, we are making the code more readable, easier to test and to maintain.

Service Providing

If we want to use our service as a singleton, then we should provide that service at the root of our application. That way Angular creates a single, shared instance of our service, available for all components.
Since Angular v6, if we create a service with the Angular CLI command: ng g service service_name, it will create a service with the providedIn metadata with the “root” value:
By providing such a service means that we don’t have to import it in the app.module file or to provide it in providers array inside the same file.
Of course, if we need it, we can do it that way as well. We can register our service at different levels.
For example in a component level:
Or in a module level:

HTTP

Let’s talk more about HttpClient Module and how to use HTTP requests in our services.

Using the HttpClient Module

Since Angular v4.3, we have a new and better way to handle HTTP requests with the HttpClient library. Even though the old HttpModule library is working just fine, it is a recommendation to switch to HttpClient. From Angular v6 is even more recommended to switch to the HttpClient library.
The way of using the HttpClient library is the same as with the old one. First, we import it into your app module:
Then register it in the imports array in the same file:
After that, we need to import it into the service we want to use HttpClient in:
Finally, we need to register it inside the constructor method in that service:
With the HttpClient library, we receive additional benefits. Error handling is much easier by using HttpErrorResponse class. Moreover, we have the ability to listen to the progress events and we have interceptors which allow us to intercept the HTTP requests.

Services to Work with HTTP Requests

Even though we can work with the HTTP requests inside our components, the recommended way is to do that by using a service. Sending HTTP requests isn’t always that simple. Many times we have to set up the headers of the request to track the progress of the request etc…
In such cases, we should transfer the HTTP handling responsibility from the component to the service. We may even create a service as a centralized place to handle the HTTP requests, and then to use that service in our application.
For more details on how we do that, you can read: https://code-maze.com/net-core-web-development-part9/#angularRepository

Environment Variables

If we develop an Angular application which will be deployed in the production environment, the environment variables inside the Angular project can be very helpful. We can set up those variables to distinguish the end-points between development and production environment.
For example, our endpoint in the development environment could be http://localhost:5000 and in production environment http://www.examplesite.com. Environment variables inside the Angular project help us with those endpoints while we work with the HTTP requests.
Once we set up those environment variables, we can use them in our repository service, and never worry which endpoint will our HTTP requests use for which environment again.
If you want to learn more about how to use and set up environment variables in Angular, you can read https://code-maze.com/net-core-web-development-part9/#environmentFiles.

Conclusion

In this article, we wanted to bring you closer to what the recommendations while developing our Angular project are. Of course, these are not all the Angular best practices but we tried to round up the most important ones in this article.
Are these the best practices you already use? We are eager to hear if we missed some practice you consider to be important, so leave us a comment below.
Thank you for reading the article and I hope you found something useful in it.

Saturday, 10 November 2018

Top 13 ASP.NET Core Features You Need to Know


ASP.NET is one of the most successful web application development frameworks by Microsoft. With every update, new and extended features are added that help developers deploy highly scalable and high-performance web applications.
When coupled with application monitoring and other performance tools, such as a profiler, ASP.NET becomes a powerful solution for building incredible apps.
Within the framework itself, there are myriad features to help you overcome common development challenges, do more with your apps, and boost performance.

13 features to build better applications with ASP.NET Core

1. Cross-platform & container support

With the introduction of .NET Core, you can now create ASP.NET applications and deploy them to Windows, Linux, and macOS. Microsoft and the community have put a huge effort into making Linux a first-class citizen for running ASP.NET.
Containers are eating the clouds these days. Docker, Kuberenetes and other technologies are all the rage. ASP.NET Core allows developers to utilize all of these new technologies. Microsoft Azure even has support for deploying your application to containers and Kubernetes.

2. High performance

Some say that performance is a critical feature of your software. I tend to agree! With the introduction of ASP.NET Core and the Kestrel web server, ASP.NET is touted as one of the fastest web application frameworks available. TechEmpower has some cool benchmarks you can check out.
The technology that powered the ASP.NET integrated pipeline and IIS was roughly 15 years old. It did everything and carried a lot of baggage with it. The new Kestrel web server was redesigned from the ground up to take advantage of asynchronous programming models, be much more lightweight, and fast!
The new Kestrel web server was redesigned from the ground up to take advantage of asynchronous programming models, be much more lightweight, and fast!

3. Asynchronous via async/await

ASP.NET has excellent support for utilizing asynchronous programming patterns. Async is now implemented in all common .NET Framework classes and most third-party libraries. Most modern applications spend most of their time and CPU cycles waiting for database queries, web service calls, and other I/O operations to complete.
One of the reasons ASP.NET Core is faster is its extensive use of asynchronous patterns within the new MVC and Kestrel frameworks.
//mark the method as async
public async Task GetGWB()
{
    HttpClient hc = new HttpClient();
    //await keyword handles all the complexity of async threading and callbacks
    await hc.GetAsync("http://geekswithblogs.net/Default.aspx");
    return true;
}

4. Unified MVC & Web API frameworks

Before ASP.NET Core, developers were most commonly using the MVC and Web API frameworks. MVC was tailored to creating web applications that served up HTML. Web API was designed to create RESTful services using JSON or XML.
With ASP.NET Core, MVC and Web API have been merged together. There was always a lot of overlap with the two frameworks. MVC could always return JSON data instead of HTML. Combining them was a good move and simplifies development.
With ASP.NET Core we also have the new Razor Pages. They extend the MVC framework to allow encapsulating the controller and model aspects of a page together with two-way binding. They are sort of a replacement for WebForms while using the familiar Razor syntax.

5. Multiple environments and development mode

One of my favorite features is the new environment feature. It allows you to easily differentiate parts of your code for their behavior in development, staging, production, etc. There was no standard way to do this before ASP.NET Core.
For example, it is used within your Startup.cs file to help configure your application. In this case, whether or not we want to show a more detailed exception page for development only.
Environments are perfect for using different CSS or Javascript files. Use your CDN in production, but local files during development. This is a snippet out of my Razor layout view.
Environments are perfect for using different CSS or Javascript files. Use your CDN in production, but local files during development. This is a snippet out of my Razor layout view.
    <environment names="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    </environment>
    <environment names="Staging,Production">
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
        </script>
        <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
        </script>
        <script src="~/js/site.min.js" asp-append-version="true"></script>
    </environment>      

6. Dependency Injection

One of the great new features of ASP.NET Core is built in dependency injection. It is heavily used within ASP.NET MVC itself. It is the preferred way that things like logging contexts, database contexts, and other things are passed into your MVC controllers.
public class PaymentService: IPaymentService
{
  public ILogger Logger { get; }

  //automatically passes the logger factory in to the constructor via dependency injection
  public PaymentService(ILoggerFactory loggerFactory)
  {
    Logger = loggerFactory?.CreateLogger();
    if(Logger == null)
    {
      throw new ArgumentNullException(nameof(loggerFactory));
    }
    Logger.LogInformation("PaymentService created");
  }
}

7. WebSockets & SignalR

ASP.NET has first class support for WebSockets. This can be used to persist long running connections and communicate back and forth with the browser. SignalR is a full framework that is also available that makes it easy handle common scenarios.
We use SignalR very heavily at Stackify. For example, when viewing the current monitoring data about one of your servers, every time we receive new data, we immediately push it to your browser so you can see it update in real time. These types of scenarios are perfect for WebSockets and SignalR makes it easy to do.
Retrace Monitoring View
RETRACE MONITORING VIEW
Note: At the time of this article, SignalR is still in beta for ASP.NET Core. 

8. Cross-Site Request Forgery (CSRF) Protection

Security is important. It is also one of those things that can be a lot of work to prevent certain types of attacks. CSRF is in referencing to hijacking users authenticated session to perform an action that they did not initiate.
For example, let’s pretend that you log in to your bank account and then navigate to a different website. If that other website could do a POST to your bank website to transfer funds, that would be a bad thing. It could potentially do that if your online session on the banking website is valid and the bank does not properly validate requests.
ASP.NET has a good framework that is available to prevent these types of attacks. It generates anti-forgery tokens.

9. “Self hosted” Web Applications

Sometimes you need to make a web application that will be deployed on to a desktop and not a server running IIS. Our free ASP.NET profiler, Prefix, is a perfect example of this. Its front end is all HTML that is loaded from an ASP.NET application running as a Windows Service.
You can create a self-hosted ASP.NET web application several different ways. In .NET 4.5 you could accomplish it by using Owin, Nancy, or WCF. For Prefix, we use ASP.NET Web API with Owin.
With ASP.NET Core, you can also use the standard Kestrel web server. One of the great advantages of .NET Core is that your web application is essentially a console application. IIS just sits in front of it as a reverse proxy. This means that you can also deploy your app only with kestrel for non-server based use cases, like Prefix.

10. Action Filters

One of the great features of ASP.NET is the support for extensible filters. This allows you to implement functionality that can be applied to an entire controller or action without modifying the action itself.
Filters are used to specify caching, error handling, authorization, or any custom logic you would like to implement.
using System;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
     public class DataController : Controller
     {
          [OutputCache(Duration=10)]
          public string Index()
          {
               return DateTime.Now.ToString("T");
          }
     }
}

11. Extensible Output Caching

This feature allows ASP.NET to cache the output generated by a page and serve this cached content for future requests. It stores the data that is not updated frequently and outputs that specific data from a cached location.
ASP.NET makes it easy to specify how long any request should be cached via common HTTP headers. It also has support for caching output within the memory on your web server itself. You can even use Redis or other providers to handle your output caching.

12. Globalization and Localization

ASP.NET makes it easy to localize dates, numbers, and the text within your web application. If you want your application to be used across the globe, localization will be very important to you.
ASP.NET enables customizing your application for multiple languages via resource files. These resource files are considered as the central repository where all texts are kept, and web pages can read this resource file and get labels populated. There are two types of resources:
  • Local Resources – specific for a page (i.e., there will be local resource file for every page)
  • Global Resources – common for the whole website (i.e., one resource file accessed by all pages)

13. Swagger OpenAPI

If you are creating API applications, you want to make sure you are using Swagger. It makes it easy to document and test your APIs.
ASP.NET has historically provided built-in functionality that is pretty similar for SOAP web services created with WCF. If you are using Web API or MVC for RESTful APIs, you definitely want to use Swagger.
ASP.NET has historically provided built-in functionality that is pretty similar for SOAP web services created with WCF. If you are using Web API or MVC for RESTful APIs, you definitely want to use Swagger.

Conclusion

ASP.NET Core has been a nice upgrade over previous versions. In this article, we highlighted some of the key features you should be aware of. Some are new, some are just key features of ASP.NET that have existed for a while.
Our products, Prefix and Retrace, both provide excellent support for ASP.NET Core. If monitoring the performance of your applications is important, you definitely want to checkout Retrace.

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...