Lifecycle hooks in Angular

Angular2 is the trending UI framework that enable you to create rich interface using typescript.

Angular2 application are the collection of components.

Like every framework it has to go through a life cycle, here in angular we called it life cycle hook. Its important to have a idea where to use these life cycle hooks. So in this blog I tried to provide an idea where to use them.

List of life cycle hooks are given below:

  1. ngOnChanges
  2. ngOnInit
  3. ngDoCheck
  4. ngAfterContentInit
  5. ngAfterContentChecked
  6. ngAfterViewInit
  7. ngAfterViewChecked
  8. ngOnDestroy

Whenever a component is loaded its constructor called first before any other life cycle hook. That is the place where we inject dependencies if any .

Example
import { Component } from ‘@angular/core’;

import { Items } from ‘../Service/items’

@Component({

selector: ‘selector-Name’,

templateUrl: ‘./my.component.html’,

styleUrls: [‘./my.component.css’]

})

export class MyAppComponent {

item:any

constructor(private items:Items){}

}

Above is a sample component where we inject our dependencies in constructor we also called it as Dependencies Injection DI.

It is recommend not to use complex logic in the constructor. And that can handle in life cycle hook.

Lets say we want to get the list of item available that can also be done in constructor like

constructor(private item:Items){

this.item=this.items.getItem();

}

But its advisable by angular team not to write logic in constructor. So we can implement ngOnInit hook to get items data as shown in code below

import { Component,OnInit } from ‘@angular/core’;

export class MyAppComponent implements OnInit

{   item:any

   constructor(private items:Items){}

  ngOnInit(): void {

  this.item=this.items.getItem();

}}

Well its your choice to use interface here. If you don’t want to implement interface you can skip that and directly use ngOnInit(). But to get intelliSense and we should make it a practice to use interface.

Above is an example about how a hook can be called . Similarly we have 7 other hook lets go through it one by one.

1.ngOnChanges:

This is called on Input Properties of a component before we bind them to the View.

Suppose I want to filter my item list and show the item that matches over filter criteria we can do that

//import and @component

export class ItemListComponent implements OnChanges {

@Input() filterBy: string

constructor(private items:Items) {

}

ngOnChanges() {

if (this.items) {

this.filterItem(this.filterBy)

—-rest of the logic

}

}

filterItem(filter){

//logic

}

}

this filterBy properties will be used in templates and it check the DOM if any changes happen in components it update the DOM with the result.

This hook is the first hook that is called in the hook life cycle after that ngOnInit is called.

2. ngOnInit : As we already gave an example if this hook. I am adding one more thing is that this hook run only one time after initializing component’s properties so any this you want to initialize at first should be done here.

3. ngDoCheck: This hook is called after ngOnInit hook the responsibility is to check any changes in the property . This can be easily be confused with ngOnChanges so I am taking this from AngularIo official site “Detect and act upon changes that Angular can’t or won’t detect on its own .Called during every change detection run, immediately after ngOnChanges()and ngOnInit().”.

4. ngAfterContentInit: After ngDoCheck hook, ngAfterContentInit called . This hook is for component of angular applications and called after angular updates the component view values. This is called after component’s external content has been initialize. External Components like content projection

5. ngAfterContentChecked:This is called when a content of a component changed and called after every ngDoCheck hook.

6. ngAfterViewInit: When Component view is fully initialize(components and child view) then this hook invoked and called after ngAfterContentChecked.

7. gAfterViewChecked: This can be called where we want to check the changes in DOM after data of a component is updated. Suppose I want to use jQuery in angular app and show the bootstrap tooltip.

example

gAfterViewChecked () {

$(function () {

$(‘[data-toggle=”tooltip”]’).tooltip()

})

7. ngOnDestroy : This hook is used to destroy components or directives and also unsubscribe the Observable.

Example

@Input(‘edit’) editClicked: Subject<any>;

ngOnInit () {

this.item = this.editClicked.subscribe((vendor) => {

this.itemInfo();

});

}

ngOnDestroy () {

this.item.unsubscribe();

}

Hope you like the article. For reference I used many links but mainly angular.io

Thanks

Advertisements

How to use Entity Framework code first with MySql using Visual studio 2015

Hello everyone, this article is targeted to .net developer who wants to use Mysql as a back end and entity framework  as ORM with code-first approach.
Minimum Requirement

  • VS2015
  • MySqlConnector with Visual Studio

If you don’t have MySql Connector in your system download from this link and install

https://dev.mysql.com/downloads/windows/visualstudio/

I have created a console application for this demo.

After adding a console application  add these packages by using Nuget.

  1. EntityFramework version 6.0.0
  2. MySql.Data 6.9.9
  3. MySql.Data.Entities 6.8.3
  4. MySql.Data.Entity. 6.8.8 (I have faced some issue with the latest version of this dll so I have used 6.8.8 ).

Now add connection string to your appconfig

<connectionStrings>

<add name=MyConnection connectionString=server=localhost;uid=root;pwd=****;database=EmployeeDb providerName=MySql.Data.MySqlClient />

connectionStrings>

Now add a class file

Employee.cs

and add this code

EmployeeClass

Create class that inherit DbContext class and add this code

dbcontext

Now run Migration command through nuget package manager console

You can open it from Tools->Nuget Package Manager->Package Manager Console.

Run commands

1. Enable-migrations

check a file will be added Configuration.cs under Migrations Folder

Add this line in Configuration constructor

2. SetSqlGenerator(“MySql.Data.MySqlClient”, new MySql.Data.Entity.MySqlMigrationSqlGenerator());

3. Add-Migration initial  // to add migration or to create fresh script

 

And you also noticed that in your console application, under Migrations Folder a temp file is created. This file will get modified automatically each time we update our database.

migrationsFolder

4. update-database// to update the changes in database

Now before running the migration commands your mysql look was like.

mysqlImagebeforemigration

And after running  migration you will notice that your data base  has created as shown below

afterMigration

So these are the steps required to achieve the desired result.

Hope you liked it.

How To Setup Angular2 in Visual Studio IDE

As a .net developer we always want that we can develop our application in Visual Studio IDE . So in this article our main focus is to add Angular2 with typescript project in VS IDE.

To do that we must have these thing installed in our machine

  • Node.js ( greater than version 4.6.*) and (npm greater than version 3.*.*).

  • Visual Studio 2015 Update 3

  • Install Typescript 2 for VS2015 from link download typescript from here

Note : We need to configure External web tool as mention in the image.

vs-external-tool

Now what we are doing here we add the the demo project provided by Angular team in the IDE and try to run it under IDE. We can download from here.

To run an Angular2 without IDE we need two command

npm install : this install all the required files in the project.

npm start : to start the application.

When we use Angular2 in IDE we don’t need to use these command.

Now we have all the dependent things installed so we can start to add Angular2 in VS IDE

Open new project ASP.NET Web Application (.net framework) and make sure the framework is 4.5.2.

open

Select any template, here I have selected Empty template.

Now go to the project location and copy the Quick Start project same place where you have your csproj file.location

Now go to the solution explorer and include these folder or file in the project under Quick Start.

  • app
  • style.css
  • Index.html
  • package.json
  • tsconfig.json
  • IDE can ask for search typescript typings select NO

Now next step is to restore angular packages. For that go to solution explorer and right click on package.json and select restore packages option. If that won’t work than this can be done be done by using npm install command.

Both the process take time as package take time to install.

Now select Index.html as default page and run the application if all steps is taken care of than we have “Hello Angular” message in the browser.

 

 

 

 

How to Use Ninject Dependency Injection in MVC

While working on MVC application in asp.net sometime we need to inject dependency also know as DI(Dependency Injection).

DI is itself a separate topic to study which I left for some other day. If you want to know more about DI

can refer to this link.

https://msdn.microsoft.com/en-us/library/ff921152.aspx

According to the wikipedia

In software engineeringdependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it.

To inject dependencies we have DI librabry like Ninject ,Unity

In this article I am going to explain how to Add Ninject in our project and how to use.

What I have used is VS2013.

I have entity Product

ProductEntity

Now I am creating Interface

Interface
IProductRepository

Now I need to implement this interface . To implement that I have creating new class ProductRepository

prod_repos
Implement Interface

Now I want to inject dependency but for that I need download some nuget package

  1. Ninject
  2. Ninject.Web.Common
  3. Ninject.Web.MVC
  4. WebActivator

When this Ninject.Web.Common dll is added a new class file “NinjectWebCommon.cs” will be added in

AppStart

NinjectWebCommon

with these information

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(ShoppingApi.App_Start.NinjectWebCommon), “Start”)]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(ShoppingApi.App_Start.NinjectWebCommon), “Stop”)]

namespace ShoppingApi.App_Start
{
using System;
using System.Web;

using Microsoft.Web.Infrastructure.DynamicModuleHelper;

using Ninject;
using Ninject.Web.Common;

public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();

/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}

/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}

/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}

/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name=”kernel”>The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
System.Web.Mvc.DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}
}
}

In RegisterServices method I need to add register my dependency. That I have done in

my class NinjectDependencyResolver by implementing interface IdependencyResolver

the class would be like

using Ninject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ShoppingApi.InfraStructure
{
public class NinjectDependencyResolver:IDependencyResolver
{
IKernel kernel = null;
public NinjectDependencyResolver(IKernel kernelParam ){
kernel=kernelParam;
AddBinding();
}

private void AddBinding()
{
kernel.Bind<IProductRepository>().To<EFProductRepository>();
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}

public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
}
}

In AddBinding() method add the binding you want to add.

Now I want to use in my controller.  I have use Parametrized constructor to set the value

public class AdminController : Controller
{
private IProductRepository repository;

public AdminController(IProductRepository prodRepository)
{
repository = prodRepository;
}

// GET: Admin
//[AllowAnonymous]
public ActionResult Index()
{

return View(repository.Products);
}

public ViewResult Edit(int productID)
{
var product=repository.Products.FirstOrDefault(p=>p.ProductId.Equals(productID));
return View(product);
}

public ViewResult AddNewItem()
{
return View();
}

[HttpPost]
public ActionResult AddNewItem(Product product)
{
if(ModelState.IsValid){
repository.SaveProduct(product);
TempData[“Message”] = string.Format(“Item {0} is successfully Added”, product.Name);
return RedirectToAction(“Index”);
}
else {
TempData[“Message”] = string.Format(“Item {0} is not Added”, product.Name);
return View(product);
}

}

[HttpPost]
public ActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
repository.SaveProduct(product);
TempData[“Message”] = string.Format(“Item {0} is successfully saved”, product.Name);
return RedirectToAction(“Index”);
}
else
{
return View(product);
}
}

[HttpPost]
public ActionResult Delete(int productID)
{
Product deleteProduct = repository.DeleteProduct(productID);
if (deleteProduct != null)
{
TempData[“Message”] = string.Format(“Item {0} is successfully Deleted”, deleteProduct.Name);

}
return RedirectToAction(“Index”);
}
}

Yes its that easy to implement. Hope that helpful for you.

Note: In WebApi we can also use Ninject but it is not the same way . This is for next article 🙂

Types of SQL Command

Introduction To Database Testing

In SQl, we have commands by using them we can talk to the SQL server.

These command can be categorized into four type:

  • Data Definition Language (DDL)
  • Data Manipulation Language (DML)
  • Data Control Language (DCL)
  • Transaction Control Language (TCL)

In the blog I am going to use abbreviation instead of using full name of the command type

What is DDL?

As the name suggest DDL commands are the commands that are used to define or modify the structure of the database object in a data base.

To store any data in a database what we need , we need a structure (database, tables , columns) and to create these objects we use DDL command. Few DDL commands are

Create : to create an object like to create new table we have a syntax like

Create table <tablename>(<columnname datatype(size)>) ;

Alter : If…

View original post 221 more words

ASP.NET Web API — Part 1

Hello All,

For Asp.net Web API, I am going to write a series of technical articles. Few of them will cover conceptual point, few will cover demos and in few of them, I will try to dig deep into it by covering important technical point like routing, hosting, security stuff.

So in this series of articles, Lets start with light node, what is ASP.NET Web API and why we should go for it.

What ?

So ASP.NET Web API is a framework that help in building HTTP services that can be consumed by clients like browsers , smart phones

Why ?
According to Wikipedia: API is the application programming Interface(API) for both web server and web browser.

I think definition needs to update, as the technology is growing and expanding with a rapid pace
services that we build are not only consumed by browsers but also mobile application need to communicate with the server, so for that they needs an interface that enabled these apps to interact with the server.

As Web API are simple light weighted and easy to parse .
ASP.NET Web API provide a platform to build a RESTfull Application.

Now question is what is RESTfull services?

REST (Representational State Transfer) and RESTfull applications(like Web API) uses HTTP Request to do its CRUD operation. The advantages are :

  • Platform Independence
  • Standard as run on top of HTTP
  • Language Independence

Currently we have version ASP.NET Web API 2.2:
which have the new feature like ODATA v4 Web API Client support for Window Phone 8.1
for detail about that please go to this link

http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-22

Stay tuned, I will be back with next article soon. 🙂

I have also post the same blog for my company :

http://unwrapdotnet.wordpress.com/2014/09/11/asp-net-web-api-part-1/