Sunday, 9 June 2019

Continuous Deployment In DevOps

What is Continuous Deployment in DevOps?
Continuous delivery is an automated deployment pipeline with automated and manual gates in between whereas Continuous Deployment is the continuous delivery pipeline with no manual gates in between.

So, Continuous Deployment need not be a ‘Release to Production’. But the code is deployed to the production and kept under mute using ‘Feature Toggles’ and when it is ready, the Feature toggle will be turned on.

These feature toggles avoid any risk of failure of the feature functionality in the production by switching OFF the deployed feature in the production.

Here, I wish to introduce another term of DevOps, that is, continuous Deployment, which should not be confused with continuous delivery because the short form of both is CD.

As we already know, Continuous delivery or CD is the Process of delivering the software or software Updates to the production in smaller increments, ensuring that the software can be released any time to the production.

It is an automated deployment pipeline with both automated and manual gates in between.

Now, let us come to Continuous Deployment.

Continuous deployment is also a continuous delivery pipeline but without any manual gates in between. I mean, no manual gates or no manual intervention, from the initial code commit till the code is into the production.



This picture will explain you the continuous deployment pipeline.

As you see in this diagram, it is same as a continuous delivery pipeline, there will be a build trigger followed by a code check-in, automated compilation, build, unit tests, deployment and other automates tests till the ‘deployment to the production’.

So, there are no manual testing phases or manual approval gates or in other words no manual intervention at all.

This happens mainly in a matured organization and in case of delivery or updates of matured products, where DevOps practices are established very well and hence just automated delivery pipeline is sufficient enough to take care of quality and no manual testing and quality gates are required.

However Feature toggles are necessary for Continuous deployment though present in both the methods, i.,e continuous delivery and continuous deployment, and they are must for Continuous deployment pipeline.

The feature toggles avoid any risk of failure of the feature functionality in the production by switching OFF the deployed feature in the production. So, this feature flag ensures that all the features that are deployed on to the production can be turned ON or OFF based on the requirement and hence need not be immediately released to the end users.

As quoted earlier, continuous deployment need not be necessarily a release to customers but a ‘deployment to production’. This option of continuous deployment is used in deploying certain time-bound features.

To give an Example, a value-added service offer of a mobile operator to the customers, during Christmas, can be deployed via continuous deployment method to production any time, so that the feature or value-added service package is kept ready on the live and opened up during Christmas or at midnight of the new year etc., through a feature toggle.

And this feature can be opened up in production during wee hours or sleeping hours and safely be turned on to the end users later during the day, after ensuring that it is working fine.

Basically, it’s like deploying the code/feature to the production, but not running the code until it is the right time or the team makes a decision to release the code or feature.

This option also allows turning on the feature to a certain set of users or certain geography or certain customer site or even for internal employees for initial evaluation and feedback.

People also refer to the DevOps practice as CI-CD model, where CD refers to continuous delivery, continuous deployment. And this is all about continuous deployment.

Continue Reading →

Continuous Delivery In DevOps

What is Continuous Delivery in DevOps?
Continuous delivery is the important process of delivering the software/Updates to production in smaller increments, ensuring that the software can be released at any time. With this approach of DevOps, the team will be always ready on ‘Delivering any time’ to the production.

So, continuous delivery is a pipeline or a life cycle of a code, where the code newly developed or updated by the software team, gets tested at different stages both through manual and automated tests and passes both the manual and automated stage gates and gets into production.

The main focus and objective of continuous delivery are to build, test and release to the customer quite faster and more frequently, in short cycles.

Given below are the benefits of the CD.
  1. Increases the number of deliveries.
  2. Minimizes the risk of failure in production.
  3. Reduces manual work.
  4. Increases confidence in the team.
  5. Enables the team to automate everything.
  6. Enables faster feedback.
We know that the main objective of DevOps is to deliver continuously with small increments of value to customers.

So, in line with this objective, Continuous Delivery, CD, in short, is something like where the Team is always ready on ‘delivering any time’ to the production, instead of our age-old model of delivering only on the certain committed delivery date and sticking to that date alone.

Thus, continuous delivery is a pipeline or a life cycle of a code, where the code newly developed or updated by the software team, gets tested at different stages both through manual and automated tests and passes both the manual and automated stage gates and gets into production.

The main focus and objective of continuous delivery is to build, test and release to the customer quite faster and more frequently. You know faster and frequently refers to just a few hours in DevOps.

In short, Continuous delivery is an approach of delivering software in short cycles.


CD embraces the total automation for its complete cycle which starts with the code check-in, compiling and building, running automated unit tests, running acceptance testing and till the code is in the production and this pipeline is called ‘Automated deployment pipeline’.


Continue Reading →

Continuous Integration In DevOps

What is Continuous Integration in DevOps?

Continuous integration -> CI ->set of processes ->Build pipeline/CI Pipeline

Continuous Integration, shortly called ‘CI’ in DevOps is an important process or a set of processes which is defined and carried out as a part of a pipeline called ‘Build Pipeline’ or ‘CI Pipeline’.

We know that in the DevOps practice, we have a single version control tool for both Development and Operations team, where everyone’s code will be deposited as a master code base and this allows the team to work in parallel.

So, Continuous Integration, in DevOps is nothing but merging individual developers code into the master copy of the code to the main branch where version control is maintained. There is no restriction on no of times for the code merge that needs to happen in a day.

As and when the developer checks in their code to the version control, immediately the process of CI kick starts.

The CI process includes,
  1. Merging of all the Developers code to the main line,
  2. Triggering a build,
  3. Compiling the code and making a build and ….lastly
  4. Carrying out the unit test.
So, Continuous Integration is a process of merging all the developer’s code to a central location and validating each one of their merges with an automated build and test.

To explain technically what happens during CI is,

There will be a server for continuous integration which hosts the CI tool, which keeps watching the version control tool for the code check-in and as soon as, a check-in is found, it triggers the automated compilation, builds and runs unit testing along with static code analysis and a basic level of automated security testing.

The various tools to carry out the automated testing, like Jenkins, TestNG, NUnit to carry out unit testing, Sonar to carry out static code analysis, and fortify to carry out the security testing, all of these tools will be integrated with the CI pipeline.

So, the complete CI pipeline is an automated process without any manual intervention and runs within a few seconds or minutes.



So, the major benefit of the CI is the rapid feedback that the developers get within no time.

The CI runs after developer checks in the code and throws out the results in seconds. So, it allows the developers to know immediately if his or her code has successfully built or broken.

It also lets the developer know if his code has successfully integrated with the other’s code or broken, that something that another team member has done to a different part of the code base. Hence, CI does the quicker code analysis and makes the later merges simpler and error free.

What are the Benefits of CI?

First of all, the entire CI process is an automated process and hence minimizes the human error by reducing the long, bug-inducing manual merges.

Any number of people can check in their code, any no of times in a day, without waiting for others to complete their coding, wait till they finish their check-in and later check-in. So, CI removes dependency or removes the waiting time of others checks in.

Thus, team members need not have to wait for the other team members to finish their check-in and hence allows to work in parallel.

Every check-in just does not stop at getting collected at the version control, but immediately gets qualified through the build formation and automated testing. So, each check-in is validated at the root itself for further processing.

There is no chance to miss anyone’s code because everyone’s code is checked into the master copy with the time stamp and hence properly recorded.

The entire process of compiling, building and testing runs in few seconds and hence quite quicker and faster and saves a lot of time and hence helps to achieve the DevOps objective of delivering faster over a period of few hours.

Since the entire process of building and testing runs over a few seconds to minutes, the feedback on individuals’ code is very quick and we need not have to run around to find out whose code has broken the build or induced the defect, as with every check-in it gives the success or failure output indicating the area of failure if there is a failure.

So, this allows the developer to check in the small amount of code intermittently, maybe even a single line of code, to ensure that it is error-free and makes the developer to have confidence that their code is good and also does not break others code. So, this in total helps to improve the quality of the code.


Continue Reading →

Wednesday, 5 June 2019

DevOps: Complete Beginners Training

What is DevOps?
DevOps is a culture which promotes collaboration between Development and Operations Team to deploy code to production faster in an automated & repeatable way. The word 'DevOps' is a combination of two words 'development' and 'operations.'
  DevOps is a software development approach which involves Continuous Development, Continuous Testing, Continuous Integration, Continuous Deployment and Continuous Monitoring of the software throughout its development life cycle. These activities are possible only in DevOps, not Agile or waterfall, and this is why Facebook and other top companies have chosen DevOps as the way forward for their business goals. DevOps is the preferred approach to develop high quality software in shorter development cycles which results in greater customer satisfaction. 

Why is DevOps is Needed?
  1. Before DevOps, the development and operation team worked in complete isolation.
  2. Testing and Deployment were isolated activities done after design-build. Hence they consumed more time than actual build cycles.
  3. Without using DevOps, team members are spending a large amount of their time in testing, deploying, and designing instead of building the project.
  4. Manual code deployment leads to human errors in production
  5. Coding & operation teams have their separate timelines and are not in synch causing further delays.
Why is DevOps used?
DevOps allows Agile Development Teams to implement Continuous Integration and Continuous Delivery. This helps them to launch products faster into the market.

Other Important reasons are:
  1. Predictability: DevOps offers significantly lower failure rate of new releases
  2. Reproducibility: Version everything so that earlier version can be restored anytime.
  3. Maintainability: Effortless process of recovery in the event of a new release crashing or disabling the current system.
  4. Time to market: DevOps reduces the time to market up to 50% through streamlined software delivery. This is particularly the case for digital and mobile applications.
  5. Greater Quality: DevOps helps the team to provide improved quality of application development as it incorporates infrastructure issues.
  6. Reduced Risk: DevOps incorporates security aspects in the software delivery lifecycle. It helps in reduction of defects across the lifecycle.
  7. Resiliency: The Operational state of the software system is more stable, secure, and changes are auditable.
  8. Cost Efficiency: DevOps offers cost efficiency in the software development process which is always an aspiration of IT companies' management.
  9. Breaks larger code base into small pieces: DevOps is based on the agile programming method. Therefore, it allows breaking larger code bases into smaller and manageable chunks.
When to adopt DevOps?
DevOps should be used for large distributed applications such as eCommerce sites or applications hosted on a cloud platform.

When not to adopt DevOps?
It should not be used in a mission-critical application like bank, power and other sensitive data sites. Such applications need strict access controls on the production environment, a detailed change management policy, access control policy to the data centers.

DevOps Lifecycle
DevOps is deep integration between development and operations. Understanding DevOps is not possible without knowing DevOps lifecycle.

Here is a brief information about the Continuous DevOps life-cycle:

1. Development
In this DevOps stage the development of software takes place constantly. In this phase, the entire development process is separated into small development cycles. This benefits DevOps team to speed up software development and delivery process.

2. Testing
QA team use tools like Selenium to identify and fix bugs in the new piece of code.

3. Integration
In this stage, new functionality is integrated with the prevailing code, and testing takes place. Continuous development is only possible due to continuous integration and testing.

4. Deployment
In this phase, the deployment process takes place continuously. It is performed in such a manner that any changes made any time in the code, should not affect the functioning of high traffic website.

5. Monitoring
In this phase, operation team will take care of the inappropriate system behavior or bugs which are found in production.

How is DevOps different from Agile? 

DevOps Vs Agile

Stakeholders and communication chain a typical IT process.



Agile addresses gaps in Customer and Developer communications


DevOps addresses gaps in Developer and IT Operations communications



Agile

DevOps
Emphasize breaking down barriers between developers and management.DevOps is about software deployment and operation teams.
Addresses gap between customer requirements and development teams.Addresses the gap between development and Operation team
Focuses more on functional and non-functional readinessIt focuses operational and business readiness.
Agile development pertains mainly to the way development is thought out by the company.DevOps emphases on deploying software in the most reliable and safest ways which aren't necessarily always the fastest.
Agile development puts a huge emphasis on training all team members to have varieties of similar and equal skills. So that, when something goes wrong, any team member can get assistance from any member in the absence of the team leader.DevOps, likes to divide and conquer, spreading the skill set between the development and operation teams. It also maintains consistent communication.
Agile development manages on "sprints. It means that the time table is much shorter (less than a month) and several features are to be produced and released in that period.DevOps strives for consolidated deadlines and benchmarks with major releases, rather than smaller and more frequent ones.
Who is a DevOps Engineer?
A DevOps Engineer is an IT professional who works with software developers, system operators, and other production IT staff to administer code releases. DevOps should have hard as well as soft skills to communicate and collaborate with development, testing, and operations teams.

DevOps approach needs frequent, incremental changes to code versions, which means frequent deployment and testing regimens. Although DevOps engineers need to code occasionally from scratch, it is important that they should have the basics of software development languages.

A DevOps engineer will work with development team staff to tackle the coding and scripting needed to connect elements of code, like libraries or software development kits.

Roles, Responsibilities, and Skills of a DevOps Engineer
DevOps engineers work full-time. They are responsible for the production and ongoing maintenance of a software application's platform.

Following are some expected Roles, Responsibilities, and Skills that is expected from DevOps engineer:
  • Able to perform system troubleshooting and problem-solving across platform and application domains.
  • Manage project effectively through open, standards-based platforms
  • Increase project visibility thought traceability
  • Improve quality and reduce development cost with collaboration
  • Analyse, design and evaluate automation scripts & systems
  • Ensuring critical resolution of system issues by using the best cloud security solutions services
  • DevOps engineer should have the soft skill of problem-solver and quick-learner
More helpfull references: Link1Link2

Continue Reading →

Tuesday, 4 June 2019

ADFS | SSO Solution

Active Directory Federation Services (ADFS) is a Single Sign-On (SSO) solution created by Microsoft. As a component of Windows Server operating systems, it provides users with authenticated access to applications that are not capable of using Integrated Windows Authentication (IWA) through Active Directory (AD).

Developed to provide flexibility, ADFS gives organizations the ability to control their employees’ accounts while simplifying the user experience: employees only need to remember a single set of credentials to access multiple applications through SSO.

How does ADFS work?
ADFS manages authentication through a proxy service hosted between AD and the target application. It uses a Federated Trust, linking ADFS and the target application to grant access to users. This enables users to log onto the federated application through SSO without needing to authenticate their identity on application directly.

The authentication process generally follows these four steps:

  1. The user navigates to a URL provided by the ADFS service.
  2. The ADFS service then authenticates the user via the organization’s AD service.
  3. Upon authenticating, the ADFS service then provides the user with an authentication claim.
  4. The user’s browser then forwards this claim to the target application, which either grants or denies access based on the Federated Trust service created.

Why do companies use ADFS?

ADFS was born out of the need to overcome the authentication challenges created by AD in an increasingly connected online world. AD and IWA have set limitations when it comes to modern authentication, and cannot authenticate users accessing AD integrated applications externally. This is a challenge in the modern workplace, where users often need to access applications that are not owned or managed by their AD organization.

ADFS is able to resolve and simplify these third-party authentication challenges, but does come with certain risks and disadvantages.

ADFS solves the problem of users who need to access AD integrated applications while working remotely, offering a flexible solution whereby they can authenticate using their standard organizational AD credentials via a web interface. It allows users from one organization to access the applications of another organization beyond the realm of their AD domain. Examples include applications in a partner organization or modern cloud services, which now form part of many organizations’ extended IT landscape.

Over 90% of organizations use Active Directory, which means many use ADFS as well.

What are the risks and disadvantages?
ADFS does have its drawbacks, which make it far from an ideal authentication solution. These disadvantages include the hidden infrastructure and maintenance costs, as well as security risks.

Even though ADFS is a free feature on Windows Server, commissioning ADFS requires a Windows Server license and a server to host the ADFS service, which comes at a cost to the organization. Notably, the cost of a server license has increased since the release of Windows Server 2016, with licensing now based on a per core basis.

Hidden maintenance costs
Over and above the direct costs of commissioning ADFS, organizations also need to consider the ongoing operational costs of managing and maintaining an ADFS service. Trusts between AD domains need to be maintained by employees with deep technical skills and ADFS servers need to be patched, updated and backed up on a regular basis. In addition, since ADFS is a critical service, high availability is key. Depending on how it is configured, ADFS can cost more than anticipated: both directly as more infrastructure is required, and indirectly as complexity increases.

Overall complexity
Commissioning, configuring, and maintaining an ADFS solution is not a simple undertaking. Furthermore, each time an application is added to an ADFS service the process is time-consuming and technically intricate, which hinders IT agility.

Security risks
An out-of-the-box, standard install of ADFS is not as secure as it can be. In order to properly secure it, there are multiple steps that IT needs to perform. In addition, as ADFS runs on a Windows Server, that too needs to be hardened and secured to ensure the solution is not at risk.

ADFS vs. Cloud identity

There is no doubt ADFS does have some advantages that make it a popular choice for organizations looking for a federated identity solution. However, ADFS does have distinct disadvantages that cannot be ignored.

Third-party cloud-based identity services can possess features that match, and in some instances surpass, those of ADFS. Cloud identity solutions are more cost effective due to the lower operational overhead needed to run them; beyond that, they have built-in high availability and seamless integration with hundreds of applications. Okta provides secure cloud based identity solutions for its users—solutions that will not only solve authentication challenges, but that will also keep security consistently front-of-mind.

Continue Reading →

Friday, 15 February 2019

Normalization of Database

What is Normalization in SQL ?
Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process: eliminating redundant data (for example, storing the same data in more than one table) and ensuring data dependencies make sense (only storing related data in a table).

Benefits :
  1. Eliminate data redundancy
  2. Improve performance
  3. Query optimization
  4. Faster update due to less number of columns in one table
  5. Index improvement
Types of Normalization

To understand normal forms consider the folowing unnormalized database table. Now we will normalize the data of below table using normal forms.

First Normal Form (1NF)

A database table is said to be in 1NF if it contains no repeating fields/columns. The process of converting the UNF table into 1NF is as follows:
  • Separate the repeating fields into new database tables along with the key from unnormalized database table.
  • The primary key of new database tables may be a composite key
1NF of above UNF table is as follows:

Second Normal Form (2NF)

A database table is said to be in 2NF if it is in 1NF and contains only those fields/columns that are functionally dependent(means the value of field is determined by the value of another field(s)) on the primary key. In 2NF we remove the partial dependencies of any non-key field.

The process of converting the database table into 2NF is as follows:

  • Remove the partial dependencies(A type of functional dependency where a field is only functionally dependent on the part of primary key) of any non-key field.
  • If field B depends on field A and vice versa. Also for a given value of B, we have only one possible value of A and vice versa, Then we put the field B in to new database table where B will be primary key and also marked as foreign key in parent table.
2NF of above 1NF tables is as follows:

Third Normal Form (3NF)

A database table is said to be in 3NF if it is in 2NF and all non keys fields should be dependent on primary key or We can also said a table to be in 3NF if it is in 2NF and no fields of the table is transitively functionally dependent on the primary key.The process of converting the table into 3NF is as follows:
  • Remove the transitive dependecies(A type of functional dependency where a field is functionally dependent on the Field that is not the primary key.Hence its value is determined, indirectly by the primary key )
  • Make separate table for transitive dependent Field.
3NF of above 2NF tables is as follows:

Boyce Code Normal Form (BCNF)

A database table is said to be in BCNF if it is in 3NF and contains each and every determinant as a candidate key.The process of converting the table into BCNF is as follows:

  • Remove the non trival functional dependency.
  • Make separate table for the determinants.
BCNF of below table is as follows:


Fourth Normal Form (4NF)

A database table is said to be in 4NF if it is in BCNF and primary key has one-to-one relationship to all non keys fields or We can also said a table to be in 4NF if it is in BCNF and contains no multi-valued dependencies.The process of converting the table into 4NF is as follows:
  • Remove the multivalued dependency.
  • Make separate table for multivalued Fields.
4NF of below table is as follows:


Fifth Normal Form (5NF)

A database table is said to be in 5NF if it is in 4NF and contains no redundant values or We can also said a table to be in 5NF if it is in 4NF and contains no join dependencies.The process of converting the table into 5NF is as follows:

  • Remove the join dependency.
  • Break the database table into smaller and smaller tables to remove all data redundancy.
5NF of below table is as follows:




Continue Reading →

Thursday, 14 February 2019

Array And ArrayList

Difference Between Array And ArrayList In C#

Array
An Array is a collection of data items of the same type. An Array is reference type so memory for the array is allocated on the heap. We can initialize an Array using the "new" operator and by specifying the type and number of elements inside the Array.

string[] array1=new string[5]; 

ArrayList
ArrayList implements the IList interface. ArrayList is one of the most flexible data structures from C# collection. Collection classes are special classes for data storage and retrieval.

using System.Collection; 

ArrayList a1 = new ArryList(); 
a1.add(null); 
a1.insert(1, ”hi”); 
a1.add(3); 
a1.add(8.23);


Continue Reading →

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.
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 →

Topics

ADFS (1) ADO .Net (2) Ajax (1) Angular (1) Angular Js (17) Angular2 (28) ASP .Net (14) Authentication (1) Azure (1) Breeze.js (1) C# (50) CD (1) CI (2) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DevOps (4) DI (4) Dotnet (22) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (8) Lamda (3) Linq (11) Mongodb (1) MVC (50) NodeJS (7) RDLC (1) Report (1) SDLC (1) Sql Server (30) SSIS (3) SSO (1) SSRS (2) UI (1) WCF (13) Web Api (11) Web Service (1) XMl (1)