Angular 6 : Component Communication using @Input, @Output and EventEmitter


Angular 6 : Component Communication using @Input, @Output and EventEmitter


Below example is implemented to communicate parent and child component using @Input, @Output and EventEmitter.

Model class
export class country{
    ID : number;
    Name : string;
}

parent.component.ts
import { ComponentOnInit } from '@angular/core';
import { country } from 'src/app/Model/Country';
@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit { 
  namestring = "DemoName";  
  vmCountrycountry
  receivedChildMessagestring;  
  receivedChildAnotherMessagecountry;
  constructor() { }
  ngOnInit() {
    this.vmCountry = new country();
    this.receivedChildAnotherMessage = new country();
    this.vmCountry.Name = "India"
  }
  
  getMessage(messagestring) {
    this.receivedChildMessage = message
  }
  getAnotherMessage(varCountry : country) { 
    this.receivedChildAnotherMessage = varCountry
  } 
}

parent.component.html
<h1>
  parent works! test
</h1>
<app-child [name]="name" [varCountry]="vmCountry" 
          (messageToEmit)="getMessage($event)" 
          (anotherMessageToEmit)="getAnotherMessage($event)"></app-child> 
<div class="row">
  <div class="col-md-2">
      {{receivedChildMessage}}
  </div>
  <div class="col-md-2">
      {{receivedChildAnotherMessage.Name}}
    </div>
</div>

child.component.ts
import { ComponentOnInitInputEventEmitterOutput } from '@angular/core';
import { country } from 'src/app/Model/Country';
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  @Input() namestring;
  @Input() varCountrycountry;
  @Output() messageToEmit = new EventEmitter<string>();
  @Output() anotherMessageToEmit = new EventEmitter<country>();
  
  constructor() { }
  ngOnInit() {
    
  }
  sendMessageToParent(messagestring) {
    this.messageToEmit.emit(message)
  }
  sendAnotherMessageToParent() {
    this.varCountry = new country;
    this.varCountry.ID = 10;
    this.varCountry.Name = "Japan";
    this.anotherMessageToEmit.emit(this.varCountry)
  }
}

child.component.html
<p>
  child works {{name}}!
</p>
<h1>{{varCountry.Name}}</h1>
<div class="row">
  <div class="col-md-2">
    <button (click)="sendMessageToParent('message from child')">Send to Parent</button>
  </div>
  <div class="col-md-2">
    <button (click)="sendAnotherMessageToParent()">Another Send to Parent </button>
  </div>
</div>


app.module.ts
@NgModule({
  declarations: [   
    ParentComponent,
    ChildComponent,
    .....
  ],
  .....
})


Hope this will help you and save your time.

Enjoy !!!

:)

Angular 6 : Parent and Child component

Angular 6 : Parent and Child component



Here is sample code, how to use parent and child component in angularjs 6.

Model Class

export class country{
    ID : number;
    Name : string;
}

Parent Component

parent.component.ts

  name : string = "DemoName";
  vmCountry : country;
  
  constructor() { }

  ngOnInit() {
    this.vmCountry = new country();
    this.vmCountry.Name = "India";
  }

parent.component.html

<div>
  Some html here
</div>

<app-child [name]="name" [varCountry]="vmCountry"></app-child> 

<div>
  Some html here
</div>

another action, so we can get it as below,

 "expression": {
 "and": [
  {
  "equals": [
   "@outputs('HttpStepName')['body']?['ResultCode']",
   "OK"
  ]
  }
 ]
},

Child Component


child.component.ts

  @Input() name : string;
  @Input() varCountry:country;

  constructor() { }

  ngOnInit() {
  }

child.component.html

<p>
  child works {{name}}!  
</p>
<h1>{{varCountry.Name}}</h1>

app.module.ts

@NgModule({
  declarations: [
    ....
    ParentComponent,
    ChildComponent
  ],  
  .....  
  })

Hope this will help you and save your time.

Enjoy !!!

:)

.Net Core : Enable CORS in ASP.net Core WebAPI

.Net Core : Enable CORS in ASP.net Core WebAPI


Enable CORS in ASP.net Core WebAPI


In ConfigureServices method

  public void ConfigureServices(IServiceCollection services)
        { 
            services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
            {
                builder.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader();
            }));

            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreDB")));
             
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

In Configure method

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            } 
            app.UseAuthentication();

            app.UseCors(
                options => options.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
            );
 
            app.UseMvc();
        }


Hope this will help you and save your time.

Enjoy !!!

:)

.Net Core : Unit Test with NUnit

.Net Core : Unit Test with NUnit


Below example is implemented with Nunit test to test .net core project feature.

Create test class,

namespace DotNetCoreDemo.Test
{
    public class EmployeeServiceTest
    {
        
    }
}

OneTimeSetUp 

 IEmployeeService employeeService;
        public Mock<IEmployeeRepository> mockEmployeeRepository;
        
        [OneTimeSetUp]
        public void Init()
        {
            mockEmployeeRepository = new Mock<IEmployeeRepository>();
            employeeService = new EmployeeService( this.mockEmployeeRepository.Object);
        }

Data Sources for test cases,

static object[] employeeSource =
        {
            new object[]
            {
                new Employee[]
                {
                    new Employee()
                    {
                        Id = 1, Name = "demo1", Email = "demo1@demo.com"
                    },
                    new Employee()
                    {
                        Id = 2, Name = "demo2", Email = "demo2@demo.com"
                    }
                } 
            }
        };

        static object[] employeeSourceNull =
        {
            new object[]
            {
                new Employee[]
                {
                    
                }
            }
        };

Test for get data,

 [Test, TestCaseSource("employeeSource")]
        public void GetEmployeeList_Return_True(Employee[] employees)
        {
            //Init            
            mockEmployeeRepository.Setup(p => p.GetAllEmployee()).Returns(employees.AsQueryable().ToList());
            
            //Act
            List<Employee> result  = employeeService.GetAllEmployee().ToList();

            ////Assert
            Assert.Greater(result.Count, 0);
        }

Test for no data,

[Test, TestCaseSource("employeeSourceNull")]
        public void GetEmployeeList_NoData_Return_True(Employee[] employees)
        {
            //Init            
            mockEmployeeRepository.Setup(p => p.GetAllEmployee()).Returns(employees.AsQueryable().ToList());

            //Act
            List<Employee> result = employeeService.GetAllEmployee().ToList();

            ////Assert
            Assert.AreEqual(result.Count, 0);
        }


Hope this will help you and save your time.

Enjoy !!!

:)

.Net Core : Host ASP.NET Core on Windows with IIS

.Net Core : Host ASP.NET Core on Windows with IIS



Please follow steps given in document,


Hope this will help you and save your time.

Enjoy !!!

:)

.Net Core : Token based Authentication in webAPI

.Net Core : Token based Authentication in webAPI



Startup.cs


public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreDB")));

            services.AddIdentity<IdentityUser, IdentityRole>()
                    .AddEntityFrameworkStores<AppDbContext>()
                    .AddDefaultTokenProviders();

            services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(options =>
                {
                    options.SaveToken = true;
                    options.RequireHttpsMetadata = false;
                    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidAudience = "http://mydomain.com",
                        ValidIssuer = "http://mydomain.com",
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret 1234567890 phase"))
                    };
                });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();

            app.UseMvc();
        }

EmployeeController.cs


[Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class EmployeeController : Controller
    {
        private readonly UserManager<IdentityUser> userManager;
        private readonly SignInManager<IdentityUser> signInManager;

        public EmployeeController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
        { 
            this.userManager = userManager;
            this.signInManager = signInManager;
        } 

        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return userManager.Users.Select(u => u.UserName).ToArray();
        }

        [HttpPost]
        [AllowAnonymous]
        [Route("Register")]
        public async Task<JsonResult> Post(VMRegister vmRegister)
        {
            IdentityResult result = new IdentityResult();
            string errorMessage = "success";

            if (ModelState.IsValid)
            {
                var user = new IdentityUser
                {
                    UserName = vmRegister.EmailId,
                    Email = vmRegister.EmailId
                };

                result = await userManager.CreateAsync(user, vmRegister.Password);

                if (result.Succeeded)
                {
                    //to Signin user
                    //signInManager.SignInAsync(user, isPersistent: false).Start();
                }
                else
                {
                    if (result.Errors.Count() > 0)
                    {
                        errorMessage = "";
                        foreach (var error in result.Errors)
                        {
                            errorMessage += error.Description;
                        }
                    }
                }
            }

            return Json(new { id = "1", message = errorMessage });
        } 

        [HttpPost]
        [AllowAnonymous]
        [Route("Login")]
        public async Task<IActionResult> Login(VMLogin vmLogin)
        {
            var user = await userManager.FindByNameAsync(vmLogin.EmailId);
            if (user != null && await userManager.CheckPasswordAsync(user, vmLogin.Password))
            {
                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                };

                var signinKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret 1234567890 phase"));

                var token = new JwtSecurityToken(
                    issuer: "http://mydomain.com",
                    audience: "http://mydomain.com",
                    expires: DateTime.UtcNow.AddHours(1),
                    claims: claims,
                    signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(signinKey, SecurityAlgorithms.HmacSha256)
                    );

                return Ok(
                    new
                    {
                        token = new JwtSecurityTokenHandler().WriteToken(token),
                        expiration = token.ValidTo
                    });
            }
            return Unauthorized();
        }  
    }

Testing












Hope this will help you and save your time.

Enjoy !!!

:)

.Net Core : Extend Identity User and add custom field in AspNetUsers table

.Net Core : Extend Identity User and add custom field in AspNetUsers table



Create new class and inherit with IdentityUser, here I created "ApplicationUser" and added 

namespace DotNetCodeDemo.Repository.Models
{
    public class ApplicationUser : IdentityUser
    {
        public string  City { get; set; }        
        public string MobileNumber { get; set; }
        public DateTime BirthDate { get; set; }
        public DateTime JoinDate { get; set; }
    }
}

Update dbContext class

namespace DotNetCodeDemo.Repository
{
    public class AppDbContext : IdentityDbContext<ApplicationUser>
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {

        }

        public DbSet<Employee> Employees { get; set; }
        public DbSet<Department> Departments { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Seed();
        }
    }
}

Update ConfigureServices method in startup class

public void ConfigureServices(IServiceCollection services)
{
 services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreDB")));

 services.AddIdentity<ApplicationUser, IdentityRole>(options =>
 {
  options.Password.RequiredLength = 10; // if you want to set your own password strength rule
  options.Password.RequiredUniqueChars = 2;
 }).AddEntityFrameworkStores<AppDbContext>(); 

 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
 services.AddScoped<IEmployeeRepository, EmployeeRepository>();
}

Update IdentityUser with ApplicationUser in your controller

namespace DotNetCodeDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AccountController : Controller
    {
        private readonly UserManager<ApplicationUser> userManager;
        private readonly SignInManager<ApplicationUser> signInManager;
        
        public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
        {
             
            this.userManager = userManager;
            this.signInManager = signInManager;
        }
         
        [HttpPost]
        [Route("Register")]
        public async Task<JsonResult> Post(VMRegister vmRegister)
        {
            IdentityResult result = new IdentityResult();
            string errorMessage = "success";

            if(ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName = vmRegister.Email,
                    Email = vmRegister.Email,
                    City = vmRegister.City
                };

                result = await userManager.CreateAsync(user, vmRegister.Password);

                if(result.Succeeded)
                {
                    //to Signin user
                    //signInManager.SignInAsync(user, isPersistent: false).Start();
                }
                else
                {
                    if(result.Errors.Count() > 0)
                    {
                        errorMessage = "";
                        foreach (var error in result.Errors)
                        {
                            errorMessage += error.Description;
                        }
                    }
                }
            }            

            return Json(new { id = "1", message = errorMessage });
        } 
    }
}

Hope this will help you and save your time.

Enjoy !!!

:)