Saturday, September 7, 2019

C# Feature Details

In this post, would like to provide the new features introduced between major version releases of C# as below:

Version 7.0
        Released on: March, 2017         Target Framework: 4.6.2         Visual Studio version: 2017
  • Out variable: In this improved version, you can now declare out variables in the argument list of a method call, rather than writing a separate declaration statement above the line and assign an initial value.
    if (int.TryParse(input, out var answer))
            Console.WriteLine(answer);
    else
            Console.WriteLine("Could not parse input");
  • Tuples and Deconstruction: Tuples are lightweight data structures that contain multiple fields to represent the data members. The fields aren't validated, and you can't define your own methods. A tuple can be created by assigning a value to each member, and optionally providing semantic names to each of the members of the tuple.
    (string Alpha, string Beta) namedLetters = ("a", "b");
    Console.WriteLine($"{namedLetters.Alpha}, {namedLetters.Beta}");
    In a tuple assignment, you can also specify the names of the fields on the right-hand side of the assignment as below:
    var alphabetStart = (Alpha: "a", Beta: "b");
    Console.WriteLine($"{alphabetStart.Alpha}, {alphabetStart.Beta}");
    There may be times when you want to unpackage the members of a tuple that were returned from a method. You can do that by declaring separate variables for each of the values in the tuple. This unpackaging is called deconstructing the tuple. It looks as below:
    (int max, int min) = Range(numbers);
    Console.WriteLine(max);
    Console.WriteLine(min);
  • Pattern matching
  • Local functions
  • Expanded expression bodied members
  • Ref locals and returns
  • Discards
  • Binary Literals and Digit Separators
  • Throw expressions
Version 6.0
        Released on: July, 2015         Target Framework: 4.6         Visual Studio version: 2015
  • Static imports
  • Exception filters
  • Auto-property initializers
  • Expression bodied members
  • Null propagator
  • String Interpolation
  • nameof operator
  • Index initializers
Version 5.0
        Released on: August, 2012         Target Framework: 4.5         Visual Studio version: 2012 and 2013
  • Asynchronous members
  • Caller info attributes
Version 4.0
        Released on: April, 2010         Target Framework: 4.0         Visual Studio version: 2010
  • Dynamic binding
  • Named/optional arguments
  • Generic covariant and contravariant
Version 3.0
        Released on: November, 2007         Target Framework: 2.0, 3.0 and 3.5         Visual Studio version: 2008 and 2010
  • Auto-implemented properties
  • Anonymous types
  • Query expressions
  • Lambda expressions
  • Expression trees
  • Extension methods
  • Implicitly typed variables
  • Partial methods
  • Object and collection initializers
Version 2.0
        Released on: November, 2005         Target Framework: 2.0         Visual Studio version: 2005
  • Generics
  • Partial types
  • Anonymous methods
  • Nullable types
  • Iterators
  • Covariance and contravariance
Version 1.0
        Released on: January, 2002         Target Framework: 1.0         Visual Studio version: 2002
  • Classes
  • Stucts
  • Interfaces
  • Events
  • Properties
  • Delegates
  • Expressions
  • Statements
  • Attributes

Saturday, February 16, 2019

ng2-table: Sorting with Pagination

Under Design...

ng2-table: Sorting

Under Design...

ngx-Bootstrap: Pagination

In this post you will find how to work with ngx-Bootstrap to implement Pagination feature using Angular 7 CLI

Get ngx-Bootstrap using below command:

npm install ngx-Bootstrap --save

Below is how the package.json file should look like (used at the time of writing this post)

{
"name": "gbpprototype-web",
"version": "0.0.0",
"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",
"ng2-bootstrap": "^1.6.3",
"ng2-table": "^1.3.2",
"ngx-bootstrap": "^3.2.0",
"rxjs": "~6.3.3",
"rxjs-compat": "^6.3.3",
"underscore": "^1.9.1",
"zone.js": "~0.8.26"
},
"devDependencies": {
"@angular-devkit/build-angular": "^0.13.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"
}
}

Import and update app.module.ts as below to include ngx-Bootstrap/Pagination

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PaginationModule } from 'ngx-bootstrap/pagination';

@NgModule({
declarations: [
      ...
],
imports: [
      BrowserModule
      ,PaginationModule.forRoot()
providers: [],
bootstrap: []
})

Import and change the component.ts as below to include ngx-Bootstrap/Pagination

import { NgModule } from '@angular/core';
import { PageChangedEvent } from 'ngx-bootstrap/pagination';

@Component({
selector: 'BasicPagination',
templateUrl:'basicPaginationView.html',
providers: [ProductService]
})

export class BasicPaginationComponent implements OnInit {
currentPage: number;
maxPageSize: number;

ngOnInit() : void {}

pageChanged(event: PageChangedEvent): void {
      const startItem = (event.page - 1) * event.itemsPerPage;
      const endItem = event.page * event.itemsPerPage;
      this.returnedProducts = this.products.slice(startItem, endItem);
}
}

Add below code to .html file which will include Pagination control to the view

<div class="pull-right">
<!-- pager -->
<pagination id="test" [totalItems] = totalProducts [itemsPerPage]=maxPageSize [directionLinks]="false" (pageChanged)="pageChanged($event)"></pagination>
</div>

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

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"