<?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 Nitesh Singhal on Medium]]></title>
        <description><![CDATA[Stories by Nitesh Singhal on Medium]]></description>
        <link>https://medium.com/@niteshsinghal85?source=rss-93f078f8e9c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*piOkyx_ZRGRiSek90BD7aA.jpeg</url>
            <title>Stories by Nitesh Singhal on Medium</title>
            <link>https://medium.com/@niteshsinghal85?source=rss-93f078f8e9c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 13:22:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@niteshsinghal85/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[Simplifying Security: Resource-Based Authorization in ASP. NET Core]]></title>
            <link>https://systemweakness.com/simplifying-security-resource-based-authorization-in-asp-net-core-3f70486059d5?source=rss-93f078f8e9c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f70486059d5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Nitesh Singhal]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 13:31:43 GMT</pubDate>
            <atom:updated>2023-04-03T15:32:13.491Z</atom:updated>
            <content:encoded><![CDATA[<h4>Authorization in .NET</h4><h4>A Short guide on how to add Resource-Based Authorization in ASP. NET Core WebAPI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*tJGQCB7vtF4p_JVvB0Dgbg.png" /><figcaption>Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><h3>Introduction</h3><p>Resource-based authorization is a security technique used to limit access to resources and content in an application. It allows developers to create policies that determine who can access particular resources and how they are allowed to interact with them. With resource-based authorization, users are only granted access if they meet the criteria set by the policy. This ensures that all users have uniform permissions within the application, which helps protect against malicious activity or unauthorized data breaches.</p><p>In ASP.NET Core, it provides flexibility for developers as well as powerful control over how resources are accessed within an application.</p><h3>Implementing Resource-Based Authorization</h3><p>Let’s us start with example, we have web API which used to manage articles for website. and anyone can view these articles but only author of the article can edit it.</p><p>With only authorize filter this would not possible as the resource “Article” is not available in the filter. so we would need a different way to check this.</p><p>Create a class called “Article” which is represent our entity stored in database.</p><pre>public class Article<br>{<br>  public int Id { get; set; }<br>  public string Title { get; set; }<br>  public string Description { get; set; }<br>  public string Author { get; set; }<br>}</pre><p>and we want to implement API to update article information</p><pre><br>[HttpPut]<br>public async Task&lt;IActionResult&gt; EditArticle(int articleId, Article article)<br>{<br>  // we will the add logic here to check if the user is allowed to the edit or not.<br>}</pre><h4>Steps to Implement a Resource-based Authorization:</h4><ol><li>Create an Authorization Requirement class. this class should inherit from the <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authorization.iauthorizationrequirement?view=aspnetcore-5.0">IAuthorizationRequirement</a>.</li><li>Add a custom policy using the “Authorization Requirement” created in previous step.</li><li>Now create authorization handlers and register them for DI.</li><li>Inject the IAuthorizationService interface in the controller class.</li><li>Call the “AuthorizeAsync” method using instance of IAuthorizationService by providing required parameters.</li><li>Check the result of previous step, if successful then proceed with changes else return Unauthorize() status to caller.</li></ol><p><strong>Create an Authorization Requirement class</strong></p><pre>public class IsAuthorRequirement : IAuthorizationRequirement<br>{<br>}</pre><p><strong>Add custom policy “IsAuthor” and register it.</strong></p><pre>builder.Services.AddAuthorization(options =&gt;<br>{<br>    options.AddPolicy( &quot;IsAuthor&quot;, <br>            policyBuilder =&gt; policyBuilder.AddRequirements(<br>                        new IsAuthorRequirement()));<br>});</pre><p><strong>Authorization handlers</strong></p><pre>public class IsAuthorAuthorizationHandler <br>             : AuthorizationHandler&lt;IsAuthorRequirement, Article&gt;<br>{<br>  protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, <br>   IsAuthorRequirement requirement, Article resource)<br>  {<br>   // we can check any condition here<br>   if (context.User.HasClaim(ClaimTypes.NameIdentifier, resource.Author))<br>   {<br>    context.Succeed(requirement);<br>   }<br>   return Task.FromResult(0);<br>  }<br>}</pre><p><strong>Register it for DI</strong></p><pre>builder.Services.AddSingleton&lt;IAuthorizationHandler, IsAuthorAuthorizationHandler&gt;();</pre><p><strong>Inject “IAuthorizationService” interface</strong></p><pre>private readonly IArticleRepository _repository;<br>private readonly IAuthorizationService _authorizationService;<br><br>public AuthorController(IArticleRepository repository, <br>   IAuthorizationService authorizationService)<br>{<br>   _repository = repository;<br>   _authorizationService = authorizationService;<br>}</pre><p><strong>Call the “AuthorizeAsync” method in API</strong></p><pre>[HttpPut]<br>public async Task&lt;IActionResult&gt; EditArticle(int articleId, Article article)<br>{<br>   var articleinDB = _repository.Find(articleId);<br>   // we need to provide the policy name<br>   var result = await _authorizationService.AuthorizeAsync(User, articleinDB, &quot;IsAuthor&quot;);<br>   if(result.Succeeded)<br>   {<br>    // here we can write the logic for further processing.<br>    return Ok(article);<br>   }<br>   else<br>   {<br>    return Unauthorized();<br>   }<br>}</pre><p>we can run the application and verify by logging in with two different users.</p><h3>Best Practices for Resource-Based Authorization</h3><p>Finally, when implementing resource-based authorization for API projects it’s recommended that developers use both explicit permission settings as well as general policies which apply across multiple areas within an application. Doing so helps keep security measures consistent throughout the entire system while still providing flexibility for developers needing fine grained control over how resources are accessed by different types of users and identities within the system itself.</p><h3>Conclusion</h3><p>Resource-based authorization is an effective method for protecting data from unauthorized access in ASP .NET Core API projects. This helps keep security measures consistent while still allowing different roles to access specific pieces of content as needed.</p><p>Hope it is helpful.</p><p><strong><em>Happy coding and keep learning..!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f70486059d5" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/simplifying-security-resource-based-authorization-in-asp-net-core-3f70486059d5">Simplifying Security: Resource-Based Authorization in ASP. NET Core</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiple example for parameters in Swagger with ASP.NET Core]]></title>
            <link>https://medium.com/@niteshsinghal85/multiple-example-for-parameters-in-swagger-with-asp-net-core-c4f3aaf1ae9f?source=rss-93f078f8e9c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4f3aaf1ae9f</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Nitesh Singhal]]></dc:creator>
            <pubDate>Wed, 28 Sep 2022 15:32:25 GMT</pubDate>
            <atom:updated>2022-09-28T15:32:25.205Z</atom:updated>
            <content:encoded><![CDATA[<h4>Swagger In .NET</h4><h4>A Short guide on how to add multiple example of route parameter in swagger doc.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*q-gS3W2v_n_H-8ZAgicPjQ.png" /><figcaption>Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>In one of my <a href="https://medium.com/@niteshsinghal85/multiple-request-response-examples-for-swagger-ui-in-asp-net-core-864c0bdc6619">previous swagger related post</a>, I have describe how can we create multiple examples for request and response body. In this post I am going to explore how can we do the same with route parameters.</p><p>Let’s start..</p><p>Let’s say we have one <strong>Get </strong>endpoint which takes a route parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*oX1IjgWM8plHNmUiH7JmMQ.png" /><figcaption>Get Endpoint Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>and when we generate swagger document we get following on swagger UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wLz5swOiifyGkiSWvJOfwA.png" /><figcaption>SwaggerUI Get Endpoint Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>Every time we have to call the API, we need to put the value and call the API.</p><p>In some case, we want to put some example value so that we don’t need to put it manually or that user is aware what kind of value is expected.</p><p>We can make use of xml comments feature along with swashbuckle to generate example along with definition.</p><p>so we make changes to <a href="https://github.com/domaindrivendev/Swashbuckle.AspNetCore#include-descriptions-from-xml-comments">IncludeXmlComments</a> in the swagger document.</p><p>and also added xml comments to the API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*OZ6g0BnRBEkMwTGO3QjGmg.png" /><figcaption>Get Endpoint With Xml Comments Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>Now we get example also.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8f9pSDzJlKerrvdPbmRi0A.png" /><figcaption>SwaggerUI Get Endpoint With Example Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>Great.. now we can try without entering anything manually. it will take example value and execute the API.</p><p>This works great for single example but in some case we want to define more then one example so that user is aware what all values are possible. also couple stackoverflow question were also asked in same direction so I thought let me try and see how can we achieve this.</p><p>first thing I tried using xml comments itself. so I changed the example tag to have multiple values. like below</p><pre>/// &lt;param name=&quot;limit&quot; example=&quot;[2,10]&quot;&gt;&lt;/param&gt;</pre><p>and when I ran the app , I get the following in swagger UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xCJSpHozX2nAOkhgrpVv0A.png" /><figcaption>SwaggerUI Get Endpoint With Multiple example Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>It included all the values as list but I can’t execute API, as it is expecting a single integer not the list.</p><p>I also searched if this is supported by OpenAPI Specification and Swagger UI in general or not and I found a link that it provides example of it.</p><p><a href="https://swagger.io/docs/specification/adding-examples/">https://swagger.io/docs/specification/adding-examples/</a></p><p>so then next, I searched swashbuckle documentation and source code for such support but couldn’t find anything.</p><h3>Solution</h3><p>As I could not found anything, I decided to try out my self by adding the examples to parameters.</p><p>I didn’t wanted to touch the xml part so I decided to use another approach.</p><p>for example, I would decorate my parameter with example values like below.</p><pre>[SwaggerParameterExample(&quot;Max&quot;, &quot;10&quot;)]int limit</pre><p>So that I see a named example “Max” on swagger UI with value “10”</p><p>Something like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-dw_3NrIHomFwLf2B3Dzw.png" /><figcaption>SwaggerUI Get Endpoint With Named example Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>Let’s see what changes are required to make it work like this.</p><p>we will start with defining the attribute class. “SwaggerParameterExampleAttribute.cs”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*WD9Uj4EdIfr5j8sMEBLbmw.png" /><figcaption>SwaggerParameterExampleAttribute class Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>and then we create a “CustomParameterFilter”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*TCwP4GTDoMzKasiF0GQfuQ.png" /><figcaption>CustomParameterFilter class Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>and add that filter to swagger configuration in AddSwaggerGen().</p><pre>builder.Services.AddSwaggerGen(c= &gt; c.ParameterFilter&lt;CustomParameterFilter&gt;());</pre><p>and last part is to decorate any parameter with attribute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*4iJE6RMpddZ4gMQZaOAcSw.png" /><figcaption>Get Endpoint with Custom attribute class Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><blockquote>Note that I have removed example from xml comments to avoid any confusion.</blockquote><p>Now when we ran our API and check on swagger we get following page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UqhcFBwNq56aJgplLPKbg.png" /><figcaption>Get Endpoint with examples Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><h3>Another Example</h3><p>Let’s take another example where I take model as an parameter to API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*P-Ng28cHzibpPIbYPa0AKQ.png" /><figcaption>Get Endpoint with Model as Parameter Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>I have modified the API to take Model as a parameter. and we can define examples inside the model definition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*rumpF0OiVYqFoH-o4bgAPQ.png" /><figcaption>LimitInfo class Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>You can see, for Limit I have defined two examples and also added one more property of string type with only value.</p><p>With only these changes let’s run our API again and look at the swagger UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2L70IbjshNzlH_-d_u_aw.png" /><figcaption>Swagger UI Get Endpoint with Examples Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>We can see now both parameters are showing the examples values as we have defined and we can select from the list whichever we want to use for execution.</p><p>One more point, as we have defined the examples, it does not mean that we can’t give any other value. these are just predefined values which gets filled when we select from dropdown. we can very well put any other values we want. and guess what swaggerUI also displays that as “[Modified value]”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5SrNNbnurGlNA_6pKUU2XQ.png" /><figcaption>Showing modified value Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>and this will be available as long as we don’t refresh the swagger UI.</p><h3>Summary</h3><p>In this short tutorial, we have seen how we can set multiple example for parameter in route.</p><p>Hope it is helpful.</p><p><em>Happy coding and keep learning..!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4f3aaf1ae9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[File upload to Web API with different Http Clients in C#]]></title>
            <link>https://medium.com/@niteshsinghal85/file-upload-to-web-api-with-different-http-clients-in-c-ae123555ef49?source=rss-93f078f8e9c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae123555ef49</guid>
            <category><![CDATA[refit]]></category>
            <category><![CDATA[csharp-programming]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[restsharp]]></category>
            <dc:creator><![CDATA[Nitesh Singhal]]></dc:creator>
            <pubDate>Tue, 06 Sep 2022 13:03:55 GMT</pubDate>
            <atom:updated>2022-09-06T13:03:55.997Z</atom:updated>
            <content:encoded><![CDATA[<h4>A collection of examples for C# client to upload file to web API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*D-iF3_MCHHIIxRwdyCN-rw.png" /><figcaption>Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>In my previous tutorial “<a href="https://medium.com/@niteshsinghal85/testing-file-upload-with-swagger-in-asp-net-core-90269bc24fe8">Testing file upload with Swagger in ASP.Net core</a>”, I have already explained how File upload can be tested using <strong>Swagger UI</strong> but in many cases I have seen we have to upload the file to a another API endpoint in that case we have to create own http request and upload the file using C# code. I have seen many people ask same question on different forum so I thought let me consolidate different example.</p><p>In this tutorial, I am going to show how different Http Clients can be used to do this.</p><p>Let’s start by setting up a Web API. I am using .NET 6.</p><h3>API expects a file only</h3><p>First let’s create a simple endpoint which expects a file only.</p><pre>[HttpPost(&quot;UploadFile&quot;)]<br>public IActionResult UploadFile(IFormFile formFile)<br>{<br>    _logger.LogInformation(&quot;UploadFile&quot; + formFile.FileName);<br>    return Ok(formFile.FileName);<br>}</pre><h4>Using HttpClient</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0be15322e65033d98644df2cd484904e/href">https://medium.com/media/0be15322e65033d98644df2cd484904e/href</a></iframe><h4>Using <a href="https://restsharp.dev/">Restsharp</a></h4><p>RestSharp is a popular HTTP client library for .NET. Featuring automatic serialization and deserialization, request and response type detection, variety of authentications and other useful features.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba37d99a582963f9edc38a24c3279e88/href">https://medium.com/media/ba37d99a582963f9edc38a24c3279e88/href</a></iframe><h4>Using <a href="https://github.com/reactiveui/refit">Refit</a></h4><p>Refit is another HTTP client library for .NET Core, Xamarin and .NET, it is known for automatic type-safety.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ed965ffc004fcb283defb63f0107cb5/href">https://medium.com/media/8ed965ffc004fcb283defb63f0107cb5/href</a></iframe><h3>API expects file as part of model</h3><p>for example we have following class which expects file object</p><pre>public class FileInformation<br>{<br>   public string Name { get; set; }<br>   public string Description { get; set; }<br>   public IFormFile File { get; set; }<br>}</pre><p>and we have API as below which expects this model as input</p><pre>[HttpPost(&quot;UploadFileWithModel&quot;)]</pre><pre>public IActionResult UploadFileWithModel([FromForm] FileInformation fileInformation)<br>{<br>    _logger.LogInformation(&quot;UploadFileWithModel &quot; +    fileInformation.File.FileName);</pre><pre>    return Ok(fileInformation.File.FileName);<br>}</pre><p>Let’s see how we can call this api with required data.</p><h4>Using HttpClient</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/234082ce396e602efb863a8e86f390c4/href">https://medium.com/media/234082ce396e602efb863a8e86f390c4/href</a></iframe><h4>Using <a href="https://restsharp.dev/">Restsharp</a></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0314a9757ffe25c81da1e4718332614d/href">https://medium.com/media/0314a9757ffe25c81da1e4718332614d/href</a></iframe><h4>Using <a href="https://github.com/reactiveui/refit">Refit</a></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32101e0d75d43c1ed2543cda84c07474/href">https://medium.com/media/32101e0d75d43c1ed2543cda84c07474/href</a></iframe><h3>Summary</h3><p>In this article, I have tried to accumulate different examples for uploading file to web API via a C# client.</p><p>Hope it is helpful..!</p><p><strong><em>Happy Coding and Keep Learning..!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae123555ef49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom code analyzer to detect usage of AllowAnonymous attribute in C#]]></title>
            <link>https://medium.com/@niteshsinghal85/custom-code-analyzer-to-detect-usage-of-allowanonymous-attribute-in-c-a225a81ab2b4?source=rss-93f078f8e9c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a225a81ab2b4</guid>
            <category><![CDATA[code-analysis]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[roslyn]]></category>
            <category><![CDATA[static-code-analysis]]></category>
            <category><![CDATA[code-review-checklist]]></category>
            <dc:creator><![CDATA[Nitesh Singhal]]></dc:creator>
            <pubDate>Fri, 17 Jun 2022 14:42:57 GMT</pubDate>
            <atom:updated>2022-06-17T14:42:57.888Z</atom:updated>
            <content:encoded><![CDATA[<h4>Code Analysis in .NET</h4><h4>A Short guide on how to write custom roslyn analyzer for .NET</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FmvXQaTHIPCaqMWtMF_2kA.png" /><figcaption>Image By <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a>, Logo by <a href="https://www.kindpng.com/">Kindpng</a></figcaption></figure><h4>What is code analyzer</h4><p>Code analyzers are great tools during development to inspect your code for style, quality, maintainability, design and other issues. they are capable of producing warnings as you are writing your code even before compiling.</p><h4>Writing Custom analyzer</h4><p>C# Roslyn analyzers support many rules which is very helpful but sometime you want to enforce organization specific rules.</p><p>C# Roslyn analyzers have great support for writing custom analyzers for such rules.</p><p>One such rule was the usage of AllowAnonymous attribute on an API in a webapi project. It is not prohibit to use it but we have to be careful while adding this attribute explicitly.</p><p>In this tutorial, I will be writing a custom analyzer to detect the usage of AllowAnonymous attribute in webapi project.</p><p>you follow this <a href="https://docs.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix">article</a> for setting up your development environment to get started.</p><h4>Create the solution</h4><ul><li>In Visual Studio, choose File -&gt; New -&gt; Project… to display the New Project dialog.</li><li>Under Visual C# -&gt; Extensibility, choose Analyzer with code fix (.NET Standard).</li><li>Name your project “ReviewAllowAnonymous” and click OK.</li></ul><p>In this tutorial, I am focusing mainly on writing the analysis part. so let’s go to “ReviewAllowAnonymous” project in the solution.</p><p>Open the <strong>“Resources.resx”</strong> to provide the custom description and change it required format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Hm9CYw2gPY_syAD9RJ8lJQ.png" /><figcaption>Resources.resx file changes</figcaption></figure><p>Now open the “<strong>ReviewAllowAnonymousAnalyzer</strong>” class and change the category to “Security” in the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*rpBgtBsSNxxE6Sgtt5wS5A.png" /></figure><p>and change the Initialize method code like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*VKBK9Spygq2h2XM36qh_Kw.png" /><figcaption>Initialize method</figcaption></figure><p>and modify the AnalyzeSymbol method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*frVxrrKB1KCt-QgU5g4yIg.png" /><figcaption>code for analysis</figcaption></figure><p>In the above method, we are checking for all the attribute assigned to a method and reporting if we find usage of AllowAnonymous attribute.</p><p>Currently it is only checking for method level attribute. it can be easily enhanced to check class level attributes also.</p><p>That’s it we are done with changes and now build the solution.</p><h4>Testing the changes</h4><p>We already have a project “ReviewAllowAnonymous.Package” in solution which creates a nuget package for us to use in other projects.</p><p>In this tutorial, I will just use this nuget package in a webapi project to verify the changes.</p><p>So I will create a sample webapi project and add this package reference</p><pre>Install-Package C:\Temp\packages\ReviewAllowAnonymous.1.0.0.nupkg</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1YPVtFB0rBcCiWF-37geIA.png" /><figcaption>Package installation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*gx08zZ5_BZHZ2VIjkFWhBA.png" /><figcaption>Analyzer shown in project reference</figcaption></figure><p>as we can see it is install successfully.</p><p>now let’s add a method and add the AllowAnonymous attribute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*69WNtx3kbtVi3qxugoAmZQ.png" /><figcaption>Sample code</figcaption></figure><p>Great..!</p><p>You can see when I added the AllowAnonymous attribute to an API and it is reporting an warning as we expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZVKzCNUnyMYPkjoCg1xNQ.png" /><figcaption>Error list showing the warning</figcaption></figure><p>also in the ErrorList window we can see the warning.</p><p>The idea of this code analysis is to just alert the developer about the usage of this attribute so that he can make informed decision if really wants to add this attribute to the method or not.</p><p>Since we don’t have any code fix required for this rule we can delete the project and respective reference from the solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*WOpFVoeHOZPJ5SO67nhexw.png" /></figure><h4>Summary</h4><p>In this short tutorial, we have learned to how to write a custom code analyzer. here we have mainly focused on writing analysis part but there are other aspect of delivering as nuget package or vsix package which are already covered in many other article.</p><p>Hope it is helpful..!</p><p><em>Happy coding and keep learning..!</em></p><p>Some other references</p><ul><li><a href="https://www.meziantou.net/writing-a-roslyn-analyzer.htm">Writing a Roslyn analyzer - Gérald Barré</a></li><li><a href="https://github.com/dotnet/roslyn/blob/main/docs/wiki/Getting-Started-Writing-a-Custom-Analyzer-&amp;-Code-Fix.md">roslyn/Getting-Started-Writing-a-Custom-Analyzer-&amp;-Code-Fix.md at main · dotnet/roslyn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a225a81ab2b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API filtering on SwaggerUI by Role in .Net core]]></title>
            <link>https://medium.com/@niteshsinghal85/api-filtering-on-swaggerui-by-role-in-net-core-6006b9bb98c4?source=rss-93f078f8e9c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6006b9bb98c4</guid>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[api-documentation]]></category>
            <dc:creator><![CDATA[Nitesh Singhal]]></dc:creator>
            <pubDate>Fri, 27 May 2022 15:26:05 GMT</pubDate>
            <atom:updated>2022-05-27T15:26:05.000Z</atom:updated>
            <content:encoded><![CDATA[<h4>Swagger in .NET</h4><h3>API filtering on SwaggerUI by Role in .Net core</h3><h4>A short guide on how to filter APIs on Swagger by Role</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TUpQdCVbCzMkqxDd" /><figcaption>Photo by <a href="https://unsplash.com/es/@loriayre?utm_source=medium&amp;utm_medium=referral">Lori Ayre</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When the swagger document gets loaded in swagger UI we can see all the API’s but what if I want to filter some of the API based on role they should be accessible.</p><p>let’s take an example, I have a following swagger doc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iB8xQc8Atd7JXz7DkkpeQ.png" /></figure><p>and following is the definition of APIs. There are two APIs, one is accessible by “<strong>Admin” </strong>role and other is one by “<strong>User” </strong>role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*e1GPDtahbzsXtzH7iwcbOQ.png" /></figure><p>and “<strong>Token</strong>” API is accessible by all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*HHlrp-i3-q499luxLo4okw.png" /></figure><p>so normally, all three API’s are visible to all but I want to filter API based on role given.</p><p>so for “<strong>Admin</strong>” role , only “<strong>Token</strong>” &amp; “<strong>GetWeatherForecastForAdmin</strong>” should be visible.</p><p>and for “<strong>User</strong>” role, only “<strong>Token</strong>” &amp; “<strong>GetWeatherForecastForUser</strong>” should be visible.</p><p>Now keeping these requirements in mind, I tried to search if something is available from Swashbuckle library but could not found anything explicitly. so I decided to try out on my own.</p><p>and with some experiments I was able achieve it.</p><p>so let’s see what we have to do to make it possible.</p><p><a href="https://medium.com/subscribe/@niteshsinghal85">🎁 Subscribe for Nitesh Singhal&#39;s Articles</a></p><p>Basically we have to use IDocumentFilter interface and add a custom document filter where we can filter the needed API which will then be showing in the UI.</p><p>so let’s start by adding class “RoleDocumentFilter.cs”. see the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c65147dcfe2e1754bf5646b80104880/href">https://medium.com/media/7c65147dcfe2e1754bf5646b80104880/href</a></iframe><p>also add following code(marked in Red) to Program.cs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*3w-MkH2e_Gwsd9pVxAJn2Q.png" /><figcaption>Program.cs changes</figcaption></figure><p>That’s it. now let’s run our API and access the swagger UI.</p><p>In RoleDocumentFiler class, you will notice that I am using query parameter to decide the filter.</p><blockquote>I could have modified swagger UI to add a selection control to choose the role but I just wanted to keep it simple and did not wanted to make any UI changes so I decided to go with query parameter.</blockquote><p>So if you want to see the API accessible for a role then we need to specify that by passing as query parameter. for example</p><p><a href="https://localhost:7152/swagger/index.html?role=Admin">https://localhost:7152/swagger/index.html?role=Admin</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jx1ByO0S0N-gYBH7dOXKg.png" /><figcaption>Swagger UI filter for Admin</figcaption></figure><p><a href="https://localhost:7152/swagger/index.html?role=User">https://localhost:7152/swagger/index.html?role=User</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlUMbtL2WySTLeNeMrsuPQ.png" /><figcaption>Swagger UI filter for User</figcaption></figure><p>That’s it, we are able to filter out the API based on role.</p><h3>Summary</h3><p>With this simple approach we were able to achieve role based filtering.</p><p>Now the next step could be to really identify the role of user based on login and only display those APIs. for that we would have to put the Swagger UI behind some kind of authentication [<a href="https://medium.com/@niteshsinghal85/securing-swagger-ui-in-production-in-asp-net-core-part-2-dc2ae0f03c73"><em>follow this article for the same</em></a>] and then we can also check role dynamically instead of passing from query parameter.</p><p>Hope it is helpful.</p><p><em>Happy coding and Keep Learning..!</em></p><p><strong>If you liked this article please share the energy and press the clap button And follow me for more interesting articles like this one.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6006b9bb98c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advance logging with Serilog and Seq in .NET]]></title>
            <link>https://medium.com/@niteshsinghal85/advance-logging-with-serilog-and-seq-in-net-9005a4a3d049?source=rss-93f078f8e9c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9005a4a3d049</guid>
            <category><![CDATA[seq]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[serilog]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Nitesh Singhal]]></dc:creator>
            <pubDate>Thu, 31 Mar 2022 17:11:34 GMT</pubDate>
            <atom:updated>2022-03-31T17:11:34.084Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tracing and Monitoring</h4><h3>Advance logging with Serilog and Seq in .NET</h3><h4>A comprehensive guide for enhancing logs and log analysis experience with Seq</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9v-u6RoPu4Igu_1QV94Sw.png" /><figcaption>Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>In this tutorial, I am going to explain how we can do some advance logging with Serilog to include some more information in logs.</p><p>also I will be using <strong>Seq </strong>for storing and visualizing the logs at centralize location for better log analysis.</p><p>Let’s start by creating a sample project and configuring serilog for basic logging.</p><p>I have project called “AwesomeMovie” which return list of movie titles.</p><p>It is typical webapi project having dbcontext and repository to interact with database.</p><p>I have added required nuget reference for serilog</p><pre>&lt;PackageReference Include=&quot;Serilog.AspNetCore&quot; Version=&quot;5.0.0&quot; /&gt;</pre><p>and did the following basic configuration in <strong>Program.cs</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*fyKX-y7f_RQo7sAb9fcyXw.png" /><figcaption><strong>Program.cs</strong></figcaption></figure><p>and also add required configuration in <strong>appsettings.json</strong> file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*QcGIltRtLBSpXNg4GoXCCA.png" /><figcaption><strong>appsettings.json</strong></figcaption></figure><p>on running the application, I can see the logs on console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*vn5AW--RXakIRyGv3yNcbQ.png" /><figcaption>Logs on console</figcaption></figure><p>Great. now let’s configure <strong>Seq </strong>and see the logs.</p><h3><strong>Setting up Seq</strong></h3><p>I have setup a <strong>Seq </strong>docker container running on 5341 port. use the following cmd to run a docker container for <strong>Seq</strong></p><pre>docker run --name seqlogger -d -p 5341:5341 -p 5342:80 -e ACCEPT_EULA=Y datalust/seq</pre><p>you can find more option for <strong>Seq </strong><a href="https://docs.datalust.co/docs/getting-started-with-docker">here</a>.</p><p>we can verify our <strong>Seq </strong>instance is running by visiting <a href="http://localhost:5342/#/events">http://localhost:534</a>2</p><p>Let’s make required changes in API project for sending the logs to <strong>Seq</strong>.</p><p>Serilog provides a sink lib for <strong>Seq</strong>. add the package reference</p><pre>&lt;PackageReference Include=&quot;Serilog.Sinks.Seq&quot; Version=&quot;5.1.1&quot; /&gt;</pre><p>and add the required configuration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*ak1KyOYDGw0V1saQuhnJFQ.png" /><figcaption><strong>Program.cs</strong></figcaption></figure><p>Let’s run our app and call the API via swagger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*aK9iWbAm6fP-4ejF3MqkFQ.png" /><figcaption>Logs in Seq UI</figcaption></figure><p>We can see some log entries in the <strong>Seq </strong>UI.</p><p>we can get more details by clicking on log entry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*pyuKMWI1wWdNKh0WTmPJ_A.png" /><figcaption>Detail Log in Seq UI</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*ELlcZRDoJQd2AC1TacDBgQ.png" /></figure><h3>Advance Logging</h3><p>By default we can see information like ActionId, ActionName, ConnectionID and so on.</p><p>but I also want to add advance information in the logs for better analysis.</p><p>we start by adding some more information like machine name, environment information etc.</p><p>Let’s make the changes.</p><p>first add required nuget reference</p><pre>&lt;PackageReference Include=&quot;Serilog.Enrichers.Environment&quot; Version=&quot;2.2.0&quot; /&gt;</pre><p>and add the required configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*DB5FVxoUD9RWA6rliMmlPg.png" /></figure><p>Now run the app and call the API.</p><p>with these changes, this information is added automatically with each log entry</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*GneFb1DR6tBdniZNdLpetQ.png" /><figcaption>Additional info</figcaption></figure><p>We can also add custom info like if I want to add the <strong>application or service name to the logs. </strong>This could be helpful in microservice architecture where multiple services are sending log data to <strong>Seq</strong>.</p><p>we can add following code to add such a information to log entry</p><pre>.Enrich.WithProperty(&quot;ApplicationName&quot;,context.HostingEnvironment.ApplicationName)</pre><p>and then in the <strong>Seq</strong>, we can see the same</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*X9aoyXSFZ1xZd0_88QK17w.png" /><figcaption>Enhanced log in Seq UI</figcaption></figure><h3>Http Request Logging</h3><p>We can enable http request logging so that each http request is logged even without writing any code to log them.</p><p>and we can write the logic to decide which information we would like to add as part of the logs.</p><p>Let’s see example</p><p>we need to add following code to enable the Http Request logging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*m06Hzn7tkh3SJSPFRDC90g.png" /></figure><p>and need to define the HttpRequestEnricher method. I have created a separate static class to define them</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f158074b8a39d24c5112eb851efc5da0/href">https://medium.com/media/f158074b8a39d24c5112eb851efc5da0/href</a></iframe><p>here I am only logging few information but this can be enhanced to log every information which HTTP Context can provide so it is up your requirement which all information you want to include.</p><blockquote><strong>A word of caution, as HTTP Context can contain some sensitive information, be careful while choosing the information to log</strong></blockquote><p>After these changes we are ready to run our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*M78xtapaWBHxz1ijZViLcA.png" /><figcaption>Http request logs in console</figcaption></figure><p>we can see some new entries in the console also which logs for each http request with status and time taken to complete the request.</p><p>Pretty cool.. right..!</p><p>Now let’s see the logs in <strong>Seq</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*cAo1R0GC8ECcJKwr_IaFxg.png" /><figcaption>Http Context info in logs</figcaption></figure><p>We can see the additional Http Context information for each Http Request.</p><h3>Exception Logging</h3><p>one of the important aspect of logging is to have correct log during exception scenario. Let’s simulate a scenario of exception being raised from API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*9hvSwruSRppG1jNztD6W6g.png" /></figure><p>I have modified the code to simulate the exception. now when we call the API with Id=0, we will get exception back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*4pMRHhRrVGIsDZ0l2Ozw3Q.png" /><figcaption>Exception in Seq UI</figcaption></figure><p>There are few things to be noticed.</p><p><strong>Seq </strong>is showing the exception is red color background for easy visualization of critical logs so that user can focus more on these logs.</p><p>It also logs the complete call stack which may be helpful for analysis.</p><p>We can enhance exception logging also by using one nuget package</p><pre>&lt;PackageReference Include=&quot;Serilog.Exceptions&quot; Version=&quot;8.1.0&quot; /&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*c5U7YEihVX44v73N0_qp0A.png" /></figure><p>When we run the app and call the api to simulate the exception we get following log in seq</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*0mAR245E0S5hoZrPF-bXsQ.png" /><figcaption>Enhanced exception logs in Seq UI</figcaption></figure><p>We can see some more details about exception in the logs.</p><p>Full source code at <a href="https://github.com/niteshsinghal85/blogs/tree/main/AdvanceLoggingSerilog">GitHub</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*ELlcZRDoJQd2AC1TacDBgQ.png" /></figure><h3>Summary</h3><p>These are just some few advance concepts for logging more information in application logs. but this is not limited to only these things there are many other things which can be done with logging.</p><p>on the other hand, <a href="https://datalust.co/seq"><strong>Seq</strong></a><strong> </strong>is very powerful log analysis tool. There are many other features also available with <strong>Seq </strong>such as health monitoring and alert management.</p><p>Hope it is helpful.</p><ul><li><a href="https://datalust.co/seq">Seq - centralized structured logs for .NET, Java, Node.js</a></li><li><a href="https://serilog.net/">Serilog - simple .NET logging with fully-structured events</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9005a4a3d049" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DateOnly and TimeOnly with  HttpRequest in .NET 6]]></title>
            <link>https://medium.com/@niteshsinghal85/dateonly-and-timeonly-with-httprequest-in-net-6-df196c5d014e?source=rss-93f078f8e9c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/df196c5d014e</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[datetime]]></category>
            <category><![CDATA[http-request]]></category>
            <dc:creator><![CDATA[Nitesh Singhal]]></dc:creator>
            <pubDate>Wed, 30 Mar 2022 17:03:29 GMT</pubDate>
            <atom:updated>2022-03-31T17:14:28.002Z</atom:updated>
            <content:encoded><![CDATA[<h4>.NET Guide</h4><h3>DateOnly Json converter with HttpRequest in .NET 6</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnM-NpPvuFoTPoUgXR6bbQ.png" /><figcaption>Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>So I was doing the experiment of using DateOnly with .NET core web Api and I had the following structure</p><pre>public class Movie<br>{<br>  public int Id { get; set; } <br>  public string? Title { get; set; }<br>  public DateOnly ReleaseDate { get; set; }<br>  public float Rating { get; set; }<br>  public string? Language { get; set; }<br>}</pre><p>It made perfect sense that we use DateOnly for release date as we need only date information.</p><p>so I wrote simple controller to return a Movie title when API is called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*EjFxE_V-g86OESn30x2o1w.png" /></figure><p>with the expectation of getting a successful result I called the API via Swagger.</p><p>But to my surprise, I got an error response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*zcTH6OesGRhFhjueC6V22Q.png" /><figcaption>Exception</figcaption></figure><p>I went through the stack and understand that Json serialization and deserialization is not supported for this new types.</p><p>with .NET 6, these types were added and I expected that we get all kind of support from .NET itself that this should be resolved automatically but unfortunately that is not the case.</p><p>with some search, I found that I have to write custom JsonConverter for making this to work.</p><p>so I wrote a simple DateOnly Converter for my experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*5UkrfoPSPyLnqGbBiPFCWw.png" /><figcaption>DateOnly Json converter</figcaption></figure><p>and in Program.cs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*8y7Chn5-_NRl-7a3Covusg.png" /><figcaption>Program.cs</figcaption></figure><p>and that’s it.</p><p>I ran the application again and..</p><p>It ran successfully this time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eq0vsUKTBkhLtuscK-lumw.png" /><figcaption>Successful response</figcaption></figure><blockquote>Note : This was enough for my experiment so I did not investigate further but I am sure this code needs little bit more handling for different scenarios.</blockquote><p>Source code at <a href="https://github.com/niteshsinghal85/blogs/tree/main/DateOnlyWithHttpRequest">Github</a></p><p>Hope it is helpful</p><p><em>Happy coding and keep learning..!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df196c5d014e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End to End Unit Testing for .NET 6 Web API]]></title>
            <link>https://medium.com/@niteshsinghal85/end-to-end-unit-testing-for-net-6-web-api-58883d1b2fe4?source=rss-93f078f8e9c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/58883d1b2fe4</guid>
            <category><![CDATA[api-testing]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[dotnet6]]></category>
            <dc:creator><![CDATA[Nitesh Singhal]]></dc:creator>
            <pubDate>Mon, 28 Mar 2022 17:32:28 GMT</pubDate>
            <atom:updated>2022-03-28T17:32:28.312Z</atom:updated>
            <content:encoded><![CDATA[<h4>UNIT TESTING</h4><h3>End to End Unit Testing for .NET 6 Web API</h3><h4>A way of unit testing end to end the Web API in .NET 6</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-QfeHC8n_h6jlwlu_0f-A.png" /><figcaption>Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p><em>Dev 1: Why do we have low code coverage for .NET core Api project?</em></p><p><em>Dev 2: We have these classes such as program.cs and startup.cs which has lot of code that are not being covered during unit tests.</em></p><p><em>Dev 1 : Then write some tests for them and increase code coverage.</em></p><p><em>Dev 2 : It is not simple as it seems.</em></p><p><em>Dev 1: So what should we do ?</em></p><p><em>Dev 2 : Exclude them from code coverage.</em></p><p><em>Dev 1 : Ok.</em></p><p><em>Dev 2 : Done.</em></p><p><em>Dev 1: Great..! but what about logic that needs testing in those files ?</em></p><p>I am sure at point of time you must have had similar conversation with your Team or architect and probably you must have done the same.</p><p>so what can be done other then excluding them.</p><p>and for sure it is not about just coverage but also to test if things are correct.</p><p>With <strong>.NET 6</strong>, there is a way of writing Unit test little differently and test your API in a kind of end to end way rather then just writing unit test separately for each class.</p><p>you can call them however you like but to me it is way of testing API from end to end.</p><p>Let’s understand by example.</p><p><a href="https://medium.com/subscribe/@niteshsinghal85">🎁 Subscribe for Nitesh Singhal&#39;s Articles</a></p><h3>Project Setup</h3><p>I have an API which returns a random activity when called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xTvuNFDKSP4GK2XHBDHvGw.png" /><figcaption>swagger UI for API project</figcaption></figure><p><strong>MyActivityController.cs</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51761b85240d8d427d5670e531b43867/href">https://medium.com/media/51761b85240d8d427d5670e531b43867/href</a></iframe><p><strong>BackendService.cs</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d19c7febdfb88af9de294809ae70527/href">https://medium.com/media/2d19c7febdfb88af9de294809ae70527/href</a></iframe><p>we have controller which call BackendService to get the activity from 3rd party API.</p><p>and now in typical old scenario we would only write the unit test for MyActivityController and BackendService separately to test the logic but program.cs class will not be tested and also tests for controller class would be kind of redundant as they would not be testing anything useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*ELlcZRDoJQd2AC1TacDBgQ.png" /></figure><h3>.NET 6 way of Testing</h3><p>Let’s see how to solve this issue with .NET 6 tests.</p><p>Let’s start by creating a UnitTest project by executing following cmd</p><pre>dotnet new nunit -o Activity.Api.Tests</pre><p>and add the required references.</p><pre><em>&lt;PackageReference Include=&quot;Microsoft.AspNetCore.Mvc.Testing&quot; Version=&quot;6.0.3&quot; /&gt;<br>&lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;16.11.0&quot; /&gt;<br>&lt;PackageReference Include=&quot;NUnit&quot; Version=&quot;3.13.2&quot; /&gt;&lt;PackageReference Include=&quot;NUnit3TestAdapter&quot; Version=&quot;4.0.0&quot; /&gt;&lt;PackageReference Include=&quot;coverlet.msbuild&quot; Version=&quot;3.1.0&quot; /&gt;<br>&lt;PackageReference Include=&quot;Moq&quot; Version=&quot;4.17.2&quot; /&gt;</em></pre><p>add the project reference to activity.api project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*msji4m6cl6OOSCqFFOhivg.png" /><figcaption>Project reference</figcaption></figure><p>we will also need one small change the Activity.Api.csproj file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*8-ocK2oA9R7gFgWLNSAgQQ.png" /></figure><blockquote>Note: we need to add this to access program.cs in the test project.</blockquote><p>Now we can write the unit tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*dC00GJZ0whHLJOAdxel_iw.png" /><figcaption>First Unit test</figcaption></figure><p>Let’s execute the tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_aCWc7E6c2KSU-74S48Sw.png" /><figcaption>Unit test execution</figcaption></figure><p>THAT’S IT and we can see the test case is passed.</p><p>Let’s also check the coverage. <em>I am using coverlet to collect the coverage</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TdLN1-6wMbgsy_ClHIxHMg.png" /><figcaption>Code coverage</figcaption></figure><p>As we can see it has covered program.cs, controller and backend service</p><p>It says 50% branch coverage and still some % left for line coverage, it is because we have written only test for success scenario. to cover the maximum we have to write the code for other scenarios also.</p><p>Let’s write the test for negative scenario also.</p><pre><em>[Test]<br>public async Task TestFailureReturnNull()<br>{<br> // Arrange<br> using var application = new WebApplicationFactory&lt;Program&gt;();<br> var client = application.CreateClient();</em></pre><pre><em>// Act <br>var responseMessage = await client.GetAsync(&quot;/MyActivity&quot;);</em></pre><pre><em>// Assert<br>Assert.AreEqual(HttpStatusCode.NoContent,responseMessage.StatusCode;<br>}</em></pre><p>and on tests execution, I get following result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DbSdaHkh6K4-Pi2YXKD84w.png" /><figcaption>Unit test execution</figcaption></figure><p>It is failed because it is getting activity with Ok response but we expected to be NoContent. On further analysis, I found that we are depending on external API for getting the activity and during unit test we can’t control the result from external API.</p><p>so then we will have to mock the external dependency.</p><p>In my previous article I have explain how to mock http client.</p><p><a href="https://medium.com/@niteshsinghal85/mocking-http-request-in-csharp-unit-testing-c4a7cef21828">Mock http request in C# for Unit testing</a></p><p>Let’s make the change and test again.</p><p>first we will write a helper method to create the mock HttpClient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*7-YAk6MYk-dDmXgEpsw26A.png" /><figcaption>Helper method for getting mock HttpClient</figcaption></figure><p>then we will write the test case</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*mtiM5Q2RFa9Dbd_7rNGgOQ.png" /><figcaption>Unit test covers failure scenario</figcaption></figure><p>Let’s execute the tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uiawQ7i-tYsl4FOAYQBRSQ.png" /><figcaption>Unit test execution</figcaption></figure><p>and we see that both tests are passing. Now let’s check the coverage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fosE_oIlVrqIQcwLuAg1wA.png" /><figcaption>Code Coverage</figcaption></figure><p>Now we see that everything is covered.</p><p>you can follow this article for setting up code coverage.</p><p><a href="https://medium.com/@niteshsinghal85/5-helpful-nuget-package-for-unit-testing-in-net-87c2e087c6d">5 helpful Nuget package for Unit Testing in .NET</a></p><p>you can find the full source code at <a href="https://github.com/niteshsinghal85/blogs/tree/main/IntegrationTests">Github</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*ELlcZRDoJQd2AC1TacDBgQ.png" /></figure><h3>Summary</h3><p>In this tutorial, I have taken very basic example but in practical scenario there is much more code written in for configuring the services and all. and since we are able to write unit test for that we often get issue from that part of code.</p><p>using this technique we can test end to end. and also we have seen in the example that we can mock external dependencies as we can’t control them during unit test execution.</p><p>Hope it is helpful.</p><p><em>Happy coding and keep learning..!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58883d1b2fe4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mock http request in C# for Unit testing]]></title>
            <link>https://medium.com/@niteshsinghal85/mocking-http-request-in-csharp-unit-testing-c4a7cef21828?source=rss-93f078f8e9c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4a7cef21828</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[moq]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[http-request]]></category>
            <dc:creator><![CDATA[Nitesh Singhal]]></dc:creator>
            <pubDate>Wed, 16 Mar 2022 15:38:25 GMT</pubDate>
            <atom:updated>2022-03-18T12:00:13.353Z</atom:updated>
            <content:encoded><![CDATA[<h4>Unit Testing</h4><h4>A short guide to mock http calls in Unit Testing in C# or .NET</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AyCt6UlOmyulq3K-zBb0bg.png" /><figcaption>Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p>Many time we call external rest API’s from our backend code and we want to write unit test for such code so that we can test our code with the expected response from API. So we have two choice either we use mock API server or we mock http call.</p><p>Mock API server is good for integration tests but for Unit tests we should not rely on external services as we can not control external service and thus it might give unexpected behavior on different runs. so another choice we have is to mock the http calls.</p><p>It should be fairly simple to mock HttpClient with any mocking library and write Unit tests.</p><p>Right ?</p><p>So what is the challenge and why it is not as straight forward as it should be.</p><p>Let’s understand with example.</p><p><a href="https://medium.com/subscribe/@niteshsinghal85">🎁 Subscribe for Nitesh Singhal&#39;s Articles</a></p><h3>Problem</h3><p>I have MVC frontend app which is calling public API to get random activity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hNLFXqBCzCgZA67gnITnbw.png" /></figure><p>and to achieve this I have a backend service which does the job of fetching the random activity using public API.</p><p>I have a <strong>Backendservice </strong>class which has logic to fetch data using <strong>HttpClient </strong>class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*14_VIad-Y5XQfg9uRy6-hQ.png" /></figure><p>Everything worked perfectly when running as application. Now I want to write Unit test for <strong>GetNewActivity </strong>method.</p><p>I have created a NUnit test project and written a simple unit test to call the <strong>GetNewActivity </strong>method and to create the instance of <strong>BackendService </strong>I had to pass an instance of HttpClient.</p><p>That’s where I tried to mock the HttpClient, but it did not allowed as it is a class and not interface or abstract class. so we can not mock HttpClient class.</p><p>This is the main issue that’s why it is not so simple to mock it.</p><p>So how do we mock it then.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*WOpFVoeHOZPJ5SO67nhexw.png" /></figure><h3>Solution</h3><p>When we have closer look to the HttpClient class, then we see that it takes HttpMessageHandler in the constructor which is abstract class and has SendAsync method which eventually is used for calling external API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYH93NbwxHKTHhvxoc3CaQ.png" /></figure><p>So at the core, we need to mock the response of this SendAsync API and since it is abstract class, we can mock it and override the SendAsync response.</p><p>Let’s look at the sample code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*E7X-orxHQJXfIrjQdFDWTw.png" /></figure><p>Here we have mocked the HttpMessageHandler class and Setup the SendAsync method to return the expected response.</p><p>and when we call GetNewActivity method on BackendService class then it will return response from this mock class instead of actually making http call to external API.</p><p>and like that we have successfully mocked the http calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cE-u_aJw8Y2eF302Yxx80A.png" /></figure><blockquote>PS: This is just one way of doing it. I am sure there are other ways of achieving it.</blockquote><p>Demo code at <a href="https://github.com/niteshsinghal85/blogs/tree/main/MockHttpRequest">Github</a></p><p>Hope it is helpful.</p><p><em>Happy Coding and Keep learning..!</em></p><p><a href="https://medium.com/@niteshsinghal85/5-helpful-nuget-package-for-unit-testing-in-net-87c2e087c6d">5 helpful Nuget package for Unit Testing in .NET</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4a7cef21828" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenTelemetry with Jaeger in .NET Core]]></title>
            <link>https://medium.com/@niteshsinghal85/opentelemetry-with-jaeger-in-net-core-9b1e009a73dc?source=rss-93f078f8e9c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b1e009a73dc</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[tracing]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[jaeger]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <dc:creator><![CDATA[Nitesh Singhal]]></dc:creator>
            <pubDate>Mon, 14 Mar 2022 15:27:06 GMT</pubDate>
            <atom:updated>2024-02-15T17:51:41.673Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tracing and Monitoring</h4><h3>OpenTelemetry with Jaeger in .NET 8</h3><h4>A step by step guide to integrate OpenTelemetry with ASP.Net core and visualize in Jaeger</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*DttRURcHcGIJFNtmuWJm3g.png" /><figcaption>Image by <a href="https://medium.com/@niteshsinghal85">Nitesh Singhal</a></figcaption></figure><p><a href="https://opentelemetry.io/"><strong>OpenTelemetry</strong></a> is a collection of tools, APIs, and SDKs. Use it to instrument, generate, collect, and export telemetry data (metrics, logs, and traces) to help you analyze your software’s performance and behavior.</p><p>In this tutorial, we will look at how it can be integrated with ASP.NET core web project.</p><p>We will use Jaeger tool to analyze and visualize the telemetry data.</p><p>Let’s get started..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*4vL20IbiTxHWPtmNYzLKFw.png" /></figure><p><a href="https://medium.com/subscribe/@niteshsinghal85">🎁 Subscribe for Nitesh Singhal&#39;s Articles</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*4vL20IbiTxHWPtmNYzLKFw.png" /></figure><h3>Project Setup</h3><p>I have set up an API project and a razor app</p><p>Let’s setup API project first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*mLYJbiXTp5-g2BDV_3vOOg.png" /><figcaption>API Project</figcaption></figure><p>add the required nuget packages</p><pre>&lt;PackageReference Include=&quot;OpenTelemetry.Exporter.OpenTelemetryProtocol&quot; Version=&quot;1.7.0&quot; /&gt;</pre><pre>&lt;PackageReference Include=&quot;OpenTelemetry.Extensions.Hosting&quot; Version=&quot;1.7.0&quot; /&gt;</pre><pre>&lt;PackageReference Include=&quot;OpenTelemetry.Instrumentation.AspNetCore&quot; Version=&quot;1.7.1&quot; /&gt;</pre><p>Now open Program.cs and add the following code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*v3dRbhBBiPm3CaFw4xYSeg.png" /></figure><p>here we are setting up Jaeger’s URI as OLTP exporter endpoint.</p><p>now Let’s setup web app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*dnica_X5ztbRrcv5qs0hjw.png" /><figcaption>Web App Project</figcaption></figure><p>and also add required nuget packages</p><pre>&lt;PackageReference Include=&quot;OpenTelemetry.Exporter.OpenTelemetryProtocol&quot; Version=&quot;1.7.0&quot; /&gt;</pre><pre>&lt;PackageReference Include=&quot;OpenTelemetry.Extensions.Hosting&quot; Version=&quot;1.7.0&quot; /&gt;</pre><pre>&lt;PackageReference Include=&quot;OpenTelemetry.Instrumentation.AspNetCore&quot; Version=&quot;1.7.1&quot; /&gt;</pre><pre>&lt;PackageReference Include=&quot;OpenTelemetry.Instrumentation.Http&quot; Version=&quot;1.7.1&quot; /&gt;</pre><p>Open Program.cs and add the following code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*wUzymK1_EsK8UpOx1Hd6RQ.png" /></figure><p>we will need to make one more change, call the API and show the result on UI.</p><p>Open the Index.chtml.cs file and add the following code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*397osC2DEk1AkMc0pf8E4g.png" /><figcaption>Index.chtml.cs</figcaption></figure><p>and Open Index.html and add the following table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*xbF57FfgmQKMIQiDNPjO3w.png" /><figcaption>Index.html</figcaption></figure><p>add the following code in Program.cs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*2r9nP7IqWRThLVDAIopOWQ.png" /><figcaption>Program.cs</figcaption></figure><p>we are ready to run the app.</p><p>Build both project and make sure they build with any errors.</p><p>Now let’s setup Jaeger</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*ELlcZRDoJQd2AC1TacDBgQ.png" /></figure><h3>Jaeger Setup</h3><p>I am using docker setup.</p><p>use the following cmd to create a docker container running for Jaeger</p><pre>docker run --name jaeger -p 13133:13133 -p 16686:16686 -p 4317:4317 -d --restart=unless-stopped jaegertracing/opentelemetry-all-in-one</pre><p>To verify if it running successfully, Go to browser and open UI at <a href="http://localhost:16686/search">http://localhost:16686</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*ELlcZRDoJQd2AC1TacDBgQ.png" /></figure><h3>Execution</h3><p>Let’s run the API and WebApp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mWwBjyE5e-GkfkSTGHuYsA.png" /><figcaption>Web App UI</figcaption></figure><p>We can see the list of weather forecast on UI. which is being fetched using API project and displayed on UI.</p><p>Now Let’s look at the Jaeger UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_R_Okl2719388U1arWVc_g.png" /><figcaption>Jaeger UI</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*gqSErmOfBZ5sX92Cm4mBwQ.png" /></figure><p>We can see both API and UI project is listed.</p><p>We can select operation from Operation drop down and Click on find trace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*beTQZWdwmh5PHB8vca__RQ.png" /><figcaption>Trace</figcaption></figure><p>We can see multiple trace result, we select one for further analysis</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xx05wTSck0zx8tiCG-FBUw.png" /><figcaption>Trace detail</figcaption></figure><p>We can see the whole trace chain from UI to API with duration and start time.</p><p>Demo code at <a href="https://github.com/niteshsinghal85/blogs/tree/main/DemoOpentelemetry">Github</a></p><p><strong>PS: This article is updated for .NET 8.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*ELlcZRDoJQd2AC1TacDBgQ.png" /></figure><h3>Summary</h3><p>It is very easy to setup Opentelemetry in .NET application. although I have use jaeger tool for analysis but there are many other tools are available and if they all follow same standard then they can also be used without any other changes.</p><p>Hope is it helpful..</p><p><em>Happy Coding and Keep learning..!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b1e009a73dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>