Wednesday 23 January 2019

Agile Methodology

What is Agile methodology in project management?
Agile is a process by which a team can manage a project by breaking it up into several stages and involving constant collaboration with Client and Developers at every stage.

The Agile methodology begins with clients describing how the end product will be used and what problem it will solve. This clarifies the customer’s expectations to the project team. Once the work begins, teams cycle through a process of planning, executing, and evaluating — which might just change the final deliverable to fit the customer’s needs better.

In short, Agile is not a set of rules. Agile is not a set of guidelines. Agile is not even a methodology. Rather, Agile is a set of principles that encourage flexibility, adaptability, communication and a working software over plans and processes.

Advantages of Agile Methodology
  1. The customers continuously get a look and feel of the project progress at the end of each iteration/sprint.
  2. Each sprint provides the customer with a working software which meets their expectations as per the definition of done provided by them.
  3. The development teams are quite responsive to the changing requirements and can accommodate changes even in the advanced stages of development.
  4. There is a constant two-way communication which keeps the customers involved, thus all stakeholders – business and technical – have a clear visibility on the project’s progress.
  5. The design of the product is efficient and fulfills the business requirements.
The Stages of the Agile Software Development Life Cycle

6 Stages of the Agile Development Life Cycle
  1. Scope out and prioritize projects
  2. Diagram requirements for the initial sprint
  3. Construction/iteration
  4. Release the iteration into production
  5. Production and ongoing support for the software release
  6. Retirement
1. Scope out and prioritize projects
During the first step of the agile software development life cycle, the team scopes out and prioritizes projects. Some teams may work on more than one project at the same time depending on the department’s organization.

2. Diagram requirements for the initial sprint
Once you have identified the project, work with stakeholders to determine requirements. You might want to use user flow diagrams or high-level UML diagrams to demonstrate how the new feature should function and how it will fit into your existing system.

3. Construction/iteration
Once a team has defined requirements for the initial sprint based on stakeholder feedback and requirements, the work begins. UX designers and developers begin work on their first iteration of the project, with the goal of having a working product to launch at the end of the sprint. Remember, the product will undergo various rounds of revisions, so this first iteration might only include the bare minimum functionality. The team can and will have additional sprints to expand upon the overall product.

4. Release the iteration into production
You’re nearly ready to release your product into the world. Finish up this software iteration with the following steps:

Test the system. Your quality assurance (QA) team should test functionality, detect bugs, and record wins and losses.
Address any defects.
Finalize system and user documentation. Lucidchart can help you visualize your code through UML diagrams or demonstrate user flows so everyone understands how the system functions and how they can build upon it further.
Release the iteration into production.

5. Production and ongoing support for the software release
This phase involves ongoing support for the software release. In other words, your team should keep the system running smoothly and show users how to use it. The production phase ends when support has ended or when the release is planned for retirement.

6. Retirement
During the retirement phase, you remove the system release from production, typically when you want to replace a system with a new release or when the system becomes redundant, obsolete, or contrary to your business model. https://www.lucidchart.com

Agile Vs Waterfall Method
Agile and Waterfall model are two different methods for software development process. Though they are different in their approach, both methods are useful at times, depending on the requirement and the type of the project.

Agile Model Waterfall Model
Agile method proposes incremental and iterative approach to software design Development of the software flows sequentially from start point to end point.
The agile process is broken into individual models that designers work on The design process is not broken into an individual models
The customer has early and frequent opportunities to look at the product and make decision and changes to the project The customer can only see the product at the end of the project
Agile model is considered unstructured compared to the waterfall model Waterfall model are more secure because they are so plan oriented
Small projects can be implemented very quickly. For large projects, it is difficult to estimate the development time. All sorts of project can be estimated and completed.
Error can be fixed in the middle of the project. Only at the end, the whole product is tested. If the requirement error is found or any changes have to be made, the project has to start from the beginning
Development process is iterative, and the project is executed in short (2-4) weeks iterations. Planning is very less. The development process is phased, and the phase is much bigger than iteration. Every phase ends with the detailed description of the next phase.
Documentation attends less priority than software development Documentation is a top priority and can even use for training staff and upgrade the software with another team
Every iteration has its own testing phase. It allows implementing regression testing every time new functions or logic are released. Only after the development phase, the testing phase is executed because separate parts are not fully functional.
In agile testing when an iteration end, shippable features of the product is delivered to the customer. New features are usable right after shipment. It is useful when you have good contact with customers. All features developed are delivered at once after the long implementation phase.
Testers and developers work together Testers work separately from developers
At the end of every sprint, user acceptance is performed User acceptance is performed at the end of the project.
It requires close communication with developers and together analyze requirements and planning Developer does not involve in requirement and planning process. Usually, time delays between tests and coding





Continue Reading →

Sunday 20 January 2019

Angular CRUD Operation- Step by step

Here in this tutorial, I am assuming that you have basic knowledge of Angular 2 or higher version. In this tutorial I am creating a simple demo with crud operation using Angular as frontend and Webapi as backend. In the previous tutorial I already created Api layer Click here. So here I'll create step by step Frontend part that includes Angular Components and Services.

1- First Install NodeJs https://nodejs.org/en/ , and Visual Studio Code for              editor https://code.visualstudio.com/

2- Open VisualStudio Code. Open Terminal window and Install CLI. To install the Angular CLI globally, run the following command on your console npm install -g @angular/cli

3- Create a new project using below command. 
 

     E:\> cd E:\Projects\SOTI\AngularApp
     E:\Projects\SOTI\AngularApp> ng new EmployeeApp

4- Open the project in Editor.


5- Add the Api Url in environment.ts file.

export const environment = {
  production: false,
  apiAddress: 'http://192.168.0.6:81/api'
};


6- Add the below folders in src/app
  1. Employee
  2. Models
  3. Services
7- Add a new class in Models folder named "employee.ts" and add the below Fields.

export class Employee {
    costructor() { }
    EmpId: number;
    FirstName: string;
    LastName: string;
}

8- Now comes to Services folder. Create a new service that interacts with your Api.

ng generate service EmployeeService

Add the below codes in your Service class.

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Http, Headers, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { environment as env } from '../../environments/environment';
import{Employee} from '../Models/employee';

@Injectable({
  providedIn: 'root'
})
export class EmployeeServiceService {
headers: Headers;
  constructor(private http: Http) {
    this.headers = new Headers({ 'content-type': 'application/json' });
   }

   getAll(): Observable<Employee[]> {
    return this.http.get(env.apiAddress + '/Employee')
        .map((res: Response) => res.json())
        .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
  get(id: number): Observable<Employee> {
      return this.http
          .get(`${env.apiAddress}/Employee/${id}`)
          .map((res: Response) => {return res.json();})
          .catch((error: any) => Observable.throw('Server error'));
  }
  add(employee: Employee): Observable<Response> {

      return this.http
          .post(`${env.apiAddress}/Employee`, JSON.stringify(employee), { headers: this.headers })
          .catch((error: any) => Observable.throw('Server error'));
  }
  update(employee: Employee): Observable<Response> {
      return this.http
          .put(`${env.apiAddress}/Employee/${employee.EmpId}`, JSON.stringify(employee), { headers: this.headers })
          .catch((error: any) => Observable.throw('Server error'));
  }
  delete(id: number): Observable<Response> {
      return this.http
          .delete(`${env.apiAddress}/Employee/${id}`)
          .catch((error: any) => Observable.throw('Server error'));
  }
}

If map operator not found then execute the below command in terminal.
npm install --save rxjs-compat@6

9-  Now I will create component for our UI things. comes to src/app/Employee folder. I will add three component for Employee List, Create and Edit. Below is the terminal command.

ng g c Employee --flat --spec false
ng g c CreateEmployee --flat --spec false
ng g c EditEmployee --flat --spec false

the above command will add the class files, html files and style files for each component. See the below Screenshot.


10- Now comes to Employee Listing component. open the employee.component.ts file and add the below code.

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { EmployeeServiceService } from '../Services/employee-service.service';

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

  employees: any[];
  constructor(private empService: EmployeeServiceService,private router: Router) { }

  ngOnInit() {
    this.getAllEmployee();
  }

  getAllEmployee(){
    this.empService.getAll().subscribe((res) => {
      this.employees = res;
    });
  }
  deleteProduct(id: number){
    if(id != undefined && id > 0){
      if(confirm("Are you sure?")){
        this.empService.delete(id).subscribe((res: any) => {
          console.log(res);
          if (res !== undefined) {
            
            this.getAllEmployee();
            alert("Employee has been deleted successfully.")           
          }
        });
      }
     }
    else{alert("Invalid Employee Id")}
   }
}

In the above code I have called the service for fetching and deleting Employee data.
Now add the below html code in employee.component.html to render data.

<h2>Employee Listing</h2>
<a [routerLink]="['/create']" class="btn btn-info">Add new Employee</a>
<hr>
<table class="table table-bordered table-hover">
  <thead>
    <tr>
      <th>Employee ID</th>
      <th>First Name</th>
      <th>Last Name</th>    
      <th>Actions</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let item of employees">
      <!-- <td>{{i+1}}</td> -->
      <td>{{item.EmpId}}</td>
      <td>{{item.FirstName}}</td>
      <td>{{item.LastName}}</td>
      <td>      
          <a [routerLink]="['/Edit', item.EmpId]" class="btn btn-info">Edit</a> | 
          <button type="button" class="btn btn-danger" (click)="deleteProduct(item.EmpId)">Delete</button>  
      </td>
    </tr>
  </tbody>
</table>

11- Now comes to Create Employee component. open the create-employee.component.ts file and add the below code.

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormGroup, FormBuilder, Validators, NgForm } from '@angular/forms';
import { EmployeeServiceService } from '../Services/employee-service.service';
import {Employee} from '../Models/employee';

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

  employee: Employee;
  constructor(private empService: EmployeeServiceService,private router: Router, private route: ActivatedRoute) {
   this.employee = new Employee();
   }

  ngOnInit() {}

  CreateEmployee(form: any)
  {
    if (form.valid) {
    this.empService.add(this.employee).subscribe((res: any) => {
      console.log(res);
      if (res !== undefined) {
        alert("Employee has been added successfully.")
        this.router.navigate(['List']);
      }
    });
  }
  else{alert("Form is invalid.");}
 }
}

In the above code I have called the service for creating new employee data.
Now add the below html code in create-employee.component.html to creating form.

<p>
  create-employee !
</p>
<a class="btn btn-default" href=".">Back to Employee list</a>

<form #form="ngForm" class="form-horizontal" (ngSubmit)="CreateEmployee(form)">
    <div class="form-group">
      <label class="col-sm-2">First name</label>
      <div class="col-sm-10">
        <input type="text" #FirstName="ngModel" name="FirstName" [(ngModel)]="employee.FirstName" required class="form-control">
        <div *ngIf="FirstName.errors && (form.submitted || FirstName.dirty)" class="text-danger">
            <span [hidden]="!FirstName.errors.required">Please Enter First Name</span>
        </div>
        
      </div>
    </div>
    <div class="form-group">
      <label class="col-sm-2">Last name</label>
      <div class="col-sm-10">
        <input type="text" #LastName="ngModel" name="LastName" [(ngModel)]="employee.LastName" required class="form-control">
        <div *ngIf="LastName.errors && (form.submitted || LastName.dirty)" class="text-danger">
            <span [hidden]="!LastName.errors.required">Please Enter Last Name</span>
        </div>
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-10 col-sm-offset-2">
        <button type="submit" class="btn btn-primary">Save</button>
      </div>
    </div>
  </form>

12- Now comes to Edit employee component. open the edit-employee.component.ts file and add the below code.

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormGroup, FormBuilder, Validators, NgForm } from '@angular/forms';
import { EmployeeServiceService } from '../Services/employee-service.service';
import {Employee} from '../Models/employee';

@Component({
  selector: 'app-edit-employee',
  templateUrl: './edit-employee.component.html',
  styleUrls: ['./edit-employee.component.css']
})
export class EditEmployeeComponent implements OnInit {
  employee: Employee;
  id: number;
  constructor(private empService: EmployeeServiceService,private router: Router, private route: ActivatedRoute) {
    this.employee = new Employee();
    this.route.params.subscribe((params) => {
    this.id = params.id;
   });
  }

  ngOnInit() {
    this.FillEmployee();
  }

  FillEmployee()
  {
    this.empService.get(this.id).subscribe((res) => {
      console.log(res);
      this.employee = res;
    });
  }

  UpdateEmployee(form: any)
  {
    if (form.valid) {
      this.empService.update(this.employee).subscribe((res: any) => {
        console.log(res);
        if (res !== undefined) {
          alert("Employee has been updated successfully.")
          this.router.navigate(['List']);
        }
      });
    }
    else{alert("Form is invalid.");}
  }
}

In the above code I have called the service for updating the existing employee data.
Now add the below html code in edit-employee.component.html for editing the data.

<p>
 Edit Employee
</p>
<a class="btn btn-default" href=".">Back to Employee list</a>

<form #form="ngForm" class="form-horizontal" (ngSubmit)="UpdateEmployee(form)">
    <div class="form-group">
      <label class="col-sm-2">First name</label>
      <div class="col-sm-10">
        <input type="text" #FirstName="ngModel" name="FirstName" [(ngModel)]="employee.FirstName" required class="form-control">
        <div *ngIf="FirstName.errors && (form.submitted || FirstName.dirty)" class="text-danger">
            <span [hidden]="!FirstName.errors.required">Please Enter First Name</span>
        </div>
      </div>
    </div>
    <div class="form-group">
      <label class="col-sm-2">Last name</label>
      <div class="col-sm-10">
        <input type="text" #LastName="ngModel" name="LastName" [(ngModel)]="employee.LastName" required class="form-control">
        <div *ngIf="LastName.errors && (form.submitted || LastName.dirty)" class="text-danger">
            <span [hidden]="!LastName.errors.required">Please Enter Last Name</span>
        </div>
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-10 col-sm-offset-2">
        <button type="submit" class="btn btn-primary">Update</button>
      </div>
    </div>
  </form>

13- Add the Routing module in src/app folder. use the below command.

ng generate module app-routing --flat --module=app


Add the below codes in the app-routing.module.ts file.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import{EmployeeComponent} from '../app/Employee/employee.component';
import {CreateEmployeeComponent} from '../app/Employee/create-employee.component';
import {EditEmployeeComponent} from '../app/Employee/edit-employee.component';

const routes: Routes = [
  { path: '', component: EmployeeComponent },
  { path: 'List', component: EmployeeComponent },
  { path: 'Edit/:id', component: EditEmployeeComponent },
  { path: 'create', component: CreateEmployeeComponent  }
];

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

14- Now run your application using ng serve command.


15- 

Download the complete angular project. Click here



Continue Reading →

Friday 18 January 2019

WebApi CRUD Operation- Step by step

In this tutorial, I am assuming you have basic knowledge of asp.net MVC, Web Api, Entity Framework.

1- Open Visual Studio 2015. Create a new Webapi project.


2- Add a new WebApi Controller named EmployeeController.cs.


3- Add a Repository Folder in the solution. add a IEmployeeRepo.cs interface and EmployeeRepo.cs class in the folder. (See above image)

4- Create Database and table in Sql server. below is the script.

CREATE DATABASE [EmployeeDB]
USE [EmployeeDB]
CREATE TABLE [dbo].[tblEmployee](
 [EmpId] [int] IDENTITY(1,1) NOT NULL,
 [FirstName] [varchar](50) NULL,
 [LastName] [varchar](50) NULL,
 CONSTRAINT [PK_tblEmployee] PRIMARY KEY CLUSTERED 
(
 [EmpId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET IDENTITY_INSERT [dbo].[tblEmployee] ON 
INSERT [dbo].[tblEmployee] ([EmpId], [FirstName], [LastName]) VALUES (1, N'Suraj', N'Kumar')
INSERT [dbo].[tblEmployee] ([EmpId], [FirstName], [LastName]) VALUES (2, N'Rahul', N'Raj')
INSERT [dbo].[tblEmployee] ([EmpId], [FirstName], [LastName]) VALUES (3, N'Amit', N'Kumar')
SET IDENTITY_INSERT [dbo].[tblEmployee] OFF

5- Add  EmployeeModel.cs class in the Model Folder.



6- Here we are using Database first approach for Entity framework so you need to add Datamodel file (.edmx).


7- Now add the below code in IEmployeeRepo.cs file.

    public interface IEmployeeRepo
    {
        List<EmployeeModel> GetAllEmp();
        void AddEmployee(EmployeeModel entity);
        void DeleteEmployee(int id);
        void UpdateEmployee(int id, EmployeeModel model);
        EmployeeModel FindByEmpId(int Id);
    }

8- Implement this interface in EmployeeRepo.cs class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EmployeeWeb.Models;

namespace EmployeeWeb.Repository
{
    public class EmployeeRepo : IEmployeeRepo
    {
        EmployeeDBEntities EmpContext;
        List<EmployeeModel> EmpObj = new List<EmployeeModel>();
        public EmployeeRepo()
        {
            EmpContext = new EmployeeDBEntities();
        }

        public List<EmployeeModel> GetAllEmp()
        {
            return MapList(EmpContext.tblEmployees.ToList());
        }

        public List<EmployeeModel> MapList(List<tblEmployee> model)
        {
            List<EmployeeModel> obj = new List<EmployeeModel>();
            foreach (var item in model)
            {
                EmployeeModel emp = new Models.EmployeeModel();
                emp.EmpId = item.EmpId;
                emp.FirstName = item.FirstName;
                emp.LastName = item.LastName;
                
                obj.Add(emp);

            }
            return obj;
        }

        public EmployeeModel FindByEmpId(int Id)
        {
            var result = (from r in EmpContext.tblEmployees where r.EmpId == Id select r).FirstOrDefault();
            return MapEntityToModelModel(result);
        }

        public EmployeeModel MapEntityToModelModel(tblEmployee emp)
        {
            EmployeeModel model = new Models.EmployeeModel();
            model.EmpId = emp.EmpId;
            model.FirstName = emp.FirstName;
            model.LastName = emp.LastName;
            return model;
        }


        public void AddEmployee(EmployeeModel model)
        {
            EmpContext.tblEmployees.Add(MapModelToEntityModel(model));
            EmpContext.SaveChanges();
        }

        public tblEmployee MapModelToEntityModel(EmployeeModel emp)
        {
            tblEmployee model = new Models.tblEmployee();
            //model.EmpId = emp.EmpId;
            model.FirstName = emp.FirstName;
            model.LastName = emp.LastName;
            return model;
        }


        public void DeleteEmployee(int id)
        {
            var emp = EmpContext.tblEmployees
                 .Where(s => s.EmpId == id)
                 .FirstOrDefault();

            EmpContext.Entry(emp).State = System.Data.Entity.EntityState.Deleted;
            EmpContext.SaveChanges();
        }

        public void UpdateEmployee(int id, EmployeeModel model)
        {          
            var existingEmp = EmpContext.tblEmployees.Where(s => s.EmpId == id)
                                                   .FirstOrDefault<tblEmployee>();
            if (existingEmp != null)
            {
                existingEmp.FirstName = model.FirstName;
                existingEmp.LastName = model.LastName;
                EmpContext.Entry(existingEmp).State = System.Data.Entity.EntityState.Modified;
                EmpContext.SaveChanges();
            }
        }
    }
}

9-  Now you need to call your repository functions from Employee api controller.

using System.Net;
using System.Net.Http;
using System.Web.Http;
using EmployeeWeb.Models;
using EmployeeWeb.Repository;
using System.Web.Http.Cors;

namespace EmployeeWeb.Controllers
{
    [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
    public class EmployeeController : ApiController
    {
        public IEmployeeRepo repository = null;   
        public EmployeeController()
        {
            repository = new EmployeeRepo();
        }

        // GET: api/Employee
        public HttpResponseMessage Get()
        {
            var result = repository.GetAllEmp();
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        // GET: api/Employee/5
        public HttpResponseMessage Get(int id)
        {
            var result = repository.FindByEmpId(id);

            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        // POST: api/Employee
        public HttpResponseMessage Post(EmployeeModel model)
        {
            repository.AddEmployee(model);
            return Request.CreateResponse(HttpStatusCode.Created);
        }

        // PUT: api/Employee/5
        public HttpResponseMessage Put(int id, EmployeeModel model)
        {
            repository.UpdateEmployee(id, model);
            return Request.CreateResponse(HttpStatusCode.OK);
        }

        // DELETE: api/Employee/5
        public HttpResponseMessage Delete(int id)
        {
            repository.DeleteEmployee(id);
            return Request.CreateResponse(HttpStatusCode.OK);
        }
    }
}

10- Add some extraa code in Register function of Webapi config to return api data in json format and to enable CORS.

   public static void Register(HttpConfiguration config)
        {
            config.EnableCors(); // Enables CORS

            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Formatters.Remove(config.Formatters.XmlFormatter);
        }

11- Change the below property for EmpId column in edmx file.


12- Now build and run your solution. Your Api is ready for functioning. Test the Api with any RestClient.


13- See the result of above request.


14- Below is the request for Post method.


15- Below is the request of update method. Here I'm updating the employee of EmpId= 5.



Let me know if you have any concern in this tutorial. Download the complete project. Click here









Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives