Saturday, 7 July 2018

CRUD operation , all pipes using Angularjs5 and web api2


WEB API :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication2.Models;
using System.Data.Entity;

namespace WebApplication2.Controllers
{
    [RoutePrefix("api/Testservice")]
    public class TestserviceController : ApiController
    {
        [Route("Tests")]
        [HttpGet]
        public IHttpActionResult Tests()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.TESTs.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
           
        }

        [Route("Test/{TID:int}", Name ="Test")]
        [HttpGet]
        public IHttpActionResult Test(int TID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.TESTs.Find(TID));
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }

        [Route("Save")]
        [HttpPost]
        public IHttpActionResult Save(TEST tst)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(tst).State = EntityState.Added;
                    obj.SaveChanges();
                    return Created(new Uri(Url.Link("Test", new { TID = tst.TID })), "Data Saved.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }

        [Route("Update/{TID:int}")]
        [HttpPut]
        public IHttpActionResult Update([FromUri]int TID,[FromBody]TEST tst)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                 
                    obj.Entry(tst).State = EntityState.Modified;
                    obj.SaveChanges();
                    return Ok("Data Updated.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }

        [Route("Delete/{TID:int}")]
        [HttpDelete]
        public IHttpActionResult Delete([FromUri]int TID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {

                    obj.Entry(obj.TESTs.Find(TID)).State = EntityState.Deleted;
                    obj.SaveChanges();
                    return Ok("Data Deleted.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }


    }
}

Angularjs View :

<form class="form-horizontal" #frmTest="ngForm">
    <div class="form-group " [class.has-error]="TID.invalid && TID.touched" [class.has-success]="TID.valid">
        <label class="control-label col-lg-4">TID</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="TID" [(ngModel)]="TEST.TID" #TID="ngModel" required />
            <span class="help-block" *ngIf="TID.invalid && TID.touched">
                TID should not blank.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="NAME.invalid && NAME.touched" [class.has-success]="NAME.valid">
        <label class="control-label col-lg-4">NAME</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="NAME" [(ngModel)]="TEST.NAME" #NAME="ngModel" required />
            <span class="help-block" *ngIf="NAME.invalid && NAME.touched">
                Name should not blank.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="GENDER.invalid && GENDER.touched" [class.has-success]="GENDER.valid">
        <label class="control-label col-lg-4">GENDER</label>
        <div class="col-lg-4">
            <input type="radio"  name="GENDER" [(ngModel)]="TEST.GENDER" #GENDER="ngModel" required value="Male" />Male
            <input type="radio" name="GENDER" [(ngModel)]="TEST.GENDER" #GENDER="ngModel" required value="Female" />Female
            <span class="help-block" *ngIf="GENDER.invalid && GENDER.touched">
                Please select a gender.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="SALARY.invalid && SALARY.touched" [class.has-success]="SALARY.valid">
        <label class="control-label col-lg-4">SALARY</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="SALARY" [(ngModel)]="TEST.SALARY" #SALARY="ngModel" required />
            <span class="help-block" *ngIf="SALARY.invalid && SALARY.touched">
                Salary should not blank.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="DOB.invalid && DOB.touched" [class.has-success]="DOB.valid">
        <label class="control-label col-lg-4">DOB</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="DOB" [(ngModel)]="TEST.DOB" #DOB="ngModel" required />
            <span class="help-block" *ngIf="DOB.invalid && DOB.touched">
                DOB should not blank.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="MARK.invalid && MARK.touched" [class.has-success]="MARK.valid">
        <label class="control-label col-lg-4">MARK</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="MARK" [(ngModel)]="TEST.MARK" #MARK="ngModel" required />
            <span class="help-block" *ngIf="MARK.invalid && MARK.touched">
                Mark should not blank.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="PERCENTAGE.invalid && PERCENTAGE.touched" [class.has-success]="PERCENTAGE.valid">
        <label class="control-label col-lg-4">PERCENTAGE</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="PERCENTAGE" [(ngModel)]="TEST.PERCENTAGE" #PERCENTAGE="ngModel" required />
            <span class="help-block" *ngIf="PERCENTAGE.invalid && PERCENTAGE.touched">
                Percentage should not blank.
            </span>
        </div>
    </div>
    <div class="form-group " >
        <label class="control-label col-lg-4"></label>
        <div class="col-lg-4">
            <input type="button" class="btn btn-primary" value="Save" style="width:80px" (click)="save(frmTest.invalid)" >
            <input type="button" class="btn btn-primary" value="Update" style="width:80px" (click)="update(frmTest.invalid)">
            <input type="button" class="btn btn-primary" value="Reset" style="width:80px" (click)="reset()">
        </div>
    </div>
    <div class="row">
        <table style="width:1000px" class="table table-bordered table-condensed table-hover table-responsive table-striped">
            <thead class="bg bg-primary">
                <tr>
                    <th>Sl No.</th>
                    <th>TID</th>
                    <th>NAME</th>
                    <th>GENDER</th>
                    <th>SALARY</th>
                    <th >DOB</th>
                    <th>MARK</th>
                    <th>PERCENTAGE</th>
                    <th>ACTION</th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let c of list;let i=index">
                    <td>{{i+1}}</td>
                    <td>{{c.TID}}</td>
                    <td>{{c.NAME|uppercase|CusomPipe:c.GENDER}}</td>
                    <td>{{c.GENDER|lowercase}}</td>
                    <td>{{c.SALARY|currency:'UST':false}}</td>
                    <td>{{c.DOB|date:"dd-MMM-y"}}</td>
                    <td>{{c.MARK|number:'1.2-2'}}</td>
                    <td>{{c.PERCENTAGE|percent}}</td>
                    <td>
                        <a (click)="edit(c.TID)">Edit</a> |
                        <a (click)="del(c.TID)">Delete</a>
                    </td>
                </tr>
            </tbody>
        </table>

    </div>
    
</form>

Angularjs Model :

export class ITEST {
    TID: number;
    NAME: string;
    GENDER: string;
    SALARY: number;
    DOB: Date;
    MARK: number;
    PERCENTAGE: number;
}


Angularjs Services :

import { Injectable } from '@angular/core';
import { Http, Headers, Request, Response, RequestOptions, RequestMethod } from '@angular/http';
import { ITEST } from '../test/test.model';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class TestServices {
    constructor(private _http: Http) { }
    Get(tid: number): Promise<ITEST> {
        return this._http.get('http://localhost:3592/api/Testservice/Test/' + tid)
            .map((res: Response) => <ITEST>res.json())
            .toPromise();
    }
    Gets(): Observable<ITEST[]> {
        return this._http.get('http://localhost:3592/api/Testservice/Tests')
            .map((res: Response) => <ITEST[]>res.json());
    }
    Save(doc: ITEST): Promise<string> {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Post, headers: headerOptions });
        return this._http.post('http://localhost:3592/api/Testservice/Save', JSON.stringify(doc), requestOptions)
            .map((res: Response) => <string>res.json())
            .toPromise();
    }
    Update(doc: ITEST): Promise<string> {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Put, headers: headerOptions });
        return this._http.put('http://localhost:3592/api/Testservice/Update/' + doc.TID, JSON.stringify(doc), requestOptions)
            .map((res: Response) => <string>res.json())
            .toPromise();
    }
    Delete(tid: number): Promise<string> {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Delete, headers: headerOptions });
        return this._http.delete('http://localhost:3592/api/Testservice/Delete/' + tid, requestOptions)
            .map((res: Response) => <string>res.json())
            .toPromise();
    }
}

Angularjs Componet :

import { Component, OnInit } from '@angular/core';
import { ITEST } from '../test/test.model';
import { TestServices } from '../test/test.service';

@Component({
  selector: 'app-test-create',
  templateUrl: './test-create.component.html',
  styleUrls: ['./test-create.component.css']
})
export class TestCreateComponent implements OnInit {
  TEST: ITEST;
  list: ITEST[];
  constructor(private _ts: TestServices) { }

  ngOnInit() {
    this.reset();
    this.fill();
  }
  save(isValid: boolean): void {
    if (isValid === false) {
      this._ts.Save(this.TEST).then(data => {
        alert(data);
        this.reset();
        this.fill();
      });
    }
  }
  update(isValid: boolean): void {
    if (isValid === false) {
      this._ts.Update(this.TEST).then(data => {
        alert(data);
        this.reset();
        this.fill();
      });
    }
  }
  fill(): void {
    this._ts.Gets().subscribe(data => this.list = data);
  }
  edit(tid: number): void {
    this._ts.Get(tid).then(data => this.TEST = data);
  }
  del(tid: number): void {
    if (confirm('Do you want to delete it ?')) {
      this._ts.Delete(tid).then(data => {
        alert(data);
        this.fill();
      });
    }

  }
  reset(): void {
    this.TEST = {
      TID: null,
      NAME: null,
      GENDER: null,
      SALARY: null,
      DOB: null,
      MARK: null,
      PERCENTAGE: null
    };
  }
}


Angularjs Custom Pipe :

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

@Pipe({
    name: 'CusomPipe'
})
export class CusomPip implements PipeTransform {
    transform(value: string, gender: string): string {
        if (gender.toLowerCase() === 'male') {
            return 'Mr.' + value;
        } else {
            return 'Miss.' + value;
        }

    }

}



2 comments: