Thursday, 17 June 2021

                     Using APIM and Azure Event Grid Topic and call two diffrent azure functions

Monday, 22 March 2021

                                  1.  Using Http trigger Azure function and showing in url call


using System;

using System.IO;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Mvc;

using Microsoft.Azure.WebJobs;

using Microsoft.Azure.WebJobs.Extensions.Http;

using Microsoft.AspNetCore.Http;

using Microsoft.Extensions.Logging;

using Newtonsoft.Json;

using System.Data.SqlClient;

using System.Collections.Generic;


namespace SQLFunction

{

    public static class Function1

    {

        [FunctionName("DatabaseFunction")]

        public static async Task<IActionResult> Run(

            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,

            ILogger log)

        {

            log.LogInformation("Connecting to SQL Database");


            //string _conn_string = "Server=adminserver1.database.windows.net,1433;Initial Catalog=ProductDb;Persist Security Info=False;User ID=adminserver1;Password=Admin@123;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";

           string _conn_string = Environment.GetEnvironmentVariable("sql_connection");


            List<Product> _products = new List<Product>();

            using (SqlConnection _connection = new SqlConnection(_conn_string))

            {

                _connection.Open();

                string _query = "select Id,Name,price from Products";



                using (SqlCommand _cmd = new SqlCommand(_query, _connection))

                {

                    SqlDataReader _reader = _cmd.ExecuteReader();

                    while (_reader.Read())

                    {

                        Product obj = new Product();

                        obj.Id = _reader.GetInt32(0);

                        obj.Name = _reader.GetString(1);

                        obj.price = _reader.GetString(2);

                        _products.Add(obj);

                    }

                }

            }


            return new OkObjectResult(_products);

        }

    }

}


and for sql data client add below


<ItemGroup>

    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.3" />

    <PackageReference Include="System.Data.SqlClient" Version="4.8.1" />

  </ItemGroup>

  <ItemGroup>

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();

        }

    }

}