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 !!!

:)

.Net Core : AspNet Membership Login Method

.Net Core : AspNet Membership Login Method



AspNet membership login method code,

[HttpPost]
[Route("Login")]
public async Task<JsonResult> Post(VMLogin vmLogin)
{
Microsoft.AspNetCore.Identity.SignInResult result = new Microsoft.AspNetCore.Identity.SignInResult();
string errorMessage = "success";

if (ModelState.IsValid)
{
  
  result = await signInManager.PasswordSignInAsync(vmLogin.Email, vmLogin.Password, vmLogin.RememberMe, false);

if (!result.Succeeded)                 
{
errorMessage = "fail";
}
}

return Json(new { message = errorMessage });
} 



Hope this will help you and save your time.

Enjoy !!!

:)

.Net Core : Change Identity password complexity rules

.Net Core : Change Identity password complexity rules



Change Identity password complexity rules,


In ConfigureServices method

services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
options.Password.RequiredLength = 10;
options.Password.RequiredUniqueChars = 2;
}).AddEntityFrameworkStores<AppDbContext>();


Hope this will help you and save your time.

Enjoy !!!

:)

.Net Core : Register User data into Identity table

.Net Core : Register User data into Identity table



Insert record in identity table,

namespace DotNetCoreDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AccountController : Controller
    {
        private readonly UserManager<IdentityUser> userManager;
        private readonly SignInManager<IdentityUser> signInManager;
        
        public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> 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 IdentityUser
                {
                    UserName = vmRegister.Email,
                    Email = vmRegister.Email
                };

                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 !!!

:)

.Net Core : ASP.NET Membership - Identity User - Setup

.Net Core : ASP.NET Membership - Identity User - Setup



1. install nuget package - Microsoft.AspNetCore.Identity.EntityFrameworkCore

2. inherit DbContext class with IdentityDbContext
e.g., public class AppDbContext : IdentityDbContext

3.Configure identity in statup file, as below,
public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreDB")));

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

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

4. add "app.UseAuthentication();" in Configure method before "app.UseMvc();".

5. Do datamigration using
Add-Migration "AddIdentity"

6. If you will get error like "The entity type 'IdentityUserLogin<string>' requires a primary key to be defined."
then 
goto appDbContext class and do changes in OnModelCreating method as below,
base.OnModelCreating(modelBuilder);

7. Now run again Add-Migration "AddIdentity"

8. then run Update-Database

9. Finally you can see there are some tables name start with "ASPNet" are added in database.

Hope this will help you and save your time.

Enjoy !!!

:)

Azure : LogicApp If Condition

Azure : LogicApp If Condition



Here is sample code to send email using Azure function app

API Response

body
{
    "ResultCode": "OK",
    "Message": "Success",
    "Data": "demo@gmail.com"
}

If Condition Step, get http API response result value, Here we are getting above result and want to get value of "ResultCode", and based on we need to perform another action, so we can get it as below,



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


Hope this will help you and save your time.

Enjoy !!!

:)

Azure : Function App

Azure : Function App



Here is sample code to send email using Azure function app

Encryption


namespace DemoFunctionApp
{
    public class EmailUsers
    {
        public string ToEmail { get; set; }
    }

    public class Response
    {
        public string StatusCode { get; set; }
        public string Message { get; set; }
        public string Data { get; set; }

    }
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            var mailmessage = new MailMessage { From = new MailAddress("user@gmail.com", "UserName") };

            var emailUsers = await req.Content.ReadAsAsync<EmailUsers>();
            
            mailmessage.To.Add(emailUsers.ToEmail);

            mailmessage.Subject = "Test email from function app" + System.DateTime.Now;
            mailmessage.IsBodyHtml = true;
            mailmessage.Body = "TEst email from function app" + System.DateTime.Now;

            SmtpClient smtpClient = null;
            smtpClient = new SmtpClient();

            smtpClient.Host = "smtp.gmail.com";
            smtpClient.Port = 587;
            smtpClient.UseDefaultCredentials = false;

            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.Credentials = new NetworkCredential("user@gmail.com", "userEmailPassword");

            smtpClient.EnableSsl = true;

            smtpClient.Send(mailmessage);

            Response response = new Response
            {
                StatusCode = HttpStatusCode.OK.ToString(),
                Message = "Success",
                Data = emailUsers.ToEmail
            };

            return req.CreateResponse(HttpStatusCode.OK, response);
        }
    }
}

Hope this will help you and save your time.

Enjoy !!!

:)

.Net Core : Database Connectivity

.Net Core : Database Connectivity

 

Model


namespace DotNetCodeDemo.Entities
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public Department Department { get; set; }
    }
}


namespace DotNetCodeDemo.Entities
{
    public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Location { get; set; }
    }
}
  

Repository


namespace DotNetCodeDemo.Repository.Contract
{
    public interface IEmployeeRepository
    {
        Employee GetEmployee(int Id);
        IEnumerable<Employee> GetAllEmployee();
        Employee Add(Employee employee);
        Employee Update(Employee employeeChanges);
        Employee Delete(int Id);
    }
}
  



namespace DotNetCodeDemo.Repository.Repositories
{
    public class EmployeeRepository : IEmployeeRepository
    {
        private readonly AppDbContext dbContext;

        public EmployeeRepository(AppDbContext dbContext)
        {
            this.dbContext = dbContext;
        }
        public Employee Add(Employee employee)
        {
            dbContext.Employees.Add(employee);
            dbContext.SaveChanges();
            return employee;
        }

        public Employee Delete(int Id)
        {
            var employee = dbContext.Employees.Find(Id);
            if(employee != null)
            {
                dbContext.Employees.Remove(employee);
                dbContext.SaveChanges();
            }            
            return employee;
        }

        public IEnumerable<Employee> GetAllEmployee()
        {
            return dbContext.Employees;
        }

        public Employee GetEmployee(int Id)
        {
            return dbContext.Employees.Find(Id);
        }

        public Employee Update(Employee employeeChanges)
        {
            var employee = dbContext.Employees.Attach(employeeChanges);
            employee.State = Microsoft.EntityFrameworkCore.EntityState.Modified;
            dbContext.SaveChanges();
            return employeeChanges;

        }
    }
}

   
namespace DotNetCodeDemo.Repository.Helper
{
    public static class ModelBuilderExtension
    {
        public static void Seed(this ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Employee>().HasData(
               new Employee
               {
                   Id = 1,
                   Name = "Demo1",
                   Email = "demo1@demo.com"
               },
               new Employee
               {
                   Id = 2,
                   Name = "Demo2",
                   Email = "demo2@demo.com"
               }
            );
        }
    }
}


namespace DotNetCodeDemo.Repository
{
    public class AppDbContext : DbContext
    {
        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)
        {
            modelBuilder.Seed();
        }
    }
}

appsettings.json


{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DotNetCoreDB" :  "data source=localhost; initial catalog=dotnetCoreDb; user id=sa; password=sa"
  }
}

Startup.cs


namespace DotNetCodeDemo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreDB")));

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

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

API Controller


namespace DotNetCodeDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        private readonly IEmployeeRepository employeeRepository;

        public EmployeeController(IEmployeeRepository employeeRepository)
        {
            this.employeeRepository = employeeRepository;
        }

        [HttpGet]
        public ActionResult<IEnumerable<Employee>> Get()
        {
            return employeeRepository.GetAllEmployee().ToList();
        }
    }
}
  





Hope this will help you and save your time.

Enjoy !!!

:)

.Net Core : Logging system

.Net Core : Logging system


 Log messages in .net core.

Step 1

Create custom logger class 

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace CoreDemo.Middleware
{
    public class MyLoggerMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;

        public MyLoggerMiddleware(RequestDelegate next, ILoggerFactory logFactory)
        {
            _next = next;
            _logger = logFactory.CreateLogger("MyLogger");
        }

        public async Task Invoke(HttpContext httpContext)
        {
            _logger.LogInformation("test log");
            //await _next(httpContext);

            var bodyStream = httpContext.Response.Body;
            var responseBodyStream = new MemoryStream();
            httpContext.Response.Body = responseBodyStream;

            await _next(httpContext);
            responseBodyStream.Seek(0, SeekOrigin.Begin);
            var responseBody = new StreamReader(responseBodyStream).ReadToEnd();

            var responseCode = httpContext.Response.StatusCode;
            var requestPath = httpContext.Request.Path;
            var requestMethod = httpContext.Request.Method;

            _logger.LogInformation($"@timeStamp = {DateTime.Now}, site = {"CoreDemo"}, Level = info, ThreadId = {Thread.CurrentThread.ManagedThreadId}, Message = logger Middleware response {responseBody}, request path = {requestPath}, request method = { requestMethod}");
                
            responseBodyStream.Seek(0, SeekOrigin.Begin);
            await responseBodyStream.CopyToAsync(bodyStream);
        }
    }

    public static class MyLoggerMiddlewareExtension
    {
        public static  IApplicationBuilder UseMyLoggerMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyLoggerMiddleware>();
        }
    }
}

  

Step 2

startup.cs

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseMyLoggerMiddleware();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            
            app.UseMvc();
        }


Hope this will help you and save your time.

Enjoy !!!

:)