<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>c# &#8211; achraf ben alaya</title>
	<atom:link href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/category/blog/c/feed/" rel="self" type="application/rss+xml" />
	<link>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net</link>
	<description>Tech Blog By Achraf Ben Alaya</description>
	<lastBuildDate>Wed, 23 Nov 2022 22:11:47 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.5</generator>

<image>
	<url>/wp-content/uploads/2022/02/cropped-me-scaled-1-32x32.jpeg</url>
	<title>c# &#8211; achraf ben alaya</title>
	<link>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">189072172</site>	<item>
		<title>How to setup nginx reverse proxy for aspnet core apps with and without  Docker compose</title>
		<link>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2022/11/16/how-to-setup-nginx-reverse-proxy-for-aspnet-core-apps-with-and-without-docker-compose/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-setup-nginx-reverse-proxy-for-aspnet-core-apps-with-and-without-docker-compose</link>
					<comments>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2022/11/16/how-to-setup-nginx-reverse-proxy-for-aspnet-core-apps-with-and-without-docker-compose/#comments</comments>
		
		<dc:creator><![CDATA[achraf]]></dc:creator>
		<pubDate>Wed, 16 Nov 2022 21:29:19 +0000</pubDate>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[docker]]></category>
		<guid isPermaLink="false">https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/?p=1471</guid>

					<description><![CDATA[Introduction First of all and before we go straight to deployment and demo let&#8217;s understand what is a reverse proxy . A reverse proxy intercepts all incoming requests and direct them to the appropriate server ,it can play the role of Load Balancer &#8221; a Traffic Cop &#8221; that will distribute the clients requests across [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>First of all and before we go straight to deployment and demo let&#8217;s understand what is a reverse proxy .</p>
<p>A reverse proxy intercepts all incoming requests and direct them to the appropriate server ,it can play the role of Load Balancer &#8221; a Traffic Cop &#8221; that will distribute the clients requests across group of servers in order to maximizes speed and capacity and making sure that no server is overloaded (in case a server is down the load balancer will redirect the traffic to the other servers ) ,more than that a reverse proxy will protect the identity of the other servers and act as a defense againsts security attacks .In this sense the reverse proxy will make sure that multiple servers can be accessed only from a single URL .</p>
<h3>Prerequisites</h3>
<ul>
<li>Visual studio or visual studio code</li>
<li>A command mine /Terminal</li>
<li>Docker installed on your system</li>
</ul>
<h2>Part 1- Without Docker Compose</h2>
<p>in this first part we will create our dotnet application that we will use now and later too , also nginx .<br />
<a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2022/11/dotnet.png"><img fetchpriority="high" decoding="async" class="aligncenter size-full wp-image-1474" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2022/11/dotnet.png" alt="" width="1004" height="668" srcset="/wp-content/uploads/2022/11/dotnet.png 1004w, /wp-content/uploads/2022/11/dotnet-300x200.png 300w, /wp-content/uploads/2022/11/dotnet-768x511.png 768w, /wp-content/uploads/2022/11/dotnet-750x499.png 750w" sizes="(max-width: 1004px) 100vw, 1004px" /></a>and we will go straight to our <strong>Index.cshtml  </strong>, and edit it to be like this :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">@page
@model IndexModel

@{
    ViewData["Title"] = "Home page";
    var hostname = ViewData["host"];
}

&lt;div class="text-center"&gt;
    &lt;h1 class="display-4"&gt;Welcome&lt;/h1&gt;
    &lt;p&gt;Learn about &lt;a href="https://docs.microsoft.com/aspnet/core"&gt;building Web apps with ASP.NET Core&lt;/a&gt;.&lt;/p&gt;
    &lt;p&gt;
        &lt;strong&gt;Hostname :&lt;/strong&gt; &lt;h3&gt; &lt;code&gt;@hostname&lt;/code&gt;&lt;/h3&gt;
    &lt;/p&gt;
&lt;/div&gt;
</pre>
<p>Also we will edit the <strong>Index.cshtml.cs </strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Net;

namespace hostnameapp.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger&lt;IndexModel&gt; _logger;
        [BindProperty]
        public string? hostname { get; set; }
        public IndexModel(ILogger&lt;IndexModel&gt; logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {
            String hostName = Dns.GetHostName();
            Console.WriteLine(hostName);
            ViewData["host"] = hostName;
            

        }
    }
}</pre>
<p>now if we run the application using IIS express we will have this view  :<br />
<a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2022/11/hostname.png"><img decoding="async" class="aligncenter size-full wp-image-1475" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2022/11/hostname.png" alt="" width="1708" height="888" srcset="/wp-content/uploads/2022/11/hostname.png 1708w, /wp-content/uploads/2022/11/hostname-300x156.png 300w, /wp-content/uploads/2022/11/hostname-1024x532.png 1024w, /wp-content/uploads/2022/11/hostname-768x399.png 768w, /wp-content/uploads/2022/11/hostname-1536x799.png 1536w, /wp-content/uploads/2022/11/hostname-750x390.png 750w, /wp-content/uploads/2022/11/hostname-1140x593.png 1140w" sizes="(max-width: 1708px) 100vw, 1708px" /></a>As you can see the goal here is to show the hostname , nothing special .</p>
<p>now we will dockeriz application by creating a dockerfile  with this content (full source code of the solution will be shared )</p>
<pre class="EnlighterJSRAW" data-enlighter-language="raw">FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine AS base

WORKDIR /app
ENV ASPNETCORE_URLS http://+:5000
# EXPOSE 80
EXPOSE 5000

FROM mcr.microsoft.com/dotnet/sdk:6.0-alpine AS build
WORKDIR /src
COPY ["hostnameapp/hostnameapp.csproj", "hostnameapp/"]
RUN dotnet restore "hostnameapp/hostnameapp.csproj"
COPY . .
WORKDIR "/src/hostnameapp"
RUN dotnet build "hostnameapp.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "hostnameapp.csproj" -c Release -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "hostnameapp.dll"]</pre>
<p>now we will create the nginx application but we have some config for the app :<br />
we will create  a file : nginx.conf</p>
<pre class="EnlighterJSRAW" data-enlighter-language="nginx">worker_processes 4;
 
events { worker_connections 1024; }
 
http {
    sendfile on;
    limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;
    # upstream app_servers {
    #     #server app:127.0.0.1:5000;
    #   # server  http://backend:5000;
    # }
 
    server {
        listen 80;
 
        location / {
            proxy_pass          http://backend:5000;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }
    }
}</pre>
<p>Also we are going to docke the nginx proxy app</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">FROM nginx:alpine
RUN rm -r  /etc/nginx/nginx.conf
COPY nginx.conf /etc/nginx/nginx.conf</pre>
<p>now we can build both apps and run them to see what will happen .</p>
<p>let&#8217;s start with our dotnet application we need to build and run our solution :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">docker build -t backend  .
docker run -it --rm -p 5000:5000   --name backend backend</pre>
<p>Now if you go to your browser and visit :  http://localhost:5000/ you will have this result :</p>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2022/11/dockerps.png"><img decoding="async" class="aligncenter size-full wp-image-1477" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2022/11/dockerps.png" alt="" width="1542" height="805" srcset="/wp-content/uploads/2022/11/dockerps.png 1542w, /wp-content/uploads/2022/11/dockerps-300x157.png 300w, /wp-content/uploads/2022/11/dockerps-1024x535.png 1024w, /wp-content/uploads/2022/11/dockerps-768x401.png 768w, /wp-content/uploads/2022/11/dockerps-1536x802.png 1536w, /wp-content/uploads/2022/11/dockerps-750x392.png 750w, /wp-content/uploads/2022/11/dockerps-1140x595.png 1140w" sizes="(max-width: 1542px) 100vw, 1542px" /></a></p>
<p>And now as you can see our hostname have the id of the container .</p>
<p>now it&#8217;s time to run the nginx proxy that will be the entry to our application or let&#8217;s say the way we will expose our application .</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">docker build -t frontend  .
docker run -it --rm -p 8082:80   --name frontend frontend</pre>
<p>if we run those commandes the project will build but will not run and we will finish by having an error saying that host not found , the host is the backend that we defined in the config file with port 5000 , and that&#8217;s because the two containers are not in the same network !<br />
now let&#8217;s make some changes :<br />
Let&#8217;s create a network :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">docker network create demonetwork-001;
#to inspect that network 
docker network inspect demonetwork-001;</pre>
<p>now we need to attach our containers to the network that we have created  :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">docker network connect demonetwork-001 backend;
#this will fail because the container did exit beceause of error
docker network connect demonetwork-001 frontend;

--------------instead we will use this -------------------------
docker run -it --rm -p 5000:5000 --network=demonetwork-001  --name backend backend
docker run -it --rm -p 8082:80  --network=demonetwork-001  --name frontend frontend</pre>
<p>and like that we will have our result  while visiting our entry point on port 8082 :<a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2022/11/finalwithoutcompose.png"><br />
<img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1478" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2022/11/finalwithoutcompose.png" alt="" width="1902" height="884" srcset="/wp-content/uploads/2022/11/finalwithoutcompose.png 1902w, /wp-content/uploads/2022/11/finalwithoutcompose-300x139.png 300w, /wp-content/uploads/2022/11/finalwithoutcompose-1024x476.png 1024w, /wp-content/uploads/2022/11/finalwithoutcompose-768x357.png 768w, /wp-content/uploads/2022/11/finalwithoutcompose-1536x714.png 1536w, /wp-content/uploads/2022/11/finalwithoutcompose-750x349.png 750w, /wp-content/uploads/2022/11/finalwithoutcompose-1140x530.png 1140w" sizes="(max-width: 1902px) 100vw, 1902px" /></a></p>
<h2>Part 2- With Docker Compose</h2>
<p>now all we need is to create a docker compose file without editing our solutions : docker-compose.yml</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">version: "3.9"
services:
  app:
    build: ./hostnameapp
    expose: 
      - "5000"    
  proxy:
    #image: nginx:alpine
    build: ./nginx
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
    depends_on:
      - app
    links:
      - app  
    ports:
      - "8082:80"</pre>
<p>now in our file we define the two apps and we say that the proxy app depends on the first app let see the result :<br />
<a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2022/11/composefinal.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1480" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2022/11/composefinal.png" alt="" width="1808" height="827" srcset="/wp-content/uploads/2022/11/composefinal.png 1808w, /wp-content/uploads/2022/11/composefinal-300x137.png 300w, /wp-content/uploads/2022/11/composefinal-1024x468.png 1024w, /wp-content/uploads/2022/11/composefinal-768x351.png 768w, /wp-content/uploads/2022/11/composefinal-1536x703.png 1536w, /wp-content/uploads/2022/11/composefinal-750x343.png 750w, /wp-content/uploads/2022/11/composefinal-1140x521.png 1140w" sizes="(max-width: 1808px) 100vw, 1808px" /></a>and this is our goal , we want the backend not to be exposed to public and we want our frontend exposed as you can see on port 8082 and we can not acces the backend , now if we modify the config file and add different backends with different port the load balancer will play it&#8217;s role to manage the traffic between the apps .</p>
<p>Now if we have the same app on different port and we edit the config file like this ofr example :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">worker_processes 4;
 
events { worker_connections 1024; }
 
http {
    sendfile on;
 
    upstream app_servers {
        server app:5000 weight=4;
        server app2:5010 weight=2;
    }
 
    server {
        listen 80;
 
        location / {
            proxy_pass         http://app_servers;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }
    }
}

</pre>
<p>the result will show that we balance between the two apps</p>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2022/11/chrome-capture-2022-10-16.gif"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1481" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2022/11/chrome-capture-2022-10-16.gif" alt="" width="1000" height="500" /></a></p>
<p>that&#8217;s it for this demo , in next post we will discuss how we will do this on <em>Azure Kubernetes Service</em> (<em>AKS</em>) .</p>
<p>&nbsp;</p>
<p>source code :<strong> <a href="https://bit.ly/3EDJVus">https://bit.ly/3EDJVus</a></strong></p>
]]></content:encoded>
					
					<wfw:commentRss>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2022/11/16/how-to-setup-nginx-reverse-proxy-for-aspnet-core-apps-with-and-without-docker-compose/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1471</post-id>	</item>
		<item>
		<title>Background Tasks With Hangfire And .Net 5</title>
		<link>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2021/01/25/hangfire/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=hangfire</link>
					<comments>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2021/01/25/hangfire/#respond</comments>
		
		<dc:creator><![CDATA[achraf]]></dc:creator>
		<pubDate>Mon, 25 Jan 2021 08:41:50 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[hangfire]]></category>
		<category><![CDATA[tasks]]></category>
		<guid isPermaLink="false">https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/?p=995</guid>

					<description><![CDATA[Introduction. Hangfire is a .Net Library that help to perform background processing in .NET and .NET Core applications in a easy way . No Windows Service or separate process required. Backed by persistent storage. Open and free for commercial use. In this article we are going to create a simple project and will be shared [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Introduction.</h1>
<p>Hangfire is a .Net Library that help to perform background processing in .NET and .NET Core applications in a easy way .<br />
No Windows Service or separate process required.<br />
Backed by persistent storage. Open and free for commercial use.</p>
<p>In this article we are going to create a simple project and will be shared in GitHub repo .</p>
<p><strong>Plan :</strong></p>
<p>1-What is Hangfire<br />
2-Background tasks in ASP.NET Core<br />
3-Setup and Configure Hangfire<br />
4-Secure the Hangfire Dashboard<br />
5-Retention Time<br />
6-Hangfire and SQL server</p>
<h1>What is Hangfire :</h1>
<p>Hangfire is an open-source framework that helps you to create, process and manage your background jobs, i.e. operations you don&#8217;t want to put in your request processing pipeline:</p>
<p>&#8211; mass notifications/newsletter  .<br />
&#8211; batch import from xml, csv, json .<br />
&#8211; creation of archives .<br />
&#8211; firing off web hooks .<br />
&#8211; deleting users .<br />
&#8211; building different graphs .<br />
&#8211; image/video processing .<br />
&#8211; purge temporary files .<br />
&#8211; recurring automated reports .<br />
&#8211; database maintenance.</p>
<p><a href="https://www.hangfire.io/overview.html">Hangfire</a> supports all kind of background tasks – short-running and long-running, CPU intensive and I/O intensive, one shot and recurrent. You don’t need to reinvent the wheel – it is ready to use.<br />
Hangfire is shipped with an awesome tool – Web Monitoring UI. It is implemented as an OWIN extension and can be hosted inside any application – ASP.NET, Console or Windows Service. Monitoring UI allows you to see and control any aspect of background job processing, including statistics, exceptions and background job history.</p>
<h1>Background tasks in ASP.NET Core :</h1>
<p>&nbsp;</p>
<p>Background tasks and scheduled jobs are something you might need to use in any application,sometimes it is necessary to schedule and create long-running methods for our .NET Core applications.</p>
<p>Note  :</p>
<p>If you are using cloud you can use in Azure :</p>
<p><strong>Azure WebJobs</strong></p>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/download.png"><img loading="lazy" decoding="async" class="size-full wp-image-997 alignleft" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/download.png" alt="" width="218" height="232" /></a></p>
<p><span style="color: #000000;">A formal Azure feature used for offloading running of background tasks outside of your Website and scale the workload.</span></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p><strong>Azure Worker Role in a Cloud Service :</strong></p>
<p>Scale the background processing workload independently of your Website and you need control over the machine .</p>
<p>&nbsp;</p>
<h1>Setup and Configure Hangfire</h1>
<p>First we are going to create a new project than we are going to install few nuget packages to our project so we can use hangfire .</p>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/hangfire1.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-998" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/hangfire1.png" alt="" width="1882" height="1048" srcset="/wp-content/uploads/2021/01/hangfire1.png 1882w, /wp-content/uploads/2021/01/hangfire1-300x167.png 300w, /wp-content/uploads/2021/01/hangfire1-1024x570.png 1024w, /wp-content/uploads/2021/01/hangfire1-768x428.png 768w, /wp-content/uploads/2021/01/hangfire1-1536x855.png 1536w, /wp-content/uploads/2021/01/hangfire1-750x418.png 750w, /wp-content/uploads/2021/01/hangfire1-1140x635.png 1140w" sizes="(max-width: 1882px) 100vw, 1882px" /></a></p>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/hangfire2.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-999" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/hangfire2.png" alt="" width="1839" height="999" srcset="/wp-content/uploads/2021/01/hangfire2.png 1839w, /wp-content/uploads/2021/01/hangfire2-300x163.png 300w, /wp-content/uploads/2021/01/hangfire2-1024x556.png 1024w, /wp-content/uploads/2021/01/hangfire2-768x417.png 768w, /wp-content/uploads/2021/01/hangfire2-1536x834.png 1536w, /wp-content/uploads/2021/01/hangfire2-750x407.png 750w, /wp-content/uploads/2021/01/hangfire2-1140x619.png 1140w" sizes="(max-width: 1839px) 100vw, 1839px" /></a></p>
<ul>
<li>Hangfire.AspNetCore  .<br />
Hangfire.SqlServer    .<br />
Hangfire.MemoryStorage .<br />
Hangfire.Dashboard.Basic.Authentication  .</li>
</ul>
<p><strong>Create Model : </strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">using System;  
using System.Collections.Generic;  
using System.ComponentModel.DataAnnotations;  
using System.Linq;  
using System.Threading.Tasks;  
  
namespace Hangfire.Model  
{  
    public class Student
    {  
        [Key]
        public int Id { get; set; }
        public string StudentName { get; set; }
        public string StudentProblem { get; set; } 
    }  
}</pre>
<p><strong> AppDbContext</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">using Hangfire.Model;  
using Microsoft.EntityFrameworkCore;  
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
  
namespace DemoHangfireNet5.AppDbContext
{
    public partial class StudentDbContext : DbContext
    {
        public StudentDbContext(DbContextOptions options) : base(options)
        {

        }
        public DbSet&lt;Student&gt; Students { get; set; }
    }
}</pre>
<p><strong>appsettings.json</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "myconnection": "Server=localhost; database=demo;Trusted_Connection=True;"
  }
}</pre>
<p>Then we have to create the table using the below migration commands in the package manager console.</p>
<p>Creates migration folder and migration script inside the target project.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">Add-Migration 'MigrationName1'  


</pre>
<p>The next command executes the migration script and creates a table in the database</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">Update-Database</pre>
<p>Note : if you have problem with <strong>The term “Add-Migration” is not recognized  you &#8221; ,</strong> you should Just install <strong>Microsoft.EntityFrameworkCore.Tools </strong>package from nuget.</p>
<p><strong>Services </strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">IStudentService.cs

namespace DemoHangfireNet5.Services
{
    public interface IStudentService
    {
        Task&lt;bool&gt; InsertStudentsAsync();
    }
}</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">   public class StudentService : IStudentService
    {
        #region Property  
        private readonly StudentDbContext _StudentDbContext;
        #endregion

        public StudentService(StudentDbContext StudentDbContext)
        {
            _StudentDbContext= StudentDbContext;
        }

        public async Task&lt;bool&gt; InsertStudentsAsync()
        {
            try
            {
                Student _Student = new Student()
                {
                    StudentName = "Alex",
                    StudentProblem = "Failing to network"

                };
                await _StudentDbContext.AddAsync(_Student);
                await _StudentDbContext.SaveChangesAsync();
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }
    } 
</pre>
<p><strong>background tasks :</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">Jobs

using DemoHangfireNet5.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DemoHangfireNet5.Jobs
{
    public class Job
    {
        #region Property
        private readonly IStudentService _IStudentService;
        #endregion

        #region Constructor
        public Job(IStudentService IStudentService)
        {
            _IStudentService = IStudentService;
        }
        #endregion

        #region Job Scheduler
        public async Task&lt;bool&gt; JobAsync()
        {
            var result = await _IStudentService.InsertStudentsAsync();
            return true;
        }
        #endregion
    }
}</pre>
<p>Note : do not forget to inject the service in startup.cs</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">services.AddTransient&lt;IStudentService, StudentService&gt;();</pre>
<p>&nbsp;</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">using DemoHangfireNet5.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HangfireBasicAuthenticationFilter;
using DemoHangfireNet5.AppDbContext;
using Microsoft.EntityFrameworkCore;
using Hangfire;
using DemoHangfireNet5.Jobs;

namespace DemoHangfireNet5
{
    public class Startup
    {
        private static IStudentService IStudentService;
        private readonly Job jobscheduler = new Job(IStudentService);
        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.AddSwaggerGen(c =&gt;
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "DemoHangfireNet5", Version = "v1" });
            });




            #region Configure Connection String
            services.AddDbContext&lt;StudentDbContext&gt;(item =&gt; item.UseSqlServer(Configuration.GetConnectionString("myconnection")));
            #endregion

            #region Configure Hangfire
            services.AddHangfire(c =&gt; c.UseSqlServerStorage(Configuration.GetConnectionString("myconnection")));
            GlobalConfiguration.Configuration.UseSqlServerStorage(Configuration.GetConnectionString("myconnection")).WithJobExpirationTimeout(TimeSpan.FromDays(7));
            #endregion

            #region Services Injection
            services.AddTransient&lt;IStudentService, StudentService&gt;();
            #endregion

        }








        // 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.UseSwagger();
                app.UseSwaggerUI(c =&gt; c.SwaggerEndpoint("/swagger/v1/swagger.json", "DemoHangfireNet5 v1"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =&gt;
            {
                endpoints.MapControllers();
            });
        }
    }
}
</pre>
<h1>Secure the Hangfire Dashboard</h1>
<p>To Secure the hangfire dashboard we setup login authentication in order to access the hangfire dashboard. I have hardcoded the username and password in the appsettings.js file to consume those in the startup.cs</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">"HangfireCredentials": {
"UserName": "adminadmin",
"Password": "admin@xxx#"
}</pre>
<p>in<strong> startup.cs</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">app.UseHangfireDashboard("/hangfire", new DashboardOptions()  
{  
    AppPath = null,  
    DashboardTitle = "Hangfire Dashboard",  
    Authorization = new[]{  
    new HangfireCustomBasicAuthenticationFilter{  
        User = Configuration.GetSection("HangfireCredentials:UserName").Value,  
        Pass = Configuration.GetSection("HangfireCredentials:Password").Value  
    }  
},  
});</pre>
<p>&nbsp;</p>
<h1>Hangfire Retention Time</h1>
<p>Usually, the hangfire jobs running in the background will elapse for 24 hours.<br />
To avoid this I have to enable the basic setting to last this job in the dashboard for at least 2 week.</p>
<p><strong>Startup.cs</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">GlobalConfiguration.Configuration.UseSqlServerStorage(Configuration.GetConnectionString("myconn")).WithJobExpirationTimeout(TimeSpan.FromDays(14));</pre>
<h1>Persistence with SQL Database</h1>
<p>Hangfire has an option to store all the job-related information in the database.<br />
For this we don&#8217;t need anything we have to configure this setup in the <strong>Startup.cs</strong> and it automatically creates all the tables where we can see the job status and respective information in those tables.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">services.AddHangfire(c =&gt; c.UseSqlServerStorage(Configuration.GetConnectionString("myconn")));</pre>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/database2.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1000" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/database2.png" alt="" width="352" height="485" srcset="/wp-content/uploads/2021/01/database2.png 352w, /wp-content/uploads/2021/01/database2-218x300.png 218w" sizes="(max-width: 352px) 100vw, 352px" /></a></p>
<p>The above set of tables were created automatically when we configured the setup and point to the database.</p>
<p>There are 4 types of jobs that mostly we will use :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">#region Job Scheduling Tasks  
// Recurring Job for every 5 min  
recurringJobManager.AddOrUpdate("Insert Employee : Runs Every 1 Min", () =&gt; jobscheduler.JobAsync(), "*/5 * * * *");  
  
//Fire and forget job   
var jobId =  backgroundJobClient.Enqueue(() =&gt; jobscheduler.JobAsync());  
  
//Continous Job  
backgroundJobClient.ContinueJobWith(jobId, () =&gt; jobscheduler.JobAsync());  
  
//Schedule Job / Delayed Job  
  
backgroundJobClient.Schedule(() =&gt; jobscheduler.JobAsync(), TimeSpan.FromDays(5));  
#endregion</pre>
<p>&#8211; Recurring job &#8211; Every 5 minutes the background task runs and inserts data into database (you can use this website to understand the cron jobs  time : https://crontab.guru/#*/5)</p>
<p>&#8211; Fire and Forget &#8211; This job runs only once when we run the application.</p>
<p>&#8211; Continuous Job &#8211; When we want to run jobs one after another at that time this will be useful so that it will execute one by one.</p>
<p>&#8211; Schedule Job &#8211; If you want to schedule a task to run at a particular time.</p>
<p>Run the application</p>
<p>By default, the swagger endpoint will open. Now type hangfireDashboard as we defined in the URL by removing the swagger. It will ask for a username and password as we had already set up the authentication mechanism .</p>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/hangfiredasboard.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1004" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/hangfiredasboard.png" alt="" width="1901" height="1070" srcset="/wp-content/uploads/2021/01/hangfiredasboard.png 1901w, /wp-content/uploads/2021/01/hangfiredasboard-300x169.png 300w, /wp-content/uploads/2021/01/hangfiredasboard-1024x576.png 1024w, /wp-content/uploads/2021/01/hangfiredasboard-768x432.png 768w, /wp-content/uploads/2021/01/hangfiredasboard-1536x865.png 1536w, /wp-content/uploads/2021/01/hangfiredasboard-750x422.png 750w, /wp-content/uploads/2021/01/hangfiredasboard-1140x642.png 1140w" sizes="(max-width: 1901px) 100vw, 1901px" /></a></p>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/dashboard1.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1001" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/dashboard1.png" alt="" width="1901" height="1069" srcset="/wp-content/uploads/2021/01/dashboard1.png 1901w, /wp-content/uploads/2021/01/dashboard1-300x169.png 300w, /wp-content/uploads/2021/01/dashboard1-1024x576.png 1024w, /wp-content/uploads/2021/01/dashboard1-768x432.png 768w, /wp-content/uploads/2021/01/dashboard1-1536x864.png 1536w, /wp-content/uploads/2021/01/dashboard1-750x422.png 750w, /wp-content/uploads/2021/01/dashboard1-1140x641.png 1140w" sizes="(max-width: 1901px) 100vw, 1901px" /></a> <a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/dashboard2.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1002" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/dashboard2.png" alt="" width="1915" height="670" srcset="/wp-content/uploads/2021/01/dashboard2.png 1915w, /wp-content/uploads/2021/01/dashboard2-300x105.png 300w, /wp-content/uploads/2021/01/dashboard2-1024x358.png 1024w, /wp-content/uploads/2021/01/dashboard2-768x269.png 768w, /wp-content/uploads/2021/01/dashboard2-1536x537.png 1536w, /wp-content/uploads/2021/01/dashboard2-750x262.png 750w, /wp-content/uploads/2021/01/dashboard2-1140x399.png 1140w" sizes="(max-width: 1915px) 100vw, 1915px" /></a> <a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/dashboard3.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1003" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/dashboard3.png" alt="" width="1906" height="578" srcset="/wp-content/uploads/2021/01/dashboard3.png 1906w, /wp-content/uploads/2021/01/dashboard3-300x91.png 300w, /wp-content/uploads/2021/01/dashboard3-1024x311.png 1024w, /wp-content/uploads/2021/01/dashboard3-768x233.png 768w, /wp-content/uploads/2021/01/dashboard3-1536x466.png 1536w, /wp-content/uploads/2021/01/dashboard3-750x227.png 750w, /wp-content/uploads/2021/01/dashboard3-1140x346.png 1140w" sizes="(max-width: 1906px) 100vw, 1906px" /></a><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/jobs.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1005" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/01/jobs.png" alt="" width="1924" height="687" srcset="/wp-content/uploads/2021/01/jobs.png 1924w, /wp-content/uploads/2021/01/jobs-300x107.png 300w, /wp-content/uploads/2021/01/jobs-1024x366.png 1024w, /wp-content/uploads/2021/01/jobs-768x274.png 768w, /wp-content/uploads/2021/01/jobs-1536x548.png 1536w, /wp-content/uploads/2021/01/jobs-750x268.png 750w, /wp-content/uploads/2021/01/jobs-1140x407.png 1140w" sizes="(max-width: 1924px) 100vw, 1924px" /></a></p>
<p>&nbsp;</p>
<p><strong>Link to project</strong> : <a href="https://bit.ly/3sSte6H">https://bit.ly/3sSte6H</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2021/01/25/hangfire/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">995</post-id>	</item>
		<item>
		<title>Swagger &#038; OpenAPI and Versioning for ASP.NET Core</title>
		<link>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/12/08/swagger-openapi-and-versioning-for-asp-net-core/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=swagger-openapi-and-versioning-for-asp-net-core</link>
					<comments>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/12/08/swagger-openapi-and-versioning-for-asp-net-core/#respond</comments>
		
		<dc:creator><![CDATA[achraf]]></dc:creator>
		<pubDate>Tue, 08 Dec 2020 11:21:32 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[swagger]]></category>
		<guid isPermaLink="false">https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/?p=897</guid>

					<description><![CDATA[Introduction When you create a new .Netcore web API project ,you need to present and define in a very easy way to read .In this case , Swagger is the solution . Swagger is an Interface Description Language for describing RESTful APIs expressed using JSON. Swagger is used together with a set of open-source software [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1 id="e41e" class="ig ih ga as ii ij ik il im in io ip iq ir is it iu iv iw ix iy iz ja jb jc jd er">Introduction</h1>
<p>When you create a new .Netcore web API project ,you need to present and define in a very easy way to read .<br />In this case , Swagger is the solution .</p>
<p>Swagger is an Interface Description Language for describing RESTful APIs expressed using JSON. Swagger is used together with a set of open-source software tools to design, build, document, and use RESTful web services. Swagger includes automated documentation, code generation, and test-case generation.</p>
<p>Adding Swagger to a Web Api Core 3.1 project</p>
<p>You can add swagger to the project by installing the following NuGet package :</p>
<p><strong>Swashbuckle.AspNetCore</strong></p>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/12/nugetswagger.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-899" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/12/nugetswagger.png" alt="" width="1884" height="647" srcset="/wp-content/uploads/2020/12/nugetswagger.png 1884w, /wp-content/uploads/2020/12/nugetswagger-300x103.png 300w, /wp-content/uploads/2020/12/nugetswagger-1024x352.png 1024w, /wp-content/uploads/2020/12/nugetswagger-768x264.png 768w, /wp-content/uploads/2020/12/nugetswagger-1536x527.png 1536w, /wp-content/uploads/2020/12/nugetswagger-750x258.png 750w, /wp-content/uploads/2020/12/nugetswagger-1140x391.png 1140w" sizes="(max-width: 1884px) 100vw, 1884px" /></a></p>
<h1>Swagger Configuration</h1>
<p>Sometimes configuring a nuget package can be hard and time wasting , but this not the case with swagger .</p>
<p>First we are going to  open <strong>Startup.cs</strong> and add Swagger service inside <strong>ConfigureServices</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">services.AddSwaggerGen(c =&gt;
          {
              c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
          });
</pre>
<p> </p>
<p>After that we are going to enable  Swagger in <strong>Configure()</strong> method :</p>
<p> </p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">app.UseSwagger();
         app.UseSwaggerUI(c =&gt; {

             c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");

         });</pre>
<p> </p>
<p>Now as I mentioned in the demo , we need to configure the launch browser in <strong>Debug</strong> from the properties of the solution :</p>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/12/debug.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-900" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/12/debug.png" alt="" width="1258" height="603" srcset="/wp-content/uploads/2020/12/debug.png 1258w, /wp-content/uploads/2020/12/debug-300x144.png 300w, /wp-content/uploads/2020/12/debug-1024x491.png 1024w, /wp-content/uploads/2020/12/debug-768x368.png 768w, /wp-content/uploads/2020/12/debug-750x359.png 750w, /wp-content/uploads/2020/12/debug-1140x546.png 1140w" sizes="(max-width: 1258px) 100vw, 1258px" /></a></p>
<p> </p>
<p>Now, when we are going to start a new debugging session, we will be redirected to :</p>
<p><strong>http://localhost:[yourportnumber]/swagger</strong></p>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/12/swaggerredicect.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-901" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/12/swaggerredicect.png" alt="" width="1880" height="781" srcset="/wp-content/uploads/2020/12/swaggerredicect.png 1880w, /wp-content/uploads/2020/12/swaggerredicect-300x125.png 300w, /wp-content/uploads/2020/12/swaggerredicect-1024x425.png 1024w, /wp-content/uploads/2020/12/swaggerredicect-768x319.png 768w, /wp-content/uploads/2020/12/swaggerredicect-1536x638.png 1536w, /wp-content/uploads/2020/12/swaggerredicect-750x312.png 750w, /wp-content/uploads/2020/12/swaggerredicect-1140x474.png 1140w" sizes="(max-width: 1880px) 100vw, 1880px" /></a></p>
<p>Now , everything done if you are going to have one version of the API ,next we are going to see how to create different versions.</p>
<h1>Versioning</h1>
<p>When we update the API major version whenever we introduce breaking changes. Internally, we update minor and patch versions whenever we add functionality and backward-compatible updates. When we release a new major version of the an API clients can choose to either continue using an existing major version or migrate to the new one , so different versions must be present .</p>
<p>Changes that we need to do in <strong>Startup.cs :</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace swaggerytDemo
{
    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();

            //Register the Swagger generator, defining 1 or more Swagger documents
            //services.AddSwaggerGen(c =&gt;
            //{
            //    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
            //});

            services.AddControllers(options =&gt;
            {
                options.Conventions.Add(new GroupingByNamespaceConvention());
            });

            services.AddSwaggerGen(config =&gt;
            {
                var titlebase = "Ytdemo1";
                var desc = "Description";
                var termsofservice = new Uri("https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/");
                var license = new OpenApiLicense()
                {
                    Name = "MIT"
                };

                var contact = new OpenApiContact()
                {
                    Name = "achraf",
                    Email = "achrafbenalaya@gmail.com",
                    Url = new Uri("https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/")

                };


                config.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = titlebase + " V 1",
                    Description = desc,
                    Contact = contact,
                    License = license,
                    TermsOfService = termsofservice


                });

                config.SwaggerDoc("v2", new OpenApiInfo
                {
                    Version = "v2",
                    Title = titlebase + " V2",
                    Description = desc,
                    Contact = contact,
                    License = license,
                    TermsOfService = termsofservice


                });

            }

      );





        }

        // 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.UseSwagger();
            app.UseSwaggerUI(c =&gt; {

                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.SwaggerEndpoint("/swagger/v2/swagger.json", "My API V2");

            });



            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =&gt;
            {
                endpoints.MapControllers();
            });
        }
    }
}</pre>
<p> </p>
<p>Now we need to add a convention to let swagger understand the different API version&#8217;s :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">public class GroupingByNamespaceConvention : IControllerModelConvention
 {
     public void Apply(ControllerModel controller)
     {
         var controllerNamespace = controller.ControllerType.Namespace;
         var apiVersion = controllerNamespace.Split(".").Last().ToLower();
         if (!apiVersion.StartsWith("v")) { apiVersion = "v1"; }
         controller.ApiExplorer.GroupName = apiVersion;
     }
 }</pre>
<p> </p>
<p>Now we must apply the convention. For that we need to go to <strong>Startup.cs</strong>  ,look for <strong>ConfigureServices()</strong> and add the convention:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">services.AddControllers(options =&gt;
{
options.Conventions.Add(new GroupingByNamespaceConvention());
});</pre>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/12/versions.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-902" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/12/versions.png" alt="" width="921" height="660" srcset="/wp-content/uploads/2020/12/versions.png 921w, /wp-content/uploads/2020/12/versions-300x215.png 300w, /wp-content/uploads/2020/12/versions-768x550.png 768w, /wp-content/uploads/2020/12/versions-120x86.png 120w, /wp-content/uploads/2020/12/versions-350x250.png 350w, /wp-content/uploads/2020/12/versions-750x537.png 750w" sizes="(max-width: 921px) 100vw, 921px" /></a></p>
<p> </p>
<p>Project <span style="text-decoration: underline; color: #993300;"><a style="color: #993300;" href="https://bit.ly/3mVp22J"><strong>Link</strong></a></span></p>
<p>Full <strong>Demos:</strong></p>


<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="Swagger &amp; OpenAPI and Versioning for ASP.NET Core" width="500" height="281" src="https://www.youtube.com/embed/oraPTgkjtDY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div><figcaption>Swagger</figcaption></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/12/08/swagger-openapi-and-versioning-for-asp-net-core/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">897</post-id>	</item>
		<item>
		<title>Reading Excel file in Azure Web Apps</title>
		<link>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/12/01/reading-excel-file-in-azure-web-apps/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=reading-excel-file-in-azure-web-apps</link>
					<comments>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/12/01/reading-excel-file-in-azure-web-apps/#respond</comments>
		
		<dc:creator><![CDATA[achraf]]></dc:creator>
		<pubDate>Tue, 01 Dec 2020 11:57:25 +0000</pubDate>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[Cloud]]></category>
		<guid isPermaLink="false">https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/?p=883</guid>

					<description><![CDATA[Earlier this month , I was working on a small project for a client ,everyday I receive a couple of excel files that contain some data  ,I have to . 1-Insert this data to a table. 2-Clean the data(empty rows removed ,rows missing data moved to another table). 3-check for duplicated data in this table [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Earlier this month , I was working on a small project for a client ,everyday I receive a couple of excel files that contain some data  ,I have to .</p>
<ul>
<li><strong>1-Insert this data to a table.</strong><br />
<strong>2-Clean the data(empty rows removed ,rows missing data moved to another table).</strong><br />
<strong>3-check for duplicated data in this table and delete them.</strong><br />
<strong>4-check for duplicated data between this table and the original table and if there is duplication and move them to another &#8216;duplication table&#8217;.</strong></li>
</ul>
<p>Now , those steps are only for one received file ,if I have more I loose a lot of time .<br />
So ,I said to my self  ,why not build a small application or website that do all this work for me .</p>
<p>The requirements for my application is to browse for an excel file, Upload the file , read each row from the excel file and insert into a table , when it finish inserting a stored procedure will run a sql query that I have created ,<br />
and of course I will host the web application on azure app service .</p>
<p>So , I developed the web application and tested on my machine and then publish it to azure and at this time ,<br />
I run into the &#8220;It works on my machine&#8221;<br />
<a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/12/live-system-crash-it-worked-on-my-machine.jpg"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-886" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/12/live-system-crash-it-worked-on-my-machine.jpg" alt="" width="400" height="400" srcset="/wp-content/uploads/2020/12/live-system-crash-it-worked-on-my-machine.jpg 400w, /wp-content/uploads/2020/12/live-system-crash-it-worked-on-my-machine-300x300.jpg 300w, /wp-content/uploads/2020/12/live-system-crash-it-worked-on-my-machine-150x150.jpg 150w, /wp-content/uploads/2020/12/live-system-crash-it-worked-on-my-machine-75x75.jpg 75w" sizes="(max-width: 400px) 100vw, 400px" /></a></p>
<p>I mean I tested the app , the connection string everything was fine , I even hosted on my local IIS and it worked smoothly .<br />
So I said it&#8217;s time to investigate so I went to my app service , looked for &#8220;<strong><span id="_weave_e_359" class="msportalfx-font-regular">Diagnose and solve problems</span></strong>&#8221; and than found out this error : &#8216;<strong>The Microsoft.ACE.OLEDB.12.0 provider is not registered on the local machine</strong>&#8216;.</p>
<p>Well  , I&#8217;m using the <strong><code>OleDbDataAdapter</code></strong>to read the data from the excel file into the <code>dataset.<br />
</code>And it seems that the Microsoft.ACE.OLEDB.12.0 Provider is only installed on my machine and can not be available on the azure app service .</p>
<p>So , I had to quickly find a new way to read my excel file without using the <strong><code>OleDbDataAdapter </code></strong>and that when I discovered a plugin : <strong>NPOI .<br />
</strong></p>
<h1>What is NPOI ?</h1>
<p>NPOI is the .NET version of POI Java project at <a href="http://poi.apache.org/" rel="nofollow">http://poi.apache.org/</a>. POI is an open source project which can help you read/write xls, doc, ppt files. It has a wide application.</p>
<p>For example, you can use it to</p>
<ul>
<li>generate a Excel report without Microsoft Office suite installed on your server and more efficient than call Microsoft Excel ActiveX at background;</li>
<li>extract text from Office documents to help you implement full-text indexing feature (most of time this feature is used to create search engines).</li>
<li>extract images from Office documents</li>
<li style="text-align: left;">generate Excel sheets that contains formulas .</li>
</ul>
<p>You can install the package by running this command :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">Install-Package DotNetCore.NPOI</pre>
<p>&nbsp;</p>
<p>Now , this is the way I was reading my excel file using the <strong><code>OleDbDataAdapter :<br />
</code><br />
</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">//get extension
string extension = Path.GetExtension(filename);           
string conString = string.Empty;
switch (extension)
{
   case ".xls": //Excel 97-03.
       conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=YES'";
       break;
   case ".xlsx": //Excel 07 and above.
       conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=YES'";
       break;
}

DataTable dt = new DataTable();
conString = string.Format(conString, filePath);

using (OleDbConnection connExcel = new OleDbConnection(conString))
{
   using (OleDbCommand cmdExcel = new OleDbCommand())
   {
       using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
       {
           cmdExcel.Connection = connExcel;
           connExcel.Open();
           DataTable dtExcelSchema;
           dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
           string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
           connExcel.Close();
           connExcel.Open();
           cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
           odaExcel.SelectCommand = cmdExcel;
           odaExcel.Fill(dt);
           var x = dt.Columns.AsParallel();
           connExcel.Close();
       }
   }
}</pre>
<p>&nbsp;</p>
<p>Now using the NPOI package we can do the same reading and clear out our problem and we don&#8217;t have to worry about it again .</p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">     private static DataTable GetRequestsDataFromExcel(string fullFilePath)
     {
         try
         {
             var sh = GetFileStream(fullFilePath);
             var dtExcelTable = new DataTable();
             dtExcelTable.Rows.Clear();
             dtExcelTable.Columns.Clear();
             var headerRow = sh.GetRow(0);
             int colCount = headerRow.LastCellNum;
             for (var c = 0; c &lt; colCount; c++)
                 dtExcelTable.Columns.Add(headerRow.GetCell(c).ToString());
             var i = 1;
             var currentRow = sh.GetRow(i);
             while (currentRow != null)
             {
                 var dr = dtExcelTable.NewRow();
                 for (var j = 0; j &lt; currentRow.Cells.Count; j++)
                 {
                     var cell = currentRow.GetCell(j);

                     if (cell != null)
                         switch (cell.CellType)
                         {
                             case CellType.Numeric:
                                 dr[j] = DateUtil.IsCellDateFormatted(cell)
                                     ? cell.DateCellValue.ToString(CultureInfo.InvariantCulture)
                                     : cell.NumericCellValue.ToString(CultureInfo.InvariantCulture);
                                 break;
                             case CellType.String:
                                 dr[j] = cell.StringCellValue;
                                 break;
                             case CellType.Blank:
                                 dr[j] = string.Empty;
                                 break;
                         }
                 }
                 dtExcelTable.Rows.Add(dr);
                 i++;
                 currentRow = sh.GetRow(i);
             }
             return dtExcelTable;
         }
         catch (Exception e)
         {
             throw;
         }
     }


private static ISheet GetFileStream(string fullFilePath)
     {
         var fileExtension = Path.GetExtension(fullFilePath);
         string sheetName;
         ISheet sheet = null;
         switch (fileExtension)
         {
             case ".xlsx":
                 using (var fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read))
                 {
                     var wb = new XSSFWorkbook(fs);
                     sheetName = wb.GetSheetAt(0).SheetName;
                     sheet = (XSSFSheet)wb.GetSheet(sheetName);
                 }
                 break;
             case ".xls":
                 using (var fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read))
                 {
                     var wb = new HSSFWorkbook(fs);
                     sheetName = wb.GetSheetAt(0).SheetName;
                     sheet = (HSSFSheet)wb.GetSheet(sheetName);
                 }
                 break;
         }
         return sheet;
     }</pre>
<p>&nbsp;</p>
<p>After this , I republished the project and everything worked fine .</p>
<p>well hope this was helpful ,time to get some food .<br />
have a good day <img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p><strong> </strong></p>
]]></content:encoded>
					
					<wfw:commentRss>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/12/01/reading-excel-file-in-azure-web-apps/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">883</post-id>	</item>
		<item>
		<title>Migration from Asp.Net Core 3.1 to 5.0 and publish to azure</title>
		<link>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/11/12/migration-from-asp-net-core-3-1-to-5-0-and-publish-to-azure/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=migration-from-asp-net-core-3-1-to-5-0-and-publish-to-azure</link>
					<comments>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/11/12/migration-from-asp-net-core-3-1-to-5-0-and-publish-to-azure/#respond</comments>
		
		<dc:creator><![CDATA[achraf]]></dc:creator>
		<pubDate>Thu, 12 Nov 2020 11:34:48 +0000</pubDate>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[Cloud]]></category>
		<guid isPermaLink="false">https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/?p=875</guid>

					<description><![CDATA[Microsoft announced the release of .NET 5.0 days ago , the stable version of course , now it&#8217;s time to think about migrating your project . I usually see my friends postpone upgrading their projects to a newer version because of some factors like : the complexity ,the effort and the cost ,so they end [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Microsoft announced the release of <strong>.NET 5.0</strong> days ago , the stable version of course , now it&#8217;s time to think about migrating your project .</p>
<p>I usually see my friends postpone upgrading their projects to a newer version because of some factors like : the complexity ,the effort and the cost ,so they end up not migrating to a new version and loose the improvements and postpone that to another time and they forget that the more the project is complex , the more the migration becomes complex .</p>
<p>You can upgrade your system by updating visual studio 2019 to the latest version (the update will install the new .NET 5.0 but if you want to install it by your self you can do it from this <span style="color: #ff0000;"><a style="color: #ff0000;" href="https://bit.ly/35kIuiR"><strong>Link</strong></a></span>)</p>
<h1>
<strong>Upgrading a net core project :</strong></h1>
<p>simply to to do the migration you have to go to properties and change the target framework to .NET 5.0 .<br />
Well , of course now you need to build the project and if everything is fine you will see succeeded ,</p>
<p>else you will have to investigate issue by issue ,for that do not forget to upgrade the packages used by your application to the newest possible version .</p>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/11/migratpro.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-876" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/11/migratpro.png" alt="" width="1895" height="1080" srcset="/wp-content/uploads/2020/11/migratpro.png 1895w, /wp-content/uploads/2020/11/migratpro-300x171.png 300w, /wp-content/uploads/2020/11/migratpro-1024x584.png 1024w, /wp-content/uploads/2020/11/migratpro-768x438.png 768w, /wp-content/uploads/2020/11/migratpro-1536x875.png 1536w, /wp-content/uploads/2020/11/migratpro-750x427.png 750w, /wp-content/uploads/2020/11/migratpro-1140x650.png 1140w" sizes="(max-width: 1895px) 100vw, 1895px" /></a></p>
<p>&nbsp;</p>
<p>I think that was easy , now what if you want to publish this project to azure ?</p>
<h1>
<strong>Publish .NET 5.0 to </strong><b>Azure</b></h1>
<p>With the announcement of the new version of .NET 5.0 , Microsoft have added a new option to publish the new update in app service .<br />
If you go and create a new app service (Create Web App) you will see under the Runtime stack a new option was added : .NET 5 (Early access) ;</p>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/11/NET5.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-877" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/11/NET5.png" alt="" width="1229" height="1027" srcset="/wp-content/uploads/2020/11/NET5.png 1229w, /wp-content/uploads/2020/11/NET5-300x251.png 300w, /wp-content/uploads/2020/11/NET5-1024x856.png 1024w, /wp-content/uploads/2020/11/NET5-768x642.png 768w, /wp-content/uploads/2020/11/NET5-750x627.png 750w, /wp-content/uploads/2020/11/NET5-1140x953.png 1140w" sizes="(max-width: 1229px) 100vw, 1229px" /></a></p>
<p>&nbsp;</p>
<p>all you have to do is to create the app download the profile and publish your solution .</p>
<p>&nbsp;</p>
<p><img decoding="async" src="https://cmdpablo74.blob.core.windows.net/mdiafiles/NET5.0.gif" /></p>
<p>&nbsp;</p>
<p>If you have any question feel free to contact me .</p>
<p>Thank you for reading my article ! <img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/11/12/migration-from-asp-net-core-3-1-to-5-0-and-publish-to-azure/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">875</post-id>	</item>
		<item>
		<title>Setting up Serilog in ASP.NET Core</title>
		<link>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/09/13/setting-up-serilog-in-asp-net-core/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=setting-up-serilog-in-asp-net-core</link>
					<comments>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/09/13/setting-up-serilog-in-asp-net-core/#respond</comments>
		
		<dc:creator><![CDATA[achraf]]></dc:creator>
		<pubDate>Sun, 13 Sep 2020 14:15:37 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[c#]]></category>
		<guid isPermaLink="false">https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/?p=680</guid>

					<description><![CDATA[WHAT TO LOG It is not enough to log errors in order to use them for troubleshooting purposes. It is also useful to log successful requests so we can have a clear idea of how users work with the application . Logs are also useful to detect  mistakes that users make, as well as for [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2><strong>WHAT TO LOG</strong></h2>
<p>It is not enough to log errors in order to use them for troubleshooting purposes. It is also useful to log successful requests so we can have a clear idea of how users work with the application .</p>
<p>Logs are also useful to detect  mistakes that users make, as well as for security purposes. Writing good logs about a user’s activity can alert us about malicious activity or any other kind of problems that we didn&#8217;t detect .</p>
<h2 id="2484" class="jt ju ga at es jv jw jx jy jz ka kb kc kd ke kf kg kh ki kj kk cr"><strong>Why use Serilog ?</strong></h2>
<p>Serilog provides basic diagnostic logging not only to the console, files, Amazon, Azure, but more ,it&#8217;s easy to integrate and to use in a few steps .</p>
<p>This article will demonstrate the console and file sinks. It is easy as 1, 2, 3 to set up with appsettings configurations.</p>
<h2><strong>Steps : </strong></h2>
<p>&nbsp;</p>
<p>First thing that we are going to do is to create a new empty solution (Web Api )</p>
<p><figure id="attachment_684" aria-describedby="caption-attachment-684" style="width: 750px" class="wp-caption aligncenter"><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/09/13/setting-up-serilog-in-asp-net-core/serielog1/" rel="attachment wp-att-684"><img loading="lazy" decoding="async" class="wp-image-684 size-jnews-750x375" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog1-750x375.png" alt="serielog" width="750" height="375" srcset="/wp-content/uploads/2020/09/serielog1-750x375.png 750w, /wp-content/uploads/2020/09/serielog1-360x180.png 360w, /wp-content/uploads/2020/09/serielog1-1140x570.png 1140w" sizes="(max-width: 750px) 100vw, 750px" /></a><figcaption id="caption-attachment-684" class="wp-caption-text">serielog</figcaption></figure></p>
<p><figure id="attachment_685" aria-describedby="caption-attachment-685" style="width: 750px" class="wp-caption aligncenter"><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/09/13/setting-up-serilog-in-asp-net-core/serielog2/" rel="attachment wp-att-685"><img loading="lazy" decoding="async" class="wp-image-685 size-jnews-750x375" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog2-750x375.png" alt="serielog" width="750" height="375" srcset="/wp-content/uploads/2020/09/serielog2-750x375.png 750w, /wp-content/uploads/2020/09/serielog2-360x180.png 360w, /wp-content/uploads/2020/09/serielog2-1140x570.png 1140w" sizes="(max-width: 750px) 100vw, 750px" /></a><figcaption id="caption-attachment-685" class="wp-caption-text">serielog</figcaption></figure></p>
<p>Now we need to use the package manager to install some extensions as in pictures below or you can use the command :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">Serilog.AspNetCore package</pre>
<p>&nbsp;</p>
<p><figure id="attachment_686" aria-describedby="caption-attachment-686" style="width: 750px" class="wp-caption aligncenter"><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/09/13/setting-up-serilog-in-asp-net-core/serielog3/" rel="attachment wp-att-686"><img loading="lazy" decoding="async" class="wp-image-686 size-jnews-750x375" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog3-750x375.png" alt="serielog" width="750" height="375" srcset="/wp-content/uploads/2020/09/serielog3-750x375.png 750w, /wp-content/uploads/2020/09/serielog3-360x180.png 360w, /wp-content/uploads/2020/09/serielog3-1140x570.png 1140w" sizes="(max-width: 750px) 100vw, 750px" /></a><figcaption id="caption-attachment-686" class="wp-caption-text">serielog</figcaption></figure></p>
<p><figure id="attachment_687" aria-describedby="caption-attachment-687" style="width: 750px" class="wp-caption aligncenter"><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog4.png" rel="attachment wp-att-687"><img loading="lazy" decoding="async" class="wp-image-687 size-jnews-750x375" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog4-750x375.png" alt="serielog" width="750" height="375" srcset="/wp-content/uploads/2020/09/serielog4-750x375.png 750w, /wp-content/uploads/2020/09/serielog4-360x180.png 360w, /wp-content/uploads/2020/09/serielog4-1140x570.png 1140w" sizes="(max-width: 750px) 100vw, 750px" /></a><figcaption id="caption-attachment-687" class="wp-caption-text">serielog</figcaption></figure></p>
<p><figure id="attachment_688" aria-describedby="caption-attachment-688" style="width: 750px" class="wp-caption aligncenter"><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog5.png" rel="attachment wp-att-688"><img loading="lazy" decoding="async" class="wp-image-688 size-jnews-750x375" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog5-750x375.png" alt="serielog" width="750" height="375" srcset="/wp-content/uploads/2020/09/serielog5-750x375.png 750w, /wp-content/uploads/2020/09/serielog5-360x180.png 360w, /wp-content/uploads/2020/09/serielog5-1140x570.png 1140w" sizes="(max-width: 750px) 100vw, 750px" /></a><figcaption id="caption-attachment-688" class="wp-caption-text">serielog</figcaption></figure></p>
<p><figure id="attachment_689" aria-describedby="caption-attachment-689" style="width: 750px" class="wp-caption aligncenter"><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog6.png" rel="attachment wp-att-689"><img loading="lazy" decoding="async" class="wp-image-689 size-jnews-750x375" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog6-750x375.png" alt="serielog" width="750" height="375" srcset="/wp-content/uploads/2020/09/serielog6-750x375.png 750w, /wp-content/uploads/2020/09/serielog6-360x180.png 360w, /wp-content/uploads/2020/09/serielog6-1140x570.png 1140w" sizes="(max-width: 750px) 100vw, 750px" /></a><figcaption id="caption-attachment-689" class="wp-caption-text">serielog</figcaption></figure></p>
<p><figure id="attachment_690" aria-describedby="caption-attachment-690" style="width: 750px" class="wp-caption aligncenter"><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog7.png" rel="attachment wp-att-690"><img loading="lazy" decoding="async" class="wp-image-690 size-jnews-750x375" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog7-750x375.png" alt="serielog" width="750" height="375" srcset="/wp-content/uploads/2020/09/serielog7-750x375.png 750w, /wp-content/uploads/2020/09/serielog7-360x180.png 360w, /wp-content/uploads/2020/09/serielog7-1140x570.png 1140w" sizes="(max-width: 750px) 100vw, 750px" /></a><figcaption id="caption-attachment-690" class="wp-caption-text">serielog</figcaption></figure></p>
<p><figure id="attachment_691" aria-describedby="caption-attachment-691" style="width: 750px" class="wp-caption aligncenter"><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog8.png" rel="attachment wp-att-691"><img loading="lazy" decoding="async" class="wp-image-691 size-jnews-750x375" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog8-750x375.png" alt="serielog" width="750" height="375" srcset="/wp-content/uploads/2020/09/serielog8-750x375.png 750w, /wp-content/uploads/2020/09/serielog8-360x180.png 360w, /wp-content/uploads/2020/09/serielog8-1140x570.png 1140w" sizes="(max-width: 750px) 100vw, 750px" /></a><figcaption id="caption-attachment-691" class="wp-caption-text">serielog</figcaption></figure></p>
<p><figure id="attachment_692" aria-describedby="caption-attachment-692" style="width: 750px" class="wp-caption aligncenter"><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog9.png" rel="attachment wp-att-692"><img loading="lazy" decoding="async" class="wp-image-692 size-jnews-750x375" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog9-750x375.png" alt="serielog" width="750" height="375" srcset="/wp-content/uploads/2020/09/serielog9-750x375.png 750w, /wp-content/uploads/2020/09/serielog9-360x180.png 360w, /wp-content/uploads/2020/09/serielog9-1140x570.png 1140w" sizes="(max-width: 750px) 100vw, 750px" /></a><figcaption id="caption-attachment-692" class="wp-caption-text">serielog</figcaption></figure></p>
<h3 id="logger-initialization-in-programcs">Logger initialization in Program.cs :</h3>
<p>To start working with Serielog we need to initilize it first in the program.cs  .<br />
You can copy replace your code with the below code :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">public static void Main(string[] args)
       {
           var configuration = new ConfigurationBuilder()
           .AddJsonFile("appsettings.json")
           .Build();

           Log.Logger = new LoggerConfiguration()
               .ReadFrom.Configuration(configuration).WriteTo.Console().CreateLogger();

           try
           {
               Log.Information("Application startinng up");
               CreateHostBuilder(args).Build().Run();
           }
           catch (Exception ex)
           {

               Log.Fatal(ex, "The application failed to start correctly");
           }
           finally
           {
               Log.CloseAndFlush();

           }



       }</pre>
<p>Also , we need to add : .UseSerilog() inside the CreateHostBuilder :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">public static IHostBuilder CreateHostBuilder(string[] args) =&gt;
           Host.CreateDefaultBuilder(args)
           .UseSerilog()
               .ConfigureWebHostDefaults(webBuilder =&gt;
               {
                   webBuilder.UseStartup&lt;Startup&gt;();
               });</pre>
<p>&nbsp;</p>
<p>Next , inside the Startup.cs we need to add : app.UseSerilogRequestLogging();</p>
<p><figure id="attachment_693" aria-describedby="caption-attachment-693" style="width: 750px" class="wp-caption aligncenter"><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog10.png" rel="attachment wp-att-693"><img loading="lazy" decoding="async" class="wp-image-693 size-jnews-750x375" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog10-750x375.png" alt="serielog" width="750" height="375" srcset="/wp-content/uploads/2020/09/serielog10-750x375.png 750w, /wp-content/uploads/2020/09/serielog10-360x180.png 360w, /wp-content/uploads/2020/09/serielog10-1140x570.png 1140w" sizes="(max-width: 750px) 100vw, 750px" /></a><figcaption id="caption-attachment-693" class="wp-caption-text">serielog</figcaption></figure></p>
<p>&nbsp;</p>
<p>Now if we run our solution , we should see inside the console a message saying : <strong>Application startinng up ,</strong></p>
<p>if you remember we added a line of code that will fire when the application start :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">Log.Information("Application startinng up");</pre>
<p>&nbsp;</p>
<p><figure id="attachment_694" aria-describedby="caption-attachment-694" style="width: 750px" class="wp-caption aligncenter"><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog11.png" rel="attachment wp-att-694"><img loading="lazy" decoding="async" class="wp-image-694 size-jnews-750x375" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog11-750x375.png" alt="serielog" width="750" height="375" srcset="/wp-content/uploads/2020/09/serielog11-750x375.png 750w, /wp-content/uploads/2020/09/serielog11-360x180.png 360w" sizes="(max-width: 750px) 100vw, 750px" /></a><figcaption id="caption-attachment-694" class="wp-caption-text">serielog</figcaption></figure></p>
<p>&nbsp;</p>
<h3 id="cleaning-up-remnants-of-the-default-logger">Cleaning up The default logger :</h3>
<p>There are a few more changes that we are going to do and now inside the appsettings.json .</p>
<p>Serilog completely replaces the logging implementation on .NET Core,it will not work together  but it will replace the default implementation . The benefit of this is that you’re not running two different logging frameworks with tricky edge cases where they overlap in functionality.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
  "AllowedHosts": "*",
  "Serilog": {
    "Using": [],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/log.txt",
          "rollingInterval": "Day",
          "outputTemplate": "{Timestamp:G} {Message}{NewLine:1}{Exception:1}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/log.json",
          "rollingInterval": "Day",
          "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
        }
      }
   
    ]
  }
}</pre>
<p>The <strong class="it ky">“Name”</strong> key here specifies the sink desired. To write to multiple sinks, add another object to the <strong class="it ky">“WriteTo” </strong>array , in our case we want to create files inside a logs folder and each day we want to create a new different file that contain the date time .</p>
<p>The <strong><code>MinimumLevel</code></strong> configuration object provides for one of the log event levels to be specified as the minimum.</p>
<p>If you see ,we have &#8220;<strong>path</strong>&#8220;: &#8220;Logs/log.txt&#8221;, where we define where we want our file to be written to and stored .</p>
<p><strong>rollingInterval </strong>here mean that we want to create a new file per day .</p>
<p>as you can see inside write to , we defined to object , one that will write to a text file and another one that&#8217;s going to write inside a json file .</p>
<p>Now let&#8217;s run our solution :</p>
<p>&nbsp;</p>
<p><figure id="attachment_695" aria-describedby="caption-attachment-695" style="width: 750px" class="wp-caption aligncenter"><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog12.png" rel="attachment wp-att-695"><img loading="lazy" decoding="async" class="wp-image-695 size-jnews-750x375" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog12-750x375.png" alt="serielog" width="750" height="375" srcset="/wp-content/uploads/2020/09/serielog12-750x375.png 750w, /wp-content/uploads/2020/09/serielog12-360x180.png 360w" sizes="(max-width: 750px) 100vw, 750px" /></a><figcaption id="caption-attachment-695" class="wp-caption-text">serielog</figcaption></figure></p>
<p><figure id="attachment_696" aria-describedby="caption-attachment-696" style="width: 750px" class="wp-caption aligncenter"><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog13.png" rel="attachment wp-att-696"><img loading="lazy" decoding="async" class="wp-image-696 size-jnews-750x375" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/09/serielog13-750x375.png" alt="serielog" width="750" height="375" srcset="/wp-content/uploads/2020/09/serielog13-750x375.png 750w, /wp-content/uploads/2020/09/serielog13-360x180.png 360w, /wp-content/uploads/2020/09/serielog13-1140x570.png 1140w" sizes="(max-width: 750px) 100vw, 750px" /></a><figcaption id="caption-attachment-696" class="wp-caption-text">serielog</figcaption></figure></p>
<p>As you can see there is a new Folder created : <strong>Logs , </strong>that contain a json file and a txt file .<br />
let explore those 2 files :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{"Timestamp":"2020-09-13T15:04:23.3942682+01:00","Level":"Information","MessageTemplate":"Application startinng up"}
{"Timestamp":"2020-09-13T15:04:25.9319025+01:00","Level":"Information","MessageTemplate":"Getting WeatherForecast details","Properties":{"ActionId":"9612d1c8-4c4e-44b7-b7fd-374fe905687c","ActionName":"SerielogDemoDay.Controllers.WeatherForecastController.Get (SerielogDemoDay)","RequestId":"0HM2NTNM09MCA:00000001","RequestPath":"/weatherforecast","SpanId":"|b35b87a8-42a0adeaed09085c.","TraceId":"b35b87a8-42a0adeaed09085c","ParentId":""}}
{"Timestamp":"2020-09-13T15:04:25.9642904+01:00","Level":"Information","MessageTemplate":"HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms","Properties":{"RequestMethod":"GET","RequestPath":"/weatherforecast","StatusCode":200,"Elapsed":134.7792,"SourceContext":"Serilog.AspNetCore.RequestLoggingMiddleware","RequestId":"0HM2NTNM09MCA:00000001","SpanId":"|b35b87a8-42a0adeaed09085c.","TraceId":"b35b87a8-42a0adeaed09085c","ParentId":""},"Renderings":{"Elapsed":[{"Format":"0.0000","Rendering":"134.7792"}]}}
</pre>
<p>As You can see the json file is very detailed file that contain all the event that happened .</p>
<p>while the txt file below , contain the actions with date time .</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">09/13/2020 15:04:23 Application startinng up
09/13/2020 15:04:25 Getting WeatherForecast details
09/13/2020 15:04:25 HTTP "GET" "/weatherforecast" responded 200 in 134.7792 ms
</pre>
<p>and now you can log anywhere inside your application by just using :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">Log.Debug("debug test!");
Log.Information("Informations here.....!");
Log.Error("Error here ....!");</pre>
<p>&nbsp;</p>
<p><span style="color: #ff6600;"><strong><a style="color: #ff6600;" href="https://bit.ly/32tv9TU">Link</a> </strong>to demo project .</span></p>
]]></content:encoded>
					
					<wfw:commentRss>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/09/13/setting-up-serilog-in-asp-net-core/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">680</post-id>	</item>
		<item>
		<title>Boxing and Unboxing in C#</title>
		<link>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/04/26/boxing-and-unboxing-in-c/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=boxing-and-unboxing-in-c</link>
					<comments>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/04/26/boxing-and-unboxing-in-c/#respond</comments>
		
		<dc:creator><![CDATA[achraf]]></dc:creator>
		<pubDate>Sun, 26 Apr 2020 17:41:11 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[c#]]></category>
		<guid isPermaLink="false">https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/?p=457</guid>

					<description><![CDATA[As part of graduation projects , each year we should have internships in summer , so we had to prepare ourselves for interviews for technical and non technical question . I remember in one of the interviews , the last question was ,’can you explain to me what is boxing and unboxing ? ‘ and [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>As part of graduation projects , each year we should have internships in summer , so we had to prepare ourselves for interviews for technical and non technical question . I remember in one of the interviews , the last question was ,’can you explain to me what is boxing and unboxing ? ‘ and I was like :</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-458" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/04/giphy-1.gif" alt="" width="217" height="255" /></p>
<p>Well , I stood like that for 5 minutes and ended up saying that I don’t know the answer , then the interviewer get up from his desk and explained it to me by writing on a blackboard . When he was explaining I was saying in my mind : ‘Dude ,I have been doing that all my life , I didn’t know it’s called boxing and unboxing ! ‘ .</p>
<p>Well , that was an interview that didn’t go well , but at least I learned something from it which encouraged me to write about it now .</p>
<p>What is Boxing And Unboxing ? Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type.</p>
<p>So when we say boxing,we say it’s the process of taking a value type ,putting it inside a new object on the heap and storing a reference to it on the stack . Unboxing is the exact opposite.</p>
<p>The difference between a value type and a reference type is that the value type stores its value directly,a reference type stores a reference that points to an object on the heap that contains the value. so : Unboxing extracts the value type from the object. Boxing is implicit and unboxing is explicit.</p>
<p>Let’s start by a simple boxing example :</p>
<p>int i = 123456;</p>
<p>// The following line boxes i inside object o. object o = i; The object o now, can be unboxed and assigned to integer variable i</p>
<p>o = 123; i = (int)o;</p>
<p>// unboxing o Let’s see one more example , so we have the following code :</p>
<p>class TestUnboxing</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">class TestUnboxing 
{ static void Main() { int i = 123; object o = i; // implicit boxing

    try
    {
        int j = (short)o;  // attempt to unbox

        System.Console.WriteLine("Unboxing OK.");
    }
    catch (System.InvalidCastException e)
    {
        System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);
    }
}
}
</pre>
<p>&nbsp;</p>
<p>So the output of this code if you try to execute it is , ” Specified cast is not valid. Error: Incorrect unboxing. ” and why is that ?</p>
<p>As you can see , we have defined i as int , but when we tried to unbox it we used short which cause the exception here , so what we need to do is :</p>
<p>int j = (int) o;<br />
A picture that can explain all that :</p>
<p><img loading="lazy" decoding="async" class=" wp-image-459 aligncenter" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2020/04/11-300x173.png" alt="" width="463" height="267" srcset="/wp-content/uploads/2020/04/11-300x173.png 300w, /wp-content/uploads/2020/04/11.png 617w" sizes="(max-width: 463px) 100vw, 463px" /></p>
<p>Performance In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, a new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally. For more information, see Performance in Microsoft official website .</p>
<p>Happy boxing &amp;&amp; unboxing day <img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2020/04/26/boxing-and-unboxing-in-c/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">457</post-id>	</item>
	</channel>
</rss>
