Using APIM and Azure Event Grid Topic and call two diffrent azure functions
Dot Net Sea
Dot Net Sea
Thursday, 17 June 2021
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
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
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; }
}
}
}
Step 3 Now configure the json file in program file.cs
Sunday, 4 October 2020
show custom exception page in .net core
Global exception handling in database in .net core
step 1 : Create global exception solution as below
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 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();
}
}
}









