Factory Pattern-C#

Factory Pattern deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The essence of this pattern is to define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to sub classes.

Suppose your company is producing several types of devices such as home appliances, entertainment devices, office devices, work devices and so on. Each time you want to create a product you need to use “new” operator to create it. There are two disadvantages to it

  1. You have to use new operator for each object creation
  2. Client has to know all the available products before creating the object.

Using factory pattern we will ask factory class, in this case device factory to create object for us based on the device type we pass. Below is the factory pattern implementation code in c#

public class IDevice
{
}

public class HomeDevices : IDevice
{
}

public class EntertainmentDevices : IDevice
{
}

public enum DeviceType
{
Home,
Entertainment,
Office
}
public class DeviceFactory
{

public IDevice CreateDeviceContext(DeviceType type)
{
IDevice deviceContext;
switch (type)
{
case DeviceType.Home: default:
deviceContext = new HomeDevices();
break;
case DeviceType.Entertainment:
deviceContext = new EntertainmentDevices();
break;
case DeviceType.Office:
deviceContext = new OfficeDevices();
break;
}
return deviceContext;
}
}

Jwt Service @angular/Ionic

In this post I will be covering about how to create a Jwt Service in angular 2 and store/retrieve the jwt token from local storage. If you are not familiar with JWT please refer to my earlier post on JWT.

Assumptions:

You have basic understanding of angular 2 and already setup angular 2 project. If not please follow this tutorial Angular Quick Start to get started.

Below is a simple Jwt.service.ts code

import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
declare var escape: any;
@Injectable()
export class JwtService {
    private _jwtKey = "customJwtToken";
    constructor(){
    }

    public get():string {
        return localStorage.getItem(this._jwtKey);
    }

    public set(token: string){
        localStorage.setItem(this._jwtKey, token);
    }

public isAuthenticated(){
    let token = this.get();
    if(!token) return false;
    let decoded = this.decodeToken(token)
    if(typeof decoded == "undefined" || decoded == null || typeof decoded.exp === "undefined") {
      return false;
    }
    return decoded.exp >= Math.round(new Date().getTime() / 1000);
}

public clear(){
    localStorage.removeItem(this._jwtKey);
}

private urlBase64Decode(str:string) {
    var output = str.replace(/-/g, '+').replace(/_/g, '/');
    switch (output.length % 4) {
      case 0: { break; }
      case 2: { output += '=='; break; }
      case 3: { output += '='; break; }
      default: {
        throw 'Illegal base64url string!';
      }
    }

return decodeURIComponent(escape(window.atob(output))); //polifyll https://github.com/davidchambers/Base64.js
  }

  private decodeToken(token:string) {
    var parts = token.split('.');

    if (parts.length !== 3) {
      throw new Error('JWT must have 3 parts');
    }

    var decoded = this.urlBase64Decode(parts[1]);
    if (!decoded) {
      throw new Error('Cannot decode the token');
    }

    return JSON.parse(decoded);
  }
}

In the above code “Set” method takes a jwt token and stores it into the local storage. To retrieve the Jwt token you can use “get” method.

isAuthenticated() method retrieves the jwt token if exists and decodes the payload and checks if the jwt is still valid else it returns false.

To clear the Jwt use clear() method. This method is called at the time of logout.

Note: The above code works in ionic as well.

Http interceptor angular @

In this post I will present the code about how to add the jwt authorization token to you rhttp calls. If you are not aware of JWT please follow my earlier blog post about JWT.

Assumptions:

You have basic understanding of angular 2 and already setup angular 2 project. If not please follow this tutorial Angular Quick Start to get started.

We will write a service called api.service.ts which is a wrapper over http.

import { Injectable } from '@angular/core';
import {Http, Headers, RequestOptions, RequestOptionsArgs, RequestMethod, Response} from '@angular/http';
import {JwtService} from '../jwt/jwt.service'
import {Observable} from 'rxjs/Observable';

@Injectable()
export class ApiService {

constructor(private _jwtService:JwtService,private http: Http) {
}

getHeaders(){
let headers:Headers;
headers = new Headers();
headers.set('Content-Type', 'application/json');
headers.set("Authorization", "Bearer " + this._jwtService.get());
return headers;
}
post(url:string, payload:any) {
let headers = this.getHeaders();
return this.http
.post(url, JSON.stringify(payload),
{headers: headers}).map(x=>x.json());
}

get(url: string) : Observable {
let headers = this.getHeaders();
return this.http.get(url,{headers: headers}).map(x=>x.json());
}

delete(url:string) {
let headers = this.getHeaders();
return this.http.delete(url, {headers:headers});
}
}

In the above method I am injecting JwtService which is a custom service to retrieve the jwt token from local storage and angular’s Http provider.

I have a “getHeaders” method and it creates a new Headers object, sets the content type and add’s the authorization token and returns the headers object.

I have wrappers for post,get, delete (you can add more). For each of this calls I am appending above header object and sending it to the servers.

Note: Use this service/wrapper after login and after setting up jwt service. In others words use this wrapper when you want to make a http request for protected api’s and want to send the bearer/jwt token information.

Touch Id Ionic 2 – Part 2

This post is a follow up to my previous post on Touch Id – Part 1. I will be covering about how to setup a TouchId service and calling init method from the Platform.ready method.

We will be using Ionic native secure storage to store the user credentials. Let’s write our TouchId.service.ts.

import { Injectable } from '@angular/core';
import {AlertController, Nav, LoadingController} from 'ionic-angular';
import { SecureStorage, TouchID } from 'ionic-native';
import {UserService} from '../../user/user.service';
import {LoginService} from '../../pages/login/login.service';
import {TabsPage} from '../../pages/tabs/tabs';

@Injectable()
export class TouchIdService {
private secureStorage: SecureStorage;
private SecureStorageName = 'testSecureStorage';
public touchIdAvailable = false;
private nav: Nav = null;
constructor(private userService: UserService, private alertCtrl: AlertController,
private login: LoginService, private loadingCtrl: LoadingController) {
}
init(nav: Nav) {
this.nav = nav;
this.secureStorage = new SecureStorage();
this.secureStorage.create(this.SecureStorageName)
.then(
x => {
this.touchIdAvailable = true;
},
error => {
console.log(error);
}
)

}
attemptTouchId() {
this.secureStorage.get('testUser').then(
(usr) => {
this.touchIdAuthentication(usr);
},
(err) => {

}
);
}
enableTouchId(usr) {
if(this.touchIdAvailable) {
this.secureStorage.set('testUser', JSON.stringify(usr))
.then(
(data) => { }
);
}
}
touchIdAuthentication(usr) {
if (usr && this.touchIdAvailable) {
TouchID.verifyFingerprint('Authenticate to login to your Dollar Tracker account')
.then(
res => {
let loading = this.loadingCtrl.create();
loading.present();
this.login.login(JSON.parse(usr))
.subscribe(result => {
this.userService.add(result);
this.nav.push(TabsPage);
loading.dismiss();
});
},
err => console.error('Error', err)
);
}
}
}

As you can see in the above service I have a init method to setup the secure storage and also hold the reference to nav. Nav is used later to navigate to TabsPage after Touch Id authentication.

After calling init method, I would immediately invoke attemptTouchId method. attemptTouchId() checks if there is already a key “testUser” in the secure storage if so retrieve the user credentials and ask the user to verify the finger prints. If finger prints are verified we will post the user credentials to the login service and get the session/jwt and navigate to the Tabs page as you can see in “touchIdAuthentication(usr)”.

enableTouchId(usr)
As mentioned earlier, in this post we will enable the touch id by default whenever user login via the login page. After successful authentication I will be calling the enableTouchId method and store the user credentials to the secure storage.

Now modifying app.component.ts file the constructor looks something like below.

constructor(platform: Platform, private touchIdService:TouchIdService) {
platform.ready().then(() => {
StatusBar.styleDefault();
TouchID.isAvailable().
then(
res => {
  this.touchIdService.init(this.nav);
  this.touchIdService.attemptTouchId();
console.log('TouchID is available!')
},
err => console.error('TouchID is not available', err)
});
}

 

 

 

Integrating pubnub in @angular, Ionic 2

In this post I will be covering about how to integrate pubnub client in angular/ionic projects.

Assumptions:

You have basic understanding of angular 2 and already setup angular 2 project. If not please follow this tutorial Angular Quick Start to get started.

You are aware of Ionic 2 framework and already setup the app. If not, please follow Installing Ionic to setup your environment.

You already setup pubnub on server side and publishing the events on particular channel.

The first step is to add the pubnub into your html file. You can either include a cdn or copy the script locally and add it to your html. I will be including the following cdn in my head tag.

http://cdn.pubnub.com/pubnub-3.16.4.min.js

The next step is to create a pubnub.service.ts with the below code

import { Injectable } from '@angular/core';
import {Observable, Subject, BehaviorSubject} from 'rxjs/Rx';
import {Http} from '@angular/http';
declare var PUBNUB;

@Injectable()
export class PubnubService {
pubnub:any;
public isReady:BehaviorSubject = new BehaviorSubject(false);
constructor(private http:Http) {
//assumptions you know how to pass any authentication headers
let url = "http://localhost/pubnubkeys";

this.http.get(url)
.take(1)
.subscribe(subKey => {
this.pubnub = PUBNUB.init({
subscribe_key:subKey
});
this.isReady.next(true);
})
}

public listen(channel:string): Observable
{
console.log("LISTENING to pubnub channel:"+channel);
return Observable.create(observer =>{
this.pubnub.subscribe({
channel: channel,
restore: false,
message: (msg) =>{
observer.next(msg);
}
})
return ()=>{
this.pubnub.unsubscribe({
channel: channel
});
};
});
}
}

In the above code, if you look into the constructor I am calling the server to get the subscription key (You can hard code the subscription key for security reasons I am getting from server)). Once I got the subscription key I am initializing pubnub and setting isReady to true. Whoever what to listen to any channel, they can do so by calling listen method of pubnub service.

Let’s do with an example. You have a notification service and you want to listen to a particular channel and show the notification count whenever you receive a new message. The following code illustrates how to you can do it.

import { Injectable } from '@angular/core';
import {Observable, Subject, BehaviorSubject, Subscription} from 'rxjs/Rx';
import {PubnubService} from './pubnub.service';
import {UserService} from '../../user/user.service';
import {Http} from '@angular/http';

@Injectable()
export class NotificationsService {
public isNewMessageAvailable:boolean = false;
public newMessagesCount = 0;
public messages:Array = [];
constructor(private _pubnubService: PubnubService, private _userService:UserService,
private http:Http) {
this._pubnubService.isReady.subscribe(x=>{
if(x) {
this._pubnubService.listen(this._userService.user.userId)
.filter(x=>x.Author != _userService.user.userId)
.subscribe(msg => {
this.isNewMessageAvailable = true;
this.newMessagesCount +=1;
});
}
});
}
}

In the above code I am registering to the userId channel (assuming you are maintaining userId of the person who logged in) and subscribing to the userId channel. Whenever I receive a new message I am increasing the message count and setting the isNewMessageAvailable flag to true. In the UI you can present a notification badge and also have a read method whenever the user reads the message.

Loading Spinner Ionic 2

In this post I will be covering about how to display a busy loading spinner whenever you do tasks such as making a http request.

Assumptions:
You are aware of Ionic 2 framework and already setup the app. If not, please follow Installing Ionic to setup your environment.

In order to show the loading spinner you have to import LoadingController from ‘ionic-angular’ module.

Let’s create a LoginPage.ts and display a LoadingSpinner when the user clicks submit button.

import {LoadingController} from 'ionic-angular';
import {Http} from '@angular/http';
@Component({
templateUrl: 'login.html'
})
export class LoginPage {
public email: string = null;
public password: string = null;
constructor(private loadingCtrl:LoadingController, private http: Http){}

public submit() {
//assuming we do validations here

let url = "http://localhost/login"; //some imaginary url
let payload = {"email": this.email, "password": this.password};
let loading = this.loadingCtrl.create();
loading.present();
this.$http.post(url, payload)
.subscribe(result => {
loading.dismiss();
//do something with the result
},
err => { loading.dismiss(); //do something with the error }
)
}
}

In the above code whenever user clicks submit I will create an instance of loading using loadingCtrl.create(), then present the loading spinner. Once the http call gets the response I would be hiding the loading spinner using loading.dismiss().

For more information about Loading please refer to Ionic documentation

Touch Id Ionic 2 – Part 1

In this post I will be covering in depth about how to integrate/enable Touch Id authentication in your Ionic 2 app. You may find some basic information about how Touch Id works, but won’t get a detailed explanation about how to integrate it into your real app.

Assumptions:

You are aware of Ionic 2 framework and already setup the app. If not, please follow Installing Ionic to setup your environment.

I will be covering Touch Id in 2 parts.
1. TouchId setup
2. Login via TouchId

In order to make use of Touch Id functionality we need to install cordova plugin.
You can do so by the following command

ionic plugin add cordova-plugin-touchid

After you install cordova plugin you need to make sure if the Touch Id functionality is available. Note: not all devices have Touch Id functionality available. For iPhone Touch Id is available since iPhone 6.

Your app.component.ts file should look like something below

import {Component} from '@angular/core';
import {Platform} from 'ionic-angular';
import { TouchID} from 'ionic-native';
import { LoginPage } from '../pages/login/login';

@Component({
template: ``
})
export class MyApp {
rootPage = LoginPage;
//rootPage = TabsPage;

constructor(platform: Platform) {
platform.ready().then(() => {
StatusBar.styleDefault();
TouchID.isAvailable().
then(
res => {
//initialize TouchID and attempt login
console.log('TouchID is available!')
},
err => console.error('TouchID is not available', err)
});
}
}

As you can see in the above code I am checking TouchID.isAvailable() inside platform.ready to make sure if the TouchID functionality is available for that device. If its available I will be initializing the TouchID  related things (which I will cover in next post) and try to attempt login (also next post).

Logout in Ionic 2

In this post I will be covering about how to logout from an Ionic 2 app and present the Login page. I chose to write a blog post for this as there was not much documentation on how to do this. If you set the root page to login, it will go to Login page but the tabs are visible.

Note: In this post I am considering only a tabs template. Ionic 2 does not support angular 2 router yet.

Assumptions:

You are aware of Ionic 2 framework and already setup the app. If not, please follow Installing Ionic to setup your environment.

Without much due here is the code.

import {Component} from '@angular/core';
import {App} from 'ionic-angular';
import {LoginPage} from '../login/login';

@Component({
templateUrl:'logout.html'
})
export class LogoutPage {
constructor(private app:App){ }
logout(){
//clear any cached data
this.app.getRootNav().setRoot(LoginPage);
}
}

logout.html looks something like this.

<br /><button class="default">Logout</button>

As you can see whenever user clicks on the logout button, I am setting LoginPage as root by call this.app.getRootNav().setRoot(LoginPage)

Success/Failure Alert message Component @angular

In this post I will be providing code on how to create a Alert component in angular 2 which shows either success/failure messages and disappear the message after few seconds.

For example you want to display invalid username or password error message when the user enters invalid credentials and want the message to be hidden after few seconds as shown in the below figure.

login_error

Assumptions:

You have basic understanding of angular 2 and already setup angular 2 project. If not please follow this tutorial Angular Quick Start to get started.

Also, I am using bootstrap 3  for styling if you are not familiar with it please follow this tutorial http://getbootstrap.com/

Without much due please follow the below code.

import { Component, OnInit, Input } from '@angular/core';

@Component({
selector: 'e-alert',
templateUrl: 'app/shared/alert/ealert.component.html'
})
export class EAlertComponent {
public messages:any[];
constructor() {
this.messages = [];
}

public success(message:string):void{
var msg = {"key":"success", "text": message}
this.messages.push(msg);
this.scheduleRemoval(msg);
}

public failure(message:string):void{
var msg = {"key":"danger", "text": message}
this.messages.push(msg);
this.scheduleRemoval(msg);
}

private scheduleRemoval(msg:any){
setTimeout(()=>{
var idx = this.messages.indexOf(msg);
this.messages.splice(idx,1);
}, 3000);
}
public remove(idx:any):void{
if(idx >= 0){
this.messages.splice(idx, 1);
}
}

@Input() malert:DtAlertComponent;
}

The ealert.component.html looks something like this.

<div>
<div class="alert alert-{{m.key}} alert-dismissible">
<span class="close">×</span>
{{m.text}}
</div>
</div>
<div>
<div class="alert alert-{{m.key}} alert-dismissible">Example usage.</div>
</div>

I above code is html coded, wordpress.com giving me hard time to render the Raw html. I will try to fix it asap.

Example usage.

In you login.ts file import the EAlertComponent
import { Component, Input, OnInit } from '@angular/core';
import {EAlertComponent} from '../shared/alert/dtalert.component'

@Component({
templateUrl: 'app/login/login.component.html'
})
export class LoginComponent {
@Input() email:string;
@Input() password:string;
public eAlert:EAlertComponent;
constructor(){
this.eAlert = new EAlertComponent();
}
public submit() {
//assume you have validation service and api to post to server and it returns //error. You can display it

this.eAlert.failure(error);
}
}

In your login.html you need to add the below code.

// your input fields code

<e-alert [malert]="eAlert"></e-alert>

Note: I assume you are aware of how to register this Component into you angular 2 module.

@angular Split Pascal Word filter

In this post I will be explaining how to write a Split Pascal Word filter in angular 2. For example you have a word like NewMessage and you want it to split it into  New Message.

Assumptions:

You have basic understanding of angular 2 and already setup angular 2 project. If not please follow this tutorial Angular Quick Start to get started.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'splitpascal'
})
export class SplitPascalWordPipe implements PipeTransform {
transform(value: string): string {
if ((typeof value) !== 'string') return value;
value = value.split(/(?=[A-Z])/).join(' ');
return value;
}
}

In the above code I created a pipe called splitpascal, it basically takes the input string and splits it.

Assuming you have a variable declared in .ts file called “eventType” and set its value as such “eventType=NewMessage”. In your .html file you can do something like the below

{{eventType | splitpascal}} and it will render as New Message. 

Note: I assume you are aware of how to register this pipe into you angular 2 module.