Wednesday, December 12, 2018

Working with SSL

SSL (Secure Sockets Layer) is the standard security technology for establishing an encrypted link between a web server and a browser. This link ensures that all data passed between server and browser remain private and integral. SSL is an industry standard to protect the online transactions.

Secure Sockets Layer (SSL) is the most widely deployed cryptographic protocol to provide security over internet communications. SSL provides a secure channel between two machines or devices operating over the internet or on an internal network. One common example is when SSL is used to secure communication between server and browser is, the website's address will change from HTTP to HTTPS, the S stands for Secure.

Need of SSL: As it supports the following security principles
  • Encryption: Protect data transmissions, for ex: browser to server, server to server, application to server etc..
  • Authentication: Ensures that the server you are connected is the correct server
  • Data Integrity: Ensures that the data that is requested or submitted is what is actually delivered
And, can be used for:
  • Internet based traffic such as networks, file sharing, extranets and database connections
  • The transfer of files over HTTPS and FTP(s) services
  • Webmil servers like outlook, exchange and office communications etc.
  • System logins to applications and control panels, namely parallels, cPanel and others
  • Hosting control panel logins
  • Online credit card and other payment type transactions
Advantages of using SSL:
  • Trust: If user gets a green address bar in the browser, they consider the site as trusted site
  • Verification: One of the best thing about installing SSL certificate on your server is that it guarantees the visitors you really are who you say you are
  • Integrity of Data: With SSL, you can guarantee integrity of data
Advantages of using SSL:
  • Cost of Certificte: As it is not recommended to use free SSL certificates, depending on the type of certificate, price changes
  • Mixed Modes: if the SSL setup is not correct, then you still have some files served via HTTP instead of HTTPS where visitors are going to get a warning message in their browser letting them know some of the data is not protected. This can be confusing to the users
  • Proxy Caching: Anther possible problem is if you have a complex proxy caching system setup on your web server. Encrypted content is not going to be able to be cached. To get around this, you need to add a server to handle the encryption before it bets to the caching server. This will require additional cost
  • Mobile: SSL was first implemented for web based applications. while the ability to go beyond HTTPS has come a long way in the last few years, it can sometimes be a pain to setup and might require changes to in-house software.

Basic Authentication

This is performed within the context which is called as "realm". The server includes the realm name as part of WWW-Authenticate header. Provided user credentials are valid within that realm. The scope of this realm cannot be changed or defined by the server. There are no optional authentication parameters.

How it works:

  • Server returns 401 (Unauthorized) response when a request requires authentication. The response includes a WWW-Authenticate header, indicating the server supports Basic Authentication
  • Client sends another request containing the client credentials as part of the Authorization header. The credentials are formatted as the string "name:password" which are of base64-encoded. These credentials are not encrypted

Advantages of using Basic Authentication:
  • Relatively easy to use as it is a simple protocol
  • This authentication is supported by all browsers
  • Follows internet standards

Disadvantages of using Basic Authentication:
  • Basic Authentication is only secure over HTTPS as credentials are sent unencrypted
  • This is also vulnerable to CSRF (Cross-Site Request Forgery) attacks. Once user provides credentials, the browser automatically sends them on subsequent request within the duration of the session
  • User credentials are sent in the request as plaintext with every request
  • The only way to log out is by ending the browser session
  • Requires anti-CSRF measures as it is vulnerable to CSRF

How to Implement: Basic Authentication can be implemented by following ways:
  • Using IIS: As the user is authenticated using their Windows credentials, which means the user must have an account on the server's domain. To enable basic authentication using IIS, set the authentication mode to "Windows" in the Web.Config of your ASP.NET project as below. In this mode, IIS uses Windows credentials to authenticate
    <system.web>
         <authentication mode="Windows" />
    </system.web>
    In addition to the above setting, one must enable Basic authentication in IIS. In IIS Manager, go to Features View, select Authentication and enable Basic Authentication. A client authenticates itself by setting the Authorization header in the request. Browser clients perform this step automatically. Nonbrowser clients will need to set the header
  • With Custom Membership: As Basic Authentication uses IIS credentials which means the user accounts needs to be created for all users on the hosting server. But for internet applications, these user accounts are typically stored in an external database. To support this scenario, HTTP module performs the Basic Authentication. In Web API 2 world, Authentication Filter or OWIN Middleware should be used instead of HTTP module.

    To enable HTTP module, make below change to Web.Config file:
    <system.webServer>
       <modules>
         <add name="BasicAuthHttpModule" type="WebHostBasicAuth.Modules.BasicAuthHttpModule, YourAssemblyName"/>
       </modules>
    </system.webServer>
    While using this, other authentication schemas like Forms and Windows Authentication should be disabled. Below is the implementation example
    namespace WebHostBasicAuth.Modules
    {
       public class BasicAuthHttpModule : IHttpModule
       {
    private const string Realm = "HTTP Test Realm";

    public void Init(HttpApplication context)
    {
    // Register event handlers
    context.AuthenticateRequest += OnApplicationAuthenticateRequest;
    context.EndRequest += OnApplicationEndRequest;
    }

    private static void SetPrincipal(IPrincipal principal)
    {
    Thread.CurrentPrincipal = principal;
    if (HttpContext.Current != null)
    {
    HttpContext.Current.User = principal;
    }
    }


    // TODO: Here is where you would validate the username and password.
    private static bool CheckPassword(string username, string password)
    {
    return username == "user" && password == "password";
    }

    private static void AuthenticateUser(string credentials)
    {
    try
    {
    var encoding = Encoding.GetEncoding("iso-8859-1");
    credentials = encoding.GetString(Convert.FromBase64String(credentials));

    int separator = credentials.IndexOf(':');
    string name = credentials.Substring(0, separator);
    string password = credentials.Substring(separator + 1);

    if (CheckPassword(name, password))
    {
        var identity = new GenericIdentity(name);
        SetPrincipal(new GenericPrincipal(identity, null));
    }
    else
    {
        // Invalid username or password.
        HttpContext.Current.Response.StatusCode = 401;
    }
    }
    catch (FormatException)
    {
    // Credentials were not formatted correctly.
    HttpContext.Current.Response.StatusCode = 401;
    }
    }

    private static void OnApplicationAuthenticateRequest(object sender, EventArgs e)
    {
    var request = HttpContext.Current.Request;
    var authHeader = request.Headers["Authorization"];
    if (authHeader != null)
    {
    var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);

    // RFC 2617 sec 1.2, "scheme" name is case-insensitive
    if (authHeaderVal.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) && authHeaderVal.Parameter != null)
    {
       AuthenticateUser(authHeaderVal.Parameter);
    }
    }
    }

    // If the request was unauthorized, add the WWW-Authenticate header
    // to the response.
    private static void OnApplicationEndRequest(object sender, EventArgs e)
    {
    var response = HttpContext.Current.Response;
    if (response.StatusCode == 401)
    {
    response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", Realm));
    }
    }

    public void Dispose()
    {
    }
       }
    }

With this I am concluding the illustration. Feel free to share your feedback. Happy Programming !!!

Monday, December 3, 2018

Angular Advantages

Below are the Advantages of using working with different versions of Angular starting 2.0 onwards:

Using Angular 2
  • Completely Component based
  • Better Change detection
  • Better Performance
  • Powerful Template system
  • Simpler API, lazy loading and easy to debug application
  • More testable
  • Provides nested level components
  • Ahead of Time Compilation (AOT) improves rendering speed
  • Can run more than two programs at the same time
  • Structural directive syntax is changed, like *ngFor instead of ng-repeat
  • Local variables are defined using hash(#) prefix
  • TypeScript can be used for developing this version of application
  • Better Syntax and Application Structure
Using Angular 4
  • Router ParamMap is introduced
  • Animations
  • ngIf can also be used with Else
  • Dynamic components with NgComponentOutlet
  • TypeScript 2.1/2.2
  • Strict NULL Checks
Using Angular 5
  • Smaller & Faster Applications
  • View engine size reduce
  • Animation package
  • NgIf and NgFor Improvement
  • Template
  • Use of AS keyword
  • Pipes
  • HTTP Request Simplified
  • Apps Testing Simplified
  • Introduce Meta Tags
  • Added some Forms validators attributes
  • Added compare select options
  • Enhancement in Router
  • Added optional parameter
  • Improvement Internationalization
Using Angular 6
  • Angular Elements are fully supported
  • Improved Component Dev Kit (CDK)
  • Improved Command Line Interface (CLI)
  • Improved Service Worker
  • Updated Web Pack
  • Multiple Form Validators
Using Angular 7
  • New interface - UrlSegment[] to canLoad interface
  • New Interface - DoBootstrap
  • New compiler - Compatibility Compiler (ngcc)
  • New pipe called KeyvaluePipe
  • Supporting TypeScrpt 2.9 and Added Virtual Scrolling and Frag & Drop
  • Added new elements features - enable Shadow DOM v1 and slots
  • New router features
  • New mappings for ngFactory and ngSummary files
  • New "Original" placeholder value on extracted XMB
  • Added new ability to recover from malformed URLs
  • Added new compiler support "dot (.)" in import statements
  • Updated compilter to flatten "nested template fns"

Tuesday, November 27, 2018

Data Structures

System.Collections is the .NET framework library used to represent the implementation and usage of DataStructures. A collection is a structured data type that stores data and provides operations for adding data to the collection, removing data from the collection, updating data in the collection, as well as operations for setting and returning the values of different attributes of the collection. Collections can be broken down into Linear and Non-Linear collections as shown below:

Linear Collections: A Linear collection is a list of elements where one element follows the previous element. Elements in a linear collection are normally ordered by position. Linear collections are further categorized into Data access collections and Sequential access collections as explained below
  • Data Access Collections
    • Array: Derived from System.Array namespace. One dimensional, Multi dimensional, Parameter and Jagged are the types of Arrays. Length, GetLength, Rank, GetType, and GetElementType are some of the important properties and functions of Arrays
    • ArrayList: Derives from System.Collections namespace. Static arrays has a limitation when the size is unknown in advance or the size changes during execution. ArrayList is a type of array which solves this problem as this automatically resizes itself when the array is out of storage space. The ArraList has a Capacity property that stores its size, which is 0 elements by default and increases by 4 elements as needed. Add, AddRange, Capacity, Clear, Contains, CopyTo, Count, GetEnumerator, GetRange, IndexOf, Insert, InsertRange, Item, Remove, RemoveAt, Reverse, Sort, ToArray and TrimToSize are some of the noted members of ArrayList
    • String: Derives from System.String namespace. C# strings allows to place escape characters inside the strings. Escape characters are used to place format characters such as line breaks and tab stops within a string. An escape character begins with a backslash (\) and is followed by a single letter that represents the format. Empty is the available field to use represent the String and Chars and Length are the properties of String
    • StringBuilder
    • Struct
  • Sequential Access Collections
    • List
    • LinkedList
    • HashTable
    • Dictionary
    • SortedList
    • Stack
    • Queue
Non-Linear Collections: A Nonlinear collection hold elements that do not have a positional order within the collection. Nonlinear collections can be either Hierarchical or Grouped collections as explained below :
  • Hierarchical Collections
    • Tree
    • BinaryTree
    • Heap
  • Grouped Collections
    • Set
    • Graph
    • Network

Tuesday, November 20, 2018

Deciding between different EF Approaches

Below is sort of guideline to use picking the Entity Framework approach to work with:

Thursday, October 18, 2018

C# Syntax

Trying to illustrate some important features and syntax of C# with examples.

Var

This is used to declare implicitly typed local variable. Which tells the compiler to identify the type at the time of compilation. This is introduced in C# 3.0 and must be initialized at the time of declaration. The value of a var variable cannot be NULL at compile time but can be NULL at run time. Once the value of var variable is initialized its data type is fixed to the initial data.

Definition Compile Time
var testString = "Testing String data type"; string testString = "Testing String data type";
var testInteger = 123; int testInteger = 123;
string test = "String data type";
var testString2 = test;
string test = test;
Anonymous Types

This is a class generated by compiler within IL to store values. Using VAR and NEW, these anonymous types can be created. These types are very handy when one wants to return the results in a desired form. Below is an example of an anonymous type:

var employee = new { FirstName = "Balaji", LastName = "Telugunti", Salary = 200000 };
Anonymous Methods

An anonymous method is an inline method within C# code with no name. In other terms, an anonymous method will have only body with optional parameters and return type. This behaves just like any other regular method and will be created using delegate keyword. This concept was introduced from C# 2.0 version. Below are some key points about anonymous methods:

  • Variables declared outside of an anonymous method can be accessed in an anonymous method, but variables declared within anonymous methods cannot be accessed from outside of the method
  • These methods are used as part of event handling
  • A method without parenthesis can be assigned to a delegate
  • An anonymous method cannot access the ref or out parameters from an outer scope
Lamda Expressions

A new way to write anonymous methods is lamda expression. These are introduced in C# 3.0. These expressions will be converted into anonymous methods at compile time using lamda expression conversion rules which is, The left of the lamda operator => represents arguments and right side is the method body. Below are the features of lamda expression:

  • Do not have a type
  • Cannot be assigned to an implicitly typed local variable since these expressions do not have type
  • Jump statements are not allowed within anonymous method/lamda expression
  • Variables declared within these expressions are accessible only within the scope of the body
  • These are used generally with the Func and Action delegates
Extension Methods

Conceptually this is the implementation of decorator structural pattern and at compile time these extension method calls will be translated into an ordinary static method calls. By definition, an extension method is a static method of a static class that can be invoked using the instance method. These are used to add new behavior of an existing type without altering the original behavior.

Delegates Delegate is a reference type that holds the reference of a class method. Any method which has the same signature as delegate can be assigned to delegate. These are immutable in nature, so when you call += or -=, a new delegate instance is created and it assigns to the existing delegate instance. All Delegates are implicitly derived from System.MulticastDelegate, class which is inherit from System.Delegate class. Delegates types are all incompatible with each other, even if their signatures are the same. Delegate instances are considered equal if they have the reference of same method. Delegate instances are considered equal if they have the reference of same method. Multicast delegates are considered equal if they reference the same methods in the same order. And, Delegates are used in event handling.

Type Casting

Is a mechanism of converting one data type to another data type. During this process, if the data types are not compatible then the compiler will throw the exception. C# provides IS and AS operators to handle this exception and handles the type casting without any issues. Below is the explanation of both the operators:

IS The IS operator helps to check whether the type of a given object is compatible with the new object type. Returns boolean value TRUE if the given object is compatible, if not returns FALSE. If the reference of the given object is NULL, then this will return FALSE as there is not object available to check its type.

The one drawback of using IS operator is, it will hit the performance since every time CLR will check base type against the specified type.

AS This AS operator also checks whether the given type object is compatible with the new object type or not. This actually return NON-NULL when both objects are compatible, and NULL in case when the objects are not compatible. If the reference of the given object is NULL, then this operator will return NULL since there is not object to check the type. This operator performs only reference conversions, nullable conversions, and boxing conversions. This cannot perform other conversions like user defined conversions.

This check the object only one time, as a result of that performance improves.

Interfaces

Typically, an interface exposes it's members to a group of clients which needs to use common functionalities. These mainly acts as contract(s) between itself and any class / struct which implements it.

Features
  • An interface just defines member of it and the implementation class/struct needs to implement the functionality
  • Interface can be referenced but cannot be instantiated
  • Contains properties, indexers, methods, delegates and event definitions
  • Cannot contain constants, members, constructors, instance variables, destructors, static members or nested interfaces
  • Cannot have access modifiers as part of definition even public
  • An interface can be inherited from one or more interfaces and can extend another interface
  • A class which implements an interface can mark any method as virtual to make that method overridden by the derived class
Advantages
  • To provide common functionality to unrelated classes
  • To group objects based on common behaviors, to support polymorphism feature of OOP
  • To create loosely couple components, easily maintainable and to support Separation of Concerns
Disadvantages
  • Interfaces are slow as they require extra time to find corresponding method in the actual class
  • When you add new members to it, then they must implement those members in all of the implemented classes or structs
Abstract Class

These classes are special type of classes which cannot be instantiated but can be base for other classes. Any of the methods which are marked as Abstract must be implemented by the derived class. Main purpose of this class is to provide basic or default functionality as well as common functionality that multiple derived classes can share and override. These are helpful as versioning is not a problem for abstract classes. New Properties or Methods can be added without breaking the code as all inheriting classes will be updated automatically.

Don't define public constructors within abstract class. Since abstract class cannot be instantiate and constructors with public access modifiers provides visibility to the classes which can be instantiated. Define a protected or internal constructor within an abstract class.

  • An Abstract class cannot be instantiated. Contains both abstract and non-abstract members
  • An Abstract class cannot be sealed as it restricts from being inherited
  • An Abstract class can be inherited brom a class, one or more interfaces and cannot support multiple inheritance
Errors and Exception Handling

Errors refer to the mistake or faults which occur during program development or execution. Different types of errors are:

Syntax Errors: These occur during development when you type mistakes in code

Runtime Errors: These occur during execution of the program which are also called exceptions. Can cause because of improper inputs or design logic. These can be handled by try-catch blocks

Logical Errors: These errors occur when the program does not produce desired result. These are difficult to find as one need to investigate where the result went wrong.

Exception handling is a mechanism to detect and handle run time errors. Using Try-Catch-Finally blocks and Throw keywords one can take care of exception handling



With this I am concluding the illustration. Feel free to share your feedback.

Happy Programming !!!

Tuesday, August 28, 2018

Angular7 Creating First Application

Below you will find how to configure the solution architecture for Angular 7 using Visual Studio Code as editor.

Below are the prerequisites to create Angular 7 Application:

Use below instructions/steps to start creating your first Angular 7 application:

  • Create new folder in your drive where you want to keep the code base
  • Launch Visual Studio Code editor and select the created folder using File -> Open -> Select Folder
  • Create new file and name it as package.json under the project folder and paste below code. This file contains all the dependencies of the project.
  • {
      "name": "angular7-demo",
      "version": "0.0.0",
      "description": "QuickStart package.json from the documentation, supplemented with testing support",
      "scripts": {
        "ng": "ng" ",
        "start": "ng serve" ",
        "build": "ng build",
        "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e"
      },
      "private": true,
      "dependencies": {
        "@angular/animations": "~7.0.0",
        "@angular/common": "~7.0.0",
        "@angular/compiler": "~7.0.0",
        "@angular/core": "~7.0.0",
        "@angular/forms": "~7.0.0",
        "@angular/http": "~7.0.0",
        "@angular/platform-browser": "~7.0.0",
        "@angular/platform-browser-dynamic": "~7.0.0",
        "@angular/router": "~7.0.0",
        "angular-font-awesome": "^3.1.2",
        "core-js": "^2.5.4",
        "font-awesome": "^4.7.0",
        "ngx-pagination": "^3.2.1",
        "rxjs": "~6.3.3",
        "rxjs-compat": "^6.3.3",
        "underscore": "^1.9.1",
        "zone.js": "~0.8.26"
      },
      "devDependencies": {
        "@angular-devkit/build-angular": "~0.10.0",
        "@angular/cli": "~7.0.2",
        "@angular/compiler-cli": "~7.0.0",
        "@angular/language-service": "~7.0.0",
        "@types/jasmine": "~2.8.8",
        "@types/jasminewd2": "~2.0.3",
        "@types/node": "~8.9.4",
        "bootstrap": "^3.3.7",
        "codelyzer": "~4.5.0",
        "jasmine-core": "~2.99.1",
        "jasmine-spec-reporter": "~4.2.1",
        "karma": "~3.0.0",
        "karma-chrome-launcher": "~2.2.0",
        "karma-coverage-istanbul-reporter": "~2.0.1",
        "karma-jasmine": "~1.1.2",
        "karma-jasmine-html-reporter": "^0.2.2",
        "protractor": "~5.4.0",
        "ts-node": "~7.0.0",
        "tslint": "~5.11.0",
        "typescript": "~3.1.1"
      }
    }
  • Create another file and name it as tsconfig.json and paste below code. This file helps guide compiler as it generates JavaScript files.
  • {
      "compileOnSave": false,
      "compilerOptions": {
        "baseUrl": "./",
        "outDir": "./dist/out-tsc",
        "sourceMap": true,
        "declaration": false,
        "module": "es2015",
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "target": "es5",
        "typeRoots": [
              "node_modules/@types"
        ],
        "typeRoots": [
              "es2018",
              "dom"
        ]
      }
    }
  • Create another file and name it as tslint.json. This is a static analysis tool which will help to check code readability, maintainability, and functionality errors.
  • {
      "rulesDirectory": [
        "arrow-return-shorthand": true
      ]
    }
  • Launch Integrated Command Terminal using View tab to install dependencies. Use npm install command to start installing the dependencies.
  • After above step, you should see node_modules and package-lock.json files created in your solution. Which is a good sign, if not, check back
  • Create two more configuration files to handle version controlling and editor configurations namely .gitignore and .editorconfig
  • Create new folder and name it as src which contains all application related folders and files in it.

You are good to run your first Angular 7 application. Using Integrated Command Terminal run ng serve --open command to launch and run the above created application.

Happy Programming !!!

Angular7 Environment Features and Components

Coming Soon ...

Differences between Angular2 and Angular7

Coming Soon ...

Differences between AngularJS and Angular2

Here are some of the differences between AngularJS and Angular 2

Feature AngularJS Angular 2
Introduction

AngularJS is a JavaScript framework which is used to build web applications. It was released by Google and is developed using TypeScript and JavaScript and uses HTML. And also uses Controllers and Scope objects.

This is not an upgraded version of AngularJS but completely rewritten with lot of improvements and released in 2016 with the goal of building complicated applications in a feasible way. Angular2 follows component-based UI and no more controllers and scope in objects in this. This is currently build uing TypeScript but also compatible with ES5 & ES5 JavaScript standards.

Prerequisites

JavaScript and HTML alone

Basic JavaScript, CSS, HTML OOP concepts and any programming language knowledge like C++, C# or Java

File Type

Uses JavaScript

Uses TypeScript

Binding

Supports both one way (<div>ng-bind="message"</div>) and two way binding (Ex: {{"message"}})

Supports both one way and two way binding but

  • One way binding supports
    Interpolation (<div>message </div>) and
    Property binding (<img [src]="imagePath" />)
  • In Two way binding you need to use [(message)] parenthesis inside brackets

Bootstrapping

Using ng-app and code are the two ways to Bootstrap AngularJS

The change is, we connect angular components to view and not modules

Routing

Performance

Watchers are killers in AngularJS, performance will hit as the number of watchers are more here

As Angular2 uses DI hierarchical system, this is much more faster than AngularJS

Mobile Support

Does not have mobile support. Using 3rd party frameworks one can achieve the functionality

Is mobile oriented as it is designed from ground up with mobile support

Services

Some of various ways to create services are like Service, Factory, Provider etc..

There is only one way t use services

Filters

Are used to filter result sets

These are renamed as Pipes and no change in functionality or purpose of the same

Angular 4 over Angular 2

Smaller & Faster Apps Comparing with Angular 2, these applications are smaller & faster
Reduced View Engine Size Changes under hood to what AOT generated code compilation that means in Angular 4, improved compilation time. These changes reduce around 60% size in most cases
Animation Package Animations now have their own package which ic @angular/platform-browser/animations
Improvement Improved *ngIf and *ngFor
Template The template is now ng-template. You should use the "ng-template" tag instead of template.
NgIf with Else Angular 4 uses else syntax:
<div *ngIf="user.length > 0; else empty"> <h2> Users </h2> </div>
As Keyword A new addition to the template syntax is the "as" keyword is use to simplify to the "let" syntax :
<div *ngFor="let user of users | slice:0:2 as total; index as = i >
       {{i+1}}/{{total.length}}; {{user.name}}
</div>

To subscribe only once to a pipe "|" with "async" and if a user is an observable, you can now use to write :
<div *ngIf="users | async as usersModel;>
       <h2> {{UserModel.name}} </h2>
</div>
Pipes Angular 4 introduced "tittlecase" pipe "|" and use to changes the first letter of each word into the uppercase
<h2> {{ 'balaji t' | titlecase }} </h2>
Http Adding search parameters to an "HTTP request" has been simplified as:
http.get('${baseUrl}/api/users', {params: {sort: 'ascending'}});
Test Overriding a template in a test has also been simplified, as :
TestBed.overrideTemplate(UsersComponent, '<h2> {{Users.name}} </h2>');
Service A new service has been introduced to easily get or update "Meta Tags" as:
@Component({
selector: 'users-app',
template: '<h1> Users </h1>'
})
export class Users/AppComponent {
    Constructor(meta: Meta) {
        meta.addTag({name: 'Blogger', content: 'Balaji T'});
   }
}
Forms Validators One new validator joins the existing "required", "minLength", "maxLength" and "Pattern". An email helps you validate that the input is a valid email.
Compare Select Options A new "compareWith" directive has been added and it used to help you compare options from a select, as:
<select> [compareWith]="byUId" [(ngModel)]="selectedUsers">
    <option *ngFor="let user of users" [ngValue]="user:UId" >{{user.name}} </option>
</select>
Router A new interface "paramMap" and "queryParamMap" has been added and it introduced to represent the parameters of a URL
const uid = this.route.snapshot.paramMap.get('UId');
this.userService.get(uid).subscribe(user => this.name = name);
CanDeativate This "CanDeactivate" interface now has an extra parameter and it is containing the next state
118n The internationalization is tiny improvement, as :
<div [ngPlural]="value">
    <ng-template ngPluralCase="0">there is nothing</ng-template>
    <ng-template ngPluralCase="1">there is one</ng-template>
</div>

Angular 5 over Angular 4

Performance Improvements
  • Use of addEventListener for the faster rendering and it is the core functionality
  • Update to new version of build-optimizer
  • Added some improvements on the abstract class methods and interfaces
  • Remove decorator DSL which depends on Reflect for Improve the Performance of Apps and this is core functionality
  • Added an option to remove blank text nodes from compiled templates
  • Switch Angular to se Static-Injector instead of Reflective-Injector
  • Improve the applications testing
  • Improve the performance of hybrid applications
  • Improvement of lazy loading
HttpClient Improvements
  • Improvement on Type-checking the response
  • Improvement on Reading the full response
  • Improvement on Error handling and fetching error details
  • Improvement on intercepting all requests or responses
  • Improvement on Logging
  • Improvement on Caching
  • Improvement on XSRF Protection
Added Features
  • Added Representation of Placeholders to xliff and xmb in the compiler
  • Added an Options Arg to Abstract controls in the forms controls
  • Added add default updateOn values for groups and arrays to form controls
  • Added updateOn blur option to form controls
  • dded updateOn submit option to form controls
  • Added an Events Tracking Activation of Individual Routes
  • Added NgTemplateOutlet API as stable in the common controls
  • Create StaticInjector which does not depend on Reflect polyfill
  • Added [@.disabled] attribute to disable animation children in the animations
Router Life Cycle Events
  • GuardsCheckStart
  • GuardsCheckEnd
  • ResolveStart and
  • ResolveEnd

Creating First Application using AngularJS

Here you will learn the important basics of an AngularJS application along with step by step of creating your first application.

ng-app - used to define and link an AngularJS application with HTML

ng-model - is a directive which helps to bind the vlues of AngularJS application data to HTML controls

ng-bind - this is the actual directive which binds the AngularJS application data to HTML tags


How AngularJS Integrates with HTML
  • ng-app directive starts the AngularJS application
  • ng-model then creates the required variables which can be used within HTML
  • ng-bind uses the created model to be displayed as part of HTML page

Use below instructions/steps to start creating your first AngularJS application
  • As AngularJS is based on pure JavaScript framework, this JavaScript library can be referenced/added as below either by using <script> tag
    <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    OR including required library files using NuGet packages
    • Create an empty project using Visual Studio
    • Using Manage Nuget option refer AngularJS to the project
    • Refer or include the required JavaScript files using <script> tag as part of Index.html
  • One of the example AngularJS application structure can look like below
    • index.html - contains all the referenced/included files with ng-app definition
    • app.js - contains the ng-module definition along with application level constant variable and required module includes
    • appScripts - this folder contains all the customized folders with .js and .html file definitions with actual code
    • Scripts - folder contains the extracted Nuget package library files required to include to work with AngularJS
  • Run your AngularJS application by launching it using index.html page as startup page


With this I am concluding the illustration. Feel free to share your feedback.

Happy Programming !!!

AngularJS Keywords and Helpful Definitions

In this section, I would like to highlight some of the key features and how to work with them in AngularJS.

Directives In AngularJS world these are helpful to extend HTML which are special attributes starting with "ng-" prefix. Below are some of the important Directives one should know as part of AngularJS.

  • ng-app this directive help start AngularJS application. And also, it defines the root element, automatically initializes or bootstraps and to load different modules of the application
    <div ng-app="myApp">
    <!-- you code goes here related to app -->
    </div>
  • ng-Init this directive help initialize application data by setting up the values to the variables which are going to be used as part of application
  • <div ng-app="myApp"> ng-init="countries = [{'United States}]"
    <!-- you code goes here related to app -->
    </div>
  • ng-model this directive binds the values to HTML controls
    <div ng-app="myApp">
    Enter Name: <input type="text" ng-model="name" >
    </div>
  • ng-Repeat this directive help repeating HTML elements of collections
    <p> List of Countries with locale </p>
    <ol>
    <li ng-repeat="country in countries" >
    {{ 'country: ' + country.name }}
    </li>
    </ol>

Expressions These are used to bind data to HTML and are written using double braces like {{ }}. Expressions behaves the same way as ng-bind directives. Some examples are as below:

Integers example:
Total Cost: $ {{ quantity * price }}
string example:
Hi {{ employee.LastName + " " + employee.FirstName }}
object example:
Hi {{ employee.Designation }}
array example:
Hi {{ employee[1].FirstName }}

Controllers These will help to control the flow of AngularJS application. A Controller is defined using ng-controller directive, and contains attributes/properties and functions. $scope refers to the application or module that controller is to control. Here is an example of Controller in an AngularJS application:

In HTML, this is how a controller is referenced:
<div ng-controller="StudentController">
... Your code goes here ...
<div>

The Controller will e defined as below:
<script>
function studentController($scope) {
$scope.student = {
firstNme: "Balaji",
lastNme: "Telugunti",
};
}
</scope>

Filters These are helpful to modify the data using a pipe (|) character and can be combined in an expression or directive. Below are the commonly used filters with examples:

Name Description Example
uppercase Converts data to UPPERCASE Last Name: {{ student.lastName | uppercase }}
lowercase Converts data to LOWERCASE Last Name: {{ student.lastName | lowercase }}
currency Converts data to a CURRENCY format Fees: {{ student.Fees | currency}}
filter FILTERS a collection to a subset based on criteria ng-repeat="subject in subjects | filter.subjectName
orderby ORDERS a collection based on criteria ng-repeat="subject in subjects | orderBy.subjectName

Modules: These are used to separate logic's like services, controllers, application etc. and keep the code clean. Best practice is to define modules in separate js files and name them as per the functionality of the module.

Ajax: $https: control works as a service to read and get data from server in AngularJS. Below is an example of how to use this:

function studentController($scope, $https:) {
var url = "data.txt"

$https:.get(url).success(function(response) {
$scope.students = response;
});
}

Views: AngularJS supports Single Page Application via multiple views on a single page. To support this, Angular has ng-view, ng-template directives as well as $routeProvider services. Here is how we can work with these:

  • ng-view This creates a place holder where a corresponding view or template can be placed by the configuration. This can be achieved as below:
    <div ng-app="mainApp">
    ...
    <div ng-view> </div>
    </div>
  • ng-template This directive is used to create a html view using script tag which contains Id attribute to refer and used by $routeProvider to map the view with a controller as below:
    <div ng-app="mainApp">
    ...
    <script type="text/ng-template" id="addStudent.htm" >
    <h2> Add Student </h2>
    {{message}}
    </script>
    </div>
  • $routeProvider This is the key service which set the configuration of urls, map them with the corresponding html or ng-templateby attaching it to controller as below:
    var mainApp = angular.module("mainApp", ['ngRoute']);

    mainApp.config(['$routeProvider', function($routeProvider) {
    $routeProvider.

    when('/addStudent', {
    templateUrl: 'addStudent.htm', controller: 'AddStudentController'
    }).

    when('/viewStudents', {
    templateUrl: 'viewStudents.htm', controller: 'ViewStudentsController'
    }).

    otherwise({
    redirectTo: '/addStudent'
    });
    }]);

Scope: Scope's responsibility is to join the controller with view. This contains the model data as well as met data which can be accessed via $scope object. Scope is controller specific and if we have nested controllers then the child scope will inherit the scope of its parent.

<scope>
var mainApp = angular.module("mainApp", []);

mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller";
$scope.type = "Shape";
});
</scope>

Services: Separation of Concerns is implements in AngularJS using services architecture. These are meant and responsible for doing a specific task only. These can be used on requirement basis and uses Dependency Injection mechanism to be used as part of controllers and filters. Services can be created wither using a factory or service

  • factory example:
    var mainApp = angular.module("mainApp", []);
    mainApp.factory('MathService', function() {
    var factory = {};

    factory.multiply = function(a, b) {
    return a * b
    }

    return factory;
    });
  • Service example:
    mainApp.service('CalcService', function(MathService){
    this.square = function(a) {
    return MathService.multiply(a,a);
    }
    });

Keywords and Helpful Definitions

In this section, I would like to highlight some of the key features and how to work with them in Angular 2.

Modules These are helpful to create boundaries in an application, meaning instead of coding everything in one module, these modules will help developing functionality separately. app.module.ts in app folder is the root module class available in an project solution.

A module is made up of following parts:
  • Bootstrap array: This is used to tell Angular which components needed to be loaded. Once the component is included in this array, it needs to be declared so that they can be used across other components within the application.
  • Export array: This helps to define export components, directives and pipes which can be used in other modules of the application
  • Import array: Helpful to import the functionality from other modules of the application
Example of app.module.ts file in an typical Angular application is as below:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule ({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

Components are the logical piece of code in an Angular application, which consists of the following. app.components.ts class in app folder contains all the definitions of components for the application.

  • Template: This contains the HTML that needs to be rendered as a view of the application, which also includes binding and directives in it.
  • Class: This is like any class defined in an object oriented world which contains properties and methods to support the view and defined in TypeScript.
  • Meta Data: This has the extra data defined for the Angular class. It is defined with a decorator.
Example of app.components.ts class is as follows:
import { Component, Input, OnInit } from '@angular/core';
import { Product } from '../../interfaces/products/product';
import { NgForm } from '@angular/forms';

// template assignment by defining the component
@Component ({
selector: 'ProductDetails',
templateUrl:'app/views/products/productDetailsView.html'
})

export class ProductDetailsComponent implements OnInit {
@Input() product: Product;
@Input() isReadOnly: boolean;
constructor() {}
ngOnInit() { }
CloseProductDetailsView() {
this.product = null
}
}

Directives A directive is a custom HTML element that is used to extend the power of HTML. As part BrowserModule Angular provides ngIf and ngFor as directives. Under app.module.ts file you can see the definition of importing BrowserModule as import { BrowserModule } from '@angular/platform-browser';

  • ngIf element is used to add elements to HTML if it evaluates to true else it will not add it to the HTML code
  • ngFor element is used to elements based on the condition of the For loop

Metadata is helpful and used to configure the expected behavior of a class. One can work with Metadata either at Class level or at Constructor level as below

  • Annotations These are at class level decorators. @Component and @Routes are examples of this type
    @Component ({
    selector: 'my-app',
    templateUrl: 'app/app.component.html'
    })
  • Parameters These set by the decoeators at the constructor level
    export class AppComponent {
    @Environment(‘test’)
    appTitle: string = 'Welcome';
    }

Error Handling By using ReactJS catch library and then using catch function, we can incorporate error handling in Angular. Below code can be added on top of CRUB operations using http

import { Injectable } from '@angular/core';
import { Http , Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import { IProduct } from './product';

@Injectable()
export class ProductService {
private _producturl = 'app/products.json';
constructor(private _http: Http){}
getproducts(): Observable {
return this._http.get(this._producturl)
.map((response: Response) => response.json())
.do(data => console.log(JSON.stringify(data)))
.catch(this.handleError);
}

private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error());
}
}
  • The catch function creates link to the Error Handler function
  • In error handler function, the error will be sent to console and also we can throw the error back to the main proram.

Dependency Injection Dependency Injection is the ability to add the functionality of components at runtime. @Injectable keyword allows class functionality to be injected and used by any modules. Using Provider inside the module the injectable service can be used.

Definiiton and Usage of Injectble class :
Definition
@Injectable()
export class classname {}

Usage
@Component ({
providers: [classname]
}]

Configuration Files Below are the helpful configuration files to set the expectations as part of Angular application

tsconfig.json: This configuration file allows to configure TypeScript used for Angular application
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
package.json: This configuration file contains information about Angular 2 project
{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation,
supplemented with testing support",

"scripts": {
"build": "tsc -p src/",
"build:watch": "tsc -p src/ -w",
"build:e2e": "tsc -p e2e/",
"serve": "lite-server -c=bs-config.json",
"serve:e2e": "lite-server -c=bs-config.e2e.json",
"prestart": "npm run build",
"start": "concurrently \"npm run build:watch\" \"npm run serve\"",
"pree2e": "npm run build:e2e",
"e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\"
--killothers --success first",
"preprotractor": "webdriver-manager update",
"protractor": "protractor protractor.config.js",
"pretest": "npm run build",
"test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
"pretest:once": "npm run build",
"test:once": "karma start karma.conf.js --single-run",
"lint": "tslint ./src/**/*.ts -t verbose"
},

"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"@angular/common": "~2.4.0",
"@angular/compiler": "~2.4.0",
"@angular/core": "~2.4.0",
"@angular/forms": "~2.4.0",
"@angular/http": "~2.4.0",
"@angular/platform-browser": "~2.4.0",
"@angular/platform-browser-dynamic": "~2.4.0",
"@angular/router": "~3.4.0",
"angular-in-memory-web-api": "~0.2.4",
"systemjs": "0.19.40",
"core-js": "^2.4.1",
"rxjs": "5.0.1",
"zone.js": "^0.7.4"
},

"devDependencies": {
"concurrently": "^3.2.0",
"lite-server": "^2.2.2",
"typescript": "~2.0.10",
"canonical-path": "0.0.2",
"tslint": "^3.15.1",
"lodash": "^4.16.4",
"jasmine-core": "~2.4.1",
"karma": "^1.3.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~4.0.14",
"rimraf": "^2.5.4",
"@types/node": "^6.0.46",
"@types/jasmine": "2.5.36"
},
"repository": {}
}
systemjs.config.json: This file contain the required system files for an Angular application which loads all the necessary script files without the need to add a script tag to the HTML pages
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config ({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},

// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',

// angular bundles
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platformbrowser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic':
'npm:@angular/platform-browserdynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api':
'npm:angular-in-memory-web-api/bundles/inmemory-web-api.umd.js'
},

// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
}
} }); })(this);

Monday, August 27, 2018

RequiredEither - Conditional Validation Attribute using MVC / Web API

This topic illustrates how to extend ValidationAttribute to enforce customized validation of checking if either of the field's value is provided or not.

Scenario: Contact.Phone or Contact.Email value should be required.

We can achieve this by following below steps, and the illustration is developed using MVC 5, Web API 2, EF 6 and Moq

As a first step, Create a new class with name "RequiredEitherValidator" (preferably in a common location of the solution ie. either in Model or a Common project, as applied) and copy below code:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class RequriedEitherValidator: ValidationAttribute
{
private string[] PropertyList { get; set; }

public RequriedEitherValidator(params string[] propertyList)
{
this.PropertyList = propertyList;
}

public override object TypeId
{
get { return this; }
}

public override bool IsValid(object value)
{
PropertyInfo propertyInfo;
foreach (string propertyName in PropertyList)
{
propertyInfo = value.GetType().GetProperty(propertyName);
if (propertyInfo != null && propertyInfo.GetValue(value, null) != null)
{
return true;
}
}
return false;
}
}
We need to create or make changes to Model(s) and Controller(s) as below to implement the created custom validation.

POCO / Model: Create or Modify Contact class to apply the custom validation on Phone and Email properties as below to define either of the field value is required.
[RequriedEitherValidator("Email", "Phone", ErrorMessage = "Either Email or Phone Data is Required")]
public class Contact
{
[Display(Name="First Name")]
[StringLength(50, ErrorMessage = "First Name cannot Exceed 50 Character length")]
[Required(ErrorMessage = "First Name is Required")]
public string FirstName {get; set; }

[Display(Name="Last Name")]
[StringLength(50, ErrorMessage = "Last Name cannot Exceed 50 Character length")]
[Required(ErrorMessage = "Last Name is Required")]
public string LastName { get; set; }

[StringLength(150)]
[RegularExpression("^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$", ErrorMessage = "Invalid Email address")]
public string Email { get; set; }

[RegularExpression(@"^([0-9]{10})$", ErrorMessage = "Invalid Phone Number")]
public string Phone { get; set; }
}
Controller: The controller for Contact entity with a POST method will look like below.
public class ContactController : ApiController
{
[AcceptVerbs("GET", "POST")]
[HttpPost]
[ActionName("CreateContact")]
public bool CreateContact([FromBody]Contact contact)
{
try
{
var isAdded = _contactRepository.CreateContact(contact);
return isAdded;
}
catch (Exception e)
{
throw e;
}
}
}
Testing: Below TestMethods will help testing the post method to check for the expected validation error:
[TestMethod]
public void FailedPhoneOrEmailDetailsTest()
{
Contact contact = new Contact { FirstName = "TestFirstName", LastName = "TestLastName", Phone = null, Email = null };
var validationResult = Validator.TryValidateObject(_Contacts, _ContactsContext, _validationResults, validateAllProperties: true);

Assert.IsFalse(validationResult);
Assert.AreEqual(1, _validationResults.Count);
Assert.AreEqual("Either Email or Phone Data is Required", _validationResults[0].ErrorMessage);
}
}
With this I am concluding the illustration. Feel free to share your feedback.

Happy Programming !!!

Monday, July 16, 2018

Creating First Application using Angular2

Below you will find how to configure the solution architecture for Angular2 using Visual Studio Code editor and system.config.js to load modules using TypeScript compiler.

Below are the prerequisites to create Angular2 Application:

Use below instructions/steps to start creating your first Angular2 application:

  • Create new folder in your drive where you want to keep the code base
  • Launch Visual Studio Code editor and select the created folder using File -> Open -> Select Folder
  • Create new file and name it as package.json under the project folder and paste below code. This file contains all the dependencies of the project.
  • {
      "name": "angular2-demo-visual-studio",
      "version": "1.0.0",
      "description": "QuickStart package.json from the documentation, supplemented with testing support",
      "scripts": {
        "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",
        "docker-build": "docker build -t ng2-quickstart .",
        "docker": "npm run docker-build && docker run -it --rm -p 3000:3000 -p 3001:3001 ng2-quickstart",
        "pree2e": "npm run webdriver:update",
        "e2e": "tsc && concurrently \"http-server -s\" \"protractor protractor.config.js\" --kill-others --success first",
        "lint": "tslint ./app/**/*.ts -t verbose",
        "lite": "lite-server",
        "postinstall": "typings install",
        "test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
        "test-once": "tsc && karma start karma.conf.js --single-run",
        "tsc": "tsc",
        "tsc:w": "tsc -w",
        "typings": "typings",
        "webdriver:update": "webdriver-manager update"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "@angular/common": "~2.0.1",
        "@angular/compiler": "~2.0.1",
        "@angular/core": "~2.0.1",
        "@angular/forms": "~2.0.1",
        "@angular/http": "~2.0.1",
        "@angular/platform-browser": "~2.0.1",
        "@angular/platform-browser-dynamic": "~2.0.1",
        "@angular/router": "~3.0.1",
        "@angular/upgrade": "~2.0.1",
        "angular-in-memory-web-api": "~0.1.1",
        "bootstrap": "^3.3.7",
        "systemjs": "0.19.39",
        "core-js": "^2.4.1",
        "reflect-metadata": "^0.1.8",
        "rxjs": "5.0.0-beta.12",
        "zone.js": "^0.6.25"
      },
      "devDependencies": {
        "concurrently": "^3.0.0",
        "lite-server": "^2.2.2",
        "typescript": "^2.0.3",
        "typings": "^1.4.0",
        "canonical-path": "0.0.2",
        "http-server": "^0.9.0",
        "tslint": "^3.15.1",
        "lodash": "^4.16.2",
        "jasmine-core": "~2.5.2",
        "karma": "^1.3.0",
        "karma-chrome-launcher": "^2.0.0",
        "karma-cli": "^1.0.1",
        "karma-htmlfile-reporter": "^0.3.4",
        "karma-jasmine": "^1.0.2",
        "karma-jasmine-html-reporter": "^0.2.2",
        "protractor": "^3.3.0",
        "rimraf": "^2.5.4"
      },
      "repository": {}
    }
  • Create another file and name it as tsconfig.json and paste below code. This file is used to compile TypeScript code.
  • {
      "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": true,
        "typeRoots": [
        "node_modules/@types"
        ]
      },
      "compileOnSave": true
    }
  • Create another file and name it as typings.json and paste below code. This file contains all TypeScript compiler libraries.
  • {
      "globalDependencies": {
        "angular-protractor": "registry:dt/angular-protractor#1.5.0+20160425143459",
        "core-js": "registry:dt/core-js#0.0.0+20160725163759",
        "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
        "node": "registry:dt/node#6.0.0+20160831021119",
        "selenium-webdriver": "registry:dt/selenium-webdriver#2.44.0+20160317120654"
      }
    }
  • Launch Integrated Command Terminal using View tab to install dependencies. Use npm install command to start installing the dependencies.
  • Create new folder and name it as app which contains all application related folders and files in it.
  • Create another new file and name it as systemjs.config.js to load modules and paste below code in it:
  • /**
    * System configuration for Angular samples
    * Adjust as necessary for your application needs.
    */
    (function(global) {
    System.config({
    paths: {
    // paths serve as alias
    'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
    // our app is within the app folder
    app: 'app',
    // angular bundles
    '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
    '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
    '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
    '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
    '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
    '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
    '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
    '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
    // other libraries
    'rxjs': 'npm:rxjs',
    'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
    app: {
    main: './main.js',
    defaultExtension: 'js'
    },
    rxjs: {
    defaultExtension: 'js'
    },
    'angular-in-memory-web-api': {
    main: './index.js',
    defaultExtension: 'js'
    }
    }
    });
    })(this);
  • Now, start creating the required files under app folder. Click on app folder and create new file called app.component.ts and paste below code in it.
  • import { Component } from '@angular/core';

    @Component ({
       selector: 'my-app',
         templateUrl:'app/views/app.component.html'
    })

    export class AppComponent {
         appTitle: string = 'Welcome';
    }
  • Create another new file called app.module.ts and paste below code:
  • import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { AppComponent } from './app.component';
    import { HttpModule } from '@angular/http';

    @NgModule({
         imports: [BrowserModule, HttpModule],
          declarations: [AppComponent],
          bootstrap: [AppComponent]
    })

    export class AppModule { }
  • Now, create new file called main.ts and paste below code. This file is used to register all your modules.
  • import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    import { AppModule } from './app.module';
    const platform = platformBrowserDynamic();
    platform.bootstrapModule(AppModule);
  • Now, last but not least, create new html file called Index.html under main folder of the application and paste below code
  • <html>
       <head>
          <title>My First Angular 2 Practice using Visual Studio 2015</title>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <!--<link rel="stylesheet" href="styles.css">-->

          <!-- 1. Load libraries -->
          <!-- Polyfill(s) for older browsers -->
          <script src="node_modules/core-js/client/shim.min.js"></script>
          <script src="node_modules/zone.js/dist/zone.js"></script>
          <script src="node_modules/systemjs/dist/system.src.js"></script>

          <!-- 2. Configure SystemJS -->
          <script src="systemjs.config.js"></script>
          <script>
             System.import('app').catch(function(err){ console.error(err); });
          </script>
       </head>

       <!-- 3. Display the application -->
       <body>
          <my-app></my-app>
       </body>
    </html>

You are good to run your first Anguar2 application. Using Integrated Command Terminal run npm start command to launch and run the above created application, which looks as below in browser:

Happy Programming !!!

Tuesday, July 10, 2018

Angular2: Environment, Features and Components

Environment: The key components which are needed for Angular 2 are:

NPM - Node Package Manager: Which is used to work with open source repositories. This is used to download the dependencies and attach them to the project as Angular 2 as a framework has dependencies on other components.

Git: Can be used to get the sample application from GitHub for Angular.

Editor: Many editors can be used to develop Angular applications such as Visual Studio Code, Visual Studio and WebStorm.

Different ways to get started with Angular are:
  • One way is to do everything from scratch which is the most difficult and not the preferred way due to the number of dependencies.
  • Another way is to use the quick start at Angular GitHub. This contains the necessary code to get started. This is normally what is opted by all developers. GitHub Location to Download
  • The final way is to use Angular CLI
Features: Following are the key features of Angular 2:
  • Components: These will help to build the applications into many modules. Components are over Controllers from AngularJS.
  • TypeScript: This is a superset of JavaScript and is the basis for Angular 2
  • Services: Services are set of code which can be shared by different components of an application. As an example, if you had a data component that picked data from a database could have it as a shared service that could be used across multiple applications

In addition, Angular 2 has better event handling capabilities, powerful templates and better support for module devices.

Components: Below are components of Angular 2:
  • Modules: help separate the functionality of application into logical pieces of code. Usually each piece of code or module is designed to perform a single task. If you are using Visual Studio Code, app.module.ts file under app folder contains the root module class.
  • Component: can be used to bring the modules together, and are logical pieces of code in an angular application. If you are using Visual Studio Code, App.component.ts file in app folder contains this file
  • Template: used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives
  • Metadata: is used to decorate a class so that it can configure the expected behavior of the class and consists of Annotations and Parameters as parts and resides as part of app.component.ts file
  • Services: used to create components which can be shared across the application
Setting up the Environment:
If you selected Visual Studio Code as your Editor:
If you selected Visual Studio 2015 as your Editor:
Verify the Installed Versions
  • Open command prompt and use node -v to get Node.js version
  • Open command prompt and use npm -v to get NPM version
  • Launch Visual Studio -> Help Menu -> About Microsoft Visual Studio to get the Visual Studio version
  • Launch Visual Studio -> Help Menu -> About Microsoft Visual Studio to get the TypeScript version

Once these are ready, we are good to START creating our FIRST Angular 2 Application.

Happy Programming !!!

Monday, July 9, 2018

Authetication & Authorization

This topic illustrates different ways of implementing Authentication and Authorization using ASP.NET, MVC and WebApi

Monday, February 5, 2018

Authorization

Authorization determines whether an identity should be granted access to a specific resource or not. This can be implemented/handled in different ways as below.

In ASP.NET: There are two ways to authorize access to a given resource:
  • File Authorization:

    This is performed by using FileAuthorizationModule which checks the access control list (ACL) of .aspx or .asmx handler file to determine whether user should have access to the resource. ACL permissions are verified for the user's Windows identity (if Windows Authentication is enabled) or for the Windows identity of the ASP.NET process

    FileAuthorizationModule verifies that the user has permission to access the requested file. This class cannot be inherited and below is the syntax of using this class

    public sealed class FileAuthorizationModule : System.Web.IHttpModule

    This module provides authorization services against file-system access-control lists (ACLs). When the mode attribute of the configuration element is set to windows then the WindowsAuthenticationModule is being used for the application. This modules ensures that the requesting user is allowed read or write access to the resource, depending on the request verb, before executing the request.

  • URL Authorization:

    This is performed using UrlAuthorizationModule which maps users and roles to URLs in ASP.NET applications. This module can be used to selectively allow or deny access to arbitrary parts of an application for specific users or roles

    Wthe URL authorization, one can explicitly allow or deny access to a particular directory by user name or role. To do so, we need to create or have an authorization section of a configuration file. The permissions established for a directory also apply to its subdirectories, unless configuration files in a subdirectory override them.

    Rules are applied as below:

    • Rules contained in application level configuration files take precedence over inherited rules. The system determines which rule takes precedence by constructing a merged list of all rules for a URL, with the most recent rules at the head of the list
    • Given a set of merged rules for an application, ASP.NET starts at the head of the list and checks rules until the first match is found.

    Examples of configuring authorization(s):

    Syntax
    <authorization>
            < [allow][deny] users roles verbs />
    </authorization>

    Grant access to Kim and members of the Admins role, and denies access to the John identity and to all anonymous users:
    <authorization>
            < <allow users ="Kim" />
            < <allow roles ="Admins" />
            < <deny users ="John" />
            < <deny users ="?" />
    </authorization>

    Allow access to John identity and deny access to all other users:
    <authorization>
            < <allow users ="John" />
            < <deny users ="*" />
    </authorization>

    Can specify multiple entities for both the users and roles attributes by using comma-separated list:
    <authorization>
            < <allow users ="Jon, Kim, Contoso\Jane" />
    </authorization>

    Allow users to perform an HTTP GET for a resource, but allows only the Kim identify to perform a POST operation:
    <authorization>
            < <allow verbs ="GET" users="*" />
            < <allow verbs ="POST" users="Kim" />
            < <deny verbs ="POST" users="*" />
    </authorization>

In Web API: Authorization happens closer to the controller which lets one to make more granular choices while grating the access.
  • Authorization filters will run before running the controller actions. Based on the filter results user will be redirected either to a error response or to a action response
  • Using current principal from ApiController.User, one can work with current principal within controller's action
Below are the available Custom Authorization Filters:
  • AuthorizeAttribute: Extend this class to perform authorization logic based on the current user and the user's roles.
  • AuthorizationFilterAttribute: Extend this class to perform synchronous authorization logic that is not necessarily based on the current user or role
  • IAuthorizationFilter: Implement this to perform asynchronous authorization logic

In cases where you want to change the behavior based on the role, we can handle this using based on the principal. Within a controller method, you can get the current principal from the ApiController.User property. Below is an example:

public HttpResponseMessage Get()
{
          if (User.IsInRole("Administrators"))
          {
                // ...
          }
}

With this I am concluding the illustration. Feel free to share your feedback. Happy Programming !!!