Thursday, 22 November 2018

Directive of loader in angular



@NgModule({
declarations: [ Loader2Directive ]
})


import { Directive, ElementRef, Renderer } from '@angular/core';

@Directive({
selector: '[appLoader]'
})
export class LoaderDirective {
constructor(private _elemRef: ElementRef, private _renderer: Renderer) {
_renderer.setElementProperty(_elemRef.nativeElement, 'innerHTML',
"<div class='ajgg'><div class='lds-ring'> <div></div><div></div> <div>
</div> <div></div></div></div>");
}
}

FilterPipe in angular (compair test)




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

@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {

// Strategies| filter: {q: searchText,find: 'Cloumn Name' }
transform(value: any, args?: any): any {
// console.log({ 'Pipe Value:': value });
// console.log({ 'Pipe OP:': args });
let id = args.q; //Find Value
let q = args.find; //Find Column
// let r = args.res; //Result Column
let res: any[] = [];
if (id == undefined || id == '') {
return value;
}

if (value != undefined) {
value.find(x => {
// console.log("X>>",x);
// console.log("Compare:", "Find:"+q+"=" + id + "
//Current:"+q+"="+x[q]+ " -> Result: "+r+"="+x[r]);
if (x[q].toLowerCase() === id.toLowerCase()) {
res.push(x);
}
});
// console.log({ 'Pipe res:': res });
return res;
}

}
}

OrderByPipe in angular


@NgModule({
declarations: [
OrderByPipe
]
})

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

@Pipe({
name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {

transform(value: Array<any>, field: any): any {

if (value == null) {
return null;
}
let sortingtype: number = parseInt(field[0] + 1);
var crntfield = field.substring(1).split('.');

function compare(a, b) {
switch (crntfield.length) {
case 1: a = a[crntfield[0]]; b = b[crntfield[0]]; break;
case 2: a = a[crntfield[0]][crntfield[1]];
b = b[crntfield[0]][crntfield[1]]; break;
case 3: a = a[crntfield[0]][crntfield[1]][crntfield[2]];
b = b[crntfield[0]][crntfield[1]][crntfield[2]]; break;
case 4: a = a[crntfield[0]][crntfield[1]][crntfield[2]][crntfield[3]];
b = b[crntfield[0]][crntfield[1]][crntfield[2]][crntfield[3]]; break;
case 5: a = a[crntfield[0]][crntfield[1]][crntfield[2]][crntfield[3]][crntfield[4]]; b = b[crntfield[0]][crntfield[1]][crntfield[2]][crntfield[3]][crntfield[4]]; break;
}
if (a < b)
return sortingtype * 1;
if (a > b)
return sortingtype * -1;
return 0;
}
return value.sort(compare);
}

}

GrdFilterPipe in angular



@NgModule({
declarations: [ GrdFilterPipe]
})

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

@Pipe({
name: 'grdFilter'
})
export class GrdFilterPipe implements PipeTransform {

// <table *ngFor="let emp of customerData
//| grdFilter: {column1: searchText, column2:searchText, colum: searchText};
//let i=index;">

transform(items: any, filter: any, defaultFilter: boolean): any {
if (!filter) {
return items;
}

if (!Array.isArray(items)) {
return items;
}

if (filter && Array.isArray(items)) {
let filterKeys = Object.keys(filter);

if (defaultFilter) {
return items.filter(item =>
filterKeys.reduce((x, keyName) =>
(x && new RegExp(filter[keyName], 'gi').test(item[keyName])) ||
filter[keyName] == "", true));
}
else {
return items.filter(item => {
return filterKeys.some((keyName) => {
return new RegExp(filter[keyName], 'gi').test(item[keyName]) ||
filter[keyName] == "";
});
});
}
}
}
}

Routing in angular





import { TestComponent } from './test/test.component';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { SubscribersComponent } from './home/subscribers/subscribers.component';
import { NotfoundComponent } from './notfound/notfound.component';
import { HomeComponent } from './home/home.component';
import { PositionsComponent } from './home/positions/positions.component';
import { PerformanceComponent } from './home/performance/performance.component';
import { AllaccountsComponent } from './home/allaccounts/allaccounts.component';


import { LogsComponent } from './logs/logs.component';
import { AuthService } from './services/auth.service';

const routes: Routes = [
{path: 'login', component: LoginComponent, data: { title: 'Login' }},
{
path: 'home', component: HomeComponent,
canActivate: [AuthService], data: { title: 'Home' },
children:[
{ path: 'subscribe', component: SubscribersComponent,
canActivate: [AuthService], data: { title: 'Subscribers' } },
{ path: 'positions', component: PositionsComponent,
canActivate: [AuthService], data: { title: 'Positions' } },
{ path: 'commission', component: SubscribersComponent,
canActivate: [AuthService],data: { title: 'Commission' } },
{ path: 'performance', component: PerformanceComponent,
canActivate: [AuthService],data: { title: 'Performance' } },
{ path: 'allaccounts', component: AllaccountsComponent,
canActivate: [AuthService], data: { title: 'All Accounts' } },
{ path: 'log', component: LogsComponent,
canActivate: [AuthService],data: { title: 'Logs' } },
{ path: 'test', component: TestComponent,
canActivate: [AuthService], data: { title: 'Logs'}},
{ path: '', component: SubscribersComponent,
canActivate: [AuthService], data: { title: 'Subscribers'}},
{path: '**', component: NotfoundComponent, data: { title: 'Page not found!'}},
]
},
{path: '', component: LoginComponent, data: { title: 'Login' }},
{path: '**', component: LoginComponent, data: { title: 'Login' }},
];

@NgModule({
imports: [
RouterModule.forRoot(routes),
// PositionsModule
],
providers: [
// PositionsModule
],
exports: [RouterModule]
})
export class AppRoutingModule { }

Rest Api




import { Injectable } from '@angular/core';
import { Http, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import { from } from 'rxjs';
import { HttpParams } from '@angular/common/http';
import { map, filter, catchError, mergeMap } from 'rxjs/operators';


//
// import { HttpHeaders } from '@angular/common/http';
// import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class RestService {

config: any = {
AppName: "Affiliate Admin",
PrimaryUrl: "http://xx.xxx..xx:5052/xxxxx",//damo
SecondaryUrl: "xx.x..x..xx5052/xxxxx",//demo
};
constructor(public http: Http) {

}

GetMethod(param: string) {
return this.http.get(param).map(response => response.json());
}
//aj
UploadProfilePic(url: string, params: any){
console.log("url:", url);
console.log("Parms:",params);
try {
return this.http.post(url, params)
.map(response => response.json());

} catch (e) {
console.log(e);
}
}
get(endPointg: string, params?: any, optn?: any) {

if (!optn) {
optn = {
params: new HttpParams()
};
};

let p = [];
let newParam;
if (params) {
for (let k in params) {

let str = k + '=' + params[k];
p.push(str);

}
newParam = p.join('&');
}

try {
return this.http.get(this.config.PrimaryUrl + '/' + endPointg + '?' + newParam)
.map(response => response.json());

} catch (e) {
console.log(e);
}
}

post(endPointg: string, params?: any, optn?: any) {

if (!optn) {
optn = {
params: new HttpParams()
};
};


try {
return this.http.post(this.config.PrimaryUrl + '/' + endPointg, params)
.map(response => response.json());

} catch (e) {
console.log(e);
}
}


get1(endPointg: string, params?: any, optn?: any) {

if (!optn) {
optn = {
params: new HttpParams()
};
};

let p = [];
let newParam;
if (params) {
for (let k in params) {

let str = k + '=' + params[k];
p.push(str);

}
newParam = p.join('&');

}

try {
return this.http.get(this.config.SecondaryUrl + '/' + endPointg + '?' + newParam)
.map(response => response.json());

} catch (e) {
console.log(e);
}
}

post1(endPointg: string, params?: any, optn?: any) {

if (!optn) {
optn = {
params: new HttpParams()
};
};


try {
return this.http.post(this.config.SecondaryUrl + '/' + endPointg, params)
.map(response => response.json());

} catch (e) {
console.log(e);
}
}

webSocket(domain: string, param?: any) {
var fws = new WebSocket(domain);
fws.onopen = function () {
fws.send(param); // Send the message 'Ping' to the server
};
return fws;
}



// ajAuthGet(){
// // var headerApi= new Headers({ "Content-Type": "application/x-www-form-urlencoded",
// // "Authorization": "Basic 488ccc4dbcd818784de6f72d9e1a7b88-us19"})
// // return this.http.get('https://us19.api.mailchimp.com/3.0/', { headers: headerApi })


// // let headers = new Headers({ 'Content-Type': 'application/json' });
// // headers.append('Authorization', 'Basic 488ccc4dbcd818784de6f72d9e1a7b88-us19 ')
// // let options = new RequestOptions({ headers: headers });

// const httpOptions = {
// headers: new HttpHeaders({
// 'Content-Type': 'application/json',
// 'Authorization': 'Basic 488ccc4dbcd818784de6f72d9e1a7b88-us19'
// })
// };
// return this.HttpClient.get('https://us19.api.mailchimp.com/3.0/', httpOptions)
// .map(response => response);
// }
}

AuthService in angular

path: 'home',
component: HomeComponent,
canActivate: [AuthService], data: { title: 'Home' },

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot }
from '@angular/router';
import { GlobalService } from './global.service';
import { CommanService } from './comman.service';

@Injectable({
providedIn: 'root'
})
export class AuthService {

constructor(private router: Router, protected global: GlobalService,
protected comm: CommanService) { }


canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let user: any = JSON.parse(localStorage.getItem('AccountDetail'));
try {

// this.comm.currentUrl.subscribe(data => {
// console.log("cUrl:", data);
// var currentUrl = data;
// this.comm.isAdmin.subscribe(data2 => {
// var isAdmin = data2;
// if (isAdmin) {
// } else {
// }
// });
// });

console.log("MasterId", user.MasterId);
if (user.MasterId > 0) {
console.log("ReferredBy", user.ReferredBy);
if (user.ReferredBy > 0) {//For User
console.log("ReferredBy:");
var currentUrl = state.url;
if (currentUrl == '/home/allaccounts') {
//not add currentUrl == '/home/subscribe'
return false;
} else {
return true;
}

} else {//For Master
return true;
}

// return true;
}
} catch (e) {
// not logged in so redirect to login page with the return url
// this.router.navigate(['login'], { queryParams: { returnUrl: state.url }});
return false;
}


// this.global.LoggedInSrc.next(0);
// // not logged in so redirect to login page with the return url
// this.router.navigate(['login'], { queryParams: { returnUrl: state.url }});
// return false;
}

}

titleService








import { Injectable } from '@angular/core';
// import { filter } from 'rxjs/operators';
// import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/filter';

import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';

const APP_TITLE = 'Trade Copier!';
const SEPARATOR = ' > ';

@Injectable()
export class TitleService {
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
private titleService: Title,
) {}

init() {
this.router.events
.filter((event) => event instanceof NavigationEnd)
.map(() => {
let route = this.activatedRoute;
while (route.firstChild) route = route.firstChild;
return route;
})
.filter((route) => route.outlet === 'primary')
.mergeMap((route) => route.data)
.map((data) => {
if ( data.title ) {
// If a route has a title set (e.g. data: {title: "Foo"}) then we use it
return data.title;
} else {
// If not, we do a little magic on the url to create an approximation
return this.router.url.split('/').reduce((acc, frag) => {
if ( acc && frag ) { acc += SEPARATOR; }
return acc + TitleService.ucFirst(frag);
});
}
})
.subscribe((pathString) =>
this.titleService.setTitle(`${pathString} - ${APP_TITLE}`));
}

static ucFirst(string) {
if ( !string ) { return string; }
return string.charAt(0).toUpperCase() + string.slice(1);
}
}

Friday, 2 November 2018

BCrypt and BasicAuthentication in Api C#

https://www.nuget.org/packages/BCrypt-Official/


Install-Package BCrypt-Official -Version 0.1.109

using BCrypt.Net;

ViewBag.Title = "Home Page";
string pwdToHash = "pass" + "^Y8~JJ"; // ^Y8~JJ is my hard-coded salt
string hashToStoreInDatabase = BCrypt.Net.BCrypt.HashPassword(pwdToHash, BCrypt.Net.BCrypt.GenerateSalt());
//string e1= BCrypt.Net.BCrypt.HashPassword("pass" + "^Y8~JJ", hashToStoreInDatabase);
bool e= BCrypt.Net.BCrypt.Verify("pass" + "^Y8~JJ", hashToStoreInDatabase);


http://csharp-video-tutorials.blogspot.com/2016/10/implementing-basic-authentication-in.html



Create a class that checks if the username and password are valid
1. Add a new class file to EmployeeService Web API project. Name it EmployeeSecurity.cs

2. Copy and paste the following code in it

using EmployeeDataAccess;
using System;
using System.Linq;

namespace EmployeeService
{
    public class EmployeeSecurity
    {
        public static bool Login(string username, string password)
        {
            using (EmployeeDBEntities entities = new EmployeeDBEntities())
            {
                return entities.Users.Any(user =>
                       user.Username.Equals(username, StringComparison.OrdinalIgnoreCase)
                                          && user.Password == password);
            }
        }
    }
}

Create basic authentication filter
1. Add a new class file to EmployeeService Web API project. Name it BasicAuthenticationAttribute.cs

2. Copy and paste the following code in it

using System;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace EmployeeService
{
    public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request
                    .CreateResponse(HttpStatusCode.Unauthorized);
            }
            else
            {
                string authenticationToken = actionContext.Request.Headers
                                            .Authorization.Parameter;
                string decodedAuthenticationToken = Encoding.UTF8.GetString(
                    Convert.FromBase64String(authenticationToken));
                string[] usernamePasswordArray = decodedAuthenticationToken.Split(':');
                string username = usernamePasswordArray[0];
                string password = usernamePasswordArray[1];

                if (EmployeeSecurity.Login(username, password))
                {
                    Thread.CurrentPrincipal = new GenericPrincipal(
                        new GenericIdentity(username), null);
                }
                else
                {
                    actionContext.Response = actionContext.Request
                        .CreateResponse(HttpStatusCode.Unauthorized);
                }
            }
        }
    }
}

Enable basic authentication
1. The BasicAuthenticationAttribute can be applied on a specific controller, specific action, or globally on all Web API controllers.

2. To enable basic authentication across the entire Web API application, register BasicAuthenticationAttribute as a filter using the Register() method in WebApiConfig class

config.Filters.Add(new RequireHttpsAttribute());

3. You can also apply the attribute on a specific controller, to enable basic authentication for all the methods in that controller

4. In our case let's just enable basic authentication for Get() method in EmployeesController. Also modify the implementation of the Get() method as shown below.

[BasicAuthentication]
public HttpResponseMessage Get(string gender = "All")
{
    string username = Thread.CurrentPrincipal.Identity.Name;

    using (EmployeeDBEntities entities = new EmployeeDBEntities())
    {
        switch (username.ToLower())
        {
            case "male":
                return Request.CreateResponse(HttpStatusCode.OK,
                    entities.Employees.Where(e => e.Gender.ToLower() == "male").ToList());
            case "female":
                return Request.CreateResponse(HttpStatusCode.OK,
                    entities.Employees.Where(e => e.Gender.ToLower() == "female").ToList());
            default:
                return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }
}

Testing basic authentication using fiddler
1. The username and password need to be colon (:) separated and base64 encoded. 

2. Just google with the string - base64 encode. The first web site that you get is https://www.base64encode.org/

3. Enter the username and password separated by colon (:) in "Encode to Base64 format"  textbox, and then click "Encode" button 
















IIS deployment support details

  Node JS - IIS deployment support details node: http://go.microsoft.com/?linkid=9784334 IISNode: https://github.com/azure/iisnode/releases/...