Thursday 25 January 2018

Passing Data To Component in Agular2 With Using Service

********************Create First Service*************

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class ProgressSpinner {
public _subject = new Subject<boolean>();
public event = this._subject.asObservable();

public SpinnerLoader(data: any) {
this._subject.next(data);
}
}

Create Object in AppComponent

import { Component } from '@angular/core';
import { alertservice, ProgressSpinner } from './shared'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
loading: boolean = false;
constructor(public _ProgressSpinner: ProgressSpinner) {
_ProgressSpinner.event.subscribe((data) => { this.loading = data });

}
}
***************Second Component***************
import { Component, OnInit, ViewEncapsulation, ElementRef } from '@angular/core'
import { MenuItem, Message, Shape_Master, Shape_Col } from '../../shared'
import { DepartmentGroupervice, GenericClass, Pagination, ProgressSpinner } from '../../shared'
import { ConfirmationService, GrowlModule } from 'primeng/primeng';

@Component({
selector: 'app-shape',
templateUrl: './shape.component.html',
styleUrls: ['./shape.component.css']
})
export class ShapeComponent implements OnInit {

constructor( private _ProgressSpinner: ProgressSpinner) {
this._ProgressSpinner.SpinnerLoader(false);

}
}

How to Create Common API SERVICE File in Angualr 2

import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { Headers, Http, Response, URLSearchParams, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx'
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { JwtService } from './jwt.service';


@Injectable()
export class ApiService {
  constructor(
    private http: Http,
    private jwtService: JwtService
  ) { }

  private setHeaders(): Headers {
    const headersConfig = {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    };
    if (this.jwtService.getToken()) {
      headersConfig['Authorization'] = `${this.jwtService.getToken()}`;
      if (sessionStorage.getItem("CurrentUserName") != null) {
        headersConfig['AuthorizationID'] = JSON.parse(sessionStorage.getItem("CurrentUserName"))['User_ID'];
      } else { headersConfig['AuthorizationID'] = "Error" }
    }
    return new Headers(headersConfig);
  }

  private formatErrors(error: any) {
    return Observable.throw(error.json());
  }

  get(path: string, params: URLSearchParams = new URLSearchParams()): Observable<any> {
    return this.http.get(`${environment.api_url}${path}`, { headers: this.setHeaders(), search: params })
      .catch(this.formatErrors)
      .map((res: Response) => res.json());
  }

  put(path: string, body: Object = {}): Observable<any> {
    const options = new RequestOptions({ headers: this.setHeaders() });
    return this.http.put(
      `${environment.api_url}${path}`,
      JSON.stringify(body),
      options
    )
      .catch(this.formatErrors)
      .map((res: Response) => res.json());
  }

  post(path: string, body: Object = {}): Observable<any> {

    const options = new RequestOptions({ headers: this.setHeaders() });
    return this.http.post(
      `${environment.api_url}${path}`,
      JSON.stringify(body),
      options
    )
      .catch(this.formatErrors)
      .map((res: Response) => {
        if (res.json().ReturnMsg === "TOKEN NUMBER NOT MATCH....!!!") {
          this.jwtService.destroyToken()
        }
        return res.json()
      });
  }
  postFile(path: string, body): Observable<any> {
    return this.http.post(`${environment.api_url}${path}`, body)
      .map((res: Response) => {
        if (res.json().ReturnMsg === "TOKEN NUMBER NOT MATCH....!!!") {
          this.jwtService.destroyToken()
        }
        return res.json()
      });
  }

  delete(path): Observable<any> {
    return this.http.delete(
      `${environment.api_url}${path}`,
      { headers: this.setHeaders() }
    )
      .catch(this.formatErrors)
      .map((res: Response) => res.json());
  }
}

******************************************************
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class JwtService {
  constructor(
    private router: Router
  ) { }
  getToken(): String {
    return sessionStorage.getItem('jwtToken');
  }

  saveToken(token: String) {
    sessionStorage.setItem('jwtToken', token.toString());
  }

  destroyToken() {
    window.localStorage.removeItem('jwtToken');
    sessionStorage.removeItem('CurrentUserName');
    sessionStorage.removeItem("HomePageAccess")
    this.router.navigateByUrl("Login");
  }

}


Filter Witn Class Array Object in angular 2

************Create First Funtion  In Component.ts File *********

transform(items: any[], field: string, value: string): any[] {
    if (!items) return [];
    return items.filter(it => it[field] == value);
  }


----------------------------------------------------
 _GenericClass: GenericClass;//Generic Class Obejct

let objLast = this.transform(this._GenericClass.Data, 'ParentGroup', Value);

Input Only Number in Iput Type in Angular 2


<input type="text"  OnlyNumber="true" > -- Html Code here

First Create Directive.ts File and Put Code Inside

*************************onlynumber.directive.ts***************************

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

@Directive({
  selector: '[OnlyNumber]'
})
export class OnlyNumber {

  constructor(private el: ElementRef) { }

  @Input() OnlyNumber: boolean;

  @HostListener('keydown', ['$event']) onKeyDown(event) {
    let e = <KeyboardEvent>event;
    if (e.which == 13) {
      e.preventDefault();
      var $next = $('[tabIndex=' + (+ parseInt(e.target['tabIndex']) + 1) + ']');
      if (!$next.length) {
        $next = $('[tabIndex=1]');
      }
      $next.focus();
     
    }
    else if (this.OnlyNumber) {

      if ([46, 8, 9, 27, 13,  190].indexOf(e.keyCode) !== -1 ||
        // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) ||
        // Allow: Ctrl+C
        (e.keyCode == 67 && e.ctrlKey === true) ||
        // Allow: Ctrl+X
        (e.keyCode == 88 && e.ctrlKey === true) ||
        // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
        // let it happen, don't do anything
        return;
      }
      // Ensure that it is a number and stop the keypress
      if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
      }
    }
  }
}


/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/

OnlyDiscount Validation in Iput Type in Angular 2

<input type="text"  OnlyDiscount="true" > -- Html Code here

First Create Directive.ts File and Put Code Inside

*************************onlydiscount.directive.ts***************************


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

@Directive({
  selector: '[OnlyDiscount]'
})
export class OnlyDiscount {

  constructor(private el: ElementRef) { }

  @Input() OnlyDiscount: boolean;

  @HostListener('keydown', ['$event']) onKeyDown(event) {
    let e = <KeyboardEvent>event;
    if (e.which == 13) {
      e.preventDefault();
      var $next = $('[tabIndex=' + (+ parseInt(e.target['tabIndex']) + 1) + ']');
      if (!$next.length) {
        $next = $('[tabIndex=1]');
      }
      $next.focus();

    }
    else if (this.OnlyDiscount) {
      var input = <HTMLInputElement>event.srcElement;
      var inputVal = input.value;
      if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39) {
        return true;
      }
      else if (parseInt(inputVal + e.key) > 99) {
        e.preventDefault();
      }
      else if (inputVal.indexOf('.') > -1 && e.key == ".") {
        e.preventDefault();
      }
      else if (parseFloat(inputVal) * 100 % 1 > 0) {
        e.preventDefault();
      }
      else if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
        // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) ||
        // Allow: Ctrl+C
        (e.keyCode == 67 && e.ctrlKey === true) ||
        // Allow: Ctrl+X
        (e.keyCode == 88 && e.ctrlKey === true) ||
        // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
        // let it happen, don't do anything
        return;
      }
      // Ensure that it is a number and stop the keypress
      else if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {

        e.preventDefault();
      }
    }
  }
}


/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/

Allow Only Decimal in Iput Type in Angular 2


 <input type="text"  OnlyDecimal="true" > -- Html Code here

First Create Directive.ts File and Put Code Inside

*************************onlynumberwithdecimal.directive.ts***************************
import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[OnlyDecimal]'
})
export class OnlyDecimal {

  constructor(private el: ElementRef) { }

  @Input() OnlyDecimal: boolean;

  @HostListener('keydown', ['$event']) onKeyDown(event) {
    let e = <KeyboardEvent>event;
    if (e.which == 13) {
      e.preventDefault();
      var $next = $('[tabIndex=' + (+ parseInt(e.target['tabIndex']) + 1) + ']');
      if (!$next.length) {
        $next = $('[tabIndex=1]');
      }
      $next.focus();

    }
    else if (this.OnlyDecimal) {
      var input = <HTMLInputElement>event.srcElement;
      var inputVal = input.value;
      if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39) {
        return true;
      }   
      else if (inputVal.indexOf('.') > -1 && e.key == ".") {
        e.preventDefault();
      }
      else if (parseFloat(inputVal) * 100 % 1 > 0) {
        e.preventDefault();
      }
      else if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
        // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) ||
        // Allow: Ctrl+C
        (e.keyCode == 67 && e.ctrlKey === true) ||
        // Allow: Ctrl+X
        (e.keyCode == 88 && e.ctrlKey === true) ||
        // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
        // let it happen, don't do anything
        return;
      }
      // Ensure that it is a number and stop the keypress
      else if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {

        e.preventDefault();
      }
    }
  }
}


/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/

FileUpload in Angular 2

<input type="file" accept=".Jpg,.Jpeg" id="uploadCaptureInputFile" class="form-control" name="documents" (change)="onChange($event)" [(ngModel)]="_FileType"
            #documents="ngModel">


****************Change Event *************

onChange(event: EventTarget) {
    let formData = new FormData();
    let eventObj: MSInputMethodContext = <MSInputMethodContext>event;
    let target: HTMLInputElement = <HTMLInputElement>eventObj.target;
    let files: FileList = target.files;
    this.file = files[0];
    let formData = new FormData();
    formData.append('FileDocument', this.file);

 return this.http.post(`UrlPath`, formData)
      .map((res: Response) => {        
      });
  }


******************WEB API******************
[HttpPost]
public void GetImage()
{
 var ImageData= System.Web.HttpContext.Current.Request.Files["FileDocument"];
 ImageData.SaveAs(Path);
}

Sharing Folder Access in C#

 public class LockUnLock
    {
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public class LockUnlock : IDisposable
        {
            private readonly SafeTokenHandle _handle;
            private readonly WindowsImpersonationContext _context;

            const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

            public LockUnlock(string domain, string username, string password)
            {
                var ok = LogonUser(username, domain, password,
                               LOGON32_LOGON_NEW_CREDENTIALS, 0, out this._handle);
                if (!ok)
                {
                    var errorCode = Marshal.GetLastWin32Error();
                    throw new ApplicationException(string.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode));
                }

                this._context = WindowsIdentity.Impersonate(this._handle.DangerousGetHandle());
            }

            public void Dispose()
            {
                this._context.Dispose();
                this._handle.Dispose();
            }

            [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
            private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

            public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
            {
                private SafeTokenHandle()
                    : base(true) { }

                [DllImport("kernel32.dll")]
                [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
                [SuppressUnmanagedCodeSecurity]
                [return: MarshalAs(UnmanagedType.Bool)]
                private static extern bool CloseHandle(IntPtr handle);

                protected override bool ReleaseHandle()
                {
                    return CloseHandle(handle);
                }
            }
        }
    }

SqlDataBaseLibrary

using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using AOS.Repository.Infrastructure; using S...