<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zied Rebhi on Medium]]></title>
        <description><![CDATA[Stories by Zied Rebhi on Medium]]></description>
        <link>https://medium.com/@ziedrebhi?source=rss-907ae9208cda------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5x10Nzo1GRS9k7TCCIWFnQ.jpeg</url>
            <title>Stories by Zied Rebhi on Medium</title>
            <link>https://medium.com/@ziedrebhi?source=rss-907ae9208cda------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:40:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ziedrebhi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Securing a .NET API C#: API Key, Basic Authentication, and JWT]]></title>
            <link>https://ziedrebhi.medium.com/securing-a-net-api-c-api-key-basic-authentication-and-jwt-369181eee672?source=rss-907ae9208cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/369181eee672</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Zied Rebhi]]></dc:creator>
            <pubDate>Thu, 12 Dec 2024 19:40:13 GMT</pubDate>
            <atom:updated>2024-12-14T14:45:29.100Z</atom:updated>
            <content:encoded><![CDATA[<h3>Securing a .NET API C#: API Key, Basic Authentication, and JWT</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6acC-WTQpnzvl7m4MFeOg.png" /><figcaption>Securing a .NET API C#: API Key, Basic Authentication, and JWT</figcaption></figure><p>When developing a .NET API, ensuring secure access control is critical to protect sensitive data and resources. Several methods are available, including API Key Authentication, Basic Authentication, and JSON Web Tokens (JWT). Each has its use case and security implication. This guide explore how to implement these methods in a .NET API.</p><h3>Sample Payment API</h3><p>Here is a basic example of a Payment API with CRUD operations:<br>You can find the full code in this <a href="https://github.com/ziedrebhi/PaymentApi">GitHub Repo</a></p><pre>    [Route(&quot;api/[controller]&quot;)]<br>    [ApiController]<br>    public class PaymentsController : ControllerBase<br>    {<br>        // Get all payments<br>        [HttpGet]<br>        public ActionResult&lt;IEnumerable&lt;Payment&gt;&gt; GetPayments()<br>        {<br>            var payments = PaymentRepository.GetPayments();<br>            return Ok(payments);<br>        }<br><br>        // Get a payment by ID<br>        [HttpGet(&quot;{id}&quot;)]<br>        public ActionResult&lt;Payment&gt; GetPayment(int id)<br>        {<br>            var payment = PaymentRepository.GetPaymentById(id);<br>            if (payment == null)<br>                return NotFound();<br>            return Ok(payment);<br>        }<br><br>        // Add a new payment<br>        [HttpPost]<br>        public ActionResult&lt;Payment&gt; PostPayment([FromBody] Payment payment)<br>        {<br>            if (payment == null)<br>                return BadRequest();<br><br>            payment.Id = PaymentRepository.GetPayments().Max(p =&gt; p.Id) + 1;  // Auto-increment ID<br>            PaymentRepository.AddPayment(payment);<br>            return CreatedAtAction(nameof(GetPayment), new { id = payment.Id }, payment);<br>        }<br><br>        // Update an existing payment<br>        [HttpPut(&quot;{id}&quot;)]<br>        public IActionResult PutPayment(int id, [FromBody] Payment payment)<br>        {<br>            if (payment == null)<br>                return BadRequest();<br><br>            PaymentRepository.UpdatePayment(id, payment);<br>            return NoContent();<br>        }<br><br>        // Delete a payment<br>        [HttpDelete(&quot;{id}&quot;)]<br>        public IActionResult DeletePayment(int id)<br>        {<br>            var payment = PaymentRepository.GetPaymentById(id);<br>            if (payment == null)<br>                return NotFound();<br><br>            PaymentRepository.DeletePayment(id);<br>            return NoContent();<br>        }<br>    }</pre><h3>1. API Key Authentication</h3><p>API Key Authentication is a simple mechanism where clients send a unique key with their request. The server validates the key to grant access.</p><p><strong>Required Package</strong></p><p>No additional package is required for API Key Authentication.</p><p><strong>Implementation</strong>:</p><ul><li><strong>Generate an API Key:</strong></li></ul><p>Create a secure and unique key for each client. Store these keys securely in your environment variables or app Settings etc to get it .</p><pre>{<br>  &quot;Logging&quot;: {<br>    &quot;LogLevel&quot;: {<br>      &quot;Default&quot;: &quot;Information&quot;,<br>      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;<br>    }<br>  },<br>  &quot;AllowedHosts&quot;: &quot;*&quot;,<br>  &quot;ApiKey&quot;: &quot;SuperSecretApiKey12345&quot;<br>}</pre><ul><li><strong>Middleware for Validation:</strong></li></ul><p>Add middleware to validate the API key in incoming requests.</p><pre>     public class ApiKeyMiddleware<br>    {<br>        private readonly RequestDelegate _next;<br>        private const string ApiKeyHeaderName = &quot;X-API-KEY&quot;;<br><br>        public ApiKeyMiddleware(RequestDelegate next)<br>        {<br>            _next = next;<br>        }<br><br>        public async Task InvokeAsync(HttpContext context, IConfiguration configuration)<br>        {<br>            if (!context.Request.Headers.TryGetValue(ApiKeyHeaderName, out var extractedApiKey))<br>            {<br>                context.Response.StatusCode = 401;<br>                await context.Response.WriteAsync(&quot;API Key is missing.&quot;);<br>                return;<br>            }<br><br>            var apiKey = configuration.GetValue&lt;string&gt;(&quot;ApiKey&quot;);<br><br>            if (!apiKey.Equals(extractedApiKey))<br>            {<br>                context.Response.StatusCode = 403;<br>                await context.Response.WriteAsync(&quot;Unauthorized client.&quot;);<br>                return;<br>            }<br><br>            await _next(context);<br>        }<br>    }<br><br>    public static class ApiKeyMiddlewareExtensions<br>    {<br>        public static IApplicationBuilder UseApiKeyMiddleware(this IApplicationBuilder builder)<br>        {<br>            return builder.UseMiddleware&lt;ApiKeyMiddleware&gt;();<br>        }<br>    }<br><br></pre><ul><li><strong>Register Middleware:</strong> In your program.cs file :</li></ul><pre>app.UseHttpsRedirection();<br>app.UseAuthorization();<br>// Use API Key <br>app.UseApiKeyMiddleware(); //add this<br>app.MapControllers();js</pre><ul><li><strong>Swagger Configuration:</strong></li></ul><p>To let your clients test the secured API throw Swagger, you should configure it :</p><pre>// Add Swagger with API Key configuration<br>builder.Services.AddSwaggerGen(c =&gt;<br>{<br>    c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo { Title = &quot;Payment API - API Key&quot;, Version = &quot;v1&quot; });<br>    c.AddSecurityDefinition(&quot;ApiKey&quot;, new OpenApiSecurityScheme<br>    {<br>        Name = &quot;X-API-KEY&quot;,<br>        Type = SecuritySchemeType.ApiKey,<br>        In = ParameterLocation.Header,<br>        Description = &quot;Enter your API Key in the header.&quot;<br>    });<br>    c.AddSecurityRequirement(new OpenApiSecurityRequirement<br>    {<br>        {<br>            new OpenApiSecurityScheme<br>            {<br>                Reference = new OpenApiReference<br>                {<br>                    Type = ReferenceType.SecurityScheme,<br>                    Id = &quot;ApiKey&quot;<br>                }<br>            },<br>            new string[] { }<br>        }<br>    });<br>});<br>var app = builder.Build();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*rbjZHivzxgFsSAS8a7YczQ.png" /></figure><p>When API key is valid, you will be authorized to use the APIs endpoints else you will get 401 error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*jXCKLALcLIYmMaB03Sb_bg.png" /></figure><h3>2. Basic Authentication</h3><p>Basic Authentication requires the client to send a username and password in the Authorization header. This method is good for internal APIs or development environment.</p><p><strong>Required Package</strong></p><p>Install the following NuGet package:</p><pre>Microsoft.AspNetCore.Authentication</pre><p><strong>Implementation:</strong></p><ul><li><strong>Create Authentication Handler:</strong></li></ul><pre>    public class BasicAuthMiddleware<br>    {<br>        private readonly RequestDelegate _next;<br><br>        public BasicAuthMiddleware(RequestDelegate next)<br>        {<br>            _next = next;<br>        }<br><br>        public async Task InvokeAsync(HttpContext context)<br>        {<br>            if (!context.Request.Headers.TryGetValue(&quot;Authorization&quot;, out var authorizationHeader))<br>            {<br>                context.Response.StatusCode = 401;<br>                context.Response.Headers[&quot;WWW-Authenticate&quot;] = &quot;Basic realm=\&quot;PaymentApi\&quot;&quot;;<br>                await context.Response.WriteAsync(&quot;Authorization header is missing.&quot;);<br>                return;<br>            }<br><br>            var authHeader = AuthenticationHeaderValue.Parse(authorizationHeader);<br>            var credentialBytes = Convert.FromBase64String(authHeader.Parameter ?? string.Empty);<br>            var credentials = Encoding.UTF8.GetString(credentialBytes).Split(&#39;:&#39;, 2);<br><br>            if (credentials.Length != 2 || credentials[0] != &quot;test&quot; || credentials[1] != &quot;test&quot;)<br>            {<br>                context.Response.StatusCode = 403;<br>                await context.Response.WriteAsync(&quot;Invalid username or password.&quot;);<br>                return;<br>            }<br><br>            await _next(context);<br>        }<br>    }<br><br>    public static class BasicAuthMiddlewareExtensions<br>    {<br>        public static IApplicationBuilder UseBasicAuthMiddleware(this IApplicationBuilder builder)<br>        {<br>            return builder.UseMiddleware&lt;BasicAuthMiddleware&gt;();<br>        }<br>    }</pre><ul><li><strong>Apply Authentication:</strong> In program.cs :</li></ul><pre>app.UseHttpsRedirection();<br>app.UseAuthorization();<br>//Use Basic Auth Middleware<br>app.UseBasicAuthMiddleware();<br>app.MapControllers();<br>app.Run();</pre><ul><li><strong>Swagger Configuration:</strong></li></ul><pre>// Add Swagger with Basic Authentication configuration<br>builder.Services.AddSwaggerGen(c =&gt;<br>{<br>    c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo { Title = &quot;Payment API - Basic Auth&quot;, Version = &quot;v1&quot; });<br>    c.AddSecurityDefinition(&quot;Basic&quot;, new OpenApiSecurityScheme<br>    {<br>        Name = &quot;Authorization&quot;,<br>        Type = SecuritySchemeType.Http,<br>        Scheme = &quot;basic&quot;,<br>        In = ParameterLocation.Header,<br>        Description = &quot;Enter your username and password as Base64 encoded value in the format &#39;username:password&#39;.&quot;<br>    });<br>    c.AddSecurityRequirement(new OpenApiSecurityRequirement<br>    {<br>        {<br>            new OpenApiSecurityScheme<br>            {<br>                Reference = new OpenApiReference<br>                {<br>                    Type = ReferenceType.SecurityScheme,<br>                    Id = &quot;Basic&quot;<br>                }<br>            },<br>            new string[] { }<br>        }<br>    });<br>});<br><br><br>var app = builder.Build();c</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*PnxT4oLnvrw-TtLajCSiIA.png" /></figure><p>Note that you should change the way how to handle the login process ( secure password etc..)</p><h3>3. JWT Authentication</h3><p>JWT (JSON Web Token) is a widely-used method for securing APIs. It provide a compact and self-contained token format that includes user claims and is signed for integrity.</p><p><strong>Required Package</strong></p><p>Install the following NuGet package:</p><pre>Microsoft.AspNetCore.Authentication.JwtBearer</pre><p><strong>Implementation:</strong></p><ul><li><strong>Add Authentication Controller :</strong> In this controller , we handle the way how users login and we generate tokens for them.</li></ul><pre>    [ApiController]<br>    [Route(&quot;api/[controller]&quot;)]<br>    public class AuthController : ControllerBase<br>    {<br>        private readonly IConfiguration _configuration;<br><br>        public AuthController(IConfiguration configuration)<br>        {<br>            _configuration = configuration;<br>        }<br><br>        [HttpPost(&quot;login&quot;)]<br>        public IActionResult Login([FromBody] LoginRequest login)<br>        {<br>            // Validate user credentials (hardcoded for example purposes)<br>            if (login.Username != &quot;test&quot; || login.Password != &quot;test&quot;)<br>                return Unauthorized(&quot;Invalid username or password&quot;);<br><br>            // Generate the JWT token<br>            var token = GenerateJwtToken(login.Username);<br><br>            return Ok(new { Token = token });<br>        }<br><br>        private string GenerateJwtToken(string username)<br>        {<br>            var jwtSettings = _configuration.GetSection(&quot;Jwt&quot;);<br><br>            var claims = new[]<br>            {<br>            new Claim(JwtRegisteredClaimNames.Sub, username),<br>            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),<br>            new Claim(ClaimTypes.Role, &quot;Admin&quot;)<br>        };<br><br>            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings[&quot;Key&quot;]));<br>            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);<br><br>            var token = new JwtSecurityToken(<br>                issuer: jwtSettings[&quot;Issuer&quot;],<br>                audience: jwtSettings[&quot;Audience&quot;],<br>                claims: claims,<br>                expires: DateTime.UtcNow.AddHours(1),<br>                signingCredentials: creds);<br><br>            return new JwtSecurityTokenHandler().WriteToken(token);<br>        }<br>    }<br><br>    public class LoginRequest<br>    {<br>        public string Username { get; set; }<br>        public string Password { get; set; }<br>    }</pre><ul><li><strong>Add Authentication Service:</strong> In program.cs , we configure the authentication service for our application :</li></ul><pre>var builder = WebApplication.CreateBuilder(args);<br><br>var jwtSettings = builder.Configuration.GetSection(&quot;Jwt&quot;);<br>var key = Encoding.UTF8.GetBytes(jwtSettings[&quot;Key&quot;]);<br><br>builder.Services.AddAuthentication(options =&gt;<br>{<br>    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;<br>    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;<br>}).AddJwtBearer(options =&gt;<br>{<br>    options.TokenValidationParameters = new TokenValidationParameters<br>    {<br>        ValidateIssuer = true,<br>        ValidateAudience = true,<br>        ValidateLifetime = true,<br>        ValidateIssuerSigningKey = true,<br>        ValidIssuer = jwtSettings[&quot;Issuer&quot;],<br>        ValidAudience = jwtSettings[&quot;Audience&quot;],<br>        IssuerSigningKey = new SymmetricSecurityKey(key)<br>    };<br>});<br>// Add services to the container.<br><br>builder.Services.AddControllers();<br>builder.Services.AddEndpointsApiExplorer();<br></pre><ul><li><strong>Apply Authentication:</strong> Let’s apply the authentication now in program.cs:</li></ul><pre>app.UseHttpsRedirection();<br>// Add Authentication<br>app.UseAuthentication();<br>app.UseAuthorization(); //&lt;--<br>app.MapControllers();<br>app.Run();</pre><ul><li><strong>Swagger Configuration : </strong>Let’s configure our swagger so it shows the Authorize button using Jwt</li></ul><pre>/ Add Swagger with JWT configuration<br>builder.Services.AddSwaggerGen(c =&gt;<br>{<br>    c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo { Title = &quot;Paymnent API - JWT&quot;, Version = &quot;v1&quot; });<br>    c.AddSecurityDefinition(&quot;Bearer&quot;, new OpenApiSecurityScheme<br>    {<br>        Name = &quot;Authorization&quot;,<br>        Type = SecuritySchemeType.Http,<br>        Scheme = &quot;Bearer&quot;,<br>        BearerFormat = &quot;JWT&quot;,<br>        In = ParameterLocation.Header,<br>        Description = &quot;Enter &#39;Bearer&#39; [space] and then your valid token.&quot;<br>    });<br>    c.AddSecurityRequirement(new OpenApiSecurityRequirement<br>    {<br>        {<br>            new OpenApiSecurityScheme<br>            {<br>                Reference = new OpenApiReference<br>                {<br>                    Type = ReferenceType.SecurityScheme,<br>                    Id = &quot;Bearer&quot;<br>                }<br>            },<br>            new string[] { }<br>        }<br>    });<br>});<br><br>var app = builder.Build();cs</pre><p>In<em> appsettings.json </em>we add the necessaries information:</p><pre> &quot;Jwt&quot;: {<br>    &quot;Key&quot;: &quot;SuperSecretKey12345SuperSecretKey12345SuperSecretKey12345SuperSecretKey12345&quot;,<br>    &quot;Issuer&quot;: &quot;SecureApiJwt&quot;,<br>    &quot;Audience&quot;: &quot;ApiUsers&quot;,<br>    &quot;ExpiryMinutes&quot;: 60<br>  }</pre><p><strong><em>Don’t forget to add [Authorize] in you controllers</em></strong></p><p>To test now , you should Login , you will get a token . In authorize button , you should add the generated token to access to the endpoints</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7TWIiA4B0av_fO4I97z7uA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vawRF2KJaoYg8Hn6Wnvtpw.gif" /><figcaption>Testing API</figcaption></figure><h3>Conclusion</h3><p>Securing your .NET API is essential to ensure the integrity and confidentiality of the data it processes.</p><p>You can find the full code in my <a href="https://github.com/ziedrebhi/PaymentApi">GitHub repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=369181eee672" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching in .NET C#: In-Memory , Distributed and Hybrid Caching explained]]></title>
            <link>https://ziedrebhi.medium.com/caching-in-net-c-in-memory-distributed-and-hybrid-caching-explained-6e14eac9ab32?source=rss-907ae9208cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e14eac9ab32</guid>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Zied Rebhi]]></dc:creator>
            <pubDate>Sun, 08 Dec 2024 20:51:06 GMT</pubDate>
            <atom:updated>2024-12-14T14:47:03.545Z</atom:updated>
            <content:encoded><![CDATA[<h3>Caching in .NET C#: In-Memory , Distributed and Hybrid Caching explained</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTmlgI4NRl-c4HGMF1_51Q.png" /><figcaption>Caching in .NET C#: In-Memory , Distributed and Hybrid Caching</figcaption></figure><p>Caching is a vital optimization technique in application development.It helps improve performance and scalability by reducing the needs for repetitive computation or data retrieval. In this guide, we’ll explore <strong>In-Memory</strong>, <strong>Distributed</strong>, and <strong>Hybrid Caching</strong> in <strong>.NET 9</strong>.</p><h3>Introduction to Caching</h3><p>Caching involves temporarily storing data in a fast-access storage layer to improve response times and reduce system loading. In .NET 9, you can use built-in caching mechanisms to implement various caching strategies:</p><ul><li><a href="https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-9.0"><strong>In-Memory Caching</strong></a>: Ideal for single-server applications.</li><li><a href="https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-9.0"><strong>Distributed Caching</strong></a>: Suitable for multi-server environments.</li><li><a href="https://learn.microsoft.com/en-us/aspnet/core/performance/caching/hybrid?view=aspnetcore-9.0"><strong>Hybrid Caching</strong></a>: Combines the benefits of in-memory and distributed caching.</li></ul><h3>1. In-Memory Caching</h3><h3>What is it?</h3><p><strong>In-Memory Caching</strong> stores data in the server’s RAM, making it fast. However, it is limited to a single server and is unsuitable for distributed systems where multiple servers are involved.</p><h3>Use Case</h3><p>A weather application that fetches frequently accessed forecasts can use in-memory caching to store responses temporarily.</p><h3>Implementation Example</h3><h4>Step 1: Create the CacheManager Class</h4><p>Encapsulate the caching logic in a reusable class.</p><pre>using Microsoft.Extensions.Caching.Memory;<br><br>public class CacheManager&lt;T&gt;<br>{<br>    private readonly IMemoryCache _memoryCache;<br><br>    public CacheManager(IMemoryCache memoryCache)<br>    {<br>        _memoryCache = memoryCache;<br>    }<br><br>    public T GetOrSet(string key, Func&lt;T&gt; fetchFunction, TimeSpan cacheDuration)<br>    {<br>        if (!_memoryCache.TryGetValue(key, out T value))<br>        {<br>            value = fetchFunction();<br>            _memoryCache.Set(key, value, cacheDuration);<br>        }<br><br>        return value;<br>    }<br>}</pre><h4>Step 2: Create a Service Class</h4><p>Fetch data and apply caching.</p><pre>public class WeatherService<br>{<br>    private readonly CacheManager&lt;string&gt; _cacheManager;<br><br>    public WeatherService(CacheManager&lt;string&gt; cacheManager)<br>    {<br>        _cacheManager = cacheManager;<br>    }<br><br>    public string GetWeather(string city)<br>    {<br>        string cacheKey = $&quot;Weather_{city}&quot;;<br>        return _cacheManager.GetOrSet(cacheKey, () =&gt; FetchWeatherFromAPI(city), TimeSpan.FromMinutes(30));<br>    }<br><br>    private string FetchWeatherFromAPI(string city)<br>    {<br>        // Simulated external API call<br>        return $&quot;{city}: 25°C, Sunny&quot;;<br>    }<br>}</pre><h4><strong>Step 3: Use the Service in a Controller</strong></h4><pre>using Microsoft.AspNetCore.Mvc;<br><br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class WeatherController : ControllerBase<br>{<br>    private readonly WeatherService _weatherService;<br><br>    public WeatherController(WeatherService weatherService)<br>    {<br>        _weatherService = weatherService;<br>    }<br><br>    [HttpGet(&quot;{city}&quot;)]<br>    public IActionResult GetWeather(string city)<br>    {<br>        var weather = _weatherService.GetWeather(city);<br>        return Ok(weather);<br>    }<br>}</pre><p>Register Dependencies in Program.cs</p><pre>builder.Services.AddMemoryCache();<br>builder.Services.AddScoped(typeof(CacheManager&lt;&gt;));<br>builder.Services.AddScoped&lt;WeatherService&gt;();</pre><h3>2. Distributed Caching</h3><h3>What is it?</h3><p><strong>Distributed Caching</strong> stores data in a centralized external system (e.g., Redis, SQL Server),allowing all servers in a distributed system to share the same cache.</p><h3>Use Case</h3><p>An online store that fetches product inventory informations can use distributed caching to ensure consistency across servers.</p><h3>Implementation Example: Using Redis</h3><h4>Step 1: Configure Redis in Program.cs</h4><pre>builder.Services.AddStackExchangeRedisCache(options =&gt;<br>{<br>    options.Configuration = &quot;localhost:6379&quot;; // Replace with your Redis configuration<br>});</pre><h4>Step 2: Create the CacheManager Class</h4><pre>using Microsoft.Extensions.Caching.Distributed;<br>using System.Text.Json;<br><br>public class DistributedCacheManager&lt;T&gt;<br>{<br>    private readonly IDistributedCache _distributedCache;<br><br>    public DistributedCacheManager(IDistributedCache distributedCache)<br>    {<br>        _distributedCache = distributedCache;<br>    }<br><br>    public async Task&lt;T&gt; GetOrSetAsync(string key, Func&lt;Task&lt;T&gt;&gt; fetchFunction, TimeSpan cacheDuration)<br>    {<br>        var cachedData = await _distributedCache.GetStringAsync(key);<br><br>        if (cachedData != null)<br>        {<br>            return JsonSerializer.Deserialize&lt;T&gt;(cachedData)!;<br>        }<br><br>        var data = await fetchFunction();<br>        var serializedData = JsonSerializer.Serialize(data);<br><br>        await _distributedCache.SetStringAsync(<br>            key,<br>            serializedData,<br>            new DistributedCacheEntryOptions<br>            {<br>                AbsoluteExpirationRelativeToNow = cacheDuration<br>            });<br><br>        return data;<br>    }<br>}</pre><h4>Step 3: Create a Service Class</h4><pre>public class ProductService<br>{<br>    private readonly DistributedCacheManager&lt;string&gt; _cacheManager;<br><br>    public ProductService(DistributedCacheManager&lt;string&gt; cacheManager)<br>    {<br>        _cacheManager = cacheManager;<br>    }<br><br>    public async Task&lt;string&gt; GetProductAsync(int productId)<br>    {<br>        string cacheKey = $&quot;Product_{productId}&quot;;<br>        return await _cacheManager.GetOrSetAsync(cacheKey, async () =&gt;<br>        {<br>            // Simulated database call<br>            await Task.Delay(500);<br>            return $&quot;Product {productId}: Fancy Gadget&quot;;<br>        }, TimeSpan.FromMinutes(10));<br>    }<br>}</pre><h4>Step 4: Use the Service in a Controller</h4><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class ProductsController : ControllerBase<br>{<br>    private readonly ProductService _productService;<br><br>    public ProductsController(ProductService productService)<br>    {<br>        _productService = productService;<br>    }<br><br>    [HttpGet(&quot;{id}&quot;)]<br>    public async Task&lt;IActionResult&gt; GetProduct(int id)<br>    {<br>        var product = await _productService.GetProductAsync(id);<br>        return Ok(product);<br>    }<br>}</pre><h3>3. Hybrid Caching</h3><h3>What is it?</h3><p><strong>Hybrid Caching</strong> combines the speed of in-memory caching with the scalability of distributed caching. Data is first checked in-memory and, if unavailable, fetched from the distributed cache.</p><h3>Implementation Example</h3><h4>Step 1: Extend CacheManager for Hybrid Logic</h4><pre>public class HybridCacheManager&lt;T&gt;<br>{<br>    private HybridCache _cache;<br>    public HybridCacheManager(HybridCache cache)<br>    {<br>        _cache = cache;<br>    }<br>    public async Task&lt;string&gt; GetCachedDataAsync(string key, CancellationToken token = default)<br>    {<br>        return await _cache.GetOrCreateAsync(<br>            $&quot;{key}&quot;,<br>            async cancel =&gt; await GetDataAsync(key, cancel),<br>            token: token<br>        );<br>    }<br>    private async Task&lt;string&gt; GetDataAsync(string key, CancellationToken token)<br>    {<br>        return $&quot;Data for cache entry with key: {key}&quot;;<br>    }<br>}</pre><p>Register Dependencies in Program.cs</p><pre>//builder.Services.AddHybridCache();<br>builder.Services.AddHybridCache(options =&gt;<br>    {<br>        options.MaximumPayloadBytes = 1024 * 1024;<br>        options.MaximumKeyLength = 1024;<br>        options.DefaultEntryOptions = new HybridCacheEntryOptions<br>        {<br>            Expiration = TimeSpan.FromMinutes(3),<br>            LocalCacheExpiration = TimeSpan.FromMinutes(3)<br>        };<br>    });<br></pre><h4>Step 2: Use HybridCacheManager in a Service</h4><pre>public class AnalyticsService<br>{<br>    private readonly HybridCacheManager&lt;string&gt; _cacheManager;<br><br>    public AnalyticsService(HybridCacheManager&lt;string&gt; cacheManager)<br>    {<br>        _cacheManager = cacheManager;<br>    }<br><br>    public async Task&lt;string&gt; GetAnalyticsAsync()<br>    {<br>        string cacheKey = &quot;DailyAnalytics&quot;;<br>        return await _cacheManager.GetOrSetAsync(cacheKey, async () =&gt;<br>        {<br>            // Simulate analytics calculation<br>            await Task.Delay(1000);<br>            return &quot;Daily Active Users: 5000&quot;;<br>        }, TimeSpan.FromMinutes(15));<br>    }<br>}</pre><h3>Best Practices</h3><ol><li><strong>Choose the Right Caching Strategy</strong>: Use in-memory for single-server setups, distributed for scalability, and hybrid for a balance of speed and consistency.</li><li><strong>Set Appropriate Expiry Policies</strong>: Avoid stale data by setting realistic cache durations.</li><li><strong>Monitor Cache Usage</strong>: Use tools like Redis insights or application logs to monitor cache performance.</li></ol><h3>Conclusion</h3><p>This article covered the three primary caching techniques in .NET 9 — In-Memory, Distributed, and Hybrid — using real-world examples with clean and modular code. By implementing these strategies, you can optimize your application’s performance and scalability effectively. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e14eac9ab32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Documenting Your .NET Web API with Swagger: The Fun Guide]]></title>
            <link>https://ziedrebhi.medium.com/documenting-your-net-web-api-with-swagger-the-fun-guide-0bcf5993b1c7?source=rss-907ae9208cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bcf5993b1c7</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Zied Rebhi]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 21:44:40 GMT</pubDate>
            <atom:updated>2024-11-18T21:44:40.965Z</atom:updated>
            <content:encoded><![CDATA[<h3>Documenting Your .NET Web API with Swagger: The Fun Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*iyS4LODqzJuTAglULuazHQ.jpeg" /></figure><p>Imagine this: You’re the new dev on the team, and someone hands you the API code to work with. You open it up and stare at it, confused, like you’ve just found a treasure map with no X marks the spot. You’re thinking, <em>Whaaaat is this thing even supposed to do?</em> 🧐</p><p>Or picture this: You’re the QA tester, and you’ve been handed this mysterious API with zero documentation. Every time you try to test, you end up with more questions than answers. You find yourself emailing the dev team with questions like, <em>What does this endpoint even return? How do I use this thing?</em> 😵</p><p>Or, worst case scenario, you’re another team that’s supposed to use the API you’ve never seen before. You try making a call, and then… boom! You’re calling the original devs non-stop for clarification, like, <em>Hey, how do I get a list of food items? What’s the format of the response?</em> It’s like they’re your personal helpdesk. 📞💻</p><p>We’ve all been there, right? But fear not, because Swagger is here to save the day! 🦸‍♂️ Let’s show you how you can turn your messy, undocumented API into something that even your new teammate, your tester, and those poor souls in other teams can understand with zero hassle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oeLqr0JhJRPkpWaBdWT0dg.png" /><figcaption>Example of documented API</figcaption></figure><h3>Why Document Your API?</h3><p>So why should we go through all this effort? Well, imagine trying to navigate a new city without a map — that’s what it’s like trying to use an undocumented API. Documentation makes everything clearer, and it’s not just for you! It’s for your team, for testers, and for those poor souls in other teams who just want to use your API without calling you every hour. 🤳</p><h3>Step 1: Set Up Swagger</h3><p>First things first: let’s set up Swagger in your project. Swagger turns your API into a shiny, interactive dashboard. It’s like giving your API a GPS, a guidebook, and a snack (just to make it extra pleasant). 🗺️🍿</p><pre>builder.Services.AddSwaggerGen(options =&gt;<br>{<br>    options.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo<br>    {<br>        Version = &quot;v1&quot;,<br>        Title = &quot;Food API&quot;,<br>        Description = &quot;A sample application with Swagger, Swashbuckle, and API versioning for managing Foods&quot;,<br>        TermsOfService = new Uri(&quot;https://example.com/terms&quot;),<br>        Contact = new OpenApiContact<br>        {<br>            Name = &quot;Example Contact&quot;,<br>            Url = new Uri(&quot;https://example.com/contact&quot;)<br>        },<br>        License = new OpenApiLicense<br>        {<br>            Name = &quot;Example License&quot;,<br>            Url = new Uri(&quot;https://example.com/license&quot;)<br>        },<br>        TermsOfService = new Uri(&quot;https://example.com/terms&quot;),<br>    });<br> // using System.Reflection;<br> var xmlFile = $&quot;{Assembly.GetExecutingAssembly().GetName().Name}.xml&quot;;<br> var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);<br> options.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);<br>});</pre><p>Then enable XML comments by adding this to your <em>.csproj</em> file :</p><p>Right-click the project in <strong>Solution Explorer</strong> and select <em>Edit &lt;project_name&gt;.csproj</em>.</p><pre>&lt;PropertyGroup&gt;<br>  &lt;GenerateDocumentationFile&gt;true&lt;/GenerateDocumentationFile&gt;<br>  &lt;NoWarn&gt;$(NoWarn);1591&lt;/NoWarn&gt;<br>&lt;/PropertyGroup&gt;</pre><p>Now you’re ready to start adding documentation to your API. This is where the magic happens!</p><h3><strong>Step 2: Documenting Your API with Swagger Annotations</strong></h3><p>Now let’s give your API some <strong>personality</strong>. Here’s an example of a Food API that’s fully documented. We’re going to make it clear, concise, and helpful — so no one has to call you 15 times a day asking questions. 😅</p><blockquote>The triple slash is your savior ///</blockquote><pre>/// &lt;summary&gt;<br>/// Manages food-related operations.<br>/// &lt;/summary&gt;<br>[ApiController]<br>[ApiVersion(&quot;1.0&quot;)]<br>[Route(&quot;api/v{version:apiVersion}/[controller]&quot;)]<br>public class FoodController : ControllerBase<br>{<br>    /// &lt;summary&gt;<br>    /// Retrieves a list of all food items.<br>    /// &lt;/summary&gt;<br>    /// &lt;remarks&gt;<br>    /// Example request:<br>    /// ```http<br>    /// GET /api/v3.0/Food<br>    /// ```<br>    /// Example response:<br>    /// ```json<br>    /// [<br>    ///     { &quot;id&quot;: 1, &quot;name&quot;: &quot;Apple&quot;, &quot;calories&quot;: 95 },<br>    ///     { &quot;id&quot;: 2, &quot;name&quot;: &quot;Banana&quot;, &quot;calories&quot;: 105 }<br>    /// ]<br>    /// ```<br>    /// &lt;/remarks&gt;<br>    [HttpGet]<br>    [SwaggerOperation(Summary = &quot;Get all food items&quot;, Description = &quot;Retrieves a list of all food items.&quot;)]<br>    [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable&lt;FoodItemDto&gt;))]<br>    public ActionResult&lt;IEnumerable&lt;FoodItemDto&gt;&gt; GetAllFoods()<br>    {<br>        return Ok(new List&lt;FoodItemDto&gt;<br>    {<br>        new FoodItemDto { Id = 1, Name = &quot;Apple&quot;, Calories = 95 },<br>        new FoodItemDto { Id = 2, Name = &quot;Banana&quot;, Calories = 105 }<br>    });<br>    }<br><br>    /// &lt;summary&gt;<br>    /// Retrieves a specific food item by ID.<br>    /// &lt;/summary&gt;<br>    /// &lt;remarks&gt;<br>    /// Example request:<br>    /// ```http<br>    /// GET /api/v3.0/Food/1<br>    /// ```<br>    /// Example response:<br>    /// ```json<br>    /// { &quot;id&quot;: 1, &quot;name&quot;: &quot;Apple&quot;, &quot;calories&quot;: 95 }<br>    /// ```<br>    /// &lt;/remarks&gt;<br>    /// &lt;param name=&quot;id&quot;&gt;The unique identifier of the food item.&lt;/param&gt;<br>    /// &lt;response code=&quot;200&quot;&gt;The food item was successfully retrieved.&lt;/response&gt;<br>    /// &lt;response code=&quot;404&quot;&gt;The food item with the given ID was not found.&lt;/response&gt;<br>    [HttpGet(&quot;{id}&quot;)]<br>    [SwaggerOperation(Summary = &quot;Get a food item by ID&quot;, Description = &quot;Retrieves a specific food item by its unique ID.&quot;)]<br>    [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(FoodItemDto))]<br>    [ProducesResponseType(StatusCodes.Status404NotFound)]<br>    public ActionResult&lt;FoodItemDto&gt; GetFoodById(int id)<br>    {<br>        if (id &lt;= 0) return NotFound();<br><br>        return Ok(new FoodItemDto { Id = id, Name = &quot;Apple&quot;, Calories = 95 });<br>    }<br><br>    /// &lt;summary&gt;<br>    /// Retrieves food details (deprecated method).<br>    /// &lt;/summary&gt;<br>    /// &lt;remarks&gt;<br>    /// **This method is obsolete. Use `GetFoodById` instead.**<br>    /// Example usage:<br>    /// ```http<br>    /// GET /api/v3.0/Food/details/1<br>    /// ```<br>    /// **Response:**<br>    /// ```json<br>    /// { &quot;id&quot;: 1, &quot;name&quot;: &quot;Apple&quot;, &quot;calories&quot;: 95 }<br>    /// ```<br>    /// **Error Response:**<br>    /// ```json<br>    /// { &quot;error&quot;: &quot;Not Found&quot; }<br>    /// ```<br>    /// &lt;/remarks&gt;<br>    /// &lt;param name=&quot;id&quot;&gt;The unique identifier of the food item.&lt;/param&gt;<br>    /// &lt;response code=&quot;200&quot;&gt;The food item was successfully retrieved.&lt;/response&gt;<br>    /// &lt;response code=&quot;404&quot;&gt;The food item with the given ID was not found.&lt;/response&gt;<br>    [Obsolete(&quot;This method is deprecated. Use GetFoodById instead.&quot;)]<br>    [HttpGet(&quot;details/{id}&quot;)]<br>    [SwaggerOperation(Summary = &quot;Get food details (deprecated)&quot;, Description = &quot;Retrieves detailed food information (use `GetFoodById` instead).&quot;)]<br>    [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(FoodItemDto))]<br>    [ProducesResponseType(StatusCodes.Status404NotFound)]<br>    public ActionResult&lt;FoodItemDto&gt; GetFoodDetails(int id)<br>    {<br>        if (id &lt;= 0) return NotFound();<br><br>        return Ok(new FoodItemDto { Id = id, Name = &quot;Apple&quot;, Calories = 95 });<br>    }<br><br>    /// &lt;summary&gt;<br>    /// Creates a new food item.<br>    /// &lt;/summary&gt;<br>    /// &lt;remarks&gt;<br>    /// Example request:<br>    /// ```json<br>    /// { &quot;name&quot;: &quot;Apple&quot;, &quot;calories&quot;: 95 }<br>    /// ```<br>    /// Example response:<br>    /// ```json<br>    /// { &quot;id&quot;: 123, &quot;name&quot;: &quot;Apple&quot;, &quot;calories&quot;: 95 }<br>    /// ```<br>    /// &lt;/remarks&gt;<br>    /// &lt;param name=&quot;foodItem&quot;&gt;The food item to create.&lt;/param&gt;<br>    /// &lt;response code=&quot;201&quot;&gt;The food item was successfully created.&lt;/response&gt;<br>    /// &lt;response code=&quot;400&quot;&gt;Invalid food item details.&lt;/response&gt;<br>    [HttpPost]<br>    [SwaggerOperation(Summary = &quot;Create a new food item&quot;, Description = &quot;Creates a new food item in the system.&quot;)]<br>    [ProducesResponseType(StatusCodes.Status201Created, Type = typeof(FoodItemDto))]<br>    [ProducesResponseType(StatusCodes.Status400BadRequest)]<br>    public ActionResult&lt;FoodItemDto&gt; CreateFood(FoodItemDto foodItem)<br>    {<br>        if (string.IsNullOrEmpty(foodItem.Name) || foodItem.Calories &lt;= 0)<br>        {<br>            return BadRequest(&quot;Invalid food item details.&quot;);<br>        }<br><br>        foodItem.Id = new Random().Next(1, 1000); // Simulate ID generation<br>        return CreatedAtAction(nameof(GetFoodById), new { id = foodItem.Id }, foodItem);<br>    }<br><br>    /// &lt;summary&gt;<br>    /// Updates an existing food item.<br>    /// &lt;/summary&gt;<br>    /// &lt;remarks&gt;<br>    /// Example request:<br>    /// ```json<br>    /// { &quot;id&quot;: 1, &quot;name&quot;: &quot;Banana&quot;, &quot;calories&quot;: 110 }<br>    /// ```<br>    /// Example response:<br>    /// ```json<br>    /// { &quot;id&quot;: 1, &quot;name&quot;: &quot;Banana&quot;, &quot;calories&quot;: 110 }<br>    /// ```<br>    /// &lt;/remarks&gt;<br>    /// &lt;param name=&quot;id&quot;&gt;The unique identifier of the food item to update.&lt;/param&gt;<br>    /// &lt;param name=&quot;foodItem&quot;&gt;The updated food item data.&lt;/param&gt;<br>    /// &lt;response code=&quot;200&quot;&gt;The food item was successfully updated.&lt;/response&gt;<br>    /// &lt;response code=&quot;400&quot;&gt;Food item ID mismatch or invalid data.&lt;/response&gt;<br>    /// &lt;response code=&quot;404&quot;&gt;The food item with the given ID was not found.&lt;/response&gt;<br>    [HttpPut(&quot;{id}&quot;)]<br>    [SwaggerOperation(Summary = &quot;Update an existing food item&quot;, Description = &quot;Updates a specific food item.&quot;)]<br>    [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(FoodItemDto))]<br>    [ProducesResponseType(StatusCodes.Status400BadRequest)]<br>    [ProducesResponseType(StatusCodes.Status404NotFound)]<br>    public ActionResult&lt;FoodItemDto&gt; UpdateFood(int id, FoodItemDto foodItem)<br>    {<br>        if (id != foodItem.Id) return BadRequest(&quot;Food item ID mismatch.&quot;);<br>        if (id &lt;= 0) return NotFound();<br><br>        return Ok(foodItem); // Return the updated food item<br>    }<br><br>    /// &lt;summary&gt;<br>    /// Deletes a food item by ID.<br>    /// &lt;/summary&gt;<br>    /// &lt;remarks&gt;<br>    /// Example request:<br>    /// ```http<br>    /// DELETE /api/v3.0/Food/1<br>    /// ```<br>    /// Example response:<br>    /// ```json<br>    /// { &quot;message&quot;: &quot;Food item deleted successfully.&quot; }<br>    /// ```<br>    /// &lt;/remarks&gt;<br>    /// &lt;param name=&quot;id&quot;&gt;The unique identifier of the food item to delete.&lt;/param&gt;<br>    /// &lt;response code=&quot;200&quot;&gt;The food item was successfully deleted.&lt;/response&gt;<br>    /// &lt;response code=&quot;404&quot;&gt;The food item with the given ID was not found.&lt;/response&gt;<br>    [HttpDelete(&quot;{id}&quot;)]<br>    [SwaggerOperation(Summary = &quot;Delete a food item&quot;, Description = &quot;Deletes a specific food item.&quot;)]<br>    [ProducesResponseType(StatusCodes.Status200OK)]<br>    [ProducesResponseType(StatusCodes.Status404NotFound)]<br>    public IActionResult DeleteFood(int id)<br>    {<br>        if (id &lt;= 0) return NotFound();<br><br>        return Ok(new { Message = &quot;Food item deleted successfully.&quot; });<br>    }<br><br>    /// &lt;summary&gt;<br>    /// Partially updates a food item (e.g., updating only calories).<br>    /// &lt;/summary&gt;<br>    /// &lt;remarks&gt;<br>    /// Example request:<br>    /// ```json<br>    /// { &quot;calories&quot;: 110 }<br>    /// ```<br>    /// Example response:<br>    /// ```json<br>    /// { &quot;id&quot;: 1, &quot;name&quot;: &quot;Apple&quot;, &quot;calories&quot;: 110 }<br>    /// ```<br>    /// &lt;/remarks&gt;<br>    /// &lt;param name=&quot;id&quot;&gt;The unique identifier of the food item to update.&lt;/param&gt;<br>    /// &lt;param name=&quot;patchDoc&quot;&gt;The JSON patch document containing the changes to apply.&lt;/param&gt;<br>    /// &lt;response code=&quot;200&quot;&gt;The food item was successfully updated.&lt;/response&gt;<br>    /// &lt;response code=&quot;400&quot;&gt;Invalid patch data.&lt;/response&gt;<br>    /// &lt;response code=&quot;404&quot;&gt;The food item with the given ID was not found.&lt;/response&gt;<br>    [HttpPatch(&quot;{id}&quot;)]<br>    [SwaggerOperation(Summary = &quot;Partially update a food item&quot;, Description = &quot;Partially updates an existing food item.&quot;)]<br>    [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(FoodItemDto))]<br>    [ProducesResponseType(StatusCodes.Status400BadRequest)]<br>    [ProducesResponseType(StatusCodes.Status404NotFound)]<br>    public ActionResult&lt;FoodItemDto&gt; PatchFood(int id, [FromBody] JsonPatchDocument&lt;FoodItemDto&gt; patchDoc)<br>    {<br>        if (id &lt;= 0) return NotFound();<br>        if (patchDoc == null) return BadRequest(&quot;Invalid patch data.&quot;);<br><br>        var foodItem = new FoodItemDto { Id = id, Name = &quot;Apple&quot;, Calories = 95 };<br><br>        patchDoc.ApplyTo(foodItem, ModelState);<br><br>        if (!ModelState.IsValid) return BadRequest(ModelState);<br><br>        return Ok(foodItem);<br>    }<br>}<br><br>/// &lt;summary&gt;<br>/// Represents a food item.<br>/// &lt;/summary&gt;<br>public class FoodItemDto<br>{<br>    /// &lt;summary&gt;<br>    /// Unique identifier of the food item.<br>    /// &lt;/summary&gt;<br>    /// &lt;example&gt;1&lt;/example&gt;<br>    public int Id { get; set; }<br><br>    /// &lt;summary&gt;<br>    /// The name of the food item.<br>    /// &lt;/summary&gt;<br>    /// &lt;example&gt;Apple&lt;/example&gt;<br>    public string Name { get; set; }<br><br>    /// &lt;summary&gt;<br>    /// The number of calories in the food item.<br>    /// &lt;/summary&gt;<br>    /// &lt;example&gt;95&lt;/example&gt;<br>    public int Calories { get; set; }<br>}</pre><h3><strong>What Have We Done?</strong></h3><p>Let’s break down exactly what’s happening here. Here’s why this documentation is a game-changer:</p><ol><li><strong>Added Summaries</strong>:<br>Each method now has a /// &lt;summary&gt; tag, which is like giving your API a clear job description. For example, Retrieves a list of all food items is super helpful for anyone trying to understand what this endpoint does.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81sS9SK90pVGdBrNGVvU7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6c8qy3YK0xQXk3Nd5rB7g.png" /></figure><p><strong>2. Clear Remarks</strong>:<br>We included /// &lt;remarks&gt; to show exactly what’s expected when making requests and receiving responses. Now testers can see the request format, and other devs won’t be left in the dark wondering what a valid response looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYbGcWpLjDNLrNIBIRv2Xg.png" /></figure><p><strong>3. Error Handling</strong>:<br>We documented potential error responses with /// &lt;response code=&quot;404&quot;&gt;, which means if something goes wrong, your API will tell the user exactly what happened. No more guessing, no more surprises! (Remember, the only surprise should be when the food&#39;s <em>really</em> good. 😜)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cn2Tpu9m7MyXfqBcoX0YVA.png" /></figure><p><strong>4. Obsolete Methods</strong>:<br>We used the [Obsolete] attribute to let users know that old methods are no longer the way to go. This is a life-saver when the next dev or team calls you up and says, <em>“Wait, should we use this?”</em> Answer: “Nope, use the new one!” ✅</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75G_PWO_NGJWAxDNBGWqOQ.png" /></figure><p><strong>5. Response Types</strong>:<br>With the [ProducesResponseType] attribute, we made sure Swagger knows what kind of responses your API sends back. So now, your users (and that other dev team calling you) can easily see that a 200 OK means success, or 404 Not Found means they might want to double-check their inputs.</p><p><strong>6. Parameter Descriptions</strong>:<br>We used /// &lt;param name=&quot;id&quot;&gt; to describe the parameters. Now, there’s no more <em>“Wait, what does this ID mean?”</em> Everyone knows exactly what each parameter represents. It’s like providing a map for your API. 🗺️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqJqY99it5-cTAO21Y5Sqg.png" /></figure><p><strong>7. Add more descriptions to our objects / DTOs :</strong></p><pre>    /// &lt;summary&gt;<br>    /// The name of the food item.<br>    /// &lt;/summary&gt;<br>    /// &lt;example&gt;Apple&lt;/example&gt;<br>    public string Name { get; set; }</pre><h3>And That’s It!</h3><p>Now your API is fully documented, and everyone (even the new devs, testers, and other teams) will love using it. No more confusing, undocumented endpoints. No more <em>“Hey, how do I use this thing?”</em> phone calls. Swagger makes your API transparent, easy to understand, and <strong>interactive</strong>. 🎉</p><p>So, to recap:</p><ul><li>No more confusion for the new devs.</li><li>No more endless questions from testers.</li><li>No more panic calls from other teams wondering how to use your API.</li></ul><p>Your API is now a smooth, well-documented experience for everyone involved. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bcf5993b1c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recurring Tasks in .NET C# : All options explained]]></title>
            <link>https://ziedrebhi.medium.com/recurring-tasks-in-net-c-all-options-explained-b28206c909c2?source=rss-907ae9208cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/b28206c909c2</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Zied Rebhi]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 19:08:27 GMT</pubDate>
            <atom:updated>2024-11-14T19:08:27.228Z</atom:updated>
            <content:encoded><![CDATA[<h3>Recurring Tasks in .NET C# : All options explained</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4I1NHMX78SldGAEYqv9dA.jpeg" /><figcaption>Recurring Tasks in .NET C# : All options explained</figcaption></figure><p>In many applications, tasks need to be run on a regular schedule. Examples include data synchronization, email reminders, cleanup routines, and background processing. .NET provides several ways to accomplish this, from simple in-app timers to robust enterprise-level scheduling with external libraries and cloud solutions.</p><h3>1. <strong>Using </strong><strong>IHostedService for Background Services :</strong></h3><p>Starting with .NET Core, IHostedService is the preferred way to run background tasks. It’s suitable for services that need to perform periodic work within the same application, such as logging, data processing, or scheduled updates.</p><h4>Key Features</h4><ul><li>Integrated with the .NET Core dependency injection (DI) container.</li><li>Runs continuously or at set intervals.</li><li>Suitable for background tasks tied closely to the lifecycle of a web app or API.</li></ul><h4>Implementation Steps</h4><ol><li><strong>Implement a Background Service:</strong></li></ol><p>Implement BackgroundService (a specialized version of IHostedService) to define a recurring task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1KxBXDR_RqBqsq7wJeEOrg.png" /></figure><p><strong>2. Register the Background Service:</strong></p><p>Register RecurringTaskService in ConfigureServices in Program.cs or Startup.cs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNWAM-xgRtrfRUpNobWT2g.png" /></figure><h4>When to Use</h4><ul><li>Simple periodic tasks.</li><li>Scenarios where the recurring job needs to be integrated with the main application’s lifecycle.</li></ul><h3>2. Using System.Threading.Timer</h3><p>System.Threading.Timer is another simple way to execute periodic tasks. It’s lightweight and does not depend on hosted services, so it can be used in standalone applications or other contexts outside of ASP.NET Core applications.</p><h4>Key Features</h4><ul><li>Runs on a timer interval.</li><li>Ideal for straightforward, low-overhead tasks.</li><li>No dependency on ASP.NET Core hosting or dependency injection.</li></ul><h4>Implementation Steps</h4><ol><li><strong>Define a Timer Service: </strong>Create a class that uses Timer to run recurring tasks.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-KKgSYC6LXpIAMN4FCRmjw.png" /></figure><p><strong>2. Register the Timer Service: </strong>Add the service to ConfigureServices to ensure it starts with your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rHLFyhMP17p-CSW-jgA-1w.png" /></figure><h4>When to Use</h4><ul><li>Lightweight tasks with straightforward timing needs.</li><li>Tasks that don’t require complex scheduling or clustering.</li></ul><h3>3. Using Quartz.NET</h3><p><a href="https://www.quartz-scheduler.net/">Quartz.NET</a> is a full-featured job scheduling library that supports complex schedules, persistence, and clustering, making it ideal for enterprise applications.</p><h4>Key Features</h4><ul><li>Supports complex schedules (e.g., cron expressions).</li><li>Allows jobs to be stored in a database for persistence.</li><li>Provides clustering for distributed systems.</li></ul><h4>Implementation Steps</h4><ol><li><strong>Install Quartz.NET: </strong>Install the Quartz package:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TokLjB0101IGeDvdNAqAIg.png" /></figure><p><strong>2. Define a Quartz Job: </strong>Create a class that implements IJob to define a recurring task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8GAfCCusCzYs_o2hRhtRbA.png" /></figure><p><strong>3. Configure Quartz in </strong><strong>Startup.cs: </strong>Configure Quartz to schedule the job with an interval, using a cron expression or a simple schedule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QqaLRAzgO6Jdli9aev12Sg.png" /></figure><h4>When to Use</h4><ul><li>Complex scheduling needs .</li><li>High scalability and reliability requirements.</li><li>Enterprise applications with distributed job scheduling.</li></ul><h3>4. Using Hangfire</h3><p><a href="https://www.hangfire.io/">Hangfire</a> is a popular library for background job scheduling in .NET that provides support for recurring jobs, real-time monitoring, and persistent storage.</p><h4>Key Features</h4><ul><li>Built-in support for recurring jobs with a visual dashboard.</li><li>Persistent storage for jobs (SQL Server, Redis, etc.).</li><li>Supports retries and error handling.</li></ul><h4>Implementation Steps</h4><ol><li><strong>Install Hangfire Package:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2xMHr2FsAUOx7bCkqD9qpA.png" /></figure><p><strong>2. Configure Hangfire in </strong><strong>Startup.cs: </strong>Set up Hangfire with persistent storage and background processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TkjQOnB8t0Kkml_ke_mig.png" /></figure><p><strong>3. Define and Schedule a Recurring Job:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzyyY-wijKo0wN8GB82p1w.png" /></figure><h4>When to Use</h4><ul><li>Applications requiring a simple, reliable job scheduler with real-time monitoring.</li><li>Tasks that need robust error handling and retries.</li><li>Scenarios where a visual dashboard for managing jobs is beneficial.</li></ul><h3>5. Using Azure Functions with Timer Triggers</h3><p>For serverless and cloud-native applications, Azure Functions can be an effective way to manage scheduled tasks.</p><h4>Key Features</h4><ul><li>Serverless execution with automatic scaling.</li><li>Managed by Azure, so no additional infrastructure management is needed.</li><li>Supports cron expressions for flexible scheduling.</li></ul><h4>Implementation Steps</h4><ol><li><strong>Create a Timer Trigger Function in Azure Functions: </strong>Define the function with a Timer Trigger using a cron expression.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ybnQbB8-Tys_EIA5OhQMwQ.png" /></figure><p><strong>2. Deploy the Function to Azure: </strong>Deploy the function to Azure and configure the interval (e.g., hourly) using cron syntax.</p><h4>When to Use</h4><ul><li>Serverless environments where you don’t want to manage infrastructure.</li><li>Scenarios where task execution needs high scalability and flexibility.</li></ul><h3>6. Using Windows Task Scheduler or Cron Jobs</h3><p>For standalone applications or systems not hosted in a cloud or web environment, Windows Task Scheduler (Windows) or Cron (Linux) can handle recurring tasks by executing your .NET application on a set schedule.</p><h4>Key Features</h4><ul><li>Decouples scheduling from application logic.</li><li>Ideal for desktop or on-premises applications.</li><li>Flexible scheduling options.</li></ul><h4>Implementation Steps</h4><ol><li><strong>Create a Console Application: </strong>Define the recurring logic in a .NET console application.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPbGgC_BYXu7pcGojMKQiA.png" /></figure><p><strong>2. Schedule the Console Application:</strong></p><ul><li><strong>Windows</strong>: Use Windows Task Scheduler to set up a recurring schedule.</li><li><strong>Linux</strong>: Use Cron jobs to run the task at specific intervals.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qpm4ttzfVyQF4ePQhJ3aSA.png" /><figcaption>Task Scheduler</figcaption></figure><h4>When to Use</h4><ul><li>Decoupled scheduling for standalone or desktop applications.</li><li>Lightweight scheduling without dependencies on third-party libraries.</li></ul><h3>Conclusion</h3><p>.NET offers a range of solutions for recurring tasks, from simple timers for lightweight jobs to enterprise-level schedulers like Quartz.NET and Hangfire, as well as cloud-native options like Azure Functions. Each method has unique strengths, and the choice depends on factors such as application architecture, infrastructure requirements, and task complexity. By selecting the most suitable approach, you can implement recurring tasks that are reliable, efficient, and aligned with your application’s needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b28206c909c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Functions in .NET (C#) — The Ultimate Fun Version]]></title>
            <link>https://ziedrebhi.medium.com/azure-functions-in-c-the-ultimate-fun-version-fc0d54ec6766?source=rss-907ae9208cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc0d54ec6766</guid>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Zied Rebhi]]></dc:creator>
            <pubDate>Wed, 13 Nov 2024 21:09:37 GMT</pubDate>
            <atom:updated>2024-11-13T21:17:53.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*MfRckjmVYoI1ZNPGYaTkaw.png" /><figcaption>Azure Functions in C#: The Ultimate Fun Version</figcaption></figure><h3>What is Azure Functions?</h3><p>Imagine you’re throwing a party. You have tons of guests (events) arriving at different times. Instead of hiring a full-time butler (server) to manage it all, you have <strong>Azure Functions</strong>, which is like a party planner who only shows up when needed. When a guest arrives (an event happens), the planner (your function) gets to work, does their thing, and leaves when the job is done. No hassle, no drama. Just pure serverless fun!</p><h3>Why Should You Care About Azure Functions?</h3><ul><li><strong>Zero Server Drama</strong>: No need to manage servers. It just works.</li><li><strong>Scalable Like a Superhero</strong>: It grows or shrinks as needed (no stress about overworking it).</li><li><strong>Pay Only for What You Use</strong>: You don’t pay for a full-time worker (server); you only pay for when your party planner shows up.</li></ul><h3>Setting Up Your First Azure Function</h3><ol><li><strong>Install Your Tools</strong>: <strong>Visual Studio</strong> or <strong>Visual Studio Code</strong> is your playground. Make sure to install the <strong>Azure Functions Tools</strong>. It’s like installing your party setup kit.</li><li><strong>Create a New Project</strong>: Open Visual Studio and create a new <strong>Azure Function</strong> project. Choose the <strong>HTTP Trigger</strong> template (because, hey, you want to start with something easy like handling guest RSVPs via HTTP, right?).</li></ol><h3><strong>Writing Your First Function (The HTTP Trigger)</strong></h3><p>Here’s where the magic happens. Imagine this function is like sending an invite that says “Hey, tell me your name!”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9JZu-WIIEWXP2EKSjt9Ew.png" /><figcaption>Azure function : HTTP Trigger</figcaption></figure><p>This function is triggered by an <strong>HTTP request</strong>. If someone says their name (via the query string name), the function greets them like a true host. If not, they get a “Please tell us your name!” nudge.</p><h4>Testing It Out Locally:</h4><ul><li>Press <strong>F5</strong> and your party planner (Azure Function) will run on your local machine.</li><li>Open up your browser and go to http://localhost:7071/api/HelloFunction?name=John. Your function should greet you: &quot;Hello, John, welcome to the party!&quot;</li></ul><h3><strong>Example 2: Timer Trigger (The Office Alarm)</strong></h3><p>Now, let’s add a fun twist! Imagine you want to send out an announcement every 5 minutes: “Time for snacks!”</p><p>Here’s how to set up a <strong>Timer Trigger</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAQ0mz1ZNlvCMrj3_NK7Yg.png" /><figcaption>Time Trigger with Azure Functions</figcaption></figure><p>The <strong>Timer Trigger</strong> runs every 5 minutes. You can think of it as the office alarm that reminds you to take a break. No more forgetting about snacks!</p><h3>Example 3: Blob Trigger (Snack Delivery)</h3><p>What if someone drops a snack (a file) into the <strong>Azure Blob Storage</strong>, and you want your function to grab it and send an alert? Here’s how:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3H39XrTWGYWcTu0__bIXA.png" /><figcaption>Blog Trigger</figcaption></figure><p>This function gets triggered when a new snack (file) is uploaded to the <strong>snack-container</strong>. Your function immediately tells everyone, “A new snack just arrived!” 🥳</p><h3>Example 4: Queue Trigger (Serving Requests)</h3><p>Sometimes, you might get too many requests at once, so you need a queue. This example shows how you can use a <strong>Queue Trigger</strong> to process snack requests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9CdoIkL4gxVeH-elLNtgCg.png" /><figcaption>Queue trigger</figcaption></figure><p>The function gets triggered whenever a message is added to the <strong>snack-requests</strong> queue. Imagine a request like “Bring me chips!” 🎉</p><h3>Example 5: Send an Email (The Party Invite)</h3><p>Let’s say you want your function to send an email whenever a new user registers for your party (or app, or whatever your event is). You can use a <strong>Queue Trigger</strong> or <strong>HTTP Trigger</strong> to handle this.</p><p>Here’s a simple example using the <strong>SendGrid</strong> email service to send an email.</p><ol><li><strong>Install SendGrid NuGet Package</strong>: First, install the <strong>SendGrid NuGet package</strong> via NuGet Package Manager or by running this in your terminal: dotnet add package SendGrid</li><li><strong>Create the Azure Function to Send an Email</strong>:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1fJsfCG4WgEj6ysNXtTucg.png" /></figure><ul><li><strong>How it works</strong>: This function triggers when a new user is added to the new-user-queue. It sends them a welcome email using <strong>SendGrid</strong>.</li><li><strong>Real use case</strong>: You could use this for sending onboarding emails to new users or subscribers.</li></ul><h3><strong>Example 6: Process Files in Blob Storage (The Snack Delivery)</strong></h3><p>Imagine you’re hosting a party and guests are dropping off snack recipes (files) in your <strong>Azure Blob Storage</strong>. You want to process those recipes and log them in the event that someone needs to order the ingredients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2s8IsJcMNSdAkiutXsQdEg.png" /><figcaption>Processing files in Blob Storage</figcaption></figure><ul><li><strong>How it works</strong>: This function listens to a blob container (snacks/). When a new file is uploaded (for example, a recipe), it triggers and logs the file contents.</li><li><strong>Real use case</strong>: You could use this for handling uploaded documents, images, or reports.</li></ul><h3><strong>Example 7: Process Messages from Service Bus Queue (The Help Desk)</strong></h3><p>Let’s say you want your function to act as a <strong>help desk</strong> that listens for incoming support requests and processes them one by one from the <strong>Azure Service Bus</strong> queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myoDPGjifl9JrS4NFy07zQ.png" /><figcaption>Process Messages from Service Bus Queue</figcaption></figure><ul><li><strong>How it works</strong>: This function is triggered by messages added to the support-requests queue. When a new support request comes in, the function processes it.</li><li><strong>Real use case</strong>: This could be part of a customer service platform where requests are added to a queue and processed sequentially.</li></ul><h3><strong>Example 8: Durable Functions (The Party Workflow)</strong></h3><p>What if you have a complex workflow? Maybe you need to send multiple emails, update databases, and even call external APIs as part of a longer-running process (like processing party RSVPs). You can use <strong>Durable Functions</strong> to chain tasks together and ensure everything runs in order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*inr5NDjr8y8-yCjIrdHR4A.png" /></figure><ul><li><strong>How it works</strong>: This example demonstrates <strong>Durable Functions</strong>, where multiple activities (like sending an invite, reminding guests about snacks, and confirming RSVPs) are orchestrated together. This is great for workflows that need to maintain state or wait for external inputs.</li><li><strong>Real use case</strong>: Perfect for processing complex tasks like order processing, multi-step approvals, or handling multi-step customer interactions.</li></ul><h3><strong>Example 9: Integrating with External APIs (The Party Food Order)</strong></h3><p>What if you need to order food or supplies from an external service (like an API)? Here’s how you can integrate <strong>Azure Functions</strong> with an external API to automate ordering party supplies!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKJ17m0DfaK0z0QACHneFg.png" /><figcaption>Integrating with External APIs</figcaption></figure><ul><li><strong>How it works</strong>: This function is triggered daily at noon (with a <strong>Timer Trigger</strong>). It calls an external API to order pizza for the party (or other supplies).</li><li><strong>Real use case</strong>: You could use this in an e-commerce setting or any business that needs to interact with external APIs on a schedule.</li></ul><h3>Cost Management: Pay Only for What You Eat (Or Use)</h3><p>The best part? You only pay when your function is doing its job, like a party planner that only bills you for the time they actually worked! There are several pricing plans:</p><ul><li><strong>Consumption Plan</strong>: Pay for only the time your function runs.</li><li><strong>Premium Plan</strong>: More control, more features (like VNET integration).</li><li><strong>Dedicated Plan</strong>: Full-time party planner with fixed scaling.</li></ul><h3>Conclusion: More Ways to Party with Azure Functions</h3><p>With these real examples, you can see how Azure Functions can be used for a variety of tasks — from sending emails, processing files, and interacting with external APIs, to managing complex workflows with Durable Functions.</p><p>The best part? <strong>Azure Functions</strong> is like the best party planner: it shows up when needed, gets the job done, and leaves without any fuss. Plus, it scales automatically, so no party is too big or too small! 🥳</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc0d54ec6766" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Guide to Unit Testing in .NET (C#) Using xUnit and Moq (Without the Boring Examples)]]></title>
            <link>https://ziedrebhi.medium.com/the-ultimate-guide-to-unit-testing-in-c-using-xunit-and-moq-without-the-boring-examples-e53624e4db2b?source=rss-907ae9208cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/e53624e4db2b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Zied Rebhi]]></dc:creator>
            <pubDate>Wed, 13 Nov 2024 19:47:43 GMT</pubDate>
            <atom:updated>2024-11-13T22:35:24.511Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_4WJuukUtH6qMbCUQkTMaA.png" /><figcaption>The Ultimate Guide to Unit Testing in C# Using xUnit and Moq (Without the Boring Examples)</figcaption></figure><p>Alright, developers, gather ‘round. We’ve all been there, right? You’re looking for some unit testing examples, and what do you get? A classic <strong>sum function test</strong>. Really? The sum of two numbers? It’s like someone telling you, “Hey, you should totally learn to swim by jumping in the shallow end of the kiddie pool.” Ugh, no thanks!</p><p>But fear not, because in this article, we’re taking things up a notch. You’ll get <strong>real-world examples</strong>, not just the “add two numbers” stuff. We’re talking <strong>asynchronous methods</strong>, <strong>complex CQRS workflows</strong>, <strong>API controllers</strong>, and <strong>services that interact with databases</strong>. Sounds like a party? You bet! 🎉</p><p>So, buckle up as we dive deep into <strong>xUnit</strong>, <strong>Moq</strong>, and all the other goodies that make testing in C# both powerful and fun. By the end of this guide, you’ll be writing tests for real code in no time, and they’ll actually <em>mean something</em>. 🚀</p><h3>Why xUnit and Moq?</h3><p>You know that feeling when you’re trying to mock a database call and nothing seems to work? Or when you’re trying to test a service, but its dependencies are just too messy? Yeah, that’s where <strong>xUnit</strong> and <strong>Moq</strong> come in to save the day.</p><ul><li><strong>xUnit</strong>: It’s like the Swiss Army knife of unit testing. Simple, easy-to-use, and powerful enough to tackle anything.</li><li><strong>Moq</strong>: The mock framework that makes dependencies easier to deal with. No more struggling with setup methods or breaking your code into a thousand pieces just to test one thing.</li></ul><p>So, <strong>xUnit</strong> and <strong>Moq</strong> are like peanut butter and jelly. Together, they make testing smoother and tastier. 🍞🍇</p><blockquote>When writing unit tests, you often need to isolate the code you’re testing from external dependencies like databases, APIs, or services. Moq allows you to create these “fake” objects, or mocks, so that you can focus on testing the logic of your code without worrying about the real external systems. With Moq, you can specify how these fake objects should behave (e.g., what they should return when a method is called), and verify that the methods are called correctly during the test. This makes testing more efficient and reliable.</blockquote><h3><strong>Setting Up xUnit and Moq (It’s Simple, I Promise)</strong></h3><p>First, let’s get these bad boys installed so we can start writing tests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQ2l66lsMTp6yWY3Q9Xz2w.png" /></figure><p>No magic here. Just a quick setup, and we’re ready to roll.</p><h3>1. Basic Service Testing (No, Not a Sum Function!)</h3><p>Let’s start with something real. We’ll write a <strong>UserService</strong> that fetches user data from a repository. Why? Because fetching user data is something you actually do in real apps, not just summing numbers. 😜</p><p><strong>Service: </strong><strong>UserService</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wUCHkcLSl0QIcGOXRboANw.png" /></figure><p><strong>Test for </strong><strong>UserService</strong></p><p>Let’s test it. Mock the repository, and then check if the GetUserByIdAsync method actually returns a user (and doesn’t just return null—we&#39;re looking for something useful here, not just empty promises).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mW_NAO5eP3XakKncj_4-7g.png" /></figure><p><strong>Takeaway</strong>: This is a <strong>real</strong> test for a service that retrieves data from a database. It’s not a “sum of two numbers” function, and you actually care about testing it. 🎯</p><h3>2. Testing Asynchronous Methods (The Real Deal)</h3><p>Let’s talk about <strong>async/await</strong> because <strong>real applications</strong> often deal with I/O-bound operations. You know, things like making HTTP calls or reading from a database. We need to test that this works correctly.</p><p><strong>Service: </strong><strong>PaymentService</strong></p><p>Here, we’ll test a service that processes payments. It calls multiple external services to check user data, order details, and payment processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_a9LWbDWn9oTSY_kdmygg.png" /></figure><p><strong>Tests for </strong><strong>PaymentService</strong></p><p>Now let’s test it, making sure everything is mocked and asynchronous behavior works as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TT9MQ7bCFvXSD1HzR30n0A.png" /></figure><p><strong>Takeaway</strong>: These tests are all about <strong>real-world async calls</strong>. They help us ensure the method interacts with multiple services and handles various scenarios correctly.</p><h3><strong>3. MediatR + CQRS (Let’s Make it Fancy)</strong></h3><p>You might have heard about <strong>CQRS</strong> (Command Query Responsibility Segregation) and <strong>MediatR</strong>. If not, let me explain: CQRS is about <strong>separating</strong> your reads and writes into different models, and MediatR helps you handle them. Let’s see how this works in real life.</p><p><strong>Command: </strong><strong>CreateOrderCommand</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8EB9jMMM6c9bKN37b_NIWg.png" /></figure><p><strong>Test for </strong><strong>CreateOrderCommandHandler</strong></p><p>We’ll test that the command handler behaves correctly and sends the <strong>OrderCreatedEvent</strong> when a new order is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*drbbKgmkYXB_Eq-9QckMZw.png" /></figure><p><strong>Takeaway</strong>: This is where things get <strong>advanced</strong>. We’re testing a CQRS command handler that uses <strong>MediatR</strong> to send events and execute commands. This is the <strong>real deal</strong> for complex applications.</p><h3><strong>4. Event-Driven Architecture (Publish-Subscribe Pattern)</strong></h3><p>In many modern systems, events drive a lot of the functionality. For instance, an order creation event might trigger a series of other actions, such as sending a confirmation email, updating the inventory, or notifying a user.</p><p>Let’s build an event-driven system using <strong>MediatR</strong> and test the subscription to an event.</p><p><strong>Event: </strong><strong>OrderCreatedEvent</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*13p0HTdVmQt5on2XnZR0tw.png" /></figure><p><strong>Handler: </strong><strong>OrderCreatedEventHandler</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9U9SkgYRBjwiYOBCumnZg.png" /></figure><p><strong>Test for </strong><strong>OrderCreatedEventHandler</strong></p><p>We’ll now write a test to ensure that the email service is triggered correctly when an order is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i21T9HwXX0JHKHw2u2ia1w.png" /></figure><p><strong>Takeaway</strong>: Event-driven systems are a common architecture, especially in microservices. This test ensures that the system reacts appropriately to events, like sending emails when an order is created.</p><h3><strong>5. Background Job Processing (Hangfire)</strong></h3><p>In many applications, you need to process tasks in the background. This is often done via background job processing systems like <strong>Hangfire</strong> or <strong>Quartz.NET</strong>.</p><p>Here’s how we can test a background job that processes a payment.</p><p><strong>Background Job: </strong><strong>ProcessPaymentJob</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QERN-qDd1di6aTChoWaSqA.png" /></figure><p><strong>Test for </strong><strong>ProcessPaymentJob</strong></p><p>Let’s test the background job by ensuring that it calls the ProcessPaymentAsync method from the IPaymentService.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3-pXMdbue7F8lrQWyiY1A.png" /></figure><p><strong>Takeaway</strong>: Background jobs are essential for handling long-running processes. This test ensures that background tasks trigger the necessary service methods.</p><h3><strong>6. Integrating with External APIs (Third-Party Service)</strong></h3><p>In real-world apps, you often need to interact with <strong>third-party APIs</strong>. Whether it’s sending a message through Twilio, fetching weather data from an external service, or processing payments through Stripe, you’ll need to test how your system interacts with these external systems.</p><p><strong>External Service: </strong><strong>WeatherService</strong></p><p>Let’s assume we have a weather service that fetches the current temperature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xLckZyeuAZgQZU-CQdHcvw.png" /></figure><p><strong>Test for </strong><strong>WeatherService</strong></p><p>To test this, we will <strong>mock the </strong><strong>HttpClient</strong> using <strong>Moq</strong> and make sure that the service returns the expected response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCK1XqhNfimxbinuYPl5rw.png" /></figure><p><strong>Takeaway</strong>: Testing integration with third-party services is crucial for external dependencies. By mocking the HTTP response, we ensure that our service works without actually calling the real API (and risking running out of API calls for the day!).</p><h3><strong>6. Testing API Controllers (With Dependency Injection)</strong></h3><p>In web applications, controllers often rely on <strong>dependency injection</strong> to get their services. Let’s look at testing an <strong>API controller</strong> that uses injected services.</p><p><strong>Controller: </strong><strong>OrderController</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yisz7VXUUOILHl_RJChYnw.png" /></figure><p><strong>Test for </strong><strong>OrderController</strong></p><p>We’ll now test the controller method GetOrderById. We’ll mock the IOrderService to simulate database interaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JvAuTqodroHTCLoliXZvAg.png" /></figure><p><strong>Takeaway</strong>: When testing API controllers, mocking the injected services ensures that you test only the controller’s behavior, without depending on real databases or external services.</p><h3>Conclusion: You’re Now Ready to Tackle Any Test!</h3><p>Congratulations, my friend! 🎉 You’ve now seen <strong>advanced tests</strong>, covering everything from <strong>event-driven architectures</strong>, <strong>background jobs</strong>, <strong>third-party service integrations</strong>, to <strong>API controllers</strong>. With the power of <strong>xUnit</strong>, <strong>Moq</strong>, and <strong>MediatR</strong>, you’re now able to confidently test even the most complex systems.</p><p>The next time you hear someone say, “I don’t know how to test this,” you can confidently say, “I got you!” 🙌</p><p>Remember, in the world of testing, the more real your examples are, the more prepared you’ll be. So keep practicing, keep building, and <strong>make testing your superpower</strong>! 💪</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e53624e4db2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complex Data Seeding in .NET Core with EF Core and Bogus]]></title>
            <link>https://ziedrebhi.medium.com/complex-data-seeding-in-net-core-with-ef-core-and-bogus-22ed1485d6c9?source=rss-907ae9208cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/22ed1485d6c9</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Zied Rebhi]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 16:37:22 GMT</pubDate>
            <atom:updated>2024-11-13T19:53:26.750Z</atom:updated>
            <content:encoded><![CDATA[<h3>Complex Data Seeding in .NET Core with EF Core and Bogus</h3><h3>Introduction</h3><p>This tutorial demonstrates how to create a sophisticated seeding system in a .NET Core Web API project. Using Bogus and Entity Framework Core, we’ll seed complex relational data, conditional on the environment type, allowing seamless data setup for development and testing.</p><h3>Prerequisites</h3><ul><li>.NET Core SDK</li><li>Visual Studio or any code editor</li><li>Basic understanding of C#, Entity Framework Core, and relational databases</li></ul><h3>Steps</h3><h4>Step 1: Create a New .NET Core Project</h4><p>Start by creating a new .NET Core Web API project.</p><pre>dotnet new webapi -n ComplexSeedingApp<br>cd ComplexSeedingApp</pre><h4>Step 2: Install Required Packages</h4><p>Add the necessary NuGet packages for Entity Framework Core and Bogus.</p><pre>dotnet add package Microsoft.EntityFrameworkCore.SqlServer<br>dotnet add package Bogus</pre><h4>Step 3: Define Complex Data Models</h4><p>We’ll create models representing Users, Profiles, Roles, and Permissions, with relationships to demonstrate more complex seeding.</p><pre>// Models/User.cs<br>public class User<br>{<br>    public int Id { get; set; }<br>    public string Username { get; set; }<br>    public string Email { get; set; }<br>    public Profile Profile { get; set; }<br>    public ICollection&lt;Role&gt; Roles { get; set; }<br>}<br>// Models/Profile.cs<br>public class Profile<br>{<br>    public int Id { get; set; }<br>    public string FirstName { get; set; }<br>    public string LastName { get; set; }<br>    public int UserId { get; set; }<br>    public User User { get; set; }<br>}<br>// Models/Role.cs<br>public class Role<br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>    public ICollection&lt;Permission&gt; Permissions { get; set; }<br>}<br>// Models/Permission.cs<br>public class Permission<br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>}</pre><h4>Step 4: Configure DbContext with Conditional Seeding Logic</h4><p>Add DbSets to DbContext and implement a seeding method that generates data using Bogus. This logic will only seed data for the Development and Test environments.</p><pre>// MyDbContext.cs<br>using Bogus;<br>using Microsoft.EntityFrameworkCore;<br>using System.Collections.Generic;<br>using System.Data;<br>using System.Reflection.Emit;<br>using System.Security;<br>public class MyDbContext : DbContext<br>{<br>    public DbSet&lt;User&gt; Users { get; set; }<br>    public DbSet&lt;Profile&gt; Profiles { get; set; }<br>    public DbSet&lt;Role&gt; Roles { get; set; }<br>    public DbSet&lt;Permission&gt; Permissions { get; set; }<br>    public MyDbContext(DbContextOptions&lt;MyDbContext&gt; options) : base(options) { }<br>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        if (Environment.GetEnvironmentVariable(&quot;ASPNETCORE_ENVIRONMENT&quot;) == &quot;Development&quot; ||<br>        Environment.GetEnvironmentVariable(&quot;ASPNETCORE_ENVIRONMENT&quot;) == &quot;Test&quot;)<br>        {<br>            SeedData(modelBuilder);<br>        }<br>    }<br>    private void SeedData(ModelBuilder modelBuilder)<br>    {<br>        // Seed Permissions<br>        var permissionFaker = new Faker&lt;Permission&gt;()<br>        .RuleFor(p =&gt; p.Name, f =&gt; f.Company.CatchPhrase());<br>        var permissions = permissionFaker.Generate(10);<br>        modelBuilder.Entity&lt;Permission&gt;().HasData(permissions);<br>        // Seed Roles with Permissions<br>        var roleFaker = new Faker&lt;Role&gt;()<br>        .RuleFor(r =&gt; r.Name, f =&gt; f.Name.JobTitle())<br>        .RuleFor(r =&gt; r.Permissions, f =&gt; f.PickRandom(permissions, 3).ToList());<br>        var roles = roleFaker.Generate(5);<br>        modelBuilder.Entity&lt;Role&gt;().HasData(roles);<br>        // Seed Users with Profiles and Roles<br>        var userFaker = new Faker&lt;User&gt;()<br>        .RuleFor(u =&gt; u.Username, f =&gt; f.Internet.UserName())<br>        .RuleFor(u =&gt; u.Email, f =&gt; f.Internet.Email())<br>        .RuleFor(u =&gt; u.Roles, f =&gt; f.PickRandom(roles, 2).ToList());<br>        var users = userFaker.Generate(20);<br>        var profileFaker = new Faker&lt;Profile&gt;()<br>         .RuleFor(p =&gt; p.FirstName, f =&gt; f.Name.FirstName())<br>         .RuleFor(p =&gt; p.LastName, f =&gt; f.Name.LastName())<br>         .RuleFor(p =&gt; p.UserId, f =&gt; f.PickRandom(users).Id);<br>        var profiles = profileFaker.Generate(20);<br>        modelBuilder.Entity&lt;User&gt;().HasData(users);<br>        modelBuilder.Entity&lt;Profile&gt;().HasData(profiles);<br>    }<br>}</pre><h4>Step 5: Set Up Application Seeding on Start</h4><p>To ensure the database seeds only in Development and Test environments, configure seeding within Startup.cs. We’ll check the environment and invoke seeding accordingly.</p><pre>// Startup.cs<br>using Microsoft.AspNetCore.Builder;<br>using Microsoft.EntityFrameworkCore;<br>using Microsoft.Extensions.DependencyInjection;<br>using Microsoft.Extensions.Hosting;<br>public class Startup<br>{<br>    public void ConfigureServices(IServiceCollection services)<br>    {<br>        services.AddDbContext&lt;MyDbContext&gt;(options =&gt;<br>        options.UseSqlServer(&quot;YourConnectionStringHere&quot;));<br>    }<br>    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, MyDbContext context)<br>    {<br>        if (env.IsDevelopment() || Environment.GetEnvironmentVariable(&quot;ASPNETCORE_ENVIRONMENT&quot;) == &quot;Test&quot;)<br>        {<br>            // Ensures database is created and seeded only in Development or Test environments<br>            context.Database.EnsureCreated();<br>        }<br>    }<br>}</pre><h4>Step 6: Ensure Database Re-seeding</h4><p>When working in development and test environments, it’s often helpful to reset and reseed the database each time you restart the application. You can accomplish this by dropping the database if it exists and re-creating it during the Configure phase.</p><pre>// Startup.cs (Updated)<br>public void Configure(IApplicationBuilder app, IWebHostEnvironment env, MyDbContext context)<br>{<br>    if (env.IsDevelopment() || Environment.GetEnvironmentVariable(&quot;ASPNETCORE_ENVIRONMENT&quot;) == &quot;Test&quot;)<br>    {<br>        context.Database.EnsureDeleted();<br>        context.Database.EnsureCreated();<br>    }<br>}</pre><h3>Conclusion</h3><p>This tutorial provided a more advanced seeding setup without using a CLI tool. By configuring seeding to run automatically based on the environment, you create realistic test data for development and testing while protecting production. This setup allows for a flexible and robust approach to database seeding that supports complex relationships, improving your application’s test and development experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22ed1485d6c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy an Azure SQL Database project using Azure DevOps [CI/CD]]]></title>
            <link>https://ziedrebhi.medium.com/deploy-an-azure-sql-database-project-using-azure-devops-ci-cd-cefcee6cabf9?source=rss-907ae9208cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/cefcee6cabf9</guid>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[azure-sql-database]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Zied Rebhi]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 00:26:41 GMT</pubDate>
            <atom:updated>2023-10-29T00:26:41.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*q-vutpOYDrEl8leiz4GLUQ.png" /><figcaption>Deploy an Azure SQL Database project using Azure DevOps [CI/CD]</figcaption></figure><p>Efficient database management and deployment are essential in today’s dynamic software development landscape. Continuous Integration and Continuous Deployment (CI/CD) with Azure DevOps offers a streamlined solution for managing database changes. In this guide, we’ll show you how to create a SQL Server Database Project ( using scripts), set up an Azure DevOps pipeline, and automate Azure SQL Database deployment. With these practices, you can ensure version control and error-free deployments, making your database development a breeze.</p><p>Let’s explore the world of Azure DevOps CI/CD for database management.</p><h3>Prerequisites</h3><p>Before you begin, make sure you have:</p><ol><li><a href="https://azure.microsoft.com/en-us/products/devops/"><strong>Azure DevOps Account</strong>:</a> Sign up for an Azure DevOps account.</li><li><a href="https://portal.azure.com/"><strong>Azure SQL Database</strong></a>: Set up an Azure SQL Database on Azure portal</li><li><strong>Visual Studio </strong>: Install Visual Studio with SQL Server Data Tools.</li><li><strong>Basic SQL Knowledge</strong>: Familiarity with SQL scripting.</li></ol><p>With these in place, you’re ready to automate your database deployment with Azure DevOps.</p><h3>Section 1: Creating the SQL Server Database Project</h3><p>In the section we will create a new project to add some scripts that we need to run in our database for our application <strong>ProjectManagement</strong>.Let’s say we will add a <strong>ProjectStatus </strong>table.</p><p>Using Visual Studio create a new project : <strong>SQL Server Database Project</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDWcKJTpL9WnvES46xIQjg.png" /><figcaption>Create a new Project : SQL Server Database Project</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_E49fW25uVOIc9bPUYBcw.png" /><figcaption>Configure the new project</figcaption></figure><p>In the solution we add a new Post Deployment Script (This file contains SQL statements that will be appended to the build script).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSjg7R7JwN-gkr4hccWEZA.png" /></figure><p>Then we add a SQL Script and we add our script to Create the <strong>ProjectStatus</strong> table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZduoHOvP0PwS5OiKbTVGg.png" /><figcaption>New script that will contains our SQL query ( Not in Build)</figcaption></figure><pre>USE TrainingDB<br>GO<br>SET ANSI_NULLS ON<br>GO<br>SET QUOTED_IDENTIFIER ON<br>GO<br>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = &#39;ProjectStatus&#39;)<br>BEGIN<br>CREATE TABLE [dbo].[ProjectStatus](<br> [ProjectStatusId] [int] IDENTITY(1,1) NOT NULL,<br> [Label] [nvarchar](50) NOT NULL,<br> CONSTRAINT [PK_ProjectStatusId] PRIMARY KEY CLUSTERED <br>(<br> [ProjectStatusId] ASC<br>)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]<br>) ON [PRIMARY]<br><br>END<br>ELSE<br>BEGIN<br>    PRINT &#39;The table &quot;ProjectStatus&quot; already exists.&#39;<br>END<br>GO</pre><p>In <strong><em>Script.PostDeployment.sql </em></strong>file we add this line (It means we need to run the script in <strong><em>ProjectStatusTable.sql)</em></strong></p><pre>:r .\ProjectStatusTable.sql</pre><p>We can add as much as we need scripts for our database. [Add SQL files then add them in <strong><em>Script.PostDeployment.sql </em></strong>file<strong><em>]</em></strong></p><blockquote>Make sure that the Target platform of the project is Microsoft Azure SQL Database</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KjFOw5pCwDddJw5heoEiMg.png" /><figcaption>Proprieties on the project then change the Target platform</figcaption></figure><p>Build the project and make sure it succeeds 😎</p><h3>Section 2: Setting up Azure DevOps:</h3><p>After we finish our scripts in the SQL Server Database project , we add the project to <a href="https://azure.microsoft.com/en-us/products/devops/">Azure DevOps</a> .</p><p>In Visual Studio click “Add to Source Control”. Then create the Git Repository to Azure DevOps as remote.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*Y2CRGJeAf9y6KFK5vbkMcg.png" /></figure><p>We check the our Azure DevOps account and verify that the solution exists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNWeejOPnv_7pOq4u-qH_g.png" /><figcaption>Repository of our SQL Server Database Project</figcaption></figure><h3>Section 3: Creating the Azure DevOps Build Pipeline:</h3><p>After pushing the code in our repository in Azure DevOps , we will create a Build Pipeline for our project .In this pipeline , we will save the output which is a database file (DACPAC) file into Azure DevOps artifact locations to be used after in the Release Pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QdiVW0Fx6QWQt2qJizfQMA.gif" /><figcaption>Create new Build Pipeline in Azure DevOps</figcaption></figure><p>The pipeline YAML will look like :</p><pre># .NET Desktop<br># Build and run tests for .NET Desktop or Windows classic desktop solutions.<br># Add steps that publish symbols, save build artifacts, and more:<br># https://docs.microsoft.com/azure/devops/pipelines/apps/windows/dot-net<br><br>trigger:<br>- master<br><br>pool:<br>  vmImage: &#39;windows-latest&#39;<br><br>variables:<br>  solution: &#39;**/*.sln&#39;<br>  buildPlatform: &#39;Any CPU&#39;<br>  buildConfiguration: &#39;Release&#39;<br><br>steps:<br>- task: NuGetToolInstaller@1<br><br>- task: NuGetCommand@2<br>  inputs:<br>    restoreSolution: &#39;$(solution)&#39;<br><br>- task: VSBuild@1<br>  inputs:<br>    solution: &#39;$(solution)&#39;<br>    platform: &#39;$(buildPlatform)&#39;<br>    configuration: &#39;$(buildConfiguration)&#39;<br><br>- task: VSTest@2<br>  inputs:<br>    platform: &#39;$(buildPlatform)&#39;<br>    configuration: &#39;$(buildConfiguration)&#39;<br><br># Add those tasks to copy and publish the Artifact (.dacpac file)<br>- task: CopyFiles@2<br>  inputs:<br>    targetFolder: &#39;$(Build.ArtifactStagingDirectory)&#39;    <br><br>- task: PublishBuildArtifacts@1    <br>  displayName: &#39;Publish Artifact: drop&#39;<br>  inputs:<br>    PathtoPublish: &#39;$(build.artifactstagingdirectory)&#39;</pre><p>Now , we run our pipeline for <em>master </em>branch :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q20V0ZD4OegkISU8mSnr5g.gif" /><figcaption>Pipeline running successfully and as we we can see the dacpac file is published</figcaption></figure><h3>Section 4: Creating the Azure DevOps Release Pipeline</h3><p>After building the project , it’s time to run it . For our case ,it means we want to run the SQL queries that we have created in our solution.</p><p>To do that , we will create a Release Pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*xFCh8aBPaxHftLck-z1GFw.png" /></figure><blockquote>If you don’t have Releases option in your Azure DevOps , Go to organization settings and disable this option “<strong>Disable creation of classic release pipelines”</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KtWZCHaltSSzv4BpV2fa3w.png" /><figcaption>Can’t see Releases in Azure DevOps =&gt; Disable this option</figcaption></figure><ul><li>New release pipeline, then choose “<strong><em>Empty Job</em></strong>” as a template.</li><li>In the Artifacts , we choose “<strong><em>Build</em></strong>” as source type and select our Build pipeline created in the previous section</li><li>For the stage , we add “<strong><em>Azure SQL Database deployment</em></strong>” task and we configure it with our Azure subscription.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02CKNIfXDMD2NGUcrbX_9Q.png" /><figcaption>Configuration the <strong><em>Azure SQL Database deployment </em></strong><em>task</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8L2RpTib5GOj_QrAyROUDw.gif" /><figcaption>Creating Release pipeline</figcaption></figure><blockquote>Activate <strong>“Continuous deployment trigger”</strong> option to create a release every time a new build is available.</blockquote><p>Now ,our Release pipeline is ready to run and deploy our project [Scripts] to our Azure SQL Server database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LGl50pSTeFrbTELISmS2JA.png" /><figcaption>Release succeed</figcaption></figure><p>Time to check our database :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*nqeI_bIFqA3MxtaKQwFBFg.png" /><figcaption><strong>ProjectStatus </strong>table created in our Azure SQL Server Database</figcaption></figure><h3>Section 5: Testing</h3><p>Let’s add some data in our table “<strong><em>ProjectStatus</em></strong>” and push the code and let’s see what will happen 🤖.</p><p>Going back to our code in Visual Studio , let’s add a new SQL Script :</p><pre>INSERT INTO ProjectStatus (ProjectStatusId, Label)<br>VALUES<br>    (1, &#39;In Progress&#39;),<br>    (2, &#39;Completed&#39;),<br>    (3, &#39;On Hold&#39;),<br>    (4, &#39;Not Started&#39;);<br>GO<br></pre><pre>:r .\ProjectStatusTable.sql  <br>:r .\ProjectStatusData.sql  </pre><p>Then Push the code to Azure DevOps and check the pipelines ⌛️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*noDeukGQDvxXyJiB0UZnuw.gif" /><figcaption>CI/CD</figcaption></figure><h3>Conclusion</h3><p>You’ve reached the end of this tutorial on Azure SQL Database deployment with Azure DevOps CI/CD. You’ve learned to automate and streamline your database development, ensuring version control and error-free deployments. With these newfound skills, you’re well-prepared to enhance your database management processes. Embrace the power of Azure DevOps CI/CD, and say goodbye to manual deployments. Your database development just got a whole lot easier.</p><p>Happy coding!</p><p>REBHI Zied</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cefcee6cabf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Design Principles in C#]]></title>
            <link>https://ziedrebhi.medium.com/solid-design-principles-in-c-ea9335115acc?source=rss-907ae9208cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea9335115acc</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[craftsmanship]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Zied Rebhi]]></dc:creator>
            <pubDate>Sat, 07 Oct 2023 04:54:48 GMT</pubDate>
            <atom:updated>2024-11-13T21:19:18.083Z</atom:updated>
            <content:encoded><![CDATA[<h3><em>SOLID</em> Design <em>Principles in </em>.NET (C#) — <em>Before &amp; After</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*i73OoXVOvKqpiPbuu0KSzQ.png" /><figcaption>SOLID Design Principles in C# [Before &amp; After]</figcaption></figure><p>In the world of software development, writing code is just the beginning; crafting code that’s maintainable and adaptable over time is where true craftsmanship lies. That’s where SOLID principles come in. These five fundamental principles offer a blueprint for cleaner and more efficient code design.</p><p>In this article, we’ll explore SOLID principles through practical examples. We’ll take a simple code snippet, apply SOLID principles, and witness the transformation from a tangled mess to an elegant and maintainable solution. By the end, you’ll grasp how these principles can revolutionize your approach to software design.</p><p>So, let’s dive into the before-and-after of SOLID principles and see how they can make your code not only work but work beautifully.</p><h3><strong>1. Single Responsibility Principle (SRP)</strong></h3><p>A class should have only <strong>one </strong>reason to change.</p><p><em>Before SRP:</em></p><pre>public class Customer<br>{<br>  public string Name { get; set; }<br>  public void AddToDatabase()<br>  {<br>      // Code to add customer to the database<br>  }<br>  public void GenerateInvoice()<br>  {<br>      // Code to generate an invoice<br>  }<br>}</pre><blockquote>In the code above, the <strong><em>Customer</em> </strong>class has multiple responsibilities: managing customer data and generating invoices. This violates the SRP.</blockquote><p><em>After SRP:</em></p><pre>public class Customer<br>{<br>    public string Name { get; set; }<br>}<br><br>public class CustomerRepository<br>{<br>    public void AddToDatabase(Customer customer)<br>    {<br>        // Code to add customer to the database<br>    }<br>}<br><br>public class InvoiceGenerator<br>{<br>    public void GenerateInvoice(Customer customer)<br>    {<br>        // Code to generate an invoice<br>    }<br>}</pre><p>In the updated code, we’ve separated the responsibilities into distinct classes: <strong><em>Customer </em></strong>now only represents customer data, <strong><em>CustomerRepository </em></strong>handles database interactions, and <strong><em>InvoiceGenerator</em></strong> takes care of invoice generation. Each class now has a single responsibility.</p><h3>2. <strong>Open-Closed Principle (OCP)</strong></h3><p>Software entities (classes, modules, functions) should be open for extension but closed for modification.</p><p><em>Before OCP:</em></p><pre>public class Rectangle<br>{<br>    public double Width { get; set; }<br>    public double Height { get; set; }<br>}<br><br>public class AreaCalculator<br>{<br>    public double CalculateArea(Rectangle rectangle)<br>    {<br>        return rectangle.Width * rectangle.Height;<br>    }<br>}</pre><blockquote>In this example, if we want to add support for calculating the area of other shapes, we would need to modify the <strong>AreaCalculator </strong>class, violating the OCP.</blockquote><p><em>After OCP:</em></p><pre>public abstract class Shape<br>{<br>    public abstract double CalculateArea();<br>}<br><br>public class Rectangle : Shape<br>{<br>    public double Width { get; set; }<br>    public double Height { get; set; }<br><br>    public override double CalculateArea()<br>    {<br>        return Width * Height;<br>    }<br>}<br><br>public class Circle : Shape<br>{<br>    public double Radius { get; set; }<br><br>    public override double CalculateArea()<br>    {<br>        return Math.PI * Radius * Radius;<br>    }<br>}</pre><p>In the updated code, we’ve introduced an abstract <strong><em>Shape</em></strong> class and derived classes for specific shapes. Now, to add support for new shapes, you can create new classes that inherit from <strong><em>Shape</em></strong> without modifying existing code, adhering to the OCP.</p><h3>3. <strong>Liskov Substitution Principle (LSP)</strong></h3><p>Subtypes must be substitutable for their base types without altering the correctness of the program.</p><p><em>Before LSP:</em></p><pre>public class Bird<br>{<br>    public virtual void Fly()<br>    {<br>        Console.WriteLine(&quot;A bird can fly.&quot;);<br>    }<br>}<br><br>public class Ostrich : Bird<br>{<br>    public override void Fly()<br>    {<br>        Console.WriteLine(&quot;An ostrich cannot fly.&quot;);<br>    }<br>}</pre><blockquote>In this example, the <strong><em>Ostrich</em></strong> class is a subtype of <strong><em>Bird</em></strong>, but it violates the LSP because it alters the behavior of the <strong><em>Fly </em></strong>method.</blockquote><p><em>After LSP:</em></p><pre>public interface IFlyable<br>{<br>    void Fly();<br>}<br><br>public class Bird : IFlyable<br>{<br>    public void Fly()<br>    {<br>        Console.WriteLine(&quot;A bird can fly.&quot;);<br>    }<br>}<br><br>public class Ostrich : IFlyable<br>{<br>    public void Fly()<br>    {<br>        Console.WriteLine(&quot;An ostrich cannot fly.&quot;);<br>    }<br>}</pre><p>In the updated code, we’ve introduced an <strong><em>IFlyable</em></strong> interface that both <strong><em>Bird </em></strong>and <strong><em>Ostrich</em></strong> implement. Now, both classes adhere to the Liskov Substitution Principle, as they can be substituted for each other without altering program correctness.</p><h3>4. <strong>Interface Segregation Principle (ISP)</strong></h3><p>Clients should not be forced to depend on interfaces they do not use.</p><p><em>Before ISP:</em></p><pre>public interface IWorker<br>{<br>    void Work();<br>    void Eat();<br>    void Sleep();<br>}<br><br>public class Engineer : IWorker<br>{<br>    public void Work()<br>    {<br>        // Implement work for an engineer<br>    }<br><br>    public void Eat()<br>    {<br>        // Implement eating for an engineer<br>    }<br><br>    public void Sleep()<br>    {<br>        // Implement sleeping for an engineer<br>    }<br>}</pre><blockquote>In this example, the <strong><em>IWorker</em></strong> interface contains methods that not all clients (e.g., <strong><em>Engineer</em></strong>) need, violating ISP.</blockquote><p><em>After ISP:</em></p><pre>public interface IWorker<br>{<br>    void Work();<br>}<br><br>public interface IEater<br>{<br>    void Eat();<br>}<br><br>public interface ISleeper<br>{<br>    void Sleep();<br>}<br><br>public class Engineer : IWorker, IEater, ISleeper<br>{<br>    public void Work()<br>    {<br>        // Implement work for an engineer<br>    }<br><br>    public void Eat()<br>    {<br>        // Implement eating for an engineer<br>    }<br><br>    public void Sleep()<br>    {<br>        // Implement sleeping for an engineer<br>    }<br>}</pre><p>In the updated code, we’ve split the <strong><em>IWorker</em></strong> interface into separate interfaces (<strong><em>IEater </em></strong>and <strong><em>ISleeper </em></strong>) to follow ISP. Now, clients like <strong><em>Engineer </em></strong>can implement only the interfaces they need, preventing unnecessary dependencies.</p><h3>5. <strong>Dependency Inversion Principle (DIP)</strong></h3><p>High-level modules should not depend on low-level modules; both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions.</p><p><em>Before DIP:</em></p><pre>public class LightBulb<br>{<br>    public void TurnOn()<br>    {<br>        // Code to turn on the light bulb<br>    }<br>}<br><br>public class Switch<br>{<br>    private readonly LightBulb _bulb;<br><br>    public Switch()<br>    {<br>        _bulb = new LightBulb();<br>    }<br><br>    public void Flip()<br>    {<br>        _bulb.TurnOn();<br>    }<br>}</pre><blockquote>In this example, the <strong><em>Switch</em></strong> class directly depends on the concrete <strong><em>LightBulb </em></strong>class, violating DIP.</blockquote><p><em>After DIP:</em></p><pre>public interface ISwitchable<br>{<br>    void TurnOn();<br>}<br><br>public class LightBulb : ISwitchable<br>{<br>    public void TurnOn()<br>    {<br>        // Code to turn on the light bulb<br>    }<br>}<br><br>public class Switch<br>{<br>    private readonly ISwitchable _device;<br><br>    public Switch(ISwitchable device)<br>    {<br>        _device = device;<br>    }<br><br>    public void Flip()<br>    {<br>        _device.TurnOn();<br>    }<br>}</pre><p>In the updated code, we’ve introduced the <strong><em>ISwitchable</em></strong> interface, allowing <em>Switch</em> to depend on an abstraction rather than a concrete implementation. This adheres to the Dependency Inversion Principle.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea9335115acc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>