<?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 Sachin Gaikwad on Medium]]></title>
        <description><![CDATA[Stories by Sachin Gaikwad on Medium]]></description>
        <link>https://medium.com/@sachingaikwad2109?source=rss-79f28e40bdda------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RDYXzx7S-EVO541r.jpg</url>
            <title>Stories by Sachin Gaikwad on Medium</title>
            <link>https://medium.com/@sachingaikwad2109?source=rss-79f28e40bdda------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:41:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sachingaikwad2109/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[Dependency Injection —Asp.net core Middleware]]></title>
            <link>https://medium.com/@sachingaikwad2109/dependency-injection-asp-net-core-middleware-e5a13e0f8289?source=rss-79f28e40bdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5a13e0f8289</guid>
            <dc:creator><![CDATA[Sachin Gaikwad]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 08:24:16 GMT</pubDate>
            <atom:updated>2025-01-08T08:24:16.344Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I was working on middleware which I have discussed in my previous article <a href="https://medium.com/@sachingaikwad2109/filters-vs-middleware-in-asp-net-core-67d5496687a7">Filter vs Middleware</a> , but while working I came across below exception <strong>“System.InvalidOperationException: Cannot resolve scoped service ‘’ from root provider.”</strong>. So after going through <a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-9.0#lifetime-and-registration-options">MS documentation</a>. I came to know there is difference the way middleware behaves with different service lifetime.</p><p>Default lifetime of middleware is <strong>singleton</strong> as per Microsoft documentation, and the dependency which I was injecting in middleware constructor was scoped, due to which it was throwing above runtime exception because <strong><em>it forces the scoped service to behave like a singleton</em></strong>. So if you intent to inject dependency in middleware with scoped lifetime you need to inject the service into the middleware with below ways:</p><ol><li>Invoke or InvokeAsync method: Below is the sample code snippet.</li></ol><pre>    public class ConventionalMiddleware<br>    {<br>        private readonly RequestDelegate _next;<br><br>        public ConventionalMiddleware(RequestDelegate next)<br>        {<br>            _next = next;<br>        }<br>        public async Task InvokeAsync(HttpContext context, IAnalyticsClient client)<br>        {<br>            // TODO: your middleware logic here<br>            await _next(context);<br>        }<br>    }</pre><p>2. FactoryBased Middleware : Below is the sample code snippet.</p><pre>public class FactoryActivatedMiddleware : IMiddleware<br>{<br>    private readonly IAnalyticsClient _analyticsClient;<br>    private readonly ITelemetryLogger _logger;<br><br>    public FactoryActivatedMiddleware(IAnalyticsClient analyticsClient, ITelemetryLogger logger)<br>    {<br>        _analyticsClient = analyticsClient;<br>        _logger = logger;<br>    }<br><br>    public async Task InvokeAsync(HttpContext context, RequestDelegate next)<br>    {<br>        // TODO: your middleware logic here<br><br>        await next(context);<br>    }<br>}</pre><p><strong>Limitations with FactoryBased Middleware:</strong> It is not possible to pass objects to the factory-activated middleware, the way we can pass to conventional middleware.</p><p>FactoryBased middleware:</p><pre> //Passing &#39;option&#39; as an argument throws a NotSupportedException at runtime.<br>    app.UseMiddleware&lt;FactoryActivatedMiddleware&gt;(option);</pre><p>Conventional middleware:</p><pre>app.UseMiddleware&lt;ConventionalMiddleware&gt;(option);</pre><p>Hope this will help you to work with middleware in future.</p><p>Happy coding..!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5a13e0f8289" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Filters vs Middleware in asp.net core]]></title>
            <link>https://medium.com/@sachingaikwad2109/filters-vs-middleware-in-asp-net-core-67d5496687a7?source=rss-79f28e40bdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/67d5496687a7</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[dot-net-core]]></category>
            <category><![CDATA[aspnet-development]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Sachin Gaikwad]]></dc:creator>
            <pubDate>Fri, 08 Nov 2024 05:05:37 GMT</pubDate>
            <atom:updated>2024-11-08T05:05:37.940Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I was working on designing a solution where I need to capture success/failure of every API call.</p><p>Below is the high level design for my solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*34D2Cdsjc4BcZPl7D2_05Q.png" /></figure><p><strong>I had two options to capture the success/failure:</strong></p><ol><li>Filters</li><li>Middleware</li></ol><p>will explain both options and which I went with.</p><h3><strong>Available filters in ASP.NET MVC</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njXx8ArRXJjHsnMaVj_6Qw.png" /><figcaption><strong>Filters execution cycle</strong></figcaption></figure><ol><li><strong>Authorization filters:</strong> used to verify that a user is authorized to access a particular controller.</li><li><strong>Resource filters:</strong> Run after Auth filter. Execution wraps most of the filter pipeline.</li><li><strong>Action filters:</strong> Their execution surrounds the execution of action methods. These are useful for implementing cross-cutting concerns such as logging.</li><li><strong>Exception filters:</strong> Exception filters are used to handle exceptions that occur during the execution of an action method. They run only if an unhandled exception is thrown.</li><li><strong>Result filters: </strong>Result filters run before and after the execution of the action method, but they specifically deal with the result returned by the action.</li></ol><p>The problem with filters is it will not capture the model validation failures. As per the documentation and above image filters are executed after model binding and model validation, thus it will not be called incase model validation fails. So I had to drop this option as I need to collect the data for all sorts of failures.</p><h3>Middleware</h3><p>Middleware is a component that executes automatically with every request. .NET Core offers built-in middleware and even creates your custom middleware. Basically, it is one type of filter request in a web application context. Middleware can be used for different purposes, including request filtering. It can filter requests based on various criteria. E.g. you might have middleware that checks whether a user is authenticated before allowing access to certain URLs or routes. By examining these attributes of incoming requests, middleware can decide whether to allow, reject, modify, or redirect them before passing them on to the main application logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*eHcMZHRcXYJtx7V92ZorrA.png" /><figcaption><strong>Request pipeline</strong></figcaption></figure><h3>Middleware ordering:</h3><p>Middleware components execute in the order they are added. It’s like creating a to-do list for your application, making sure each task is done at the correct time and in the proper sequence.</p><p>The order matters because each middleware plays a specific role and affects the outcome of the response.</p><p>The first middleware received the request, updated it as needed, and then gave control to the next middleware. Similarly, the first middleware executes at last while processing the response. That’s why it’s important to have error handlers (Exception handler middleware) first in the process they can catch any problems and show them in a way that’s easy for the user to understand.</p><p><strong><em>Middleware gets executed for every request/response, no matter whether the request fails/succeeds.</em></strong></p><p>So in my use case, I had to go with custom middleware as it is a good fit for my requirement.</p><h3>Conclusion</h3><p>It entirely depends on which one to use filters or middleware, filter has its own use case same with middleware.</p><blockquote>Hope this post helps you.!! Happy coding.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67d5496687a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bulk Insert using MERGE statement and Table variable.]]></title>
            <link>https://medium.com/@sachingaikwad2109/bulk-insert-using-merge-statement-and-table-variable-9d55951e322d?source=rss-79f28e40bdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d55951e322d</guid>
            <dc:creator><![CDATA[Sachin Gaikwad]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 09:26:52 GMT</pubDate>
            <atom:updated>2024-03-28T09:26:52.367Z</atom:updated>
            <content:encoded><![CDATA[<p>In software industry we always come across a situation where we need to do bulk insert into database, on the same line recently I was working on a task where I need to bulk insert records in sql server db. So I decided to go with table variable and MERGE statement approach.</p><p><strong>So below are design steps:</strong><br>1. Create table variable.<br>2. Insert data using MERGE statement.<br>3. Create stored procedure and pass table variable as input parameter.</p><p><strong>Table variable: </strong>The table variable is a <strong>special type</strong> of the <em>local variable</em> that helps to store data temporarily, similar to the <strong><em>temp table</em></strong> in SQL Server. In fact, the table variable provides all the properties of the local variable, but the local variables have some limitations, unlike temp or regular tables. We can also have constraints on a table variable, below are some of the constraints:</p><p><strong>Primary Key<br>Unique<br>Null</strong></p><p><strong>Syntax: </strong>The following syntax describes how to declare a table variable:</p><pre>CREATE TYPE dbo.UDT_SampleTableVariable AS TABLE <br>(<br> column_1 DATATYPE, <br> column_2 DATATYPE, <br> column_N DATATYPE<br>)<br><br>--e.g: with primary key<br>CREATE TYPE [dbo].[UDT_BulkReturns] AS TABLE(<br> [Id] [varchar](500) NOT NULL,<br> [Name] [varchar](500) NULL,<br> [Version] [varchar](10) NULL,<br> [Type] [varchar](500) NULL,<br> PRIMARY KEY CLUSTERED <br>(<br> [Id] ASC<br>)WITH (IGNORE_DUP_KEY = OFF)<br>)</pre><p><strong>Merge Statement: </strong>The MERGE statement in SQL is a very popular clause that can handle <strong><em>inserts, updates, and deletes</em></strong> all in a <strong>single transaction</strong> without having to write separate logic for each of these. You can specify conditions on which you expect the MERGE statement to insert, update, or delete, etc. But in this post we are going to look into MERGE statement with insert.</p><p><strong>Merge for Insert syntax:</strong></p><pre>BEGIN<br> MERGE [CCH].Returns AS Target<br> USING @BulkReturns AS Source<br> ON Source.Id= Target.Id<br>  WHEN NOT MATCHED BY Target THEN<br>    INSERT (Id, Name,Status,Version,Type) <br>    VALUES (Source.Id,Source.Name,Source.Status,Source.Version,Source.Type);<br>END</pre><p><strong>Stored Procedure: </strong>Need to create stored procedure to combine table variable and the MERGE statement to insert data into table.</p><pre>CREATE OR ALTER PROCEDURE [dbo].[usp_BulkInsert]<br>@BulkReturns [dbo].[UDT_BulkReturns] READONLY<br>AS<br>BEGIN<br> MERGE [CCH].Returns AS Target<br> USING @BulkReturns AS Source<br> ON Source.Id= Target.Id<br>  WHEN NOT MATCHED BY Target THEN<br>    INSERT (Id, Name,Status,Version,Type) <br>    VALUES (Source.Id,Source.Name,Source.Status,Source.Version,Source.Type);<br>END</pre><p><strong>Conclusion:</strong></p><p>In this article we saw the use of table variable and MERGE statement for bulk insert. There are other ways as well to perform bulk insert.</p><p><em>Happy Reading and Learning!!!</em></p><p><strong>Primary Key<br>Unique<br>Null</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d55951e322d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retry http calls using Microsoft.Extensions.Http.Polly]]></title>
            <link>https://medium.com/@sachingaikwad2109/retry-http-calls-using-microsoft-extensions-http-polly-ff3cf0bd1c5b?source=rss-79f28e40bdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff3cf0bd1c5b</guid>
            <dc:creator><![CDATA[Sachin Gaikwad]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 07:43:16 GMT</pubDate>
            <atom:updated>2024-02-09T07:44:03.258Z</atom:updated>
            <content:encoded><![CDATA[<p>Retry http calls using <strong>Microsoft.Extensions.Http.Polly</strong></p><p>While working in web application, mainly when we consume any rest endpoint. Sometimes we need to retry the api calls upto certain retires.</p><p>Recently I was working on an assignment where I need to retry the api calls like for 401 only 1 retry should happen. So polly is something which I used but in a customised way.</p><p><strong>What is polly?</strong></p><p>Polly is a . NET library that provides resilience and transient-fault handling capabilities. You can implement those capabilities by applying Polly policies such as Retry, Circuit Breaker, Bulkhead Isolation, Timeout, and Fallback.</p><p>As mentioned above I customed Polly or rather extended Polly.</p><pre>    public static class HttpRetryPolicyExtensions<br>    {<br>        private static readonly Func&lt;HttpResponseMessage, bool&gt; UnauthorizedHttpStatusCodePredicate = (response) =&gt;<br>        {<br>            return response.StatusCode == HttpStatusCode.Unauthorized;<br>        };<br><br>        public static PolicyBuilder&lt;HttpResponseMessage&gt; HandleUnauthorizedHttpError()<br>        {<br>            return Policy&lt;HttpResponseMessage&gt;.Handle&lt;HttpRequestException&gt;().OrUnauthorizedHttpStatusCodePredicate();<br>        }<br><br>        public static PolicyBuilder&lt;HttpResponseMessage&gt; OrUnauthorizedHttpStatusCodePredicate(this PolicyBuilder&lt;HttpResponseMessage&gt; policyBuilder)<br>        {<br>            ArgumentNullException.ThrowIfNull(nameof(policyBuilder));<br><br>            return policyBuilder.OrResult(UnauthorizedHttpStatusCodePredicate);<br>        }<br>    }<br><br></pre><pre>        private static IAsyncPolicy&lt;HttpResponseMessage&gt; AddUnAuthorizedRetryPolicy(IServiceProvider services) =&gt; HttpRetryPolicyExtensions.HandleUnauthorizedHttpError()<br>                .WaitAndRetryAsync(retryCount: RetryConstants.UnauthorizedRetryCount, sleepDurationProvider: (retryAttempt) =&gt; TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),<br>                                            onRetry: (exception, _, attemptNumber, _) =&gt;<br>                                            {<br>                                             <br>                                            });</pre><p>Above policy will execute only if the HttpStatus code is 401.</p><p>Thanks for reading..!! happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff3cf0bd1c5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interface with multiple Implementation in dotnet.]]></title>
            <link>https://medium.com/@sachingaikwad2109/interface-with-multiple-implementation-in-dotnet-065d26d3d2ff?source=rss-79f28e40bdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/065d26d3d2ff</guid>
            <dc:creator><![CDATA[Sachin Gaikwad]]></dc:creator>
            <pubDate>Mon, 25 Dec 2023 13:53:48 GMT</pubDate>
            <atom:updated>2023-12-25T14:15:24.275Z</atom:updated>
            <content:encoded><![CDATA[<p>In software development most of the time we come across a situation where we end up one interface having multiple implementation. So I personally have faced such situation many times. But there are multiple ways to overcome from this. Below are the ways:</p><ol><li>Using delegate:</li></ol><pre>            services.AddScoped&lt;TextNotificationFactory&gt;();<br>            services.AddScoped&lt;EmailNotificationFactory&gt;();<br><br>            services.AddScoped&lt;Func&lt;string, IPatternMigration&gt;&gt;(ser =&gt; key =&gt;<br>            {<br>                switch (key)<br>                {<br>                    case &quot;text&quot;:<br>                        return ser.GetService&lt;TextNotificationFactory&gt;();<br>                    case &quot;email&quot;:<br>                        return ser.GetService&lt;EmailNotificationFactory&gt;();<br>                    default:<br>                        throw new NotSupportedException(&quot;notification not supported&quot;);<br>                }<br>            });</pre><p>2 Using Generic interface:</p><pre>    //Declare generic interface  <br>    public interface INotificationFactory&lt;T&gt; where T : class<br>    {<br>        Task&lt;bool&gt; SendNotification();<br>    }<br><br>    //implement INotificationFactory in EmailNotificationFactory<br>    public class EmailNotificationFactory : INotificationFactory&lt;EmailNotificationFactory&gt;<br>    {<br>        public async Task&lt;bool&gt; SendNotification()<br>        {<br>            return await Task.FromResult(true);<br>        }<br>    }<br><br>    //implement INotificationFactory in TextNotificationFactory<br>    public class TextNotificationFactory : INotificationFactory&lt;TextNotificationFactory&gt;<br>    {<br>        public async Task&lt;bool&gt; SendNotification()<br>        {<br>            return await Task.FromResult(true);<br>        }<br>    }<br><br>   //Interface injection in controller.<br>    [Route(&quot;api/[controller]&quot;)]<br>    [ApiController]<br>    public class ValuesController : ControllerBase<br>    {<br>        private readonly INotificationFactory&lt;TextNotificationFactory&gt; _textNotification;<br>        private readonly INotificationFactory&lt;EmailNotificationFactory&gt; _emailNotification;<br>    <br>        public ValuesController(INotificationFactory&lt;TextNotificationFactory&gt; textNotification,<br>                                                       INotificationFactory&lt;EmailNotificationFactory&gt; emailNotification)<br>        {<br>            _textNotification=textNotification;<br>            _emailNotification=emailNotification;<br>        }<br>    <br>        [HttpPost]<br>        [Route(&quot;send-email-notification&quot;)]<br>        public IActionResult PostEmailNotification([FromBody] string value)<br>        {<br>            _emailNotification.SendNotification();<br>            return Ok();<br>        }<br>    <br>        [HttpPost]<br>        [Route(&quot;send-text-notification&quot;)]<br>        public IActionResult PostTextNotification([FromBody] string value)<br>        {<br>            _textNotification.SendNotification();<br>            return Ok();<br>        }<br>    }<br><br> //Interface Registeration in startup.cs<br>  builder.Services.AddScoped&lt;INotificationFactory&lt;TextNotificationFactory&gt;, TextNotificationFactory&gt;();<br>  builder.Services.AddScoped&lt;INotificationFactory&lt;EmailNotificationFactory&gt;, EmailNotificationFactory&gt;();</pre><p>Thanks for reading!</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=065d26d3d2ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating batch out of list in C# using chunk function.]]></title>
            <link>https://medium.com/@sachingaikwad2109/creating-batch-out-of-list-in-c-using-chunk-function-3852cabb2cb8?source=rss-79f28e40bdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/3852cabb2cb8</guid>
            <dc:creator><![CDATA[Sachin Gaikwad]]></dc:creator>
            <pubDate>Mon, 25 Dec 2023 12:39:32 GMT</pubDate>
            <atom:updated>2023-12-25T14:16:08.812Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1HtrIi-IXPDHinCS6_VfjA.png" /></figure><p>Recently I was working on an assignment where I had to call some other api, so while calling the api I had to pass the request in batches i.e. in a batch of 20 or based on the configured value.</p><p>So I had option by doing it in:</p><ol><li><strong>Traditional way:</strong> Add some custom logic to break the list into batch based upon the batch size.</li><li><strong>Chunks:</strong> It is an inbuilt function by Microsoft introduced in .net 6 and onwards framework. It helps to Splits the elements of a sequence into chunks of size at most size. Below is the syntax of <strong>chunk:</strong></li></ol><pre>IEnumerable&lt;TSource[]&gt; Chunk&lt;TSource&gt; (<br>    IEnumerable&lt;TSource&gt; source, <br>    int size<br>);<br><br></pre><pre>It takes 2 parameters:<br>1. Source: To be converted into chunks.<br>2. Size: Size for each chunk.</pre><p><strong>Below is the code snippet for chunk:</strong></p><pre>var numbers = new List&lt;int&gt;(Enumerable.Range(1, 25));<br><br>foreach (var chunk in numbers.Chunk(5))<br>{<br>    Console.WriteLine($&quot;Chunk of {chunk.Count()} items:&quot;);<br>    chunk.ToList().ForEach(x =&gt; Console.WriteLine($&quot; {string.Join(&quot;,&quot;, x)}&quot;));<br>}<br></pre><pre><strong>Output:<br></strong><br>Chunk of 5 items:<br> 1<br> 2<br> 3<br> 4<br> 5<br>Chunk of 5 items:<br> 6<br> 7<br> 8<br> 9<br> 10<br>Chunk of 5 items:<br> 11<br> 12<br> 13<br> 14<br> 15<br>Chunk of 5 items:<br> 16<br> 17<br> 18<br> 19<br> 20<br>Chunk of 5 items:<br> 21<br> 22<br> 23<br> 24<br> 25</pre><p><strong>Expected exception:</strong></p><blockquote>ArgumentNullException<br>source is null.</blockquote><blockquote>ArgumentOutOfRangeException<br>size is below 1.</blockquote><p>Thanks for reading!</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3852cabb2cb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>