Posts

Behavioral Design Patterns

Behavioral Design Patterns (C# / .NET) Definition Focus on communication between objects Defines how objects interact and share responsibilities Purpose Improve communication flow Reduce tight coupling between objects Make behavior dynamic and flexible Encapsulate business logic Types with Real-Time Usage 1. Strategy Pattern Idea: Change behavior at runtime Real Scenario: Tax / Discount calculation in invoice public interface ITaxStrategy { decimal Calculate(decimal amount); } public class GstTax : ITaxStrategy { public decimal Calculate(decimal amount) => amount * 0.18m; } public class NoTax : ITaxStrategy { public decimal Calculate(decimal amount) => 0; } public class InvoiceService { private readonly ITaxStrategy _tax; public InvoiceService(ITaxStrategy tax) { _tax = tax; } public decimal GetTotal(decimal amount) { return amount + _tax.C...

Structural Design Patterns

Structural Design Patterns (C# / .NET) Definition Focus on how classes and objects are structured Helps in connecting different parts of a system Purpose Simplify complex structures Improve code organization Enable flexible relationships between objects Make systems easier to extend Types with Real-Time Usage 1. Adapter Pattern Idea: Converts one interface into another (compatibility layer) Real Scenario: Integrating 3rd-party API into your system public interface IPayment { void Pay(); } // Third-party service public class ThirdPartyPayment { public void MakePayment() { Console.WriteLine("Paid via third-party"); } } // Adapter public class PaymentAdapter : IPayment { private readonly ThirdPartyPayment _thirdParty; public PaymentAdapter(ThirdPartyPayment thirdParty) { _thirdParty = thirdParty; } public void Pay() { _thirdPart...

Creational Design Pattern (C# / .NET)

Creational Design Pattern (C# / .NET) Definition Focuses on how objects are created Hides object creation logic instead of using new directly Provides flexible and reusable object creation Types of Creational Patterns 1. Singleton Only one instance exists in entire app Example: Logging, Configuration 2. Factory Method Creates objects without exposing creation logic Example: Payment types, Report generation 3. Abstract Factory Creates families of related objects Example: UI themes (Dark theme → buttons, inputs, etc.) 4. Builder Builds complex objects step by step Example: Invoice with multiple fields 5. Prototype Creates object by cloning existing object Example: Copy invoice template Pros Loose coupling (no direct new ) Better code reuse Flexible object creation Easier testing Scalable architecture Cons ...

Design Pattern

Design Pattern (C# / Software Development) Definition: Reusable solution to common software design problems Not actual code → it's a template / approach Helps structure code in a clean, maintainable way Purpose Solve recurring design problems Improve code reusability & maintainability Provide standard best practices Reduce code complexity Improve communication between developers Pros Reusable solutions (no need to reinvent) Cleaner architecture Easier maintenance & scalability Improves readability Follows SOLID principles Helps in large enterprise apps (like .NET Core APIs) Cons Over-engineering for small apps Increases initial complexity Learning curve (many patterns) Wrong usage can make code worse Adds extra abstraction layers Types of Design Patterns (C# / .NET) 1. Creational Patterns Definition: Deal with object c...

🔐 Security in .NET: Preventing XSS (Cross-Site Scripting)

Modern web applications must treat user input as untrusted . One of the most common vulnerabilities developers face is XSS (Cross-Site Scripting) . If not handled properly, attackers can inject malicious JavaScript into your application to: Steal session cookies Impersonate users Modify UI content Execute unauthorized actions Redirect users to malicious websites In this article, we will explore: ✔ What XSS is ✔ Why Regex-based protection fails ✔ Professional solution using HtmlSanitizer in .NET ✔ Automatic protection using JsonConverter 1️⃣ What is XSS (Cross-Site Scripting)? XSS (Cross-Site Scripting) is a security vulnerability where attackers inject malicious scripts into webpages or APIs. These scripts execute in the browser of other users without their knowledge. The Attack Example Imagine a Product API where users submit a product description. Normal Input A nice blue shirt. Malicious Input <script> fetch('https://hacker.com/...

🛡️ Security in .NET: Content Security Policy (CSP)

While input sanitization protects your database, Content Security Policy (CSP) acts as your application's "Bodyguard" in the browser. Even if a malicious script bypasses validation filters, CSP instructs the browser: Do not execute this script. In this guide, we implement a production-ready Security Middleware that includes: Content Security Policy (CSP) HTTP Strict Transport Security (HSTS) Cross-Origin Isolation headers Swagger compatibility 1️⃣ Why CSP is Mandatory Modern XSS attacks are highly sophisticated. Attackers may attempt to: Inject malicious inline <script> tags Load malicious JavaScript from external domains Execute dynamic code using eval() Inject scripts through compromised third-party libraries A Content Security Policy is an HTTP response header that tells browsers which resources are trusted and allowed to execute. By blocking inline scripts and restricting resource origins, CSP significantly reduces the...

🏗️ Consistent API Architecture: The Unified Response & Exception Wrapper

In a professional API, consistency is one of the most valuable architectural principles. If your frontend has to handle different JSON structures for each endpoint — and different formats for errors — your codebase quickly becomes difficult to maintain and error-prone. By implementing a Unified Response Wrapper , we ensure every request follows a predictable response structure — whether the result is: 200 OK 400 Bad Request 404 Not Found 500 Internal Server Error All responses are wrapped inside a standardized JSON "Envelope Pattern" . 📜 Standardized Response Contract Every response from the API follows a strict JSON schema. ✅ Success Response { "success": true, "traceId": "0HMNK92L8S1A", "data": { "id": 1, "name": "Blue Shirt" } } ❌ Error Response { "success": false, "traceId": "0HMNK92L8S1A", "error": { ...