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

:)

Angular 6 : call API in Angular

Angular 6 : call API in Angular


Countrydetail class


export class CountryDetail {
CountryId: number;
CountryName: string;
}
  

country.service.ts


import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../../environments/environment';
@Injectable()
export class CountryDetailService {
private httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json; charset=utf-8'
}),
};
constructor(private http: HttpClient) {
}
async getCountryDetail(countryId: number): Promise<CountryDetail> {
let request = this.http.post(environment.apiUrl + environment.countrydetailurl, { data: {CountryId: countryId} }, this.httpOptions).
toPromise().
then(res => {
return res["d"] as CountryDetail;
}).
catch(err => {
console.log(err);
return null;
});
let result = await request;
return result;
}
}
  

country.component.ts


export class CountryComponent implements OnInit {
spinnerService: any;
public detail = new CountryDetail();
showSpinner: boolean = true;
constructor(private countryDetailService: CountryDetailService, private router: Router,
private route: ActivatedRoute) {
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
}
}
async ngOnInit() {
const productId = +this.route.snapshot.queryParamMap.get('id');
let data = await this.countryDetailService.getCountryDetail(productId);
this.detail = data as CountryDetail;
this.showSpinner = false;
}
}
  

country.component.html


<table>
<tr *ngFor="let country of detail">
<td>country.CountryName</td>
<td><a href="/detail/country.CountryId">Detail</a></td>
</tr>
</table>
  
Hope this will help you and save your time.

Enjoy !!!

:)

Angular 6 : Find value from existing array, Update array value

Angular 6 : Find value from existing array, Update array value 


Find value from existing array, Update array value  in Angular 6, here I explained step by steps.


let ProductSizes = Array<Size>();
let productSize = new Size();
 
productSize.Quantity = size.Quantity;
productSize.SizeName = size.SizeName;
productSize.sizeId = size.sizeId;
     
Check Value from existing array     
let existingSize = this.ProductSizes.find(item=> item.sizeId== sizeId);

if(existingSize != null)
{
  let sizeIndex = this.ProductSizes.indexOf(existingSize);
  this.ProductSizes[sizeIndex] = productSize;
}
else
{
 this.ProductSizes.push(productSize);
}

  
Hope this will help you and save your time.

Enjoy !!!

:)

Angular 6 : Multi Language Usage

Angular 6 : Multi Language Usage


We can use multi languages in Angular 6, here I explained step by steps.

Steps, how to use it.

Step 1

Install required packages

npm install @ngx-translate/core --save
npm install ngx-translate-http-loader --save
  

Step 2

Configuration

Create folder "i18n" in "assets" folder
Create language specific file like., en.json, gu.json, hn.json as many you have language
And store language specific value in .json file as below

en.json

{
    "Product": {
        "ProductName": "Name",  
        "ProductPrice": "Price"        
    }
}

  

gu.json

{
    "Product": {
        "ProductName": "નામ",  
        "ProductPrice": "કિંમત"        
    }
}

  

hn.json

hn.json
{
    "Product": {
        "ProductName": "नाम",  
        "ProductPrice": "किम्मत"        
    }
}

  

Step 3

app.module.ts

import { TranslateModule, TranslateLoader, TranslateService } from '@ngx-translate/core';
import { TranslateHttpLoader } from "@ngx-translate/http-loader";
import { HttpClientModule, HttpClient } from '@angular/common/http';

  
export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
}
  
imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HttpClientModule,
    FormsModule, 
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  providers: [RecordsService],
  bootstrap: [AppComponent]
})



  

Step 4

app.component.ts

import { Component, ElementRef } from '@angular/core'; 
import { Router, ActivatedRoute } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    
showLoadingIndicator = true;

constructor(private router : Router, private route: ActivatedRoute, private eleRef: ElementRef,public translate: TranslateService ) { 
  //language start
  const langsArray: string[] = ['en', 'gu', 'hn'];
    translate.addLangs(langsArray);
      translate.setDefaultLang('en');
      let profileLanguage = this.eleRef.nativeElement.getAttribute('language');
    const browserLang: string =  translate.getBrowserLang();
    
    let UserLanguage = localStorage.getItem('UserLanguage'); 
    if(UserLanguage != null)
    {
      translate.use(UserLanguage);
    }
    else{
      if (profileLanguage) {
        translate.use(profileLanguage);
      } else {
        translate.use(langsArray.includes(browserLang) ? browserLang : 'en');
      }
    }    
  //language end  
}

  changeLanguage(lang) : void{     
    localStorage.setItem('UserLanguage', lang);
    this.translate.use(lang);
    this.router.routeReuseStrategy.shouldReuseRoute = () => false;
    this.router.onSameUrlNavigation = 'reload';
    this.router.navigate([this.router.url]);
  }
}

  

Step 5

app.component.html

 <select #langselect (change)="changeLanguage(langselect.value)">
      <option *ngFor="let lang of translate.getLangs()" [value]="lang">{{lang}}</option>
 </select>


  

Step 6

how to use language specific value

<h1>
    {{ 'Product.ProductName' | translate }}
</h1>
<h2>
    {{ 'Product.ProductPrice' | translate }}
</h2>



  

Hope this will help you and save your time.

Enjoy !!!

:)

Angular 6 : "reloading" same page when navigate to same route with different param

Angular 6 : "reloading" page when navigate to same route with different params



app-routing.module.html

const routes: Routes = [
{ path: 'detail/:id', component: DetailComponent },
] ;

detail.component.html


<button (change)="gotoDetailPage(record.ID)" >{{record.Name}}</button>

detail.component.cs


import { Router } from '@angular/router';
constructor(private router: Router) {
this.router.routeReuseStrategy.shouldReuseRoute = function(){
return false;
}
}
ngOnInit() {
//To get id's value, e.g., detail/123
const id = +this.route.snapshot.paramMap.get('id');
//To get querystring id's value, e.g., detail?id=123
//const id = +this.route.snapshot.queryParamMap.get('id');
console.log(id)
}
gotoDetailPage(id)
{
this.router.navigate(['/detail', id]);
}
  



Hope this will help you and save your time.

Enjoy !!!

:)

Angular 6 : DevOps VSTS

Angular 6 : DevOps VSTS


Overview


Using VSTS we can make build of Angular project and deploy on server. 

We need to make build and release pipeline in VSTS. Here I have explained it step by step.



Build








Release (Deployment)








Hope this will help you and save your time.

Enjoy !!!

:)

Angular 6 : Show HTML text on UI (remove html tags on html view page)

Angular 6 : Show HTML text on UI  

(remove html tags on html view page)


Issue

HTML text which contains the html tags, to show proper html view use below property.

<div id="description">{{detail.ProductDescription}}</div>

Solution 

<div [innerHTML]="detail.ProductDescription"></div>

Hope this will help you and save your time.

Enjoy !!!

:)