<?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 Nuwan Pradeep on Medium]]></title>
        <description><![CDATA[Stories by Nuwan Pradeep on Medium]]></description>
        <link>https://medium.com/@nuwanpkumara128?source=rss-c8c84c515ea9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*SCIbotWpzRlfxNHA</url>
            <title>Stories by Nuwan Pradeep on Medium</title>
            <link>https://medium.com/@nuwanpkumara128?source=rss-c8c84c515ea9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:21:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nuwanpkumara128/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[A Fresh Ubuntu VPS: Server Hardening Before Coolify Deployment]]></title>
            <link>https://medium.com/@nuwanpkumara128/a-fresh-ubuntu-vps-server-hardening-before-coolify-deployment-4f581113f93d?source=rss-c8c84c515ea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f581113f93d</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[self-hosting]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Nuwan Pradeep]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 17:18:56 GMT</pubDate>
            <atom:updated>2026-11-03T17:18:56.042Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A hands-on journey through Ubuntu server hardening, SSH security, firewalls, Docker troubleshooting, and self-hosted deployments.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjVlC7_k0cPfvZV54Z4GOQ.png" /><figcaption>Securing a fresh Ubuntu VPS with SSH hardening, UFW firewall, Fail2ban, and Docker before deploying self-hosted applications using Coolify.</figcaption></figure><h3>Introduction</h3><p>As part of my learning journey in DevOps and server administration, I decided to set up my own VPS to gain practical experience with Linux server management, security configurations, and self-hosted deployment platforms.</p><p>My initial plan was straightforward:</p><ol><li>Purchase a VPS.</li><li>Install Docker.</li><li>Set up Coolify.</li><li>Start deploying applications.</li></ol><p>However, I quickly realised something important.</p><p><strong>Before deploying applications, I needed to understand how to prepare and secure a fresh server.</strong></p><p>A newly provisioned VPS is not automatically a production-ready environment. SSH access, firewall configuration, user permissions, automatic security updates, and resource management all need attention.</p><p>Instead of immediately installing Coolify, I decided to prepare the server step by step.</p><p>This turned out to be a much more valuable learning experience than I initially expected.</p><p>In this article, I’ll share my experience securing an Ubuntu VPS, the challenges I encountered, the solutions I applied, and how I eventually installed Coolify successfully.</p><h3>1. Understanding the Server Environment</h3><p>I selected a Contabo Cloud VPS 4 for this learning project.</p><h3>Server specifications</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAqHzHvPIOJOCoiDKm-SCw.png" /><figcaption>Table 1. Technical specifications of the Contabo VPS used for server deployment.</figcaption></figure><p>My objective was to create an environment where I could host development, staging, and production applications.</p><p>Before doing that, I wanted to establish a secure foundation.</p><h3>2. Creating a Non-Root User</h3><p>The first thing I addressed was server access.</p><p>Initially, I connected to the server using the root account. Although root access is useful for initial configuration, using it for everyday server administration is not a good practice.</p><p>I created a separate administrative user and granted sudo privileges.</p><pre>adduser adminuser<br>usermod -aG sudo adminuser</pre><p>I then switched to the new user:</p><pre>su - adminuser</pre><p>This allowed me to perform administrative operations using sudo instead of logging in directly as root.</p><p>For example:</p><pre>sudo apt update<br>sudo systemctl status ssh</pre><p><strong>Lesson learned:</strong> Use a dedicated administrative account for routine server management rather than relying on root access.</p><h3>3. Configuring SSH Key-Based Authentication</h3><p>SSH is one of the most important access points to a VPS.</p><p>I used MobaXterm on Windows to connect to my server.</p><p>Instead of relying on password-based SSH authentication, I configured SSH key-based authentication.</p><p>The process involved:</p><ol><li>Generating an SSH key pair.</li><li>Protecting the private key with a passphrase.</li><li>Adding the public key to the server’s authorized_keys file.</li><li>Connecting through MobaXterm using the private key.</li></ol><p>The public key was stored under:</p><pre>~/.ssh/authorized_keys</pre><p>I also ensured the SSH directory and file permissions were correct:</p><pre>chmod 700 ~/.ssh<br>chmod 600 ~/.ssh/authorized_keys</pre><p>After confirming that key-based login worked, I disabled root login and password authentication.</p><p>I created a dedicated SSH configuration file:</p><pre>sudo nano /etc/ssh/sshd_config.d/00-security.conf</pre><p>Configuration:</p><pre>PermitRootLogin no<br>PasswordAuthentication no<br>PubkeyAuthentication yes</pre><p>Then I checked the SSH configuration:</p><pre>sudo sshd -t</pre><p>And verified the effective settings:</p><pre>sudo sshd -T | grep -E \<br>&#39;permitrootlogin|passwordauthentication|pubkeyauthentication&#39;</pre><p>Expected output:</p><pre>permitrootlogin no<br>passwordauthentication no<br>pubkeyauthentication yes</pre><p>Finally, I reloaded SSH:</p><pre>sudo systemctl reload ssh</pre><p>I tested a new SSH connection before closing my existing session.</p><h3>A problem I encountered</h3><p>Ubuntu’s cloud-init configuration already contained an SSH setting that enabled password authentication.</p><p>Simply editing the main SSH configuration was not enough to guarantee the intended setting.</p><p>I investigated the configuration files under:</p><pre>/etc/ssh/sshd_config.d/</pre><p>I then created an earlier-loading configuration file to override the conflicting setting.</p><p><strong>Lesson learned:</strong> Always verify the effective SSH configuration using sshd -T. Don&#39;t assume that editing one configuration file means your settings are active.</p><h3>4. Configuring the Contabo Firewall</h3><p>After securing SSH, I configured the external firewall provided by Contabo.</p><p>I created a firewall policy with the following rules:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AbTRvFG4Z__lP7kbUSqayA.png" /><figcaption>Figure 2. Contabo VPS firewall inbound rules allowing HTTP (port 80), HTTPS (port 443), and SSH (port 22), while blocking all other incoming traffic by default.</figcaption></figure><p>These ports were selected for:</p><ul><li><strong>Port 22:</strong> SSH administration.</li><li><strong>Port 80:</strong> HTTP traffic.</li><li><strong>Port 443:</strong> HTTPS traffic.</li></ul><p>I assigned the firewall to my VPS and tested SSH access again.</p><p>The important point is that the firewall should allow only the services that are actually required.</p><p>The external firewall provides an additional layer of protection before traffic reaches the server.</p><h3>5. Configuring Ubuntu UFW</h3><p>The Contabo firewall provides an external security layer. I also configured the Ubuntu firewall inside the server.</p><p>I used UFW (Uncomplicated Firewall).</p><p>First, I configured the default policies:</p><pre>sudo ufw default deny incoming<br>sudo ufw default allow outgoing</pre><p>Then I allowed the required ports:</p><pre>sudo ufw allow 22/tcp<br>sudo ufw allow 80/tcp<br>sudo ufw allow 443/tcp</pre><p>Finally, I enabled UFW:</p><pre>sudo ufw enable</pre><p>To verify the configuration:</p><pre>sudo ufw status verbose</pre><p>The expected policy was:</p><ul><li>Incoming connections denied by default.</li><li>Outgoing connections allowed by default.</li><li>SSH, HTTP, and HTTPS explicitly allowed.</li></ul><h3>An important Docker consideration</h3><p>During my research, I also learned that Docker-published ports can bypass normal UFW filtering in some configurations.</p><p>This is particularly important when deploying applications through Docker Compose or a deployment platform such as Coolify.</p><p>Therefore, firewall rules need to be considered carefully when publishing Docker container ports.</p><p>I kept the external Contabo firewall as an additional security layer and avoided exposing unnecessary application and administrative ports.</p><p><strong>Lesson learned:</strong> Having UFW enabled does not automatically mean every Docker-published port is protected by the same rules. Always verify actual network exposure.</p><h3>6. Installing and Configuring Fail2ban</h3><p>Even with SSH key authentication, I wanted another layer of protection against repeated authentication attempts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-0-5WWTFaIXq7Ok6MA_WQ.png" /><figcaption>Figure 3. Fail2ban workflow illustrating SSH login monitoring, authentication failure detection, threshold-based IP blocking, and automated firewall protection.</figcaption></figure><p>I installed Fail2ban:</p><pre>sudo apt install fail2ban -y</pre><p>I created a dedicated SSH jail configuration:</p><pre>sudo nano /etc/fail2ban/jail.d/sshd.local</pre><p>Configuration:</p><pre>[sshd]<br>enabled = true<br>backend = systemd<br>maxretry = 5<br>findtime = 10m<br>bantime = 1h</pre><p>This configuration tells Fail2ban to:</p><ul><li>Monitor SSH authentication attempts.</li><li>Allow up to five failed attempts within the configured window.</li><li>Evaluate attempts within a ten-minute period.</li><li>Ban an offending IP address for one hour.</li></ul><p>I enabled and started the service:</p><pre>sudo systemctl enable --now fail2ban</pre><p>To check its status:</p><pre>sudo fail2ban-client status</pre><p>To inspect the SSH jail:</p><pre>sudo fail2ban-client status sshd</pre><p><strong>Lesson learned:</strong> Fail2ban is a useful additional protection layer, but it does not replace SSH hardening or firewall rules.</p><h3>7. Enabling Automatic Security Updates</h3><p>A server needs regular security updates. Manually remembering to update packages is not always reliable.</p><p>I installed unattended-upgrades:</p><pre>sudo apt update<br>sudo apt install unattended-upgrades -y</pre><p>I configured automatic package list updates and unattended upgrades:</p><pre>sudo nano /etc/apt/apt.conf.d/20-auto-upgrades</pre><p>Configuration:</p><pre>APT::Periodic::Update-Package-Lists &quot;1&quot;;<br>APT::Periodic::Unattended-Upgrade &quot;1&quot;;</pre><p>I also checked the update timers:</p><pre>systemctl list-timers | grep apt</pre><p>This helped automate routine package maintenance and security updates.</p><p>Automatic updates are useful, but they do not eliminate the need to monitor updates, review logs, and plan maintenance when necessary.</p><h3>8. Setting the Correct Server Timezone</h3><p>Since I manage the server from Sri Lanka, I configured its timezone accordingly.</p><pre>sudo timedatectl set-timezone Asia/Colombo</pre><p>To verify:</p><pre>timedatectl</pre><p>I also checked that Network Time Protocol (NTP) synchronization was active.</p><p>Correct server time is important for:</p><ul><li>Application logs.</li><li>Scheduled jobs.</li><li>Database timestamps.</li><li>Monitoring.</li><li>Troubleshooting.</li></ul><p>It is a small configuration step, but it makes server administration much easier.</p><h3>9. Configuring Swap Memory</h3><p>My VPS has 8 GB of RAM.</p><p>Although that is sufficient for many small deployments, I wanted a small swap allocation to provide some additional memory headroom.</p><p>I created a 1 GB swap file:</p><pre>sudo fallocate -l 1G /swapfile</pre><p>Then I secured its permissions:</p><pre>sudo chmod 600 /swapfile</pre><p>I formatted and enabled it:</p><pre>sudo mkswap /swapfile<br>sudo swapon /swapfile</pre><p>To make the configuration persistent across reboots, I added the following line to /etc/fstab:</p><pre>/swapfile none swap sw 0 0</pre><p>I also adjusted the kernel memory settings:</p><pre>sudo nano /etc/sysctl.conf</pre><p>Added:</p><pre>vm.swappiness=10<br>vm.vfs_cache_pressure=50</pre><p>Applied the settings:</p><pre>sudo sysctl -p</pre><p>Finally, I checked the memory and swap configuration:</p><pre>free -h<br>swapon --show</pre><p>Swap is not a replacement for physical RAM. It is an additional safety mechanism when memory pressure occurs.</p><p><strong>Lesson learned:</strong> Understand your server’s available resources before deploying multiple applications. Swap can provide some headroom, but it cannot compensate for insufficient RAM.</p><h3>10. Reviewing the Server Before Installing Coolify</h3><p>Before moving to Coolify, I checked the server’s overall condition.</p><p>These were some of the useful commands I used during the verification process.</p><h3>Check the operating system and current user</h3><pre>cat /etc/os-release<br>whoami<br>id</pre><h3>Check SSH</h3><pre>sudo systemctl status ssh</pre><h3>Check effective SSH security</h3><pre>sudo sshd -T | grep -E \<br>&#39;permitrootlogin|passwordauthentication|pubkeyauthentication&#39;</pre><h3>Check open ports</h3><pre>sudo ss -lntup</pre><h3>Check firewall</h3><pre>sudo ufw status verbose</pre><h3>Check memory</h3><pre>free -h</pre><h3>Check storage</h3><pre>df -h</pre><h3>Check available updates</h3><pre>apt list --upgradable</pre><p>At this point, I had completed the basic server hardening process.</p><p>I was finally ready to move on to Docker and Coolify.</p><h3>11. Installing Coolify: An Unexpected Problem</h3><p>My next objective was to install Coolify as the deployment and server management platform.</p><p>One question I had before installation was:</p><p><strong>Do I need to install Docker separately before installing Coolify?</strong></p><p>After checking the official documentation, I confirmed that Coolify’s automated installer can install Docker if it is not already available.</p><p>I used the official installation command:</p><pre>curl -fsSL https://cdn.coollabs.io/coolify/install.sh | sudo bash</pre><p>The installer successfully:</p><ul><li>Installed Docker Engine.</li><li>Configured Docker.</li><li>Downloaded Coolify configuration files.</li><li>Generated the SSH key used for local access.</li></ul><p>However, the installation failed while pulling the Coolify helper image.</p><p>The error was:</p><pre>Failed to pull docker.io/coollabsio/coolify-helper:1.1.3</pre><p>Initially, I investigated whether this was caused by Docker, network connectivity, or firewall restrictions.</p><p>I confirmed that Docker was working:</p><pre>sudo docker pull hello-world</pre><p>I also checked Docker registry connectivity.</p><p>The investigation showed that Docker itself was working. The requested helper image tag was the problem.</p><p>Instead of repeatedly running the installer, I decided to investigate the installation files and logs.</p><h3>12. Troubleshooting the Coolify Image Version</h3><p>One particularly useful file was:</p><pre>/data/coolify/source/upgrade.sh</pre><p>I also inspected the official Coolify version manifest:</p><pre>curl -fsSL https://cdn.coollabs.io/coolify/versions.json | jq .</pre><p>At the time of my investigation, the manifest reported the following stable versions:</p><p>ComponentVersionCoolify4.5.3Helper1.0.19Sentinel1.1.3</p><p>This revealed an important difference: 1.1.3 was the Sentinel version, not the helper version.</p><p>The installer had requested a helper image tagged 1.1.3, but the official version manifest identified 1.0.19 as the helper version.</p><p>I tested the helper image through GitHub Container Registry (GHCR):</p><pre>sudo docker pull ghcr.io/coollabsio/coolify-helper:1.0.19</pre><p>The image downloaded successfully.</p><p>I then inspected the upgrade script to understand its argument order:</p><pre>sudo head -n 25 /data/coolify/source/upgrade.sh</pre><p>After confirming the expected arguments, I ran:</p><pre>sudo bash /data/coolify/source/upgrade.sh \<br>4.5.3 1.0.19 ghcr.io</pre><p>This instructed the upgrade script to use:</p><ul><li>Coolify version 4.5.3.</li><li>Helper version 1.0.19.</li><li>GitHub Container Registry (ghcr.io).</li></ul><p>The upgrade process completed successfully.</p><h3>Verifying the installation</h3><p>I checked the running containers:</p><pre>sudo docker ps -a</pre><p>The result showed:</p><pre>coolify       Up (healthy)<br>coolify-db    Up (healthy)<br>coolify-redis Up (healthy)</pre><p>I also checked the installation log. The final status confirmed:</p><pre>Upgrade completed successfully<br>Version: 4.5.3</pre><p>This was one of the most valuable parts of the experience.</p><p><strong>Lesson learned:</strong> When an installation fails, investigate the actual error before reinstalling everything. Checking official version manifests, logs, image tags, and configuration files can save significant time.</p><h3>13. Accessing Coolify Securely Through an SSH Tunnel</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VT2OEe3eOK4yVZok5zIYhw.png" /><figcaption>Figure 4. MobaXterm local SSH port forwarding configuration for securely accessing a remote VPS service through an encrypted SSH tunnel.</figcaption></figure><p>After Coolify was running, I needed to access its dashboard.</p><p>The application was listening on port 8000, but my firewall rules did not expose that port publicly.</p><p>Rather than opening port 8000 to the entire internet, I used an SSH tunnel through MobaXterm.</p><h3>What is an SSH tunnel?</h3><p>An SSH tunnel creates a secure connection between your local computer and a remote server through SSH.</p><p>In my case, I used local port forwarding.</p><p>The connection worked like this:</p><p><strong>Windows computer → SSH tunnel → Ubuntu VPS → Coolify dashboard</strong></p><p>I configured local port forwarding in MobaXterm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nU3ZMD_6zhTGaBVvCu5rlw.png" /><figcaption>Table 2. SSH local port forwarding configuration used to securely access the VPS-hosted service.</figcaption></figure><p>After starting the tunnel, I could access the dashboard from my Windows browser:</p><pre>http://127.0.0.1:8000</pre><p>The browser connected to my local port, and MobaXterm forwarded the traffic through the encrypted SSH connection to the VPS.</p><p>This allowed me to access Coolify without making its administrative dashboard port publicly accessible.</p><h3>Why use an SSH tunnel?</h3><ul><li>The dashboard port does not need to be exposed publicly.</li><li>Access is protected by SSH authentication.</li><li>It reduces unnecessary internet-facing services.</li><li>It is convenient for initial server administration.</li></ul><p>One limitation is that the tunnel works only while the SSH connection and forwarding session remain active.</p><p><strong>Lesson learned:</strong> Not every administration interface needs to be publicly accessible. SSH tunnelling is a useful approach for securely accessing private server services.</p><h3>14. Final Server Hardening Checklist</h3><p>Here is the checklist I completed before moving into application deployment.</p><h3>Server access and SSH</h3><ul><li>Created a non-root administrative user.</li><li>Configured SSH key-based authentication.</li><li>Protected the private key with a passphrase.</li><li>Disabled root SSH login.</li><li>Disabled password-based SSH authentication.</li><li>Verified effective SSH configuration.</li></ul><h3>Firewall and security</h3><ul><li>Configured the Contabo external firewall.</li><li>Enabled Ubuntu UFW.</li><li>Installed and configured Fail2ban.</li><li>Enabled unattended security updates.</li></ul><h3>Server configuration</h3><ul><li>Configured the Asia/Colombo timezone.</li><li>Enabled NTP synchronization.</li><li>Created a 1 GB swap file.</li><li>Configured kernel memory settings.</li><li>Reviewed server resources and open ports.</li></ul><h3>Docker and Coolify</h3><ul><li>Installed Docker through the Coolify installer.</li><li>Investigated and resolved the helper image version issue.</li><li>Installed Coolify successfully.</li><li>Verified Coolify, PostgreSQL, and Redis health.</li><li>Configured SSH tunnelling for dashboard access.</li></ul><p>Backups and monitoring are still planned as the next stage, before relying on the server for important production workloads.</p><h3>15. What I Learned From This Experience</h3><p>This experience taught me several practical lessons.</p><h3>1. Secure the server before deploying applications</h3><p>Application deployment should not be the first step when preparing a new VPS.</p><p>Start with user permissions, SSH, and firewall configuration. Build a secure foundation before introducing more services.</p><h3>2. Multiple security layers matter</h3><p>Using an external provider firewall together with UFW, SSH key authentication, and Fail2ban provides multiple layers of protection.</p><p>No single security measure is sufficient on its own.</p><h3>3. Always verify configuration changes</h3><p>For example, checking sshd -T helped me identify an SSH configuration conflict that I would otherwise have missed.</p><p>It is important to verify the effective configuration rather than simply assuming a command worked.</p><h3>4. Don’t blindly repeat failed installations</h3><p>The Coolify installation issue was not caused by Docker or network connectivity.</p><p>Inspecting the logs, official version manifest, and image tags helped me identify the version mismatch and find a working installation path.</p><h3>5. Understand what your deployment tools expose</h3><p>Docker and deployment platforms make application deployment easier, but they also introduce additional networking and security considerations.</p><p>Using an SSH tunnel instead of publicly exposing the Coolify dashboard was a useful way to reduce unnecessary internet exposure.</p><h3>6. Server administration is an ongoing process</h3><p>Securing a VPS is not something that can be completed once and forgotten.</p><p>Backups, monitoring, security updates, access reviews, and resource monitoring are all important parts of maintaining a reliable server.</p><h3>16. What’s Next?</h3><p>With Ubuntu secured and Coolify running, the next stage of my learning journey is to prepare the environment for actual application deployments.</p><p>My planned tasks include:</p><ol><li>Configuring custom domains and HTTPS.</li><li>Connecting GitHub repositories.</li><li>Deploying applications using Coolify.</li><li>Configuring development, staging, and production environments.</li><li>Setting up application databases.</li><li>Implementing automated backups.</li><li>Setting up monitoring and alerting.</li><li>Reviewing resource usage and server performance.</li></ol><p>I also want to understand how to manage multiple applications and services efficiently on a single VPS without compromising security or stability.</p><h3>Conclusion</h3><p>What started as a simple plan to install Coolify became a valuable hands-on Linux server administration and DevOps learning experience.</p><p>I now have an Ubuntu VPS with basic security hardening, Docker, and Coolify running successfully.</p><p>More importantly, I have a better understanding of what happens behind the scenes when preparing a server for self-hosted applications.</p><p>If you’re preparing a fresh VPS for your own projects, my recommendation is simple:</p><p><strong>Don’t rush into deployment. Build a secure foundation first.</strong></p><p>You don’t need to understand everything about server administration before starting. But you should be willing to investigate problems, read logs, verify configurations, and learn from each step.</p><p>That is what made this experience valuable to me.</p><p><em>This article documents my personal learning experience and troubleshooting process. The commands and software versions reflect my setup at the time of writing. Always verify current software documentation and adapt firewall and security configurations to your own environment.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f581113f93d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Open-Source Observability Stack for a .NET Application]]></title>
            <link>https://medium.com/@nuwanpkumara128/building-an-open-source-observability-stack-for-a-net-application-20553614b598?source=rss-c8c84c515ea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/20553614b598</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Nuwan Pradeep]]></dc:creator>
            <pubDate>Sat, 08 Aug 2026 07:28:19 GMT</pubDate>
            <atom:updated>2026-08-08T07:28:19.690Z</atom:updated>
            <content:encoded><![CDATA[<p><em>My practical journey with OpenTelemetry, Prometheus, Grafana, Windows Exporter, SQL Exporter, Uptime Kuma, and Docker</em></p><p>An application being up is only the beginning. We also need to know how it is performing.</p><p>Is the application responding slowly?<br>Is the server running out of memory?<br>Is SQL Server becoming a bottleneck?<br>Is an API unavailable?<br>Did something stop working after a server restart?</p><p>These questions led me to explore and build an open-source observability stack for a .NET application.</p><p>The final stack consists of:</p><ul><li><a href="https://opentelemetry.io/"><strong>OpenTelemetry</strong></a> — application metrics</li><li><a href="https://prometheus.io/"><strong>Prometheus</strong></a> — metrics collection and storage</li><li><a href="https://grafana.com/oss/"><strong>Grafana</strong></a> — visualization and dashboards</li><li><a href="https://github.com/prometheus-community/windows_exporter"><strong>Windows Exporter</strong></a> — Windows server metrics</li><li><a href="https://github.com/burningalchemist/sql_exporter"><strong>SQL Exporter</strong></a> — SQL Server metrics</li><li><a href="https://github.com/louislam/uptime-kuma"><strong>Uptime Kuma</strong></a> — availability monitoring</li><li><a href="https://www.docker.com/"><strong>Docker</strong></a> — containerized deployment</li></ul><h3>The Architecture</h3><p>The basic architecture looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HY00TU91hDfaVDa-1PDb_w.png" /><figcaption>The idea is to separate <strong>application monitoring</strong> from <strong>infrastructure monitoring</strong> and <strong>availability monitoring</strong>.</figcaption></figure><h3>1. Starting with OpenTelemetry</h3><p>The first step was monitoring the application itself.</p><p>I integrated OpenTelemetry into the ASP.NET Core application and enabled:</p><pre>builder.Services.AddOpenTelemetry()<br>    .WithMetrics(metrics =&gt;<br>    {<br>        metrics<br>            .AddAspNetCoreInstrumentation()<br>            .AddHttpClientInstrumentation()<br>            .AddRuntimeInstrumentation()<br>            .AddPrometheusExporter();<br>    });</pre><p>This exposed a Prometheus-compatible metrics endpoint:</p><pre>http://localhost:5113/metrics</pre><p>The application started exposing metrics related to:</p><ul><li>HTTP requests</li><li>Request duration</li><li>Active requests</li><li>HTTP client requests</li><li>HTTP client connections</li><li>ASP.NET Core routing</li><li>.NET runtime information</li></ul><p>This was my first important distinction:</p><blockquote><strong><em>Monitoring the application is different from monitoring the server running the application.</em></strong></blockquote><h3>2. Monitoring the Windows Server</h3><p>Next, I needed visibility into the Windows server itself.</p><p>For this, I used <strong>Windows Exporter</strong>.</p><p>The exporter exposes metrics through:</p><pre>http://localhost:9182/metrics</pre><p>Prometheus can then collect information about:</p><ul><li>CPU</li><li>Memory</li><li>Disk</li><li>Network</li><li>Processes</li><li>Windows services</li></ul><p>I installed Windows Exporter as a Windows Service and configured it for <strong>Automatic (Delayed Start)</strong>.</p><p>This means it can start automatically after Windows boots.</p><h3>3. Monitoring SQL Server</h3><p>Application performance is often closely connected to database performance.</p><p>For SQL Server monitoring, I used <strong>SQL Exporter</strong>.</p><p>I created a dedicated monitoring login with the required permissions:</p><pre>CREATE LOGIN prometheus WITH PASSWORD = &#39;StrongPassword123!&#39;;<br><br>USE master;<br><br>CREATE USER prometheus FOR LOGIN prometheus;<br><br>GRANT VIEW SERVER STATE TO prometheus;<br>GRANT VIEW ANY DEFINITION TO prometheus;</pre><p>The exporter was configured to connect through TCP:</p><pre>target:<br>  data_source_name: &quot;sqlserver://prometheus:&lt;password&gt;@127.0.0.1:1433?database=master&quot;</pre><p>It exposes metrics through:</p><pre>http://localhost:9399/metrics</pre><p>Among the metrics available are:</p><ul><li>Active connections</li><li>Deadlocks</li><li>Batch requests</li><li>Buffer cache</li><li>I/O stalls</li><li>SQL Server memory</li><li>Log growth</li><li>Page life expectancy</li></ul><p>One small but useful lesson I learned was that connecting to SQL Server through the <strong>TCP port</strong> was more reliable than trying to resolve the named SQL Server instance.</p><h3>4. Prometheus — Bringing Everything Together</h3><p>Now I had three different sources of metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a7ZdX7ITbqEPCSJgvQtbNA.png" /></figure><p>Prometheus became the central collector.</p><p>It periodically scrapes each /metrics endpoint and stores the resulting time-series data.</p><p>The Prometheus <strong>Targets</strong> page became an important part of the setup because it immediately showed whether each exporter was:</p><p>UP or DOWN</p><p>This made troubleshooting much easier.</p><h3>5. Grafana — Turning Metrics into Dashboards</h3><p>Prometheus is excellent for collecting and querying metrics, but raw PromQL isn’t the best way for a team to monitor a system every day.</p><p>That’s where Grafana comes in.</p><p>I connected Grafana to Prometheus and started exploring community dashboards.</p><p>Windows Server and SQL Server dashboards were relatively easy to find.</p><p>The application side was different.</p><p>I found that many community dashboards expected different metric names from the ones my OpenTelemetry setup was producing.</p><p>For example, my application exposed metrics such as:</p><pre>http_server_request_duration_seconds<br>http_server_active_requests<br>http_client_request_duration_seconds</pre><p>Rather than trying to force an incompatible dashboard to work, I started creating custom Grafana panels.</p><p>For example:</p><p>Requests per second</p><pre>sum(rate(http_server_request_duration_seconds_count[5m]))</pre><p>Active requests</p><pre>sum(http_server_active_requests)</pre><p>Average response time</p><pre>sum(rate(http_server_request_duration_seconds_sum[5m]))<br>/<br>sum(rate(http_server_request_duration_seconds_count[5m]))</pre><p>This approach gives much more control over what the dashboard actually represents.</p><h3>6. Uptime Kuma — Is the Application Actually Available?</h3><p>Metrics answer questions such as:</p><blockquote><em>How many requests are coming in?</em></blockquote><blockquote><em>How long are requests taking?</em></blockquote><p>But there is another simple question:</p><blockquote><strong><em>Can users actually reach the application?</em></strong></blockquote><p>For this, I added Uptime Kuma.</p><p>I configured it to monitor application endpoints and external websites.</p><p>It provides:</p><ul><li>Availability percentage</li><li>Response time</li><li>Downtime history</li><li>Monitor status</li><li>Notifications</li></ul><p>This gives the monitoring stack another layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YhnjyjVFhpXNzvwc8gyWlg.png" /><figcaption>Monitoring Stack Overview</figcaption></figure><h3>7. Moving the Stack to Docker</h3><p>Initially, I tested the components directly on my Windows machine.</p><p>Once everything was working, I moved:</p><p>Prometheus<br>Grafana<br>Uptime Kuma</p><p>into Docker.</p><p>The Docker Compose setup was straightforward:</p><pre>services:<br><br>  prometheus:<br>    image: prom/prometheus:latest<br>    container_name: prometheus<br>    restart: unless-stopped<br>    ports:<br>      - &quot;9090:9090&quot;<br><br>  grafana:<br>    image: grafana/grafana-oss:latest<br>    container_name: grafana<br>    restart: unless-stopped<br>    ports:<br>      - &quot;3000:3000&quot;<br><br>  uptime-kuma:<br>    image: louislam/uptime-kuma:latest<br>    container_name: uptime-kuma<br>    restart: unless-stopped<br>    ports:<br>      - &quot;3001:3001&quot;</pre><p>The exporters remain on the Windows machine because they are responsible for collecting metrics from the Windows host and SQL Server.</p><h3>8. The Docker Networking Lesson</h3><p>One of the most useful problems I encountered happened after moving Prometheus into Docker.</p><p>My original Prometheus configuration contained:</p><pre>http://localhost:5113/metrics</pre><p>It worked perfectly when Prometheus was running directly on Windows.</p><p>But after moving Prometheus into Docker, the target became: DOWN</p><p>The reason was simple.</p><p>Inside a Docker container: “localhost” means <strong>the container itself</strong>.</p><p>It does not mean the Windows host.</p><p>For Docker Desktop, I changed the targets to:</p><pre>http://host.docker.internal:5113/metrics<br>http://host.docker.internal:9182/metrics<br>http://host.docker.internal:9399/metrics</pre><p>The same concept appeared with Grafana.</p><p>Initially, Grafana was configured to connect to:</p><pre>http://localhost:9090</pre><p>But Grafana was also running inside Docker.</p><p>Instead, Grafana should communicate with the Prometheus container using the Docker service name:</p><pre>http://prometheus:9090</pre><p>That was a good practical reminder that:</p><blockquote><strong><em>Moving an application into Docker also means thinking about how networking changes.</em></strong></blockquote><h3>What the Final Stack Looks Like</h3><p>The resulting architecture is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wcFVADhokwWX75FnpDeiA.png" /></figure><h3>What I Learned</h3><p>This project was not just about installing monitoring tools.</p><p>It helped me understand how different observability layers fit together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GBaeiSOawjMQOCI-GWUqcg.png" /></figure><h3>What’s Next?</h3><p>The next step is to move from purely technical metrics toward <strong>application-specific business metrics</strong>.</p><p>For example:</p><pre>Requests<br>Response time<br>Error rate<br>Background job status<br>External API failures<br>Database performance<br>Application availability</pre><p>And eventually, custom application metrics can be added where they provide meaningful operational value.</p><p>The goal isn’t to create hundreds of graphs.</p><p>The goal is to answer important questions quickly:</p><blockquote><strong><em>Is the application healthy?</em></strong></blockquote><blockquote><strong><em>If it isn’t healthy, where is the problem?</em></strong></blockquote><blockquote><strong><em>When did the problem start?</em></strong></blockquote><blockquote><strong><em>Is the problem in the application, server, database, or network?</em></strong></blockquote><h3>Final Thoughts</h3><p>What started as a simple question — <em>“How can I monitor my application?”</em> — turned into a practical exploration of observability.</p><p>The combination of:</p><p><strong>OpenTelemetry + Prometheus + Grafana + Windows Exporter + SQL Exporter + Uptime Kuma + Docker</strong></p><p>provides a powerful open-source foundation without requiring a large commercial monitoring platform.</p><p>The biggest lesson for me was:</p><blockquote><strong><em>Monitoring isn’t about collecting as many metrics as possible. It’s about collecting the right metrics and turning them into information that helps you make better decisions.</em></strong></blockquote><p>This was a great hands-on learning experience in <strong>observability, .NET, Prometheus, Grafana, SQL Server monitoring, Docker, and infrastructure monitoring</strong>.</p><h3>Technologies Used</h3><p>C# · .NET · ASP.NET Core · OpenTelemetry · Prometheus · Grafana · Windows Exporter · SQL Exporter · Uptime Kuma · Docker · SQL Server</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20553614b598" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Browser Sandbox: Building Local Bridge Services for Web Applications]]></title>
            <link>https://medium.com/@nuwanpkumara128/beyond-the-browser-sandbox-building-local-bridge-services-for-web-applications-2b96ef85ba9c?source=rss-c8c84c515ea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b96ef85ba9c</guid>
            <dc:creator><![CDATA[Nuwan Pradeep]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 17:50:31 GMT</pubDate>
            <atom:updated>2026-02-08T17:50:31.517Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uo44DStmG1BSvgCGcPPvcQ.png" /></figure><p>Modern web applications are powerful, fast, and user-friendly.<br> But when it comes to accessing <strong>local hardware </strong>like scanners, printers, barcode readers, or serial devices browsers suddenly hit a wall.</p><p>This article explains <strong>how and why</strong> that happens, and how we can solve it using a <strong>Local Bridge Service</strong> pattern, based on my real experience building a browser-based document scanner.</p><h3>The Browser Security Paradox</h3><p>Browsers are designed to protect users.<br> That protection comes from a <strong>security sandbox</strong> that strictly limits what a website can do.</p><h3>Browsers intentionally block:</h3><ul><li>Direct access to USB devices</li><li>Serial / COM ports</li><li>Printers and scanners</li><li>System files and folders</li><li>Operating system APIs</li></ul><p>This is great for security but painful for real-world business applications.</p><h3>My Real-World Problem</h3><p>I built a <strong>browser-based document scanner</strong>.</p><h3>What I wanted:</h3><ul><li>Scan documents directly from a web app</li><li>No heavy desktop software</li></ul><h3>What I learned:</h3><ul><li>Browsers <strong>cannot talk directly to scanners</strong></li><li>HTTPS introduces <strong>extra security restrictions</strong></li><li>Browser behavior is <strong>not the same across all browsers</strong></li></ul><p>The solution was a <strong>Local Bridge Service</strong>.</p><h3>The Localhost Bridge Pattern</h3><p>Instead of letting the browser talk to hardware directly, we introduce a <strong>local service</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*XCzQm9-sFe_JVNim0tSQ5g.jpeg" /><figcaption>Architecture Diagram</figcaption></figure><h3>Why Browsers Can’t Access Local Hardware</h3><h3>Core reasons:</h3><ol><li><strong>Same-Origin Policy</strong><br> Prevents unsafe cross-site access</li><li><strong>No Native API Access</strong><br> JavaScript cannot call OS-level APIs</li><li><strong>User Safety</strong><br> Prevents malware disguised as websites</li></ol><p>So the browser must talk only through <strong>HTTP / HTTPS / WebSocket</strong>.</p><h3>HTTP vs HTTPS — What I Discovered</h3><p>This part caused the most confusion during development.</p><h3>My test results:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Wf1BV5QZQR_ZTC99BvCSA.png" /></figure><h3>Why this happens</h3><p>When a website runs on <strong>HTTPS</strong>, browsers block calls to <strong>HTTP services</strong>, even on localhost.<br> This is called <strong>Mixed Content Blocking</strong>.</p><p>Most browsers allow exceptions for localhost, but <strong>Brave is stricter by default</strong>.</p><h3>Brave Browser Issue</h3><p>Brave blocks localhost communication more aggressively.</p><h3>Possible solutions:</h3><ol><li>Ask users to <strong>disable Shields for the site</strong></li><li>Run the local service with <strong>HTTPS</strong></li><li>Use <strong>WebSocket (WSS)</strong> instead of fetch</li><li>Provide clear browser compatibility notes</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxnMHSUOO8fuO3nflEqszQ.png" /><figcaption>Browser Compatibility</figcaption></figure><h3>Implementation Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*tgb1KFTjU10dNo9H0Wwyzg.jpeg" /><figcaption>Implementation Architecture</figcaption></figure><h3>Technology Choices</h3><h3>Local Service</h3><ul><li>C# + ASP.NET Core (best for Windows hardware)</li><li>Node.js + Express</li><li>Python + Flask</li><li>Go (single binary, fast)</li></ul><h3>Communication</h3><ul><li>REST API</li><li>WebSocket (recommended for real-time)</li></ul><h3>Security Best Practices</h3><p>✔ Bind service to <strong>localhost only</strong><br> ✔ Use authentication tokens<br> ✔ Validate all inputs<br> ✔ Rate-limit requests<br> ✔ Code-sign executables</p><p>❌ Never expose service to LAN or public IPs</p><h3>Common Challenges &amp; Solutions</h3><h3>Installation friction</h3><ul><li>MSI installer</li><li>Silent install</li><li>Auto-start on boot</li></ul><h3>Antivirus warnings</h3><ul><li>Code signing</li><li>Clear documentation</li></ul><h3>Service crashes</h3><ul><li>Auto-restart</li><li>Health check endpoint</li></ul><h3>When to Use This Pattern</h3><p>Scenario Use Local Bridge?</p><p>Scanner / Printer✅</p><p>Legacy hardware✅</p><p>Serial devices✅</p><p>Simple USB❌ Try Web USB first</p><h3>Future: Native Web APIs vs Local Services</h3><p>Browsers are improving with:</p><ul><li>WebUSB</li><li>Web Serial</li><li>Web Bluetooth</li><li>File System Access</li></ul><p>But <strong>enterprise hardware and legacy devices still need local services</strong>.</p><p>The best approach is <strong>hybrid</strong>:</p><pre>Try Web API → fallback to Local Service</pre><h3>Final Thoughts</h3><p>Local Bridge Services are a <strong>powerful but under-discussed architecture</strong>.</p><p>They allow:</p><ul><li>Hardware access</li><li>Better performance</li><li>Offline processing</li><li>Strong privacy</li></ul><p>If you’re building <strong>serious web applications</strong>, this pattern is worth mastering.</p><h3>Conclusion</h3><p>Browsers are designed to be secure, not powerful system controllers.<br> Trying to force them to access local hardware will only lead to frustration, blocked features, and inconsistent behavior across browsers.</p><p>The <strong>Local Bridge Service</strong> pattern offers a practical and scalable solution.</p><p>By moving hardware access into a small, trusted local service and letting the browser communicate through safe web protocols, we get the best of both worlds:</p><ul><li>Strong browser security</li><li>Full access to local devices</li><li>Better performance and reliability</li><li>Cleaner system architecture</li></ul><p>This approach is already used sometimes quietly in healthcare systems, POS software, logistics platforms, and enterprise tools. It proves that modern web applications <strong>don’t need to be limited</strong> by the browser sandbox.</p><h3>Call to Action</h3><p>If you’re facing browser limitations with:</p><ul><li>Scanners</li><li>Printers</li><li>Barcode readers</li><li>Serial or USB devices</li><li>Legacy hardware</li></ul><p>👉 <strong>Stop fighting the browser. Build a bridge.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b96ef85ba9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Secure .NET 8 API with Clean Architecture and Azure Entra ID]]></title>
            <link>https://medium.com/@nuwanpkumara128/build-a-secure-net-8-api-with-clean-architecture-and-azure-entra-id-1284308d8823?source=rss-c8c84c515ea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1284308d8823</guid>
            <dc:creator><![CDATA[Nuwan Pradeep]]></dc:creator>
            <pubDate>Sat, 06 Sep 2025 03:39:33 GMT</pubDate>
            <atom:updated>2025-09-06T03:39:33.369Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Build a Secure .NET 8 API with Clean Architecture and Azure Entra ID</strong></h3><p>A complete template with authentication, role-based auth, and Swagger support. Avoid common pitfalls like 403 errors and token validation issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEedp9Q41d_B5er7IR4TDg.png" /></figure><p>Clean Architecture and enterprise-grade authentication go hand in hand for building maintainable and secure .NET APIs. This template removes the friction of configuration and gives developers a solid starting point with Azure Entra ID already integrated.</p><p>This guide walks you through a functional template that combines:</p><ul><li><strong>Clean Architecture</strong> principles for maintainability.</li><li><strong>Azure Entra ID</strong> for secure authentication.</li><li><strong>Role-Based Authorization</strong> to control access.</li><li><strong>Swagger UI</strong> with built-in OAuth2 for easy testing.</li></ul><p>You can clone the complete project and use it as a template for your next enterprise API.</p><h3>Architecture Overview</h3><p>The solution is structured into four core projects, ensuring a clear separation of concerns:</p><p>CleanArch.EntraApi/<br>├── Domain/ # Entities &amp; Interfaces<br>├── Application/ # CQRS, MediatR, Business Logic<br>├── Infrastructure/ # DbContext, Azure Entra Setup<br>└── WebApi/ # Controllers, Swagger, Auth</p><h3>Step 1: Configure Azure Entra ID (Azure AD)</h3><p>The first and most critical step is configuring the application in Azure. Missing a single setting here is the root cause of most errors.</p><ol><li><strong>Register a new application</strong> in the <a href="https://portal.azure.com/">Azure Portal</a>.</li><li><strong>Define App Roles</strong>: Under “App roles,” create roles like Admin and User. These must match the roles you use in your [Authorize(Roles=&quot;Admin&quot;)] attributes.</li><li><strong>Set Redirect URIs</strong>: Under “Authentication,” add these exact URIs for local development:https://localhost:&lt;PORT&gt;/signin-oidc, https://localhost:&lt;PORT&gt;/swagger/oauth2-redirect.html</li><li><strong>Enable Implicit Flow</strong>: In the same section, ensure <strong>ID tokens</strong> and <strong>Access tokens</strong> are checked under “Implicit grant and hybrid flows.”</li></ol><h3>Step 2: Implement the Code Structure</h3><p>The key to making this work is precise configuration in the Infrastructure and WebApi layers.</p><p><strong>1. Configure Authentication and Authorization:</strong></p><p>In your ServiceCollectionExtensions.cs file, ensure you correctly set up the authentication and specify the role claim type.</p><pre>services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)<br>    .AddMicrosoftIdentityWebApi(options =&gt;<br>    {<br>        configuration.Bind(AzureAdOptions.SectionName, options);<br>        // This line is crucial for resolving 403 errors<br>        options.TokenValidationParameters.RoleClaimType = &quot;roles&quot;;<br>    }, options =&gt; { configuration.Bind(AzureAdOptions.SectionName, options); });<br><br>services.AddAuthorization(options =&gt;<br>{<br>    options.AddPolicy(&quot;Admin&quot;, policy =&gt; policy.RequireRole(&quot;Admin&quot;));<br>    options.AddPolicy(&quot;User&quot;, policy =&gt; policy.RequireRole(&quot;User&quot;));<br>});</pre><p><strong>2. Set Up Swagger for OAuth2:</strong></p><p>Configure Swagger to use the Implicit flow, which is more straightforward for testing than the Authorization Code flow with PKCE.</p><pre>services.AddSwaggerGen(c =&gt;<br>{<br>    c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo { Title = &quot;CleanArch.EntraApi&quot;, Version = &quot;v1&quot; });<br>    c.AddSecurityDefinition(&quot;oauth2&quot;, new OpenApiSecurityScheme<br>    {<br>        Type = SecuritySchemeType.OAuth2,<br>        Flows = new OpenApiOAuthFlows<br>        {<br>            Implicit = new OpenApiOAuthFlow // Use Implicit flow<br>            {<br>                AuthorizationUrl = new Uri($&quot;{instance}{tenantId}/oauth2/v2.0/authorize&quot;),<br>                Scopes = new Dictionary&lt;string, string&gt; { { scope, &quot;Access API&quot; } }<br>            }<br>        }<br>    });<br>    // Add security requirement<br>    c.AddSecurityRequirement(new OpenApiSecurityRequirement() { ... });<br>});</pre><h3>Step 3: Troubleshoot Common Issues</h3><p>Here are solutions to the most common problems you’ll encounter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ABTuUMU-LucuMjUwA-8DNQ.png" /><figcaption>.NET 8 Web API Authentication Errors with Azure Entra ID</figcaption></figure><h3>Get the Template</h3><p>Instead of building everything from scratch, you can use the complete, pre-configured solution:<br>🔗 <strong>GitHub Repository: </strong><a href="https://github.com/Nuwan128/CleanArch.EntraApi"><strong>CleanArch.EntraApi</strong></a></p><h3>Conclusion</h3><p>By following this structure and configuration, you can build a robust foundation for any .NET API that requires secure authentication. This template handles the complex integration between Azure Entra ID and Clean Architecture, allowing you to focus on developing your application’s unique business logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ycxvzFSBvXqXzr1Ibvn66w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jQcqjGvdNtKZ-m51MO55Wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nxD_8nrG0E7zrg_wP5_3kw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KiReWMWmwRfjV68tJGdaBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBViaWiUYYPT2m0kcKE6SQ.png" /><figcaption><strong>This visual walkthrough showcases the end-to-end authentication flow and secure API interaction within the integrated Swagger UI. From initiating the OAuth2 login with Azure Entra ID to successfully accessing role-protected endpoints, the sequence demonstrates a fully configured and functional .NET 8 Web API. The final screenshot highlights the crucial token claims that enable role-based authorization, ensuring only permitted users can access specific resources.</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1284308d8823" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Deploying a .NET Web API on AWS ECS — My Journey & Lessons Learned]]></title>
            <link>https://medium.com/@nuwanpkumara128/deploying-a-net-web-api-on-aws-ecs-my-journey-lessons-learned-a69ada421b70?source=rss-c8c84c515ea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a69ada421b70</guid>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[web-api-development]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Nuwan Pradeep]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 17:30:36 GMT</pubDate>
            <atom:updated>2025-02-28T17:30:36.373Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Deploying a .NET Web API on AWS ECS — My Journey &amp; Lessons Learned</h3><h3>📌 Introduction</h3><p>Deploying applications to the cloud is an essential skill for modern developers. Recently, I had the opportunity to deploy a <strong>.NET Web API</strong> using <strong>AWS Elastic Container Service (ECS)</strong>, and I want to share my experience. From containerizing the application to handling AWS Secrets Manager and troubleshooting common issues, here’s my step-by-step guide.</p><h3>🔧 Step-by-Step Deployment Process</h3><h3>1️⃣ Building the .NET Web API Docker Image</h3><p>Before deploying to AWS, I first containerized my .NET Web API.</p><p><strong>Steps:</strong></p><ul><li>Create a Dockerfile:</li></ul><pre># See https://aka.ms/customizecontainer for customization details<br><br>FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base<br>USER app<br>WORKDIR /app<br>EXPOSE 8080<br>EXPOSE 8081<br><br>FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build<br>ARG BUILD_CONFIGURATION=Release<br>WORKDIR /src<br><br># Copy project files<br>COPY [&quot;src/MyApp.API/MyApp.API.csproj&quot;, &quot;src/MyApp.API/&quot;]<br>COPY [&quot;src/MyApp.Application/MyApp.Application.csproj&quot;, &quot;src/MyApp.Application/&quot;]<br>COPY [&quot;src/MyApp.Domain/MyApp.Domain.csproj&quot;, &quot;src/MyApp.Domain/&quot;]<br>COPY [&quot;src/MyApp.Infrastructure/MyApp.Infrastructure.csproj&quot;, &quot;src/MyApp.Infrastructure/&quot;]<br><br>RUN dotnet restore &quot;./src/MyApp.API/MyApp.API.csproj&quot;<br>COPY . .<br>WORKDIR &quot;/src/src/MyApp.API&quot;<br>RUN dotnet build &quot;./MyApp.API.csproj&quot; -c $BUILD_CONFIGURATION -o /app/build<br><br>FROM build AS publish<br>ARG BUILD_CONFIGURATION=Release<br>RUN dotnet publish &quot;./MyApp.API.csproj&quot; -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false<br><br>FROM base AS final<br>WORKDIR /app<br>COPY --from=publish /app/publish .<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;MyApp.API.dll&quot;]</pre><ul><li>Build the Docker image:</li></ul><pre>docker build -t my-dotnet-app .</pre><ul><li>Run and test locally:</li></ul><pre>docker run -p 8080:80 my-dotnet-app</pre><h3>2️⃣ Pushing the Image to Amazon ECR (Elastic Container Registry)</h3><p>AWS ECR is a managed container registry for storing and retrieving Docker images.</p><p><strong>Steps:</strong></p><ul><li>Create an ECR repository:</li></ul><pre>aws ecr create-repository --repository-name my-dotnet-app</pre><ul><li>Authenticate Docker with AWS ECR:</li></ul><pre>aws ecr get-login-password | docker login --username AWS --password-stdin &lt;aws_account_id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com</pre><ul><li>Tag and push the image:</li></ul><pre>docker tag my-dotnet-app &lt;aws_account_id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com/my-dotnet-app:latest docker push &lt;aws_account_id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com/my-dotnet-app:latest</pre><h3>3️⃣ Setting Up AWS ECS (Elastic Container Service)</h3><p>AWS ECS allows you to run containers on AWS infrastructure using either EC2 instances or Fargate.</p><p><strong>Steps:</strong></p><ul><li>Create an ECS cluster:</li></ul><pre>aws ecs create-cluster --cluster-name my-dotnet-cluster</pre><ul><li>Define a task definition:</li></ul><pre>{<br>  &quot;family&quot;: &quot;my-dotnet-task&quot;,<br>  &quot;containerDefinitions&quot;: [<br>    {<br>      &quot;name&quot;: &quot;my-dotnet-app&quot;,<br>      &quot;image&quot;: &quot;&lt;aws_account_id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com/my-dotnet-app:latest&quot;,<br>      &quot;memory&quot;: 512,<br>      &quot;cpu&quot;: 256,<br>      &quot;essential&quot;: true,<br>      &quot;portMappings&quot;: [{ &quot;containerPort&quot;: 80, &quot;hostPort&quot;: 80 }]<br>    }<br>  ]<br>}</pre><ul><li>Register the task definition:</li></ul><pre>aws ecs register-task-definition --cli-input-json file://task-definition.json</pre><ul><li>Create an ECS service to run the task:</li></ul><pre>aws ecs create-service --cluster my-dotnet-cluster --service-name my-dotnet-service --task-definition my-dotnet-task --desired-count 1 --launch-type FARGATE</pre><h3>4️⃣ Configuring AWS Secrets Manager for Secure Credentials</h3><p>Instead of hardcoding database credentials, AWS Secrets Manager provides a secure way to store secrets.</p><p><strong>Steps:</strong></p><ul><li>Store a secret in AWS Secrets Manager:</li></ul><pre>aws secretsmanager create-secret --name RDSConnectionStringSecret --secret-string &quot;Server=mydb.xxxx.us-east-1.rds.amazonaws.com;Database=mydb;User=myuser;Password=mypassword;&quot;</pre><ul><li>Retrieve the secret in .NET Web API:</li></ul><pre>var secretName = configuration[&quot;AWS:SecretsManager:RDSConnectionStringSecret&quot;];<br>var region = configuration[&quot;AWS:SecretsManager:Region&quot;];<br><br>var client = new AmazonSecretsManagerClient(RegionEndpoint.GetBySystemName(region));<br>var response = await client.GetSecretValueAsync(new GetSecretValueRequest { SecretId = secretName });<br>var connectionString = response.SecretString;</pre><h3>5️⃣ Deploying &amp; Running the Web API</h3><ul><li>Set up an <strong>Application Load Balancer (ALB)</strong> for traffic routing.</li><li>Configure <strong>Auto Scaling</strong> to handle increased loads.</li><li>Enable <strong>CloudWatch Logs</strong> to monitor logs and troubleshoot issues.</li></ul><h3>💡 Common Errors &amp; Fixes</h3><h3>❌ IAM Permission Issues</h3><p>If your ECS tasks fail due to permission errors, ensure the <strong>ECS Task Execution Role</strong> has the necessary permissions:</p><pre>{<br>  &quot;Effect&quot;: &quot;Allow&quot;,<br>  &quot;Action&quot;: [&quot;secretsmanager:GetSecretValue&quot;],<br>  &quot;Resource&quot;: &quot;*&quot;<br>}</pre><h3>❌ ECS Task Failing Without Clear Logs</h3><p>Ensure the task <strong>logging driver</strong> is set to CloudWatch:</p><pre>&quot;logConfiguration&quot;: {<br>  &quot;logDriver&quot;: &quot;awslogs&quot;,<br>  &quot;options&quot;: {<br>    &quot;awslogs-group&quot;: &quot;my-log-group&quot;,<br>    &quot;awslogs-region&quot;: &quot;us-east-1&quot;,<br>    &quot;awslogs-stream-prefix&quot;: &quot;ecs&quot;<br>  }<br>}</pre><h3>❌ Load Balancer Not Routing Traffic</h3><ul><li>Verify that <strong>health checks</strong> are correctly configured.</li><li>Ensure security groups allow inbound traffic.</li><li>Check ALB target groups for registered tasks.</li></ul><h3>🎯 Lessons Learned &amp; Best Practices</h3><p>✅ <strong>Use AWS Secrets Manager</strong> instead of hardcoding credentials.<br> ✅ <strong>Enable CloudWatch Logs</strong> for better monitoring and debugging.<br> ✅ <strong>Optimize costs</strong> by using <strong>Fargate Spot Instances</strong>.<br> ✅ <strong>Automate deployments</strong> using <strong>CI/CD (GitHub Actions + ECS)</strong>.</p><h3>🚀 Conclusion &amp; What’s Next?</h3><p>Deploying a <strong>.NET Web API on AWS ECS</strong> was an exciting challenge, and I learned valuable lessons along the way. My next step is implementing <strong>CI/CD pipelines</strong> to automate deployments.</p><p>If you found this helpful, drop a comment or share your thoughts! Have you deployed a .NET API on AWS ECS? What challenges did you face? 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a69ada421b70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Successfully Deploy a React App with AWS Amplify: A Beginner’s Tutorial]]></title>
            <link>https://medium.com/@nuwanpkumara128/how-to-successfully-deploy-a-react-app-with-aws-amplify-a-beginners-tutorial-4d8ea94449ec?source=rss-c8c84c515ea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d8ea94449ec</guid>
            <category><![CDATA[aws-amplify]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[cloud-hosting]]></category>
            <category><![CDATA[react-applications]]></category>
            <dc:creator><![CDATA[Nuwan Pradeep]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 19:09:49 GMT</pubDate>
            <atom:updated>2025-01-13T19:09:49.502Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s fast-paced development environment, deploying applications quickly and efficiently is a must-have skill. I recently deployed a React app using AWS Amplify and want to share my experience — the process, the challenges, and the lessons learned along the way.</p><h3>Why AWS Amplify?</h3><p>AWS Amplify is a robust infrastructure designed to simplify hosting full-stack web applications. Its seamless integration with React, effortless setup for CI/CD pipelines, and numerous backend services make it an excellent choice for rapid app deployment.</p><h3>Guide to Deploying a React Application Using AWS Amplify</h3><h4>1. Prepare Your React App</h4><p>Before deployment, ensure your app is production-ready:</p><ul><li>Test it locally to confirm functionality.</li><li>Optimize images and other assets.</li><li>Update dependencies to their latest stable versions.</li></ul><h4>2. Set Up an AWS Amplify Project</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUT48uK2hyoFTIbF53gVkw.png" /><figcaption>AWS Amplify Console — Choose Source Code Provider</figcaption></figure><ol><li>Go to the AWS Amplify console and click on “Get Started” under the “Host Web App” section.</li><li>Connect your Git repository (Amplify supports GitHub, GitLab, Bitbucket, and more).</li><li>Select the repository and branch containing your React app.</li></ol><h4>3. Configure Build Settings</h4><p>Amplify automatically detects your app type and sets up default build settings. However, you can modify the build configuration, such as:</p><ul><li>Adding environment variables.</li><li>Changing build commands if needed.</li></ul><h4>4. Deploy the App</h4><p>Once setup is complete, Amplify will handle the deployment. You’ll receive a unique URL to access your live app. The deployment process is quick, often completing within minutes, depending on the app’s complexity.</p><h4>5. Custom Domain (Optional)</h4><p>To map your custom domain to the app:</p><ul><li>Navigate to the domain settings in the Amplify console.</li><li>Follow the steps to configure and link your domain.</li></ul><h3>Challenges Encountered</h3><p>The process was mostly smooth, but I did face minor challenges:</p><ul><li>Configuring environment variables for different stages (development vs. production).</li><li>Resolving build errors caused by missing dependencies.</li></ul><p>Thankfully, Amplify provides detailed error logs, making it easy to troubleshoot and resolve these issues.</p><h3>Key Takeaways</h3><ol><li><strong>CI/CD Integration</strong>:<br>Amplify’s seamless CI/CD pipeline ensures that every push to your repository automatically builds and deploys the latest version.</li><li><strong>Scalability and Flexibility</strong>:<br>Amplify scales your app effortlessly. You can also add backend services like APIs and databases as your project grows.</li><li><strong>User-Friendly Interface</strong>:<br>The Amplify console is intuitive, making it accessible even for first-time AWS users.</li></ol><h3>Conclusion</h3><p>Deploying my React app with AWS Amplify was a rewarding experience. The CI/CD pipeline, scalability, and user-friendly interface made the process seamless and efficient. If you’re considering hosting your React application, AWS Amplify is definitely worth exploring.</p><h3>Call to Action</h3><p>If you have any questions about the deployment process or encounter any challenges, feel free to reach out. I’d be happy to help!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d8ea94449ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building the Slide Capture Application: Automating Zoom Slide Management for Productivity]]></title>
            <link>https://medium.com/@nuwanpkumara128/building-the-slide-capture-application-automating-zoom-slide-management-for-productivity-d36561e4782b?source=rss-c8c84c515ea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d36561e4782b</guid>
            <category><![CDATA[pdf-automation]]></category>
            <category><![CDATA[zoom-slide-capture]]></category>
            <category><![CDATA[github-release]]></category>
            <category><![CDATA[c-sharp-development]]></category>
            <category><![CDATA[open-source-projects]]></category>
            <dc:creator><![CDATA[Nuwan Pradeep]]></dc:creator>
            <pubDate>Wed, 16 Oct 2024 23:18:10 GMT</pubDate>
            <atom:updated>2024-10-16T23:18:10.001Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>As someone who has spent countless hours in online lectures and meetings, I often found myself needing a simple solution to capture and organize slides from Zoom presentations. While taking screenshots works, it’s neither efficient nor practical, especially for long sessions. This sparked the idea to develop a tool that would automatically capture slides, filter out duplicates, and generate a PDF — all with minimal user input. Thus, the <strong>Slide Capture Application</strong> was born!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*a42aHLzsMx552uK9mOTcSw.png" /><figcaption>Slide Capture Application interface.</figcaption></figure><p>In this article, I want to take you through my journey of developing this open-source project, the technical challenges I faced, and how I leveraged tools like <strong>C# .NET</strong>, <strong>Windows Forms</strong>, and <strong>AI-based image comparison</strong> to bring this idea to life.</p><h3>The Problem: Managing Online Presentation Slides</h3><p>Online learning and virtual meetings have become the new normal. For students, professionals, and educators, taking notes while trying to keep up with presentations can be challenging. Often, by the time you’ve taken your notes, the presenter has moved on to the next slide, leading to missed information. Additionally, manually capturing each slide can be repetitive and inefficient.</p><p>I wanted to create a tool that would not only capture slides automatically but also intelligently recognize and skip duplicates. This would reduce storage waste and ensure only unique slides were saved.</p><h3>The Solution: Slide Capture Application</h3><p>The <strong>Slide Capture Application</strong> is designed to automatically capture, organize, and save presentation slides during Zoom meetings. It allows users to focus on the content rather than on capturing and organizing slides manually.</p><h3>Key Features:</h3><ul><li>📸 <strong>Automated Slide Capture</strong>: No need to press a button for each slide; the app automatically captures slides at regular intervals.</li><li>🔄 <strong>Duplicate Slide Detection</strong>: Using an AI-based comparison algorithm, the app filters out duplicates to optimize storage.</li><li>📝 <strong>One-Click PDF Generation</strong>: After the session, the captured slides are instantly available as a PDF with just one click.</li><li>🔧 <strong>User-Friendly Interface</strong>: With a clean and intuitive interface, it’s easy for anyone to start capturing slides right away.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*5eZkSC_5btnAT_VONazG1g.png" /><figcaption>Slide capture and PDF generation workflow.</figcaption></figure><h3>The Technology Behind It</h3><p>For the development, I chose to work with <strong>C# .NET</strong>, using <strong>Windows Forms</strong> for the UI and <strong>Dependency Injection</strong> for flexibility. I also integrated AI-based slide comparison to detect and ignore duplicate slides.</p><p>Here’s a breakdown of the tech stack:</p><ul><li><strong>C# .NET</strong>: The core functionality, including screen capture and PDF generation, was implemented using C#.</li><li><strong>Windows Forms</strong>: For the user interface, I used Windows Forms to ensure a familiar and easy-to-use experience.</li><li><strong>AI-Based Image Comparison</strong>: I implemented a slide comparison algorithm to check for duplicate slides, optimizing memory usage and performance.</li><li><strong>Dependency Injection</strong>: This pattern helped me maintain clean code and easily extend or modify the application as needed.</li></ul><h3>Overcoming Challenges</h3><p>One of the key challenges was ensuring the app could efficiently differentiate between slides. If a presenter stayed on the same slide for several minutes, I didn’t want multiple copies of the same slide in the final PDF. Implementing AI-based slide comparison solved this issue by detecting even subtle changes between slides.</p><p>Another challenge was balancing performance with accuracy. I had to ensure the app could capture slides without slowing down the user’s system or consuming excessive memory.</p><h3>Open Source and Collaboration</h3><p>Making this project open source was a key part of my vision. I wanted to share this tool with others who might benefit from it and also give back to the developer community. The project is now live on GitHub, where I encourage contributions from anyone interested in improving it further.</p><p>I couldn’t have done this alone, and I’m extremely grateful to my friends who helped along the way. <a href="https://www.linkedin.com/in/subhash-jeewantha-3212a0213/"><strong>Subhash Jeewantha</strong></a> provided invaluable UI support, ensuring the application was easy to use and aesthetically pleasing. My friends <a href="https://www.linkedin.com/in/lakshan-maduka/"><strong>Lakshan Maduka</strong></a> and <a href="https://www.linkedin.com/in/dushmantha-ranathunga/"><strong>Dushmantha Ranathunga</strong></a> played an important role in testing the app, ensuring that it worked smoothly in real-world scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iP9eWZ4JHU2PeauJexrZzQ.png" /><figcaption>Download the application from the GitHub release page.</figcaption></figure><p>You can check out the project here: <a href="https://github.com/Nuwan128/SlideCaptureApplication">GitHub Repository Link</a></p><h3>Future Plans: Zoom Extension?</h3><p>While the Slide Capture Application is a standalone tool for now, I’m considering extending its functionality into a <strong>Zoom extension</strong>. This would allow users to directly capture slides within the Zoom interface, further simplifying the process. I believe this integration could take the app to the next level and make it even more accessible to users who regularly use Zoom for meetings and lectures.</p><h3>Conclusion</h3><p>Developing the Slide Capture Application has been an incredibly rewarding experience. From conceptualizing the idea to implementing AI for slide comparison, I’ve learned a lot and had a chance to collaborate with amazing friends and contributors.</p><p>If you’re someone who frequently attends online presentations and struggles to manage slides and notes, I encourage you to try out the app and share your feedback. It’s open-source, so feel free to contribute or suggest features that could make it even better.</p><p>Thank you for taking the time to read about my journey, and I look forward to seeing how this project evolves with the help of the developer community.</p><p>👉 <strong>Check out the project here</strong>: <a href="https://github.com/Nuwan128/SlideCaptureApplication">GitHub Repository Link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d36561e4782b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Client-Side and Server-Side Validation in ASP.NET MVC with .NET 8]]></title>
            <link>https://medium.com/@nuwanpkumara128/understanding-client-side-and-server-side-validation-in-asp-net-mvc-with-net-8-1bf6dcb37ed6?source=rss-c8c84c515ea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bf6dcb37ed6</guid>
            <dc:creator><![CDATA[Nuwan Pradeep]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 08:39:40 GMT</pubDate>
            <atom:updated>2024-08-11T09:06:37.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Client-Side and Server-Side Validation in ASP.NET MVC with .NET 8</h3><p>When building web applications, it’s essential to ensure that your data is accurate and your users have a seamless experience. Validation is a key part of this process, helping to confirm that the information users provide meets the necessary criteria. In ASP.NET MVC with .NET 8, you can handle validation on both the client side and the server side. we’ll dive into both approaches, discussing their advantages and showing you how to implement them effectively.</p><h3>What is Client-Side Validation?</h3><p>Client-side validation occurs in the user’s browser before the data is sent to the server. This type of validation provides immediate feedback, allowing users to correct errors without needing to reload the page.</p><h3>How It Works</h3><p>When a user fills out a form, the browser checks the input against predefined rules. If the input doesn’t meet the criteria, error messages are displayed instantly, and the form is not submitted until all fields are valid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*1EvqyLyn1Mja_o22GvORDA.png" /><figcaption>A form with client-side validation in action.</figcaption></figure><h3>Implementing Client-Side Validation in ASP.NET MVC</h3><p>ASP.NET MVC offers built-in support for client-side validation using data annotations and unobtrusive JavaScript.</p><pre>public class UserViewModel<br>{<br>    [Required(ErrorMessage = &quot;First Name is required&quot;)]<br>    [StringLength(50, ErrorMessage = &quot;First Name can&#39;t be longer than 50 characters&quot;)]<br>    public string FirstName { get; set; }<br><br>    [Required(ErrorMessage = &quot;Email is required&quot;)]<br>    [EmailAddress(ErrorMessage = &quot;Invalid Email Address&quot;)]<br>    public string Email { get; set; }<br>}</pre><p>In the view, simply include:</p><pre>@model UserViewModel<br><br>&lt;div class=&quot;container mt-5&quot;&gt;<br>    &lt;div class=&quot;row justify-content-center&quot;&gt;<br>        &lt;div class=&quot;col-md-6&quot;&gt;<br>            &lt;div class=&quot;card shadow&quot;&gt;<br>                &lt;div class=&quot;card-header bg-primary text-white&quot;&gt;<br>                    &lt;h4 class=&quot;mb-0&quot;&gt;User Information&lt;/h4&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;card-body&quot;&gt;<br>                    &lt;form id=&quot;userForm&quot; asp-action=&quot;SubmitForm&quot;&gt;<br>                        &lt;div class=&quot;mb-3&quot;&gt;<br>                            &lt;label for=&quot;firstName&quot; class=&quot;form-label&quot;&gt;First Name&lt;/label&gt;<br>                            &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;firstName&quot; asp-for=&quot;FirstName&quot; placeholder=&quot;Enter your first name&quot; /&gt;<br>                            &lt;span asp-validation-for=&quot;FirstName&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;<br>                        &lt;/div&gt;<br>                        &lt;div class=&quot;mb-3&quot;&gt;<br>                            &lt;label for=&quot;email&quot; class=&quot;form-label&quot;&gt;Email&lt;/label&gt;<br>                            &lt;input type=&quot;email&quot; class=&quot;form-control&quot; id=&quot;email&quot; asp-for=&quot;Email&quot; placeholder=&quot;Enter your email address&quot; /&gt;<br>                            &lt;span asp-validation-for=&quot;Email&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;<br>                        &lt;/div&gt;<br>                        &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary w-100&quot;&gt;Submit&lt;/button&gt;<br>                    &lt;/form&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;<br><br>@section Scripts {<br>    @{<br>        await Html.RenderPartialAsync(&quot;_ValidationScriptsPartial&quot;);<br>    }<br>}</pre><h3>Benefits of Client-Side Validation</h3><ul><li><strong>Instant Feedback</strong>: Users receive immediate notifications about errors.</li><li><strong>Reduced Server Load</strong>: Validating on the client side reduces unnecessary server requests.</li><li><strong>Improved User Experience</strong>: The form feels more responsive, enhancing the overall user experience.</li></ul><h3>What is Server-Side Validation?</h3><p>Server-side validation occurs after the data has been submitted to the server. This ensures that no malicious or incorrect data bypasses the client-side validation and reaches your application.</p><h3>How It Works</h3><p>Once the user submits the form, the data is sent to the server, where it is validated against business rules. If the data is invalid, error messages are sent back to the client, and the user is prompted to correct their input.</p><h3>Implementing Server-Side Validation in ASP.NET MVC</h3><p>Server-side validation is handled in the controller. Here’s how you can validate the data model:</p><pre>public class UserController : Controller<br>{<br>    public IActionResult Index()<br>    {<br>        return View();<br>    }<br><br>    [HttpPost]<br>    public IActionResult SubmitForm(UserViewModel model)<br>    {<br>        if (ModelState.IsValid)<br>        {<br>            return RedirectToAction(&quot;Success&quot;);<br>        }<br>        return View(model);<br>    }<br><br>    public IActionResult Success()<br>    {<br>        return View();<br>    }<br>}</pre><p>This ensures that even if a user bypasses client-side validation, the server will catch any invalid data.</p><h3>Benefits of Server-Side Validation</h3><ul><li><strong>Security</strong>: Protects your application from malicious data that could bypass client-side validation.</li><li><strong>Consistency</strong>: Ensures data is validated according to the same rules as on the client side, preventing discrepancies.</li><li><strong>Robustness</strong>: Even if JavaScript is disabled on the client side, the server will still validate the data.</li></ul><h3>Combining Client-Side and Server-Side Validation</h3><p>For the best user experience and security, it’s recommended to use both client-side and server-side validation. Client-side validation provides a smooth experience with instant feedback, while server-side validation ensures that all data is validated securely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*i1LaUJ7dfETBa2G8WtBKUg.png" /><figcaption>Combined Validation Flow</figcaption></figure><h3>Best Practices</h3><ul><li><strong>Always Validate on the Server</strong>: Never rely solely on client-side validation for critical checks.</li><li><strong>Use Data Annotations</strong>: They make it easy to enforce validation rules consistently across both client and server sides.</li><li><strong>Provide Clear Error Messages</strong>: Help users understand what went wrong and how to fix it.</li></ul><h3>Conclusion</h3><p>Validation is a crucial part of building secure and user-friendly web applications. By implementing both client-side and server-side validation in ASP.NET MVC with .NET 8, you can ensure that your application provides a great user experience while protecting against invalid or malicious data.</p><p><strong>Example Repository</strong><br>For a complete example that combines both client-side and server-side validation, check out this <a href="https://github.com/Nuwan128/aspnet-mvc-validation-example">GitHub repository</a>. This repository includes a sample project demonstrating the concepts discussed in this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bf6dcb37ed6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>