Sunday, 18 October 2020

                                            Some important docker commands 


dockerfile with out any extension

.dockerignore 

docker build please put the . at the last


1. Important commands


To create image.

docker build -t myimage .


To create container

docker run -d -p 8080:80 --name  t1image myimage


To list all images in a computer

docker images


To list all containers in a computer.

docker container list -a


To check container details like IP address

docker inspect mvccore5


To stop a image

docker stop imagename


Power shell commands to delete all images and containers.

docker ps -a -q | % { docker rm $_ }

docker images -q | % { docker rmi $_ }


Check if there are issues with the container

docker logs containername


with out stopping you can not delete



2. docker file for MVC core (dockerfile)



FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build

WORKDIR /MyCore123

# copy csproj and restore as distinct layers

COPY *.sln .

COPY MyCore123/*.csproj ./MyCore123/

RUN dotnet restore


# copy everything else and build app

COPY MyCore123/. ./MyCore123/

RUN dotnet publish -c Release -o out



FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS runtime

WORKDIR /MyCore123/MyCore123

COPY --from=build /MyCore123/out ./

ENTRYPOINT ["dotnet", "MyCore123.dll"]



2. docker file for MVC 5(dockerfile)


FROM microsoft/aspnet

COPY ./bin/Release/Publish/ /inetpub/wwwroot


Step 3 :- .dockerignore


# directories

**/bin/

**/obj/




Saturday, 17 October 2020

                           Pushing your asp.net core application to under docker


Step1 create dotnet core application as structure below by name Myapp2


step 2 Now create the docker file under the project without any  extension and also create the .dockerignore file 

step 3  now our project working directory would be like the below ,where we put docker file and .dockerignore file


step 4 now under the dockerfile write the below code so that required things install  in docker container


FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /Myapp2
# copy csproj and restore as distinct layers
COPY *.sln .
COPY Myapp2/*.csproj ./Myapp2/
RUN dotnet restore

# copy everything else and build app
COPY Myapp2/. ./Myapp2/
RUN dotnet publish -c Release -o out


FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS runtime
WORKDIR /Myapp2/Myapp2
COPY --from=build /Myapp2/out ./
ENTRYPOINT ["dotnet", "Myapp2.dll"]

step 5 now use the .dockerignore file mentioned the below code under it so that those folders get ignore 


# directories
**/bin/
**/obj/


step 6 now come to the working directory Myapp2 on cmd  and run the build command 


docker build -t myapp2:v1 .






now you can see our docker build command success and image has created 



step 7 Now create the container by using the below command as per our application

docker run -d -p 8080:80 --name mycoreconatiner myaap2:v2



step 8 use this command to find the ip of running container means ip address ,

docker inspect mycoreconatiner


now you can see our application running on the below ip address




now do the request of this url(http://172.27.59.53/weatherforecast) on browser then our application will run as below












Sunday, 11 October 2020

                                                    Using Ocelot Gateway 


here we will create ocelot gateway and 

1) we will call the backend services through gate way

2)we will use aggregation in gateway to call two service 

3)we will apply the authentication on each service using ocelot gate way means we will create naked ms service and will the authentication on gateway label


First Service -User Service

Step 1  first create the ms user micro service as below structure



in user controller paste the below code,

using System;

using System.Collections.Generic;

using System.IdentityModel.Tokens.Jwt;

using System.Linq;

using System.Security.Claims;

using System.Text;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Mvc;

using Microsoft.IdentityModel.Tokens;


namespace user_ms.Controllers

{

    [Route("api/user")]

    [ApiController]

    public class UserController : ControllerBase

    {

        // GET api/values

        [HttpGet("getUser")]

        public ActionResult<IEnumerable<User>> Get()

        {

            User user = GetData();

            return Ok(user);

        }

        [AllowAnonymous]

        [HttpGet("login")]

        public IActionResult Get(string name, string password)

        {

            //just hard code here.  

            if (name == "mukesh" && password == "123")

            {

                var now = DateTime.UtcNow;


                var claims = new Claim[]

                {

            new Claim(JwtRegisteredClaimNames.Sub, name),

            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),

            new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64)

                };

                var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("hello god ,we are depend on you so please do help"));

                var tokenValidationParameters = new TokenValidationParameters

                {

                    ValidateIssuerSigningKey = true,

                    IssuerSigningKey = signingKey,

                    ValidateIssuer = true,

                    ValidIssuer = "mukesh",

                    ValidateAudience = true,

                    ValidAudience = "enduser",

                    ValidateLifetime = true,

                    ClockSkew = TimeSpan.Zero,

                    RequireExpirationTime = true,

                };

                var jwt = new JwtSecurityToken(

                    issuer: "mukesh",

                    audience: "enduser",

                    claims: claims,

                    notBefore: now,

                    expires: now.Add(TimeSpan.FromMinutes(20)),

                    signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)

                );

                var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

                var responseJson = new

                {

                    access_token = encodedJwt,

                    expires_in = (int)TimeSpan.FromMinutes(2000).TotalSeconds

                };

                return Ok(responseJson);

            }

            else

            {

                return Ok("");

            }

        }

        private User GetData()

        {

            User user = new User

            {

                Id = 1,

                Name = "Mukesh trivedi",

                Email = "mukeshtrvd105@gmail.com",

                Mobile="8845345223"

            };

            return user;

        }

        public class User

        {

            public int Id { get; set; }

            public string Name { get; set; }

            public string Email { get; set; }

            public string Mobile { get; set; }

        }

    }

}


when we run the user micro service it will give the result as below,



Second Service 

Step 2 similarly we will create the second product service and  use in the gateway for concurrent calling product structure is like below

now under  the product controller copy the below code 

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace product_ms.Controllers
{
    [Route("api/product")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        // GET api/values
        [HttpGet("getProduct")]
        public ActionResult<IEnumerable<string>> Get()
        {
            Product product = GetProductData();
            return Ok(product);
        }


        private Product GetProductData()
        {
            Product product = new Product
            {
                Id = 1,
                Name = "Samsung Galaxy",
                Price = "RS 20000"
            };
            return product;
        }

        public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Price { get; set; }
        }

    }
}
 
when the product ms service will call it look like below,

Gateway 

now come to the ocelot gate way service , now create a web api and then install the ocelot gate way from nuget package 

Step 1 down load the ocelot pakage as below

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
    <PackageReference Include="Ocelot" Version="13.5.1" />
  </ItemGroup>

</Project>

Step 2 ,now write the routing in ocelot json file  

Ocelot json file where we set the routing for both the micro service

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/user/getUser",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": "44307"
        }
      ],
      "UpstreamPathTemplate": "/getUser",
      "Key": "User",
      "AuthenticationOptions": {
        "AuthenticationProviderKey": "TestKey",
        "AllowedScopes": []
      }
    },
    {
      "DownstreamPathTemplate": "/api/product/getProduct",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": "44300"
        }
      ],
      "UpstreamPathTemplate": "/getProduct",
      "Key": "Product"
    }
  ],
  "Aggregates": [
    {
      "ReRouteKeys": [
        "User",
        "Product"
      ],
      "UpstreamPathTemplate": "/UserAndProduct"
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://localhost:44338/"
  }
}

Step 3 Now configure the json file in program file.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace web_api
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
           WebHost.CreateDefaultBuilder(args)
           .ConfigureAppConfiguration((host, config) =>
           {
               config.AddJsonFile("ocelot.json");
           })
               .UseStartup<Startup>();
    }
}

Step 4 ,now registered the dependency in ioc container and request/response pipeline

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

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

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            //authentication  logic

            string textKey = "hello god ,we are depend on you so please do help";

            var key = Encoding.ASCII.GetBytes(textKey);

            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(textKey));
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,
                ValidateIssuer = true,
                ValidIssuer = "mukesh",
                ValidateAudience = true,
                ValidAudience = "enduser",
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero,
                RequireExpirationTime = true,
            };


            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
              .AddJwtBearer("TestKey", x =>
              {
                  x.RequireHttpsMetadata = false;
                  x.TokenValidationParameters = tokenValidationParameters;
              });

            services.AddOcelot(Configuration);
        }

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

            await app.UseOcelot();

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }
}


now we using post man for calling two service concurrent result at one go.
we will pass the token during the service call


requested url:https://localhost:44338/UserAndProduct


Passing Token

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtdWtlc2giLCJqdGkiOiIxNWU2NDNlZS1hZjJkLTQ1MDEtODc2NS1hN2RmOGQ2YjZkNTAiLCJpYXQiOiIxMS0xMC0yMDIwIDE2OjIwOjAxIiwibmJmIjoxNjAyNDMzMjAxLCJleHAiOjE2MDI0MzQ0MDEsImlzcyI6Im11a2VzaCIsImF1ZCI6ImVuZHVzZXIifQ.oVfWK5qRDGYbyY5c6N6ol1BHT9hVWqcPn9fkjZIyfGg


Result

{
    "User": {
        "id"1,
        "name""Mukesh trivedi",
        "email""mukeshtrvd105@gmail.com",
        "mobile""8845345223"
    },
    "Product": {
        "id"1,
        "name""Samsung Galaxy",
        "price""RS 20000"
    }
}

now calling the single service by requesting the gate way url such as

Requested url -----> https://localhost:44338/getUser


Passing token same as above


eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtdWtlc2giLCJqdGkiOiIxNWU2NDNlZS1hZjJkLTQ1MDEtODc2NS1hN2RmOGQ2YjZkNTAiLCJpYXQiOiIxMS0xMC0yMDIwIDE2OjIwOjAxIiwibmJmIjoxNjAyNDMzMjAxLCJleHAiOjE2MDI0MzQ0MDEsImlzcyI6Im11a2VzaCIsImF1ZCI6ImVuZHVzZXIifQ.oVfWK5qRDGYbyY5c6N6ol1BHT9hVWqcPn9fkjZIyfGg

Result

{
    "id"1,
    "name""Mukesh trivedi",
    "email""mukeshtrvd105@gmail.com",
    "mobile""8845345223"
}


































Sunday, 4 October 2020

                show custom exception page in .net core


Step 1  first create the solution as below  and 





Step 2   
then create the error controller 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace GlobalException.Controllers
{
    public class ErrorController : Controller
    {
        [Route("Error/{StatusCode}")]
        public IActionResult StatusCodeHandle(int statusCode)
        {
            switch (statusCode)
            {
                case 404:
                    ViewBag.ErrorMessasge = $"I am having {statusCode}" + " Error code Message";
                    break;
            }
            return View(statusCode);
        }

    }
}

Step 3 create the view as below,StatusCodeHandle.cshtml

<h1>@ViewBag.ErrorMessasge</h1>
eror


Step 4 Now write the code in start file to call custom page,below highlighted code is mandatory to route the request

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GlobalException.WebApi.Filter;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace GlobalException
{
    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.AddControllersWithViews(); // This is the imporatant line for handling No service reg
            services.AddMvcCore();

            services.AddScoped<IExceptionLogService, ExceptionLogService>();
            services.AddScoped<DbExceptionFiltercs>();// for Error Log
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseStatusCodePagesWithRedirects("/Error/{0}");       this is the import line 
            }
            

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}


now ,i am doing the request of http://localhost:51605/weatherforecast/tip,result will be like below





                                         Global exception handling in database in .net core


 step 1 :  Create global exception solution as below 



 step 2:Create common folder for recording parameters and create the LogEntryRequest.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;


namespace GlobalException.WebApi.Common

{

    public class LogEntryRequest

    {

        public DateTime TimeStamp { get; set; }

        public string RequestId { get; set; }

        public string Message { get; set; }

        public string Type { get; set; }

        public string Source { get; set; }

        public string StackTrace { get; set; }

        public string RequestPath { get; set; }

        public string Action { get; set; }


    }

}

Step 3:Create filter folder and create class as below,


using GlobalException.WebApi.Common;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Filters;
//using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GlobalException.WebApi.Filter
{
    public class DbExceptionFiltercs:ExceptionFilterAttribute
    {
        private readonly IExceptionLogService _iExceptionLogService;
        [Obsolete]
        private readonly IHostingEnvironment _iHostingEnvironment;

        [Obsolete]
        public DbExceptionFiltercs(IExceptionLogService iExceptionLogService,IHostingEnvironment iHostingEnvironment)
        {
           _iExceptionLogService = iExceptionLogService;
            _iHostingEnvironment = iHostingEnvironment;
        }

        public override void OnException(ExceptionContext context)
        {
            if (_iHostingEnvironment.IsDevelopment())
            {
                LogEntryRequest log = new LogEntryRequest
                {
                    TimeStamp = DateTime.Now,
                    Action = context.ActionDescriptor.DisplayName,
                    Message = context.Exception.Message,
                    RequestPath = context.HttpContext.Request.Path,
                    Source = context.Exception.Source,
                    StackTrace = context.Exception.StackTrace,
                    Type = context.Exception.GetType().ToString()
                };

               _iExceptionLogService.Add(log);   //using this line exception is recorded in database
            }
        }


    }
}

Step 4: for recording the data create the interface for recording the data in database

using GlobalException.WebApi.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GlobalException
{
    public interface IExceptionLogService
    {
        long Add(LogEntryRequest viewModel);
    }
}

now create the class to implement the interface

using GlobalException.WebApi.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GlobalException
{
    public class ExceptionLogService: IExceptionLogService
    {
        private readonly IExceptionLogRepository _iExceptionLogRepository;

        public ExceptionLogService()
        {
            _iExceptionLogRepository = repository;
        }

        public long Add(LogEntryRequest viewModel)
        {
            _iExceptionLogRepository.Add(viewModel);
            return res;
        }
    }
}


 Step5: now set the dependency in startup file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GlobalException.WebApi.Filter;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace GlobalException
{
    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.AddControllers();
            services.AddScoped<IExceptionLogService, ExceptionLogService>();
            services.AddScoped<DbExceptionFiltercs>();// for Error Log
        }

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

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

step 6:now apply the global exception in controller


using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using GlobalException.WebApi.Filter;

using Microsoft.AspNetCore.Mvc;

using Microsoft.Extensions.Logging;


namespace GlobalException.Controllers

{

    [ServiceFilter(typeof(DbExceptionFiltercs))]     calling exception on controller

    [ApiController]

    [Route("[controller]")]

    public class WeatherForecastController : ControllerBase

    {

        private static readonly string[] Summaries = new[]

        {

            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"

        };


        private readonly ILogger<WeatherForecastController> _logger;


        public WeatherForecastController(ILogger<WeatherForecastController> logger)

        {

            _logger = logger;

        }


        [HttpGet]

        public IEnumerable<WeatherForecast> Get()

        {

            int a = 1;

            int b = 0;

            //int c = 0;

            int c = a / b;          knowingly generate exception

            //var t = 1 / 0;

            var rng = new Random();

            return Enumerable.Range(1, 5).Select(index => new WeatherForecast

            {

                Date = DateTime.Now.AddDays(index),

                TemperatureC = rng.Next(-20, 55),

                Summary = Summaries[rng.Next(Summaries.Length)]

            })

            .ToArray();

        }

    }

}





Saturday, 3 October 2020

                                                           Use NLog in project


first install the below  highlighted nlog package using nuget.

step1:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>

    <TargetFramework>netcoreapp3.1</TargetFramework>

  </PropertyGroup>

  <ItemGroup>

    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.4" />

    <PackageReference Include="NLog.Config" Version="4.7.3" />

    <PackageReference Include="NLog.Web.AspNetCore" Version="4.9.3" />

  </ItemGroup>

  <ItemGroup>

    <None Update="C:\Users\mukesh\.nuget\packages\nlog.config\4.7.3\contentFiles\any\any\NLog.config">

      <CopyToOutputDirectory>Always</CopyToOutputDirectory>

    </None>

  </ItemGroup>

</Project>

Step 2

Now create the project and create NLOG.config and paste the below code.
and create the folders demologs in c drive 


<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true">
<targets>
<target xsi:type="File" name="fileTarget" fileName="C:\DemoLogs\nlog-all-${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="consoleTarget" />
<logger name="Microsoft.*" maxlevel="Info" final="true" />
<logger name="*" minlevel="Trace" writeTo="fileTarget" />
</rules>
</nlog>

now create a controller such as a random name and put the code below

Step 3:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Fluent;

namespace NLOG.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class NlogController : ControllerBase
    {
        private static ILogger<NlogController> _logger;
        public NlogController(ILogger<NlogController> logger)
        {
            _logger = logger;
        }
        [HttpGet]
        public void Get()
        {
            _logger.LogInformation(" Nlog Controller request");
            int count;
            try
            {
                for (count = 0; count <= 5; count++)
                {
                    if (count == 3)
                    {
                        throw new Exception("Nlog Exception Occured");
                    }
                    else
                    {
                        _logger.LogInformation("Iteration Count is {iteration}", count);
                    }
                }
            }
            catch (Exception ex)
            {

                _logger.LogError(ex, "Exception Caught");
            }
        }
    }
}

Step 4:

configuring in program.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using NLog.Web;

namespace NLOG.WebApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var logger = NLog.Web.NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger();
            try
            {
                logger.Debug("Application Starting Up");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception exception)
            {
                //NLog: catch setup errors
                logger.Error(exception, "Stopped program because of exception");
                throw;
            }
            finally
            {
                // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
                NLog.LogManager.Shutdown();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                })
                .UseNLog();  // NLog: Setup NLog for Dependency injection
    }
}

output would be like this







Saturday, 26 September 2020

                                    Rabbit MQ Single Producer and multiple Consumer



Step 1: first install the rabbit mq in your local system ,then create a console application for pushing

the messages in Rabbit MQ.

Name -RabbitMQProducer ,then  install the dependencies as showing here such as newtonsoft and rabbitMQ Client.




Now create a class by name QueueProducer and write the below code as mention below,

using Newtonsoft.Json;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace RabbitMQProducer{
   public static class QueueProducer
 {
        public static void publish(IModel  channel)
        {

           channel.QueueDeclare("demo-queue",
            durable: true,
            exclusive: false,
            autoDelete: false,
            arguments: null);
            int count = 0;
            while (true)
            {
                var message = new { Name = "Producer", Message = $"Hello Count:+{count}"};
                var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));
                channel.BasicPublish("", "demo-queue", null, body);
                count++;
                //Thread.Sleep(1000);
            }

        }
    }
}

===================================================================
Program .cs

using System;
using System.Text;
using Newtonsoft.Json;
using RabbitMQ.Client;

namespace RabbitMQProducer
{
    class Program
    {
        static void Main(string[] args {
            var factory = new ConnectionFactory
        {
                Uri = new Uri("amqp:guest:guest@localhost:5672")
            };
            using var connection = factory.CreateConnection();
            using var channel = connection.CreateModel();
            QueueProducer.publish(channel);

        }
    }
}

now run the program ,in this way we are able to push data in rabbit mq.
as you can see we have queued the lakhs of records in rabbit mq.




here you can see there is no consumer.

now we are activating two consumers by clicking on exe  2 times.









Friday, 18 September 2020

                                  Using CQRS And MediatR pattern in micro service



Step1  first create  the solution  by any name as i have taken CQRS.WEB API

Step2 : Create Models folder and create model class by name product.  as below

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;


namespace CQRS.WebApi.Models

{

    public class Product

    {

        public int Id { get; set; }

        public string Name { get; set; }

        public string Barcode { get; set; }

        public bool IsActive { get; set; } = true;

        public string Description { get; set; }

        public decimal Rate { get; set; }

        public decimal BuyingPrice { get; set; }

        public string ConfidentialData { get; set; }

    }

}

Step 3: install the below package using package manager console

Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.Relational
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package MediatR
Install-Package MediatR.Extensions.Microsoft.DependencyInjection
Install-Package Swashbuckle.AspNetCore
Install-Package Swashbuckle.AspNetCore.Swagger

once install it will display like below.



Step 4 now create a folder Context and under this create interface and its implementation.


interface -IApplicationContext

using System.Threading.Tasks;
using CQRS.WebApi.Models;
using Microsoft.EntityFrameworkCore;

namespace CQRS.WebApi.Context
{
    public interface IApplicationContext
    {
        DbSet<Product> Products { get; set; }

        Task<int> SaveChanges();
    }
}

Now create it implementation as below by name ApplicationContext

using CQRS.WebApi.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CQRS.WebApi.Context
{
    public class ApplicationContext : DbContext, IApplicationContext
    {
        public DbSet<Product> Products { get; set; }
        public ApplicationContext(DbContextOptions<ApplicationContext> options)
            : base(options)
        { }
        public async Task<int> SaveChanges()
        {
            return await base.SaveChangesAsync();
        }
    }
}


Step 5:create connection string in appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=developmentDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "AllowedHosts": "*"
}

step 6 : configuring the api services to support entity framework core

used name spaces 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using CQRS.WebApi.Context;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;




 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
          //  services.AddMediatR(Assembly.GetExecutingAssembly());

            services.AddDbContext<ApplicationContext>(options =>
               options.UseSqlServer(
                   Configuration.GetConnectionString("DefaultConnection"),
                   b => b.MigrationsAssembly(typeof(ApplicationContext).Assembly.FullName)));


            #region Swagger
            services.AddSwaggerGen(c =>
            {
             //   c.IncludeXmlComments(string.Format(@"{0}\CQRS.WebApi.xml", System.AppDomain.CurrentDomain.BaseDirectory));
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "CQRS.WebApi",
                });

            });
            #endregion


            services.AddScoped<IApplicationContext>(provider => provider.GetService<ApplicationContext>());

            services.AddMediatR(Assembly.GetExecutingAssembly());
            services.AddControllers();

         //   services.AddValidatorsFromAssembly(typeof(Startup).Assembly);


        }


configure swagger in pipeline

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

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            #region Swagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "CQRS.WebApi");
            });
            #endregion


        }


Step 7 now Create product controller  and 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CQRS.WebApi.Features.ProductFeatures.Commands;
using CQRS.WebApi.Features.ProductFeatures.Queries;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace CQRS.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private IMediator _mediator;

        protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService<IMediator>();

        [HttpPost]
        public async Task<IActionResult> Create(CreateProductCommand command)
        {
            return Ok(await Mediator.Send(command));
        }
        [HttpGet]
        public async Task<IActionResult> GetAll()
        {
            return Ok(await Mediator.Send(new GetAllProductsQuery()));
        }
        [HttpGet("{id}")]
        public async Task<IActionResult> GetById(int id)
        {
            return Ok(await Mediator.Send(new GetProductByIdQuery { Id = id }));
        }
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            return Ok(await Mediator.Send(new DeleteProductByIdCommand { Id = id }));
        }
        [HttpPut("{id}")]
        public async Task<IActionResult> Update(int id, UpdateProductCommand command)
        {
            if (id != command.Id)
            {
                return BadRequest();
            }
            return Ok(await Mediator.Send(command));
        }
    }

}

Step 9 : mandatory package should be installed before doing migration in database 


now do the migration so open the package manager console and run the below command


add-migration "initial"

update-database

when you will run the above command below database and product table will create in database.



now micro service is ready to use on swagger



when fetch the data using get it will display the records like below