Saturday, April 12, 2025

Unified Modeling Language (UML)

Unified Modeling Language (UML) is a visual language used to model the structure and behavior of software systems. It's like a blueprint for designing, understanding, and documenting systems—especially object-oriented systems.

UML helps you draw diagrams that describe what your system looks like and how it behaves, so you can plan it better and explain it clearly.

Why Use UML?

  • To visualize how your system is organized
  • To communicate ideas between team members
  • To design before coding
  • To document systems for future maintenance


Types of UML Diagrams

UML has 2 main categories:

1. Structural Diagrams – What the system is (static)

  • Class Diagram: shows classes, their properties, methods, and relationships
  • Object Diagram: a snapshot of objects and their values at a point in time
  • Component Diagram: how parts/modules of a system are wired
  • Deployment Diagram: how software runs on hardware (e.g., servers, devices)

2. Behavioral Diagrams – What the system does (dynamic)

  • Use Case Diagram: shows user interactions with the system
  • Sequence Diagram: shows how objects exchange messages over time
  • Activity Diagram: flowchart of tasks or logic
  • State Diagram: how an object changes state in response to events

Example

Say you're building an online shopping app.

  • A Use Case Diagram might show:
    Customer → [Place Order] → [Track Order] → [Make Payment]
  • A Class Diagram might have:
    Customer, Order, Payment, with relationships like Customer has many Orders
  • A Sequence Diagram might show:
    Customer → OrderService → PaymentGateway → EmailService to visualize the flow when placing an order.

Benefits of Using UML

  • Improved Communication:
    UML provides a standardized language that bridges the gap between technical and non-technical stakeholders, ensuring everyone is on the same page regarding system design and requirements.
  • Documentation:
    It offers a way to document system architecture and design decisions, facilitating maintenance and future enhancements.
  • Design Validation:
    By visualizing system structures and behaviors, UML helps in validating that the design aligns with business requirements and can reveal potential issues early in the development process.
  • Facilitates Development:
    UML diagrams can serve as blueprints during the coding phase, improving clarity and consistency in implementation.

Practical Application

While UML is comprehensive, its use depends on the size and complexity of the project. For large, complex systems, UML diagrams can be invaluable for planning and communication. In contrast, for smaller or less complex projects, lightweight modeling might suffice, and overuse of detailed UML diagrams might be unnecessary.

In summary, UML is a powerful toolkit for modeling systems, serving as a bridge between theoretical design and practical implementation, and remains an important part of best practices in software architecture and design.



Domain Driven Design (DDD)

Domain-Driven Design (DDD) is a software design approach that focuses on modeling software based on the core business domain and its rules, rather than just technical concerns. It helps developers build software that's aligned closely with how the business actually works.

"Let the business drive the design."
Model your software structure and behavior around the business domain, using a shared language between developers and domain experts.

Key Concepts 

1. Domain

  • The subject area your app is built for (e.g., banking, healthcare, logistics).

2. Entities

  • Objects with a distinct identity that runs through time and different states.
  • Example: Customer, Order

3. Value Objects

  • Objects that have no identity and are defined only by their values.
  • Example: Money, DateRange, Address

4. Aggregates

  • A cluster of domain objects treated as a single unit.
  • One entity is the aggregate root.
  • Example: Order (root) → contains OrderLines (value objects)

5. Repositories

  • Provide access to aggregates from a data store.
  • Encapsulate the logic to fetch and store entities.

6. Services

  • Used when behavior doesn’t naturally fit into an entity or value object.
  • Example: CurrencyConversionService

7. Domain Events

  • Captures things that happen within the domain.
  • Example: OrderPlaced, PaymentReceived

8. Ubiquitous Language

  • A common language used by both developers and domain experts.
  • Used in code, documentation, conversations, and tests.

It’s a shared vocabulary used by developers, domain experts, QA, PMs—basically, everyone working on a project—to describe the domain and its behavior.

The goal is to eliminate miscommunication between tech and business by making sure everyone speaks the same language—literally.

Example

Let’s say you’re working on a loan approval system. Business experts might talk like this:

    • “A loan application can be either approved or rejected.”
    • “Every applicant needs a credit score and income verification.”
    • “We send a risk assessment before final approval.”

With DDD and Ubiquitous Language:

    • Your class is called LoanApplication, not FormData.
    • You have a method Approve() not SetStatus("A").
    • There’s a service called RiskAssessmentService.
    • You model CreditScore as a value object. 

Good Ubiquitous Language:

    • Comes directly from conversations with domain experts
    • Is used in code (classes, method names, events, variables) 
    • Is used in documentation, tests, and discussions 
    • Avoids technical jargon unless it’s part of the domain 

Saturday, April 5, 2025

Web API | Json Web Token - JWT

Creating JWT -

  1. Import “Microsoft.AspNetCore.Authentication.JwtBearer” package from Nuget. 
  2. Select the algorithm. like HMACSHA256. 
  3. Creating the claims collection. Remember there are standard claims and you can add your own. 
  4. Create credentials object using algo and secret key.
  5. Generate token using claims and credentials.
  6. Add [Authorize] attribute to controller, then action methods of this controller will be authorized. 
JWT token has this format: Header.payload.signature
Header: Contains algorithm used to create JWT like HSA256
Payload: Contains information related to user and authentication
Signature: Created using Header and payload

JWT is encoded not encrypted, so never put critical information in it.



Validating JWT at Application


Validating JWT token in middleware



Refresh Token: This is sent by server along with jwt, when jwt expired client sends this refresh token to server and server generate new JWT and refresh token and sends to client.
Benefit of refresh token is that again and again client no need to send user credentials.

Storing JWT at client end:
In-memory: Using the application variable we can store the token when the application is running. this is for application session only.
Cookie: If you want to store beyond application session(log time). cookie is a good place.
Indexed DB, Session storage and local storage are prone to XSS attacks.
Create cookie using HTTP only. By doing so this cookie can not be read using JavaScript “document.cookie”. In other words cookie is safe from XSS attacks.


Below could be third party Google, amazon, facebook or self owned services -

Open Id: Used for authentication, you want to just know if the user exists in the system in or not. Like shopping sites , mobile applications , single sign on etc. 
OAUTH: Used for authorization, when third party application tries to access resources. 
Open ID Connect: Used for authentication plus authorization both, when you want to authenticate and authorize as well like intranet websites.

Identity Server: This is a free open source server that you can use to implement Open Id Connect and Auth. It is certified by OpenId Foundation.
Single Sign on: Organizations those use single sign on, they redirects requests to their Identity server from each of their web portals, user get authenticated get token from Identity server and can access the web portals.
Identity server could a third party like Okta.


Web API | Roles Vs Claims

 



Web API Facts

Web Api is REST based service on web works on http or https.

REST - Representational State Transfer 

Facts 

Rest Facts

  1. Client-Server model: Its client server model but there is no coupling, completely decoupled model.
  2. Statelessness: Web API is rest based service, is request has complete information to serve, there is no state management.
  3. Catchability: Data can be cached for better performance.
  4. Layered system: There might be multiple layers at service end, client doesn't need to care about it. When client calling an endpoint, that might be an intermediate endpoint.
  5. Uniform Interface - 
    • Unique identification
    • Resource manipulation through representation
    • Self descriptive message


Facts About Web API

  1. Web API controller inherit ControllerBase class while MVC controller inherits Controller class.
  2. Web API returns only data while MVC controller can return view or partial view as well.
  3. What is content Negotiation?
    Web API can return data format based on "Accept" request header.


  4. Web API Vs WCF



WCF Rest Vs WA Rest: Web API built for Rest only from start, while Rest is added with WCF later.

.Net Core | Web API Basics

Web API is REST based web service.

Why Web API?
  1. Reuse logic for internal application
  2. Reuse logic for external application
  3. Separation of concerns
  4. Security 
  5. Environment of multiple teams 

*DI is not only limited to controllers, any class implements injected interface can use them.
*Web application and Web API both can use same classes in .Net Core.

Some Facts to be noted about ASP.Net Core Web API:
  1. Attribute Routing: Actions automatically called without mentioning action name as routes mentioned above actions.

    [Route("api/[controller]")]
        [ApiController]
        public class ValuesController : ControllerBase
        {
            // GET api/values
            [HttpGet]
            public ActionResult<IEnumerable<string>> Get()
            {
                return new string[] { "value1", "value2" };
            }

            // GET api/values/5
            [HttpGet("{id}")]
            public ActionResult<string> Get(int id)
            {
                return "value";
            }

            // POST api/values
            [HttpPost]
            public void Post([FromBody] string value)
            {
            }

            // PUT api/values/5
            [HttpPut("{id}")]
            public void Put(int id, [FromBody] string value)
            {
            }

            // DELETE api/values/5
            [HttpDelete("{id}")]
            public void Delete(int id)
            {
            }
        }
     
  2. Automatic Model validation: Posted model validated automatically no need to write any code. In case of any issue in validation, it returns with 400.
  3. Binding Source Attributes: 
    1. [FromBody]
    2. [FromForm]
    3. [FromQuery]
    4. [FromHeader]
    5. [FromRoute]
    6. [FromServices]

      // POST api/values
      [HttpPost]
      public void Post([FromBody] string value)
      {
      }
  4. Core Web API supports only Json in response, even if you request some other format type in request header.

    If you want to use XML format in request and response than 
    • You need to install below package from nuget.
      Microsoft.ASPNetCore.Mvc.Formatters.xml
    • Add AddXmlSerializerFormatters() method with AddMvc()
      public void ConfigureServices(IServiceCollection services)
              {
                  services.AddMvc()
                      .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                      .AddXmlSerializerFormatters();
              } 
  5. HttpClient is the class to call and use WebAPI from .Net classes.
  6. Calling WebAPI using client side script

    Add a new item

    function addItem() {
      const item = {
        name: $("#add-name").val(),
        isComplete: false
      };

      $.ajax({
        type: "POST",
        accepts: "application/json",
        url: uri,
        contentType: "application/json",
        data: JSON.stringify(item),
        error: function(jqXHR, textStatus, errorThrown) {
          alert("Something went wrong!");
        },
        success: function(result) {
          getData();
          $("#add-name").val("");
        }
      });
    }

    Update an exiting item 
    $.ajax({
      url: uri + "/" + $("#edit-id").val(),
      type: "PUT",
      accepts: "application/json",
      contentType: "application/json",
      data: JSON.stringify(item),
      success: function(result) {
        getData();
      }
    });

    Delete an item
    $.ajax({
      url: uri + "/" + id,
      type: "DELETE",
      success: function(result) {
        getData();
      }
    });

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...