<?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 Chathuraishara on Medium]]></title>
        <description><![CDATA[Stories by Chathuraishara on Medium]]></description>
        <link>https://medium.com/@chathuraishara63?source=rss-8e08a444414f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K2Z3b5QGLGUhT1xbar7FCg.png</url>
            <title>Stories by Chathuraishara on Medium</title>
            <link>https://medium.com/@chathuraishara63?source=rss-8e08a444414f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:26:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chathuraishara63/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[What Are Webhooks? Simple Explanation with a Real-World Example]]></title>
            <link>https://medium.com/@chathuraishara63/what-are-webhooks-simple-explanation-with-a-real-world-example-3d8d060b1423?source=rss-8e08a444414f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d8d060b1423</guid>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[intergratiion]]></category>
            <category><![CDATA[webhooks]]></category>
            <dc:creator><![CDATA[Chathuraishara]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 18:33:03 GMT</pubDate>
            <atom:updated>2026-04-30T18:33:03.859Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gv51GnNu5o_wskgnmWIRCQ.png" /><figcaption>what is webhook?</figcaption></figure><h3>Introduction</h3><p>Modern applications often need to communicate with each other automatically whenever an important event happens. Instead of repeatedly checking for updates, systems can instantly notify other applications in real time using <strong>webhooks</strong>.</p><p>Webhooks are widely used in platforms like GitHub, Stripe, PayPal, Slack, and many more for automation, notifications, and system integration.</p><h4>What is a Webhook?</h4><p>A <strong>webhook</strong> is an HTTP-based callback mechanism that allows one system to automatically send data to another system when a specific event occurs.</p><h4>How Webhooks Work</h4><h3>Basic workflow:</h3><ol><li>You create a webhook endpoint in your application</li><li>You register that endpoint with another service (like GitHub)</li><li>When an event occurs, that service sends an HTTPS POST request to your endpoint</li><li>Your server processes the incoming data</li></ol><h4>Common Use Cases of Webhooks</h4><ul><li>GitHub push notifications</li><li>Stripe payment confirmations</li><li>PayPal transaction alerts</li><li>Slack notifications</li><li>CI/CD automation</li><li>CRM integrations</li><li>Email marketing triggers</li></ul><h4>Why Security Matters in Webhooks</h4><p>Because webhook endpoints are publicly accessible, attackers could send fake requests.</p><h4>Common security methods:</h4><ul><li>Secret tokens</li><li>HMAC signature verification</li><li>HTTPS encryption</li><li>IP whitelisting</li></ul><p>GitHub uses <strong>SHA256 signature verification</strong> to ensure requests are authentic.</p><h4>Building a GitHub Webhook Listener with Node.js</h4><h4>Project Requirements</h4><p>Install dependencies:</p><pre>npm install express dotenv</pre><h3>Environment Configuration</h3><p>Create a .env file:</p><pre>PORT=3000<br>GITHUB_WEBHOOK_SECRET=mysecret123</pre><h4>Node.js Webhook Server Example (server.js)</h4><pre>const express = require(&quot;express&quot;);<br>const crypto = require(&quot;crypto&quot;);<br>require(&quot;dotenv&quot;).config();<br><br>const app = express();<br>const PORT = process.env.PORT || 3001;<br>const SECRET = process.env.GITHUB_WEBHOOK_SECRET;<br><br>app.use(express.json({<br>  verify: (req, res, buf) =&gt; {<br>    req.rawBody = buf;<br>  }<br>}));<br><br>function verifyGitHubSignature(req) {<br>  const signature = req.headers[&quot;x-hub-signature-256&quot;];<br>  if (!signature || !SECRET) return false;<br><br>  const hmac = crypto.createHmac(&quot;sha256&quot;, SECRET);<br>  const digest = &quot;sha256=&quot; + hmac.update(req.rawBody).digest(&quot;hex&quot;);<br><br>  return crypto.timingSafeEqual(<br>    Buffer.from(signature),<br>    Buffer.from(digest)<br>  );<br>}<br><br>app.post(&quot;/webhook&quot;, (req, res) =&gt; {<br>  if (!verifyGitHubSignature(req)) {<br>    console.log(&quot;Invalid GitHub signature&quot;);<br>    return res.status(403).send(&quot;Invalid signature&quot;);<br>  }<br><br>  console.log(&quot;GitHub Event:&quot;, req.headers[&quot;x-github-event&quot;]);<br>  console.log(&quot;Repo:&quot;, req.body.repository?.name);<br>  console.log(&quot;Pusher:&quot;, req.body.pusher?.name);<br><br>  res.status(200).send(&quot;Webhook received&quot;);<br>});<br><br>app.listen(PORT, () =&gt; {<br>  console.log(`Server running on port ${PORT}`);<br>});</pre><h4>Testing Locally with ngrok</h4><p>Since GitHub cannot access localhost, use ngrok:</p><pre>ngrok http 3000</pre><p>Example:</p><pre>https://your-ngrok-url.ngrok-free.app</pre><p>GitHub webhook URL:</p><pre>https://your-ngrok-url.ngrok-free.app/webhook</pre><p>Github repo configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OHq1NjvmlAF2cmei15lnMw.png" /><figcaption>github repo configuration</figcaption></figure><h4>Example Output</h4><p>When pushing code to GitHub:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Vi0FDlbRPBYld_SXGjJNw.png" /><figcaption>output of backend server,when push some code to github repo</figcaption></figure><h4>Github repo page webhooks dashboard</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCfdK0KrXg19wYgovq_zbQ.png" /><figcaption>after succesfull triggering</figcaption></figure><h4>Advantages of Webhooks</h4><ul><li>Real-time communication</li><li>Efficient resource usage</li><li>Automation-friendly</li><li>Easy integration</li><li>Faster workflows</li></ul><h4>Best Practices</h4><p>To build reliable webhooks:</p><ul><li>Always verify signatures</li><li>Use HTTPS</li><li>Log incoming events</li><li>Handle retries gracefully</li><li>Secure secrets with environment variables</li><li>Validate payload structure</li></ul><h4>Conclusion</h4><p>Webhooks are a powerful tool for enabling real-time communication between applications. They eliminate inefficient polling and provide immediate event-driven updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d8d060b1423" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Your C# Code Cleaner with Dependency Injection]]></title>
            <link>https://medium.com/@chathuraishara63/make-your-c-code-cleaner-with-dependency-injection-6fcd62bd0a8c?source=rss-8e08a444414f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fcd62bd0a8c</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[design-patter]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Chathuraishara]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 17:57:04 GMT</pubDate>
            <atom:updated>2026-04-10T17:57:04.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*seeEsRHd_I0athH4qkyzkg.png" /><figcaption>Dependency Injection in C#</figcaption></figure><h4>Introduction</h4><p>When building applications in C#, managing dependencies between classes is very important. If classes are tightly connected, the code becomes hard to maintain, test, and extend.</p><p>This is where <strong>Dependency Injection (DI)</strong> helps. It is a simple but powerful design pattern used in modern applications, especially in frameworks like ASP.NET Core.</p><h4>What is Dependency Injection?</h4><p>Dependency Injection means <strong>providing required dependencies (objects) to a class from the outside instead of creating them inside the class</strong>.</p><h4>Simple Example</h4><p>Instead of this:</p><pre>var service = new EmailService();</pre><p>We inject it:</p><pre>public MyController(EmailService service)<br>{<br>    _service = service;<br>}</pre><p>This makes the code more flexible and easier to test.</p><h4>Why Use Dependency Injection?</h4><p>Dependency Injection solves several common problems:</p><ul><li>Reduces tight coupling between classes</li><li>Improves code maintainability</li><li>Makes unit testing easier</li><li>Promotes clean architecture</li></ul><h4>Types of Dependency Injection</h4><p>There are three main ways to implement DI:</p><ol><li>Constructor Injection</li></ol><p>This is the <strong>most commonly used method</strong>.Dependencies are provided through the class constructor.</p><ul><li>When the object is created, all required dependencies are passed.</li><li>Ensures the object is always fully initialized</li></ul><pre>using System;<br><br>class Hammer{<br>    public void use()<br>    {<br>         Console.WriteLine (&quot;Hammering Nails&quot;);<br>    }<br>}<br><br>class Saw{<br>    public void use()<br>    {<br>         Console.WriteLine (&quot;Sawing hood&quot;);<br>    }<br>}<br><br>class Builder{<br>    public Hammer _hammer;<br>    public Saw _saw;<br>    public Builder(Hammer hammer,Saw saw)<br>    {<br>        _hammer = hammer;<br>        _saw= saw;<br>    }<br>    public void build()<br>    {<br>        _hammer.use();<br>        _saw.use();<br>    }<br>}<br><br>public class HelloWorld<br>{<br>    public static void Main(string[] args)<br>    {<br>       Hammer hammer =new Hammer();<br>       Saw saw =new Saw();<br><br>       Builder builder = new Builder(hammer,saw);<br>       builder.build();<br>       Console.WriteLine (&quot;build house&quot;);<br>    }<br>}</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*pGzUFlERMqp4nelPeaB-wQ.png" /><figcaption>Constructor DI output</figcaption></figure><p>2️. Setter (Property) Injection</p><p>Dependencies are set using public properties.</p><ul><li>Dependency is optional</li><li>Can be changed after object creation</li></ul><pre>using System;<br><br>class Hammer{<br>    public void use()<br>    {<br>         Console.WriteLine (&quot;Hammering Nails&quot;);<br>    }<br>}<br><br>class Saw{<br>    public void use()<br>    {<br>         Console.WriteLine (&quot;Sawing hood&quot;);<br>    }<br>}<br><br>class Builder{<br>    public Hammer Hammer {get; set; }<br>    public Saw Saw {get; set; }<br>    public void build()<br>    {<br>        Hammer.use();<br>        Saw.use();<br>    }<br>}<br><br>public class HelloWorld<br>{<br>    public static void Main(string[] args)<br>    {<br>       Hammer hammer =new Hammer();<br>       Saw saw =new Saw();<br><br>       Builder builder = new Builder();<br>       builder.Hammer=hammer;<br>       builder.Saw=saw;<br><br>       builder.build();<br>       Console.WriteLine (&quot;build house&quot;);<br>    }<br>}</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*GMoXV-i_doPUs1nOExuTMw.png" /><figcaption>Setter DI output</figcaption></figure><p>3️. Interface Injection</p><p>Dependency is provided through an interface method.</p><ul><li>Less commonly used</li><li>Requires the class to implement an interface for injection</li></ul><pre><br>using System;<br><br>public class Hammer{<br>    public void use()<br>    {<br>         Console.WriteLine (&quot;Hammering Nails&quot;);<br>    }<br>}<br><br>public class Saw{<br>    public void use()<br>    {<br>         Console.WriteLine (&quot;Sawing hood&quot;);<br>    }<br>}<br><br>public interface IToolUser{<br>     void setHammer(Hammer hammer);<br>     void setSawer(Saw saw);<br>}<br><br>class Builder: IToolUser{<br>    private Hammer _hammer;<br>    private Saw _saw;<br>    <br>    public void setHammer(Hammer hammer)<br>    {<br>        _hammer = hammer;<br>    }<br>    <br>    public void setSawer(Saw saw)<br>    {<br>        _saw = saw;<br>    }<br>    public void build()<br>    {<br>        _hammer.use();<br>        _saw.use();<br>    }<br>}<br><br>public class HelloWorld<br>{<br>    public static void Main(string[] args)<br>    {<br>       Hammer hammer =new Hammer();<br>       Saw saw =new Saw();<br><br>       Builder builder = new Builder();<br>       builder.setHammer(hammer);<br>       builder.setSawer(saw);<br><br>       builder.build();<br>       Console.WriteLine (&quot;build house&quot;);<br>    }<br>}</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*GMoXV-i_doPUs1nOExuTMw.png" /><figcaption>Interface DI output</figcaption></figure><h4>Conclusion</h4><p>Dependency Injection is a key concept in modern C# development. It helps you write clean, maintainable, and testable code.</p><p>By understanding and using constructor, setter, and interface injection, you can design better applications and follow best practices used in frameworks like ASP.NET Core.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fcd62bd0a8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Middleware in ASP.NET Core]]></title>
            <link>https://medium.com/@chathuraishara63/understanding-middleware-in-asp-net-core-c7a5c0cf9d3d?source=rss-8e08a444414f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7a5c0cf9d3d</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[custom-middleware]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Chathuraishara]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 15:22:43 GMT</pubDate>
            <atom:updated>2026-04-09T15:22:43.716Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tXoWSJitZJIRnFGdnxCn-Q.png" /><figcaption>Request and Response Pipeline</figcaption></figure><h4>What is Middleware?</h4><p>Middleware is a component in ASP.NET Core that handles HTTP requests and responses in a pipeline.</p><p>Each request passes through multiple middleware components, where each one can:</p><ul><li>Process the request</li><li>Modify the request or response</li><li>Pass it to the next middleware</li><li>Or stop it completely (short circuiting)</li></ul><h4>Built-in Middleware in ASP.NET Core</h4><p>Some commonly used built-in middleware include:</p><ul><li>useRouting()<br> Handles routing of incoming requests to the correct endpoint.</li><li>useAuthorization()<br> Ensures that the user has permission to access a resource.</li><li>useAuthentication()<br> Validates user identity before accessing secured endpoints.</li><li>useStaticFiles()<br> Serves static files like images, CSS, and JavaScript.</li><li>useEndpoints() / useMapControllers()<br> Maps incoming requests to controllers or endpoints.</li><li>useHttpHandlers()<br> Handles exceptions globally and returns proper error responses.</li><li>useHttpRedirection()<br> Redirects HTTP requests to HTTPS.</li></ul><pre>app.UseHttpsRedirection();<br><br>app.UseAuthorization();<br><br>app.UseMiddleware&lt;MiddlewareTest.CustomMiddleware.MyCustomMiddleWare&gt;();<br><br>app.MapControllers();</pre><h4>How Middleware Works</h4><ul><li>A request enters the application</li><li>It flows through each middleware (in order)</li><li>Each middleware decides continues or stop (returns)</li></ul><h4>Key Concept: Request Pipeline</h4><ul><li>Middleware executes <strong>in the order it is registered</strong></li><li>The response flows back in reverse order</li><li>If it does not pass it to the newxt middleware, the pipeline stops</li></ul><h4>Why Use Middleware?</h4><ul><li>Authentication checks</li><li>Logging</li><li>Adding custom headers</li><li>Request validation</li><li>Error handling</li></ul><h4>Creating a Custom Middleware</h4><p>In this example, we create a middleware that:</p><ul><li>Reads API key from <strong>query parameter</strong></li><li>Stops request if missing</li><li>Adds a transaction ID to the <strong>response header</strong></li></ul><h4>Step 1: Middleware Logic</h4><pre>namespace CustomMiddleware<br>{<br>    public class MyCustomMiddleWare<br>    {<br>        private readonly RequestDelegate _next;<br><br>        public MyCustomMiddleWare(RequestDelegate next)<br>        {<br>            _next = next;<br>        }<br><br>        public async Task Invoke(HttpContext context)<br>        {<br>            var apiKey = context.Request.Query[&quot;api_Key&quot;].ToString();<br>            if (string.IsNullOrWhiteSpace(apiKey))<br>            {<br>                await context.Response.WriteAsync(&quot;API Key is missing.Short circuit the pipeline&quot;);<br>                return;<br>            }<br>            var transactionId = Guid.NewGuid().ToString();<br>            context.Response.Headers[&quot;X-Transaction-Id&quot;] = transactionId;<br><br>            //Call next middleware in the pipeline<br>            await _next(context);<br>        }<br>    }<br>}</pre><h4>Step 2: Register Middleware</h4><pre>app.UseMiddleware&lt;MyCustomMiddleWare&gt;();<br><br>app.MapControllers();<br><br>app.MapGet(&quot;/&quot;, () =&gt;<br>{<br>    return &quot;Reached to the endpoint&quot;;<br>});</pre><p>The middleware checks whether an API key is provided in the request. If the API key is missing, it immediately stops the request and returns a message. If the API key is present, it generates a unique transaction ID and adds it to the response before allowing the request to continue.</p><h4>Expected Behavior</h4><ol><li>Without API Key:</li></ol><p>Request:</p><pre>https://localhost:7107/</pre><p>Response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7152biNGZgbkK1vo6nZhuA.png" /><figcaption>Request and response</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GkOfgcsoCOzu1OR6_G9sng.png" /><figcaption>No X-Transaction-Id in the response header</figcaption></figure><p>2. With API Key</p><p>Request:</p><pre>https://localhost:7107/?api_Key=abc123</pre><p>Response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*od7c3I-_PRPi0pf3AbZc9Q.png" /><figcaption>Request and response</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PIf3pbsFslCkSdhqBsbV1g.png" /><figcaption>X-Transaction-Id in the response header</figcaption></figure><h4>Conclusion</h4><p>Middleware is a powerful feature in ASP.NET Core that allows you to control how requests and responses are handled in your application.</p><p>In this article, we looked at both built-in middleware and how to create a custom middleware. With our custom example, we implemented simple request validation using an API key and added a transaction ID to the response for tracking purposes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7a5c0cf9d3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with ASP.NET Core Identity: Simple Authentication & Authorization Guide]]></title>
            <link>https://medium.com/@chathuraishara63/getting-started-with-asp-net-core-identity-simple-authentication-authorization-guide-dec64d4faba7?source=rss-8e08a444414f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dec64d4faba7</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Chathuraishara]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 11:46:24 GMT</pubDate>
            <atom:updated>2026-04-04T11:46:24.774Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9TqDiEy9hPz-mkcZ5oKhyA.png" /></figure><h4>Introduction</h4><p>Authentication and authorization are essential parts of any modern web application. Instead of building everything from scratch, ASP.NET Core provides a powerful built-in system called <strong>Identity</strong>.</p><p>In this article, we’ll learn how to quickly set up authentication and authorization using ASP.NET Core Identity with minimal configuration.</p><h4><strong>What is ASP.NET Core Identity?</strong></h4><p>ASP.NET Core Identity is a built-in framework that helps you manage:</p><ul><li>User registration</li><li>Login and logout</li><li>Password hashing and security</li><li>Roles and authorization</li></ul><p>It saves time by providing a <strong>ready-made authentication system</strong>.</p><h4>Project Setup</h4><p>First, create a new ASP.NET Core Web API project.</p><p>Then install required packages:</p><ul><li>Identity + Entity Framework Core</li><li>Database provider (InMemory or SQL Server)</li></ul><p>This allows us to store user data and manage authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FyHfLeHsaaUZlrCoL6hbg.png" /><figcaption>Required packages</figcaption></figure><p>For this demo, we will use an <strong>In-Memory database</strong> instead of a real database like SQL Server.</p><h4>Creating the Database Context</h4><p>We create a custom database context by extending the Identity system.</p><ul><li>This connects Identity with the database.</li><li>It automatically create tables like users, roles, claims.</li></ul><pre>using Microsoft.AspNetCore.Identity;<br>using Microsoft.EntityFrameworkCore;<br>using Microsoft.AspNetCore.Identity.EntityFrameworkCore;<br><br>namespace Authentication.db<br>{<br>    public class AuthDbContext: IdentityDbContext&lt;IdentityUser&gt;<br>    {<br>        public AuthDbContext(DbContextOptions options) : base(options)<br>        {<br><br>        }<br>    }<br>}</pre><h4>Configuring Services</h4><p>Next, we configure services in Program.cs.</p><ul><li>Add controllers → to handle API requests</li><li>Add Swagger → to test APIs</li><li>Add DbContext → to configure database</li><li>Add Identity → to enable authentication</li></ul><pre>using Microsoft.EntityFrameworkCore;<br>using AuthenticationPractise;<br>using AuthenticationPractise.db;<br>using Microsoft.AspNetCore.Identity;<br>using Microsoft.OpenApi.Models;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>// Add services to the container.<br><br>builder.Services.AddControllers();<br>// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle<br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen(options =&gt;<br>{<br>    options.SwaggerDoc(&quot;v1&quot;, new Microsoft.OpenApi.Models.OpenApiInfo()<br>    {<br>        Title = &quot;Auth Demo&quot;,<br>        Version = &quot;v1&quot;<br>    });<br><br>    options.AddSecurityDefinition(&quot;Bearer&quot;, new Microsoft.OpenApi.Models.OpenApiSecurityScheme()<br>    {<br>        Name = &quot;Authorization&quot;,<br>        In = Microsoft.OpenApi.Models.ParameterLocation.Header,<br>        Type = Microsoft.OpenApi.Models.SecuritySchemeType.Http,<br>        Scheme = &quot;Bearer&quot;,<br>        BearerFormat = &quot;JWT&quot;,<br>        Description = &quot;Input your Bearer token in this format - Bearer {your token here} to access this API&quot;,<br>    });<br><br>    options.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement<br>    {<br>        {<br>            new OpenApiSecurityScheme<br>            {<br>                Reference = new OpenApiReference<br>                {<br>                    Type = ReferenceType.SecurityScheme,<br>                    Id = &quot;Bearer&quot;<br>                }<br>            },<br>            []<br>        }<br>    });<br>        <br>});<br>builder.Services.AddDbContext&lt;AuthDbContext&gt;(options =&gt;<br>{<br>   options.UseInMemoryDatabase(&quot;AuthDb&quot;);<br>});</pre><h4>Enabling Identity Endpoints</h4><p>ASP.NET Core provides built-in endpoints for authentication.</p><ul><li>No need to manually write login/register APIs</li><li>Identity automatically generates them</li></ul><p>Examples:</p><ul><li>/register → create user</li><li>/login → authenticate user</li></ul><pre>builder.Services.AddIdentityApiEndpoints&lt;IdentityUser&gt;()<br>    .AddEntityFrameworkStores&lt;AuthDbContext&gt;();</pre><h4>Middleware Configuration</h4><p>Middleware defines how requests are processed.</p><ol><li>Request comes in</li><li>Authentication checks user identity</li><li>Authorization checks permissions</li><li>Response is returned</li></ol><p>Important middleware:</p><ul><li>useAuthentication() → identifies user</li><li>useAuthorization() → checks access</li></ul><h4>Using Swagger for Testing</h4><p>Swagger makes it easy to test APIs.</p><ul><li>You can register a user</li><li>Then log in</li><li>Then use the token to access protected endpoints</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jzsj-_qe_mLhEW6rb3ZBow.png" /><figcaption>Swagger UI</figcaption></figure><h4>Authorization</h4><p>Authorization controls what users can access.</p><ul><li>Only logged-in users can access certain endpoints</li></ul><pre>[Authorize]</pre><ul><li>This protects endpoints</li><li>Only authenticated users can access</li></ul><pre> [HttpGet(Name = &quot;GetWeatherForecast&quot;)]<br> [Authorize]<br> public IEnumerable&lt;WeatherForecast&gt; Get()<br> {<br>     return Enumerable.Range(1, 5).Select(index =&gt; new WeatherForecast<br>     {<br>         Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),<br>         TemperatureC = Random.Shared.Next(-20, 55),<br>         Summary = Summaries[Random.Shared.Next(Summaries.Length)]<br>     })<br>     .ToArray();<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DE6jlvS9UOddp83PQ6Yuaw.png" /><figcaption>Login endpoint results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OwqfrQwyxjTON84fFN7jCA.png" /><figcaption>get authenticating using a bearer token</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xs0BDMKTCNQYGmJwJAsqMg.png" /><figcaption>Acessing weather forecast endpoint by providing Authorization headers</figcaption></figure><h4>Benefits of Using Identity</h4><ul><li>Built-in security features</li><li>Saves development time</li><li>Easy to integrate with databases</li><li>Supports roles and claims</li></ul><h4>Conclusion</h4><p>ASP.NET Core Identity makes authentication and authorization simple and secure. With minimal setup, you can build a complete login system without writing complex logic.</p><p>It’s a great starting point for any application that requires user management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dec64d4faba7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From “What” to “Why”: Feature Importance Analysis using SHAP]]></title>
            <link>https://medium.com/@chathuraishara63/from-what-to-why-feature-importance-analysis-using-shap-f84a060d3fad?source=rss-8e08a444414f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f84a060d3fad</guid>
            <dc:creator><![CDATA[Chathuraishara]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 04:08:47 GMT</pubDate>
            <atom:updated>2025-12-05T04:08:47.476Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*o9fHEAzpz_Y3VGxZKltc4g.png" /><figcaption>SHAP value (impact on model output)</figcaption></figure><p>In the world of modern machine learning, we often face a difficult trade-off: <strong>Accuracy vs. Interpretability.</strong></p><p>Simple models, like Linear Regression or Decision Trees, are easy to understand. You can look at the coefficients or the tree splits and explain exactly <em>why</em> the model made a decision. However, these models often lack the predictive power needed for complex, real-world tasks.</p><p>On the other hand, complex algorithms like Gradient Boosting (XGBoost, LightGBM, CatBoost) and Deep Neural Networks provide incredible accuracy. But they come at a cost: they are “Black Boxes.” We feed data in, and we get a prediction out, but understanding the internal mechanics of <em>how</em> that specific prediction was reached is often a mystery.</p><p><strong>This is where SHAP (SHapley Additive exPlanations) comes in</strong></p><p>In this article, we will explore what SHAP values are, why they are superior to standard feature importance methods, and how you can implement them in Python to make your models transparent.</p><p><strong>The Problem with Standard Feature Importance</strong></p><p>Most tree-based models (like Random Forest or XGBoost) come with a built-in <em>feature_importance </em>attribute. While useful, this metric has two major flaws:</p><ol><li><strong>It is Global, not Local:</strong> It tells you which features are important <em>on average</em> across the whole dataset, but it cannot explain why a <em>specific</em> user was denied a loan or why a <em>specific</em> transaction was flagged as fraud.</li><li><strong>It lacks Directionality:</strong> It might tell you that “Age” is an important feature, but it won’t tell you if higher age leads to a higher or lower prediction.</li></ol><p>SHAP solves both of these problems.</p><p><strong>What is SHAP? (The Theory)</strong></p><p>SHAP is based on <strong>Game Theory</strong>, specifically the concept of <em>Shapley Values</em>, introduced by Lloyd Shapley in 1951.</p><p>Imagine a soccer team wins a match 3–0. To distribute the bonus money fairly, you need to determine how much each player contributed to the win. Did the striker score the goals? Did the midfielder make the assists? Did the goalkeeper keep a clean sheet?</p><p>In the context of Machine Learning:</p><ul><li><strong>The Game:</strong> The prediction task.</li><li><strong>The Players:</strong> The features (e.g., Age, Income, Temperature).</li><li><strong>The Payout:</strong> The actual prediction value minus the average prediction value.</li></ul><p>SHAP calculates the contribution of each feature by iterating through every possible combination of features and measuring how the model’s prediction changes when that feature is present versus when it is absent.</p><p>Mathematically, the Shapley value for feature <em>i</em> is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*mR3Jd-sStG_bEf6OSPTTWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*a6H84y72MF__m-6FlJtAOQ.png" /></figure><p>Don’t let the math scare you. The intuition is simple: SHAP assigns each feature an importance value for a particular prediction.</p><p><strong>Global vs. Local Interpretability</strong></p><p>The true power of SHAP lies in its ability to zoom in and out.</p><p>1. Local Interpretability (The Waterfall)</p><p>If you are building a credit risk model, you need to explain to a specific customer why they were rejected. SHAP allows you to say: <em>“Your base score started at 600. Your high income increased it by +50, but your recent late payments decreased it by -80, resulting in a final score of 570.”</em></p><p>2. Global Interpretability (The Beeswarm)</p><p>By aggregating the local SHAP values of every row in your dataset, you can see global trends. You can see which features are most important overall, and crucially, how the value of the feature (High or Low) impacts the output.</p><p><strong>Python Implementation</strong></p><p>Let’s look at how to implement this using the <em>shap</em> library and <em>xgboost</em>. We will use the classic California Housing dataset to predict house prices.</p><p><strong>Step 1: Install Libraries</strong></p><pre>pip install shap xgboost pandas scikit-learn</pre><p><strong>Step 2: Train the Model</strong></p><pre>import xgboost as xgb<br>import shap<br>import pandas as pd<br>from sklearn.datasets import fetch_california_housing<br>from sklearn.model_selection import train_test_split<br><br># Load data<br>data = fetch_california_housing()<br>X = pd.DataFrame(data.data, columns=data.feature_names)<br>y = data.target<br><br># Split data<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Train an XGBoost model<br>model = xgb.XGBRegressor(objective=&#39;reg:squarederror&#39;)<br>model.fit(X_train, y_train)</pre><p><strong>Step 3: Calculate SHAP Values</strong></p><pre># Initialize the explainer<br>explainer = shap.Explainer(model)<br><br># Calculate SHAP values for the test set<br>shap_values = explainer(X_test)</pre><p><strong>Step 4: Visualization</strong></p><p><em>The Waterfall Plot (Local)</em> This visualizes the first prediction in our test set. It shows how we get from the average house price to the specific price for this house.</p><pre># Visualize the first prediction&#39;s explanation<br>shap.plots.waterfall(shap_values[0])</pre><p><em>The Beeswarm Plot (Global)</em> This is the most information-dense plot. It sorts features by importance and uses color to show the relationship.</p><pre># Visualize global feature importance<br>shap.plots.beeswarm(shap_values)</pre><p>Interpreting the Beeswarm:</p><ul><li><strong>Y-Axis:</strong> Features are ranked by importance (top is most important).</li><li><strong>X-Axis:</strong> The SHAP value. Positive values (right) mean the feature pushes the price <em>up</em>. Negative values (left) mean it pushes the price <em>down</em>.</li><li><strong>Color:</strong> Red means the feature value is high; Blue means it is low.</li></ul><p><em>Example:</em> If “MedInc” (Median Income) has a cluster of red dots on the far right, it means high income strongly increases the predicted house price.</p><p><strong>The Pros and Cons</strong></p><p><strong>The Pros:</strong></p><ul><li><strong>Model Agnostic:</strong> While optimized for trees, SHAP can theoretically work on any model (KernelSHAP).</li><li><strong>Consistency:</strong> Unlike other methods, SHAP guarantees that if a model changes so that it relies <em>more</em> on a feature, the importance of that feature will not decrease.</li><li><strong>Granularity:</strong> It provides explanations for individual data points, which is essential for debugging and regulatory compliance.</li></ul><p><strong>The Cons:</strong></p><ul><li><strong>Speed:</strong> Exact Shapley value calculation is NP-hard (computationally very expensive). The <em>shap</em> library uses approximations (like TreeSHAP) to make it feasible, but it can still be slow on massive datasets.</li><li><strong>Correlated Features:</strong> If two features are highly correlated (e.g., “Square Footage” and “Number of Rooms”), SHAP might split the importance between them, making it look like neither is the “dominant” driver.</li></ul><p><strong>Conclusion</strong></p><p>As Artificial Intelligence becomes more integrated into healthcare, finance, and criminal justice, “trust” becomes just as important as “accuracy.”</p><p>We can no longer afford to blindly trust black boxes. SHAP provides a mathematical and visual framework to open these boxes, allowing data scientists to explain their models to stakeholders, detect bias, and ensure fairness.</p><p>If you aren’t using SHAP in your machine learning workflow yet, now is the time to start.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f84a060d3fad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Imbalanced Datasets: Smarter Techniques for Better Machine Learning Models]]></title>
            <link>https://medium.com/@chathuraishara63/mastering-imbalanced-datasets-smarter-techniques-for-better-machine-learning-models-2da1df1e21d8?source=rss-8e08a444414f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2da1df1e21d8</guid>
            <dc:creator><![CDATA[Chathuraishara]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 14:49:27 GMT</pubDate>
            <atom:updated>2025-08-21T16:24:25.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*O8mcIp-hSeWKpf4M2zEUYg.png" /><figcaption>Imbalanced data set</figcaption></figure><p>In real-world machine learning, data is rarely perfect. One of the most common challenges is imbalanced data sets.when one class has far more samples than the others(that means in the target column data).This is happened due to some mistakes or some rear cases.For example, in fraud detection, the number of fraudulent transactions is much smaller compared to legitimate ones. This imbalance can trick models into always predicting the majority class, giving high accuracy but poor performance on the minority class.</p><p>Handling this imbalance is crucial because in many applications, the minority class is the most important one to detect. In this article, we’ll explore why imbalanced data is a problem, how it affects machine learning models, and practical strategies to overcome it.</p><h3><strong>What is the Problem with Imbalanced Datasets?</strong></h3><p>When we train a machine learning model on an imbalanced dataset, the model tends to favor the majority class because it sees it more often. This makes the model biased towards one outcome.</p><p>For example, imagine building a model to detect fraudulent transactions where 99% of the data is normal transactions and only 1% is fraud. If the model predicts “normal” for every transaction, it will still achieve 99% accuracy- but it completely fails to detect fraud.</p><p>This shows that traditional metrics like accuracy can be misleading with imbalanced data. The model may look good on paper but perform poorly in real-world scenarios where detecting the minority class is critical.</p><h3><strong>How to Overcome Imbalanced Datasets?</strong></h3><p>The good news is that there are several techniques to deal with imbalanced datasets and improve model performance. Here are three common approaches:</p><ol><li><strong>Undersampling</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*Oaoc9Yw9Zm7-DrNVXQ2T0Q.png" /><figcaption>underSampling</figcaption></figure><p>This method reduces the size of the majority class by randomly removing some of its samples. The dataset becomes more balanced, but the downside is that we might lose useful information since we are discarding data.</p><p><strong>2. Oversampling</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*O3cozA1eroV134tWv7u-ew.png" /><figcaption>overSampling</figcaption></figure><p>In this approach, we increase the size of the minority class by duplicating some of its samples. This helps the model see the minority class more often, but it can also lead to overfitting since the same data points are repeated.</p><p><strong>3. SMOTE (Synthetic Minority Oversampling Technique)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38kzm_wgGWRWVLq9PjNvDQ.png" /><figcaption>SMOTE</figcaption></figure><p>SMOTE is a smarter version of oversampling. Instead of simply duplicating minority samples, it creates synthetic new sample by combining existing ones. This helps balance the dataset without making the model memorize repeated data.</p><h3>Conclusion</h3><p>Imbalanced datasets are a common challenge in machine learning and can lead to biased models that fail to detect the most important outcomes. While accuracy alone can be misleading, techniques like undersampling, oversampling and SMOTE provide effective ways to balance data and improve model performance.</p><p>The key is to choose the right method depending on the problem and dataset size. By carefully handling imbalance, we can build fairer, more reliable models that perform well not just on paper, but in real-world applications too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2da1df1e21d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Terraform?]]></title>
            <link>https://medium.com/@chathuraishara63/why-terraform-6bb3b51dddaa?source=rss-8e08a444414f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bb3b51dddaa</guid>
            <dc:creator><![CDATA[Chathuraishara]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 17:59:30 GMT</pubDate>
            <atom:updated>2025-08-18T17:59:30.269Z</atom:updated>
            <content:encoded><![CDATA[<p>Terraform lets you easily create and manage your cloud infrastructure with code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*8-Rihz67AqfxTCwXKwA0Rg.png" /></figure><h3><strong>Do We Really Need Terraform?</strong></h3><p>eventhough i have mentioned above terraform lets use easily crate and mange cloud infrastructure with code,you did not get the point.let’s take this as a simple scenario.</p><p>Suppose you are a system administrator in a software company, and your organization has decided to use AWS as its cloud provider. As part of your role, you are required to learn and work with tools like the AWS CLI or CloudFormation Templates (CFT) to manage resources in AWS. For example, whenever developers request new EC2 instances, you write a script or a CloudFormation template and run it to provision the instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*PEr1iFgqLJGR-Prgx_1wdA.png" /><figcaption>You work with AWS cloud providers.</figcaption></figure><p>After some time, your organization decides to switch from AWS to Azure. Now you need to learn Azure Resource Manager, and all the scripts and templates you wrote for AWS become useless. Later, if the company moves back to physical data centers or chooses another platform like OpenStack, you would again have to learn a different technology, such as Heat templates, to manage infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qlj5NR75BbifToj06JNaUw.png" /></figure><p>Nowadays, many organizations use a hybrid cloud approach. For example, they might use AWS S3 buckets for storage services while running virtual servers on Azure VMs, and similar combinations across multiple providers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*6yDJMdFPn956Agc4zYMIqg.png" /></figure><p>So, what’s the real problem here? Each cloud provider requires you to learn different technologies and tools, which is both difficult and inefficient. This is where Terraform comes into play — providing a single, consistent way to manage infrastructure across multiple platforms.</p><h3><strong>How Terraform solve this?</strong></h3><p>Terraform acts as an Infrastructure as Code (IaC) tool. All we need to do is specify the cloud service provider in the Terraform configuration file, and Terraform takes care of the rest through the provider’s APIs. This means we don’t have to worry about learning different tools for each cloud provider. If, at some point, we want to migrate to another cloud, we simply update the provider in the configuration file, and Terraform handles everything else. This approach is often referred to as <em>API as Code</em> because Terraform interacts directly with cloud providers through their APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bb3b51dddaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamline HubSpot Task Management with Ballerina’s HubSpot Engagement Tasks Connector]]></title>
            <link>https://medium.com/@chathuraishara63/streamline-hubspot-task-management-with-ballerinas-hubspot-engagement-tasks-connector-5c6f258b6855?source=rss-8e08a444414f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c6f258b6855</guid>
            <dc:creator><![CDATA[Chathuraishara]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 03:18:03 GMT</pubDate>
            <atom:updated>2025-03-07T03:18:03.083Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4UKrE4-6MHvmZI5DW5jtg.jpeg" /></figure><p><strong>Customer Relationship Management (CRM) </strong>systems play a crucial role in managing customer interactions, improving efficiency, and enhancing business relationships. <a href="https://www.hubspot.com/">HubSpot</a> is a widely used CRM platform that provides various APIs to streamline operations, including task management. In this article, we will guide you through integrating HubSpot CRM Engagement Tasks into your Ballerina application using the <a href="https://github.com/ballerina-platform/module-ballerinax-hubspot.crm.engagements.tasks">HubSpot CRM Engagement Tasks connector.</a> Let’s explore how this connector simplifies task automation in your CRM workflow.</p><h3>Table of Contents</h3><ol><li>Overview</li><li>Prerequisites</li><li>Setting Up a HubSpot Developer Account</li><li>Creating a HubSpot App</li><li>Obtaining OAuth2 Tokens</li><li>Quickstart</li><li>Examples</li><li>Conclusion</li></ol><h3>Overview</h3><p><a href="https://www.hubspot.com/">HubSpot</a> is a powerful CRM platform with RESTful APIs for seamless integration. The HubSpot Engagement Tasks API lets users create, assign, and track tasks within CRM records.</p><p>The <strong>Ballerina HubSpot CRM Engagement Tasks Connector</strong> (ballerinax/hubspot.crm.engagement.tasks) enables seamless integration with the<a href="https://developers.hubspot.com/docs/guides/api/crm/engagements/tasks"> HubSpot Engagement Tasks API</a>. It provides simplified functions to create, assign, and manage tasks, ensuring efficient task automation within your CRM.</p><h3>Prerequisites</h3><p>Before you begin:</p><ol><li><strong>Ballerina Language</strong>: Install <a href="https://ballerina.io/">Ballerina</a>.</li><li><strong>HubSpot Developer Account</strong>: Ensure you have or <a href="https://developers.hubspot.com/get-started">create</a> a HubSpot Developer Account.</li><li><strong>HubSpot App</strong>: You’ll need to create a HubSpot App to obtain your Client ID and Client Secret.</li><li><strong>cURL (Optional)</strong>: For generating OAuth tokens via the command line.</li></ol><h3>Setting Up a HubSpot Developer Account</h3><h4>Create or Login to a Developer Account</h4><ol><li>Navigate to the <a href="https://developers.hubspot.com/">HubSpot Developer Portal</a>.</li><li>If you already have an account, log in directly. Otherwise, sign up for a free developer account.</li></ol><h4>Create a Developer Test Account (Optional)</h4><p>Developer Test Accounts are isolated from your production data and are ideal for testing integrations.</p><ol><li>In your HubSpot developer dashboard, go to <strong>Test accounts</strong> from the left sidebar.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MbGpQhY_EoAAwrQ0Ucmftw.png" /></figure><p>2. Click <strong>Create developer test account</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6PjooBpX9Lvx2mr0D-OVtQ.png" /></figure><p>3. Provide a name and click <strong>Create</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AB-7FK9EbQskaylMJ0E6nA.png" /></figure><h4>Creating a HubSpot App</h4><p>Once you have a developer account (and optionally, a test account), the next step is to create a HubSpot App.</p><ol><li>In your developer portal, go to <strong>Apps</strong> from the left sidebar.</li><li>Click on <strong>Create app</strong> on the top right corner.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TG-5-r9I1ksuxCrvswtJqg.png" /></figure><p>3. Give your app a <strong>Name</strong> and a <strong>Description</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4cCikNSDLZmMTsz7bolWqw.png" /></figure><h4>Configure Authentication</h4><ol><li>Switch to the <strong>Auth</strong> tab of the newly created app.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0y0ydcWF6SMg7Oh45mzFg.png" /></figure><p>2. Add <strong>Scopes</strong> to your application. For this connector, at minimum you need:</p><ul><li>crm.objects.owners.read</li><li>crm.objects.owners.write</li></ul><p>Click <strong>Add new scopes</strong> and add crm.objects.owners.readand crm.objects.owners.write.These scopes define which parts of the HubSpot data your app can access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8-KEvNH9QLPa3FxSTIHng.png" /></figure><p>3. . In the <strong>Redirect URL</strong> section, add the URL where HubSpot should redirect the user after the OAuth flow. For testing, you might use <a href="http://localhost./">http://localhost</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_P7xbztLnjjGaHJuQqncQ.png" /></figure><p><strong>Important</strong>: This <strong>Redirect URL</strong> must match exactly what you will use in the OAuth process later.</p><p>After you have added the scope and redirect URL, click <strong>Create App</strong>.</p><h4><strong>Retrieve Client ID and Client Secret</strong></h4><p>Under the <strong>Auth</strong> tab, you’ll find the <strong>Client ID</strong> and <strong>Client Secret</strong>. Copy or store these safely — these values are critical for obtaining tokens later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0y0ydcWF6SMg7Oh45mzFg.png" /></figure><h4>Obtaining OAuth2 Tokens</h4><p>Before proceeding with the Quickstart, ensure you have set the correct <strong>Redirect URL</strong> and obtained the <strong>Access Token</strong> or <strong>Refresh Token</strong> using the following steps:</p><ol><li>Construct the following URL and paste it in your browser. Replace the placeholder values with your own:</li></ol><pre>https://app.hubspot.com/oauth/authorize<br>    ?client_id=&lt;YOUR_CLIENT_ID&gt;<br>    &amp;scope=&lt;YOUR_SCOPES&gt;<br>    &amp;redirect_uri=&lt;YOUR_REDIRECT_URI&gt;</pre><p>2. Paste this URL into your browser. When prompted, select your HubSpot developer test account (or production account) to <strong>Install App</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-ISLTN6E_OkJHEpEeDFzQ.png" /></figure><p>3. After clicking <strong>Connect App</strong>, you will be redirected to &lt;YOUR_REDIRECT_URI&gt; with a code query parameter in the URL. Copy this code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oy55-0vVZP8JVqBzyVW8KA.png" /></figure><p>4. Use this code to request an <strong>Access Token</strong> and <strong>Refresh Token</strong>, for example, via cURL:</p><ul><li><strong>Linux/macOS</strong></li></ul><pre>curl --request POST \<br>  --url https://api.hubapi.com/oauth/v1/token \<br>  --header &#39;content-type: application/x-www-form-urlencoded&#39; \<br>  --data &#39;grant_type=authorization_code&amp;code=&lt;CODE&gt;&amp;redirect_uri=&lt;YOUR_REDIRECT_URI&gt;&amp;client_id=&lt;YOUR_CLIENT_ID&gt;&amp;client_secret=&lt;YOUR_CLIENT_SECRET&gt;&#39;</pre><ul><li><strong>Windows</strong>:</li></ul><pre>curl --request POST ^<br>  --url https://api.hubapi.com/oauth/v1/token ^<br>  --header &#39;content-type: application/x-www-form-urlencoded&#39; ^<br>  --data &#39;grant_type=authorization_code&amp;code=&lt;CODE&gt;&amp;redirect_uri=&lt;YOUR_REDIRECT_URI&gt;&amp;client_id=&lt;YOUR_CLIENT_ID&gt;&amp;client_secret=&lt;YOUR_CLIENT_SECRET&gt;&#39;</pre><p>This request will return a JSON response containing the access_token, refresh_token, and expires_in values:</p><pre>{<br>  &quot;token_type&quot;: &quot;bearer&quot;,<br>  &quot;refresh_token&quot;: &quot;&lt;Refresh Token&gt;&quot;,<br>  &quot;access_token&quot;: &quot;&lt;Access Token&gt;&quot;,<br>  &quot;expires_in&quot;: 1800<br>}</pre><p>5. Store the <strong>Refresh Token</strong> securely for use in your application since you’ll need it to obtain new access tokens when they expire.</p><h4>Quickstart</h4><p>Below is a minimal example of using the Hubspot CRM Owners connector in a Ballerina application.</p><ol><li>Import the Module</li></ol><pre>import ballerinax/hubspot.crm.engagements.tasks as hstasks;<br>import ballerina/oauth2;</pre><p>2. Create a Config.toml file and configure your credentials:</p><pre>clientId = &quot;&lt;Client ID&gt;&quot;<br>clientSecret = &quot;&lt;Client Secret&gt;&quot;<br>refreshToken = &quot;&lt;Refresh Token&gt;&quot;</pre><p>3. Instantiate a hstasks:ConnectionConfig in your Ballerina code:</p><pre>configurable string clientId = ?;<br>configurable string clientSecret = ?;<br>configurable string refreshToken = ?;<br><br>hsowners:ConnectionConfig config = {<br>    auth: {<br>        clientId: clientId,<br>        clientSecret: clientSecret,<br>        refreshToken: refreshToken,<br>        credentialBearer: oauth2:POST_BODY_BEARER<br>    }<br>};<br><br>final hstasks:Client hubspot= check new (config);</pre><p>4. Use the connector to interact with HubSpot Owners data. For example:</p><pre>import ballerina/io;<br><br>public function main() returns error? {<br>    // Retrieve a page of task with limit=10<br>     hstasks:CollectionResponseSimplePublicObjectWithAssociationsForwardPaging getPageOfTasks= check taskClient-&gt;/.get(limit=10);<br>     io:println(&quot;Tasks: &quot;, getPageOfTasks);<br>}</pre><h4>Examples</h4><p><a href="https://github.com/ballerina-platform/module-ballerinax-hubspot.crm.engagements.tasks/tree/main/examples/mark-a-task-as-completed"><strong>Task Completion Update and Status Change in HubSpot</strong></a> example demonstrates how to use the HubSpot CRM Tasks connector to check the status of a task assigned to a specific owner. It first retrieves the task details based on the task ID and checks its current status. If the status is not “Completed,” the task owner updates it to “Completed.” This process allows task owners to manage and track their tasks effectively, ensuring tasks are marked as completed when done, directly from the HubSpot CRM.</p><p><a href="https://github.com/ballerina-platform/module-ballerinax-hubspot.crm.engagements.tasks/tree/main/examples/assign-or-extend-a-task"><strong>Task Search, Assignment, or Extension in HubSpot</strong></a> example demonstrates how to use the HubSpot CRM Tasks connector to manage tasks efficiently. It first searches for a task by its subject to check if it already exists. If no matching task is found, a new task is created with the given subject. However, if the task is already available, it is extended by updating relevant details such as the due date or priority.</p><h4>Wrap-Up</h4><p>By following these steps, you can easily integrate with HubSpot’s CRM Engagement Tasks. Ballerina’s connector approach, with strong type checking and built-in concurrency, simplifies task automation and ensures seamless CRM workflows.</p><p><strong>Key Takeaways</strong>:</p><ul><li><strong>Keep Credentials Secure</strong>: Your Client ID, Client Secret, and Refresh Token are sensitive details — store them safely.</li><li><strong>Refresh Tokens</strong>: Leverage the Refresh Token flow to handle token expirations gracefully.</li><li><strong>Exact Redirect URL</strong>: Always ensure the Redirect URL in your HubSpot app matches the one used in your OAuth flow.</li></ul><p>Happy Coding! If you found this guide useful, feel free to share it with your team or leave a star on the <a href="https://github.com/ballerina-platform/module-ballerinax-hubspot.crm.owners">connector’s GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c6f258b6855" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with xUnit Testing in ASP.NET: A Beginner’s Guide]]></title>
            <link>https://medium.com/@chathuraishara63/getting-started-with-xunit-testing-in-asp-net-a-beginners-guide-de938a7cf4a0?source=rss-8e08a444414f------2</link>
            <guid isPermaLink="false">https://medium.com/p/de938a7cf4a0</guid>
            <dc:creator><![CDATA[Chathuraishara]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 04:12:44 GMT</pubDate>
            <atom:updated>2024-07-04T04:12:44.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*85Eq0rbFSrg2VqEITwANaw.jpeg" /></figure><h3>what is unit testing?</h3><p>Unit testing is a fundamental practice in software development that involves writing tests for individual units of code, typically functions or methods, to ensure they perform as expected. By isolating each unit and testing it independently, developers can quickly identify and fix bugs, leading to more robust and reliable code. Unit tests serve as a safety net that catches errors early in the development process, reducing the likelihood of defects making it into production. Additionally, unit testing facilitates code refactoring and maintenance by providing immediate feedback on changes, ensuring that modifications do not introduce new issues. Tools and frameworks, such as xUnit for .NET, offer a structured and efficient way to implement unit testing, making it an indispensable part of modern software development.</p><h3>Xunit testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*kq-Mu7YbJ75POpdAo_CZQQ.png" /></figure><p>xUnit is a popular testing framework for .NET applications that simplifies the process of writing and running unit tests. Known for its extensibility, flexibility, and ease of use, xUnit allows developers to create automated tests that verify the correctness of their code. It supports various test attributes, enabling the organization of tests and the execution of setup and teardown code. With xUnit, developers can test their code in isolation, using mocks and stubs to simulate dependencies, ensuring that each component functions correctly on its own.</p><p>The framework integrates seamlessly with continuous integration (CI) pipelines, allowing for automated test runs and immediate feedback on code changes. By leveraging xUnit, developers can enhance the quality and reliability of their ASP.NET applications, catching issues early and facilitating a more efficient development process.</p><h4>Step 1: Set Up Your xUnit Test Project</h4><p>1. Add New Project:<br> — Open your solution in Visual Studio.<br> — Right-click on the solution in Solution Explorer.<br> — Select `Add` -&gt; `New Project`.</p><p>2. Select xUnit Test Project:<br> — From the list of project templates, choose `xUnit Test Project`.<br> — Click `Next` to proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OUcBFqtoZCQX1gc-EFweNg.png" /></figure><p>3. Name the Project:<br> — Provide a meaningful name for your test project, such as `MyApp.Tests`.<br> — Click `Create` to add the project to your solution</p><p>By setting up your xUnit test project, you’re laying the foundation for creating robust and reliable tests for your ASP.NET application.</p><h4>Step 2: Configure the Test Project</h4><ol><li>Add Dependencies:<br> — Open `NuGet Package Manager` by right-clicking on your test project in Solution Explorer and selecting `Manage NuGet Packages`.<br> — Search for and install the following packages:<br> — `xunit`<br> — `xunit.runner.visualstudio`<br> — `Moq` (if you need to mock dependencies)<br> — `Microsoft.EntityFrameworkCore.InMemory` (for in-memory database testing)<br> — `FluentAssertions` (for more readable and fluent assertions)<br> — Ensure these packages are correctly added to your test project.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bMfB7wF1h-xNQ8sMpP93w.png" /></figure><p>Configuring the test project with the necessary dependencies ensures you have all the tools required to write and run effective unit tests for your ASP.NET application, making your testing process more efficient and comprehensive.</p><h4>Step 3: Write Your First Test</h4><p>1. Create Test Classes:<br> — Inside the test project, add a new class for your tests. For example, create a class named `CalculatorTests`.</p><p>2. Write Test Methods:<br> — In your test class, create methods to test your application’s functionality. Decorate these methods with `[Fact]` to indicate they are unit tests. <br> — Here’s an example:</p><pre>public class CalculatorTests<br>{<br>    [Fact]<br>    public void Add_TwoNumbers_ReturnsSum()<br>    {<br>        // Arrange<br>        var calculator = new Calculator();<br><br>        // Act<br>        var result = calculator.Add(2, 3);<br><br>        // Assert<br>        Assert.Equal(5, result);<br>    }<br>}</pre><p>Writing your first test sets the stage for a robust testing framework, ensuring each unit of your ASP.NET application performs as expected.</p><h4>Step 4: Run Tests</h4><p>1. Open Test Explorer:<br> — In Visual Studio, navigate to `Test` -&gt; `Test Explorer` to open the Test Explorer window.</p><p>2. Run All Tests:<br> — In the Test Explorer, click `Run All` to execute all your tests.<br> — Check the results in the Test Explorer to see which tests passed and which failed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ho0kzDZE0kgtbotT_Gl1uQ.png" /></figure><p>Running your tests ensures that your code behaves as expected and helps you catch any issues early in the development process.</p><h4>Simplified Example: Testing GetEmployeeById Method with In-Memory Database</h4><h4>Step 1: Define EmployeeService</h4><p>First, define the EmployeeService class responsible for retrieving employee data from an in-memory database.</p><pre>public class EmployeeService<br>{<br>    private readonly ApplicationDbContext _dbContext;<br><br>    public EmployeeService(ApplicationDbContext dbContext)<br>    {<br>        _dbContext = dbContext;<br>    }<br><br>    public async Task&lt;Employee&gt; GetEmployeeById(int id)<br>    {<br>        return await _dbContext.Employees.FirstOrDefaultAsync(e =&gt; e.Id == id);<br>    }<br>}</pre><h4>Step 2: Write xUnit Test Using Mock Data</h4><p>Next, create an xUnit test class (EmployeeServiceTests) to verify the GetEmployeeById method functionality using mock data within an in-memory database.</p><pre>public class EmployeeServiceTests : IDisposable<br>{<br>    private readonly ApplicationDbContext _dbContext;<br><br>    public EmployeeServiceTests()<br>    {<br>        // Initialize an in-memory database for testing<br>        var options = new DbContextOptionsBuilder&lt;ApplicationDbContext&gt;()<br>            .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())<br>            .Options;<br><br>        _dbContext = new ApplicationDbContext(options);<br><br>        // Add mock data to the in-memory database<br>        _dbContext.Employees.AddRange(new[]<br>        {<br>            new Employee { Id = 1, FirstName = &quot;John&quot;, LastName = &quot;Doe&quot;, Position = &quot;Developer&quot; },<br>            new Employee { Id = 2, FirstName = &quot;Jane&quot;, LastName = &quot;Smith&quot;, Position = &quot;Designer&quot; }<br>        });<br><br>        _dbContext.SaveChanges();<br>    }<br><br>    [Fact]<br>    public async Task GetEmployeeById_ReturnsEmployee()<br>    {<br>        // Arrange<br>        var employeeService = new EmployeeService(_dbContext);<br>        int employeeId = 1;<br><br>        // Act<br>        var result = await employeeService.GetEmployeeById(employeeId);<br><br>        // Assert<br>        Assert.NotNull(result);<br>        Assert.Equal(employeeId, result.Id);<br>        Assert.Equal(&quot;John&quot;, result.FirstName);<br>        Assert.Equal(&quot;Doe&quot;, result.LastName);<br>        Assert.Equal(&quot;Developer&quot;, result.Position);<br>    }<br><br>    public void Dispose()<br>    {<br>        // Dispose of the in-memory database context after each test run<br>        _dbContext.Dispose();<br>    }<br>}</pre><ul><li><strong>EmployeeService</strong>: Manages interactions with the Employee entity through ApplicationDbContext.</li><li><strong>EmployeeServiceTests</strong>: Validates the GetEmployeeById method by injecting an in-memory database context (ApplicationDbContext) populated with mock employee data.</li></ul><p>This approach ensures the GetEmployeeById method accurately retrieves employee information based on the provided ID from the in-memory database. It enables rapid and isolated testing without relying on external databases, enhancing test reliability and efficiency.</p><p>“Software testing is crucial as it helps identify and fix issues before software is deployed, ensuring it works as expected and meets user needs effectively.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de938a7cf4a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Zero to Hero: Using FullCalendar in Your React App]]></title>
            <link>https://medium.com/@chathuraishara63/from-zero-to-hero-using-fullcalendar-in-your-react-app-ccc3ed2cbdcd?source=rss-8e08a444414f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccc3ed2cbdcd</guid>
            <dc:creator><![CDATA[Chathuraishara]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 17:50:48 GMT</pubDate>
            <atom:updated>2024-06-20T17:50:48.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*Fcn70d7tQQ5OarBaVTJ7pg.png" /></figure><h3>What is fullCalendar?</h3><p>FullCalendar is a powerful and flexible JavaScript library designed to create and manage interactive and dynamic event calendars within web applications. It provides a wide array of features, including different view modes (month, week, day), customizable event rendering, and various utility functions to handle event data. FullCalendar integrates seamlessly with popular frontend frameworks like React, Angular, and Vue, making it a versatile tool for developers. It is highly customizable, allowing users to tailor the appearance and behavior of the calendar to suit their specific needs.</p><p><em>In this article, we will explore how to integrate FullCalendar into a React application.</em></p><h3>How to install FullCalendar packages?</h3><pre>npm install @fullcalendar/react @fullcalendar/core @fullcalendar/daygrid @fullcalendar/timegrid @fullcalendar/interaction</pre><pre>yarn add @fullcalendar/react @fullcalendar/core @fullcalendar/daygrid @fullcalendar/timegrid @fullcalendar/interaction</pre><h3>Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ezglqBZg3-ZrXVwjmL0yg.png" /><figcaption>Custom Design Calendar</figcaption></figure><pre>import FullCalendar from &#39;@fullcalendar/react&#39;<br>import dayGridPlugin from &#39;@fullcalendar/daygrid&#39;<br><br>const events = [<br>  { title: &#39;Meeting&#39;, start: new Date() }<br>]<br><br>export function MyApp() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;My App&lt;/h1&gt;<br>      &lt;FullCalendar<br>        plugins={[dayGridPlugin]}<br>        initialView=&#39;dayGridMonth&#39;<br>        weekends={false}<br>        events={events}<br>        eventContent={renderEventContent}<br>        dayCellContent={renderDayCellContent}<br>        dateClick={handleDateClick}<br>      /&gt;<br>    &lt;/div&gt;<br>  )<br>}<br>// a custom render function<br>function renderEventContent(eventInfo) {<br>  return (<br>    &lt;&gt;<br>      &lt;b&gt;{eventInfo.timeText}&lt;/b&gt;<br>      &lt;i&gt;{eventInfo.event.title}&lt;/i&gt;<br>    &lt;/&gt;<br>  )<br>}<br>// Function to render custom content in day cells<br>  const renderDayCellContent = (dayCellContent) =&gt; {<br>    return (<br>      &lt;div&gt;<br>        &lt;div&gt;{dayCellContent.dayNumberText}&lt;/div&gt;<br>        &lt;div style={{ fontSize: &#39;0.7em&#39;, color: &#39;red&#39; }}&gt;Custom&lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  };<br><br>  // Function to handle date clicks<br>  const handleDateClick = (arg) =&gt; {<br>    alert(`Date clicked: ${arg.dateStr}`);<br>  };</pre><p>The renderDayCellContent function is used to add custom content to each day cell. In this example, it adds a small &quot;Custom&quot; text below the day number:</p><p>The handleDateClick function handles clicks on the date cells. In this example, it simply alerts the date that was clicked:</p><p>In the Calendar component, these functions are passed as props to FullCalendar. When a date cell is clicked, handleDateClick is called, and each day cell is rendered with custom content via renderDayCellContent.</p><p>This example demonstrates how to enhance FullCalendar in a React application with custom day cell content and date click handling. You can further customize these functions as needed for your specific use case.</p><h3>Conclusion</h3><p>FullCalendar simplifies adding a powerful calendar to your React app. With its rich features and easy integration, you can efficiently manage events and schedules, enhancing the overall user experience. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccc3ed2cbdcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>