Skip to main content

๐Ÿš€Master User Authentication in .NET 8 Web API Email Confirmation, Password Reset, 2FA & Lockout with JWT & Identity๐Ÿ”

Part 3️⃣ - Order API |๐Ÿ›’ Build .NET 8 eCommerce Microservice ๐Ÿš€with API Gateway, Rate Limiting, Caching & more ๐Ÿงบ

Domain Layer

Order Entity

The Order entity represents an order within the e-commerce system. It captures essential details related to a customer's purchase and is a core component of the Order API.

Properties

  • Id:

    • Type: int
    • Description: Unique identifier for the order. This serves as the primary key in the database.
  • ProductId:

    • Type: int
    • Description: Identifier for the product associated with the order. This links the order to a specific product in the Product API.
  • ClientId:

    • Type: int
    • Description: Identifier for the client who placed the order. This associates the order with a specific customer.
  • PurchaseQuantity:

    • Type: int
    • Description: The quantity of the product purchased in the order.
  • OrderedDate:

    • Type: DateTime
    • Description: The date and time when the order was placed. Defaults to the current UTC time when the order is created.

Summary

The Order entity is a crucial part of the Order API, encapsulating the data required to manage and process customer orders. It links to both product and client information and tracks the quantity and timing of purchases, providing a comprehensive record of each transaction.


Application Layer

AppUserDTO

The AppUserDTO is a Data Transfer Object (DTO) used to encapsulate user-related data for the Order API. It is designed to facilitate the transfer of user information between different layers of the application, particularly for user management and authentication processes.

Properties

  • Id:

    • Type: int
    • Description: Unique identifier for the user. This serves as the primary key in the system.
  • Name:

    • Type: string
    • Description: The full name of the user. This property is required.
  • TelephoneNumber:

    • Type: string
    • Description: The contact telephone number of the user. This property is required.
  • Address:

    • Type: string
    • Description: The residential address of the user. This property is required.
  • Email:

    • Type: string
    • Description: The email address of the user. This property is required and must be a valid email address.
  • Password:

    • Type: string
    • Description: The password for the user account. This property is required.
  • Role:

    • Type: string
    • Description: The role assigned to the user, which determines their permissions and access levels. This property is required.

Summary

The AppUserDTO record is essential for representing user data in a structured format. It ensures that user information is accurately validated and transferred between different parts of the Order API, supporting operations such as user registration and authentication. Each property is annotated to enforce validation rules and ensure data integrity.

OrderDetailsDTO

The OrderDetailsDTO is a Data Transfer Object (DTO) used to represent detailed information about an order within the Order API. It is designed to encapsulate all relevant order details, facilitating data transfer and management operations.

Properties

  • OrderId:

    • Type: int
    • Description: Unique identifier for the order. This property is required.
  • ProductId:

    • Type: int
    • Description: Identifier for the product associated with the order. This property is required.
  • Client:

    • Type: int
    • Description: Identifier for the client who placed the order. This property is required.
  • Name:

    • Type: string
    • Description: The name of the client. This property is required.
  • Email:

    • Type: string
    • Description: The email address of the client. This property is required and must be a valid email address.
  • Address:

    • Type: string
    • Description: The residential address of the client. This property is required.
  • TelephoneNumber:

    • Type: string
    • Description: The contact telephone number of the client. This property is required.
  • ProductName:

    • Type: string
    • Description: The name of the product being ordered. This property is required.
  • PurchaseQuantity:

    • Type: int
    • Description: The quantity of the product ordered. This property is required.
  • UnitPrice:

    • Type: decimal
    • Description: The price per unit of the product. This property is required and is formatted as currency.
  • TotalPrice:

    • Type: decimal
    • Description: The total price of the order, calculated as the unit price multiplied by the quantity. This property is required and is formatted as currency.
  • OrderedDate:

    • Type: DateTime
    • Description: The date and time when the order was placed. This property is required.

Summary

The OrderDetailsDTO record provides a comprehensive representation of order details, capturing all necessary information for processing and displaying orders. It includes client information, product details, pricing, and timestamps, ensuring a complete view of each order's context and data.


OrderDTO

The OrderDTO is a Data Transfer Object (DTO) used to encapsulate the basic details of an order within the Order API. It is designed for transferring order information between different parts of the application, particularly for operations involving order creation, updating, and retrieval.

Properties

  • Id:

    • Type: int
    • Description: Unique identifier for the order. This property is optional, often used for existing orders where the ID is already assigned.
  • ProductId:

    • Type: int
    • Description: Identifier for the product associated with the order. This property is required and must be greater than 0.
  • ClientId:

    • Type: int
    • Description: Identifier for the client who placed the order. This property is required and must be greater than 0.
  • PurchaseQuantity:

    • Type: int
    • Description: The quantity of the product ordered. This property is required and must be greater than 0.
  • OrderedDate:

    • Type: DateTime
    • Description: The date and time when the order was placed. This property is optional and can be omitted if not needed.

Summary

The OrderDTO record provides a simplified view of order data, focusing on the essential attributes necessary for order management processes. It ensures that the data transferred between different parts of the system is validated for correctness, particularly for product, client, and quantity details.


ProductDTO

The ProductDTO is a Data Transfer Object (DTO) used to represent the essential details of a product within the Order API. It is designed for transferring product information between different layers of the application, supporting operations such as product listing, creation, and updates.

Properties

  • Id:

    • Type: int
    • Description: Unique identifier for the product. This property is typically used for referencing specific products and is essential for operations involving existing products.
  • Name:

    • Type: string
    • Description: The name of the product. This property is required and should clearly describe the product.
  • Quantity:

    • Type: int
    • Description: The available quantity of the product. This property is required and must be greater than 0, representing the stock level of the product.
  • Price:

    • Type: decimal
    • Description: The price of the product. This property is required and is formatted as currency, reflecting the cost of one unit of the product.

Summary

The ProductDTO record provides a structured way to represent product information, ensuring that essential attributes such as ID, name, quantity, and price are consistently handled across the system. It facilitates data transfer and management for various product-related operations within the Order API.


IOrder Interface

The IOrder interface defines the contract for the order management operations within the Order API. It extends from the IGenericInterface<T> to inherit common data access methods while introducing specific functionality related to orders.

Key Methods

  • GetOrdersAsync
    • Parameters:
      • Expression<Func<Order, bool>> predicate: An expression used to filter orders based on specific criteria.
    • Returns: Task<IEnumerable<Order>>
    • Description: Asynchronously retrieves a collection of orders that match the provided filter criteria. This method allows for flexible querying of order data, enabling various search and retrieval operations based on the specified predicate.

Summary

The IOrder interface is essential for defining and implementing order-related operations within the Order API. By extending the IGenericInterface<Order>, it provides a foundation for generic data access methods while adding custom functionality to support the retrieval of orders with specific filtering criteria. This interface ensures a consistent approach to managing order data and enables efficient querying and manipulation of orders within the application.


IOrderService Interface

The IOrderService interface defines the contract for services related to order management within the Order API. It provides methods for retrieving order data, tailored to specific business needs.

Key Methods

  • GetOrdersByClientId

    • Parameters:
      • int clientId: The unique identifier for the client whose orders are to be retrieved.
    • Returns: Task<IEnumerable<OrderDTO>>
    • Description: Asynchronously retrieves a collection of orders placed by a specific client. This method returns a list of OrderDTO objects, each representing an order associated with the given client ID.
  • GetOrderDetails

    • Parameters:
      • int orderId: The unique identifier for the order whose details are to be fetched.
    • Returns: Task<OrderDetailsDTO>
    • Description: Asynchronously retrieves detailed information about a specific order. This method returns an OrderDetailsDTO object, which includes comprehensive details about the order, such as client information, product details, and pricing.

Summary

The IOrderService interface is crucial for handling order-related operations within the Order API. It provides a clear contract for retrieving order information, including both summary and detailed data. By defining these methods, the interface ensures that order management services can efficiently provide the necessary data for various business processes and client interactions.


OrderService Class

The OrderService class implements the IOrderService interface, providing services for managing and retrieving order-related information within the Order API. It integrates with external services and utilizes resilience strategies to ensure robust data access.

Key Methods

  • GetProduct

    • Parameters:
      • int productId: The unique identifier for the product to retrieve.
    • Returns: Task<ProductDTO>
    • Description: Asynchronously fetches product details from the Product API through the API Gateway. This method handles HTTP requests and deserializes the response into a ProductDTO. If the request fails, it returns a null object.
  • GetUser

    • Parameters:
      • int userId: The unique identifier for the user to retrieve.
    • Returns: Task<AppUserDTO>
    • Description: Asynchronously retrieves user details from the Product API (intended to be the User API in actual implementation) using the API Gateway. It processes the HTTP response and converts it into an AppUserDTO. If the request fails, it returns a null object.
  • GetOrderDetails

    • Parameters:
      • int orderId: The unique identifier for the order to retrieve details.
    • Returns: Task<OrderDetailsDTO>
    • Description: Asynchronously fetches detailed information about an order. It retrieves the order entity, then uses a resilience pipeline to retry fetching associated product and user details. It compiles all data into an OrderDetailsDTO for comprehensive order information.
  • GetOrdersByClientId

    • Parameters:
      • int clientId: The unique identifier for the client whose orders are to be retrieved.
    • Returns: Task<IEnumerable<OrderDTO>>
    • Description: Asynchronously retrieves a collection of orders for a specified client. It fetches orders from the IOrder interface and converts the order entities into OrderDTO objects for use in the application.

Summary

The OrderService class is integral to the Order API, providing essential methods for managing and accessing order data. It leverages HTTP client calls to interact with external APIs, implements resilience strategies using the Polly package, and integrates data conversion and handling to deliver comprehensive order information. This service ensures reliable and efficient processing of order-related requests while maintaining robust error handling and data integrity.


OrderConversion Class

The OrderConversion class provides static methods for converting between domain entities and Data Transfer Objects (DTOs) within the Order API. It facilitates the transformation of order data for use across different layers of the application, ensuring consistency and ease of data handling.

Key Methods

  • ToEntity

    • Parameters:
      • OrderDTO order: The DTO representing an order.
    • Returns: Order
    • Description: Converts an OrderDTO object into an Order entity. This method maps properties from the DTO to the domain entity, enabling seamless integration of DTO data into the domain model.
  • FromEntity

    • Parameters:
      • Order? order: An optional single Order entity.
      • IEnumerable<Order>? orders: An optional collection of Order entities.
    • Returns: (OrderDTO?, IEnumerable<OrderDTO>?)
    • Description: Converts order entities to their corresponding DTO representations. It handles both single and multiple order conversions:
      • If a single Order entity is provided and the collection is null, it returns a single OrderDTO.
      • If a collection of Order entities is provided and the single entity is null, it returns a list of OrderDTO objects.
      • It can return both null values if neither input is provided, ensuring flexibility in handling different conversion scenarios.

Summary

The OrderConversion class is essential for translating between domain entities and DTOs within the Order API. By providing methods for both single and bulk conversions, it ensures that order data can be efficiently transformed and utilized across various application layers. This class plays a critical role in maintaining data consistency and supporting effective communication between different components of the system.


Infrastructure Layer

OrderDbContext Class

The OrderDbContext class is the Entity Framework Core (EF Core) database context for the Order API. It is responsible for managing the interaction between the application and the underlying database, specifically for handling order-related data.

Key Components

  • Orders
    • Type: DbSet<Order>
    • Description: Represents the collection of Order entities in the database. This property provides the EF Core context with the necessary configuration to perform CRUD operations on the Order table, including querying, inserting, updating, and deleting order records.

Constructor

  • OrderDbContext(DbContextOptions<OrderDbContext> options)
    • Parameters:
      • DbContextOptions<OrderDbContext> options: Options to configure the context, such as connection strings and provider-specific settings.
    • Description: Initializes a new instance of the OrderDbContext class with the specified options, allowing EF Core to configure the context for database interactions.

Summary

The OrderDbContext class is central to data access in the Order API, enabling interactions with the database through EF Core. By defining the Orders DbSet, it facilitates the management of order records and supports various database operations. This class ensures that the Order API can effectively store and retrieve order data, maintaining data integrity and enabling efficient data access.


OrderRepository Class

The OrderRepository class is a crucial component of the Order API's data access layer, implementing the IOrder interface to handle CRUD operations for Order entities. It provides a range of methods to interact with the database while ensuring consistent error handling and logging.

Key Methods

  • CreateAsync(Order entity)

    • Description: Adds a new order to the database. If the operation is successful, it returns a response indicating success; otherwise, it returns a response with an error message.
    • Error Handling: Catches exceptions, logs the details using LogException.LogExceptions, and returns a user-friendly error message.
  • DeleteAsync(Order entity)

    • Description: Deletes an existing order from the database. If the order is not found, it returns a response indicating failure. If successful, it confirms the deletion.
    • Error Handling: Handles exceptions, logs them, and provides a user-friendly error message.
  • FindByIdAsync(int id)

    • Description: Retrieves an order by its ID. Returns the order if found; otherwise, it throws an exception.
    • Error Handling: Catches and logs exceptions, then throws a generic error message.
  • GetAllAsync()

    • Description: Fetches all orders from the database. Returns a list of orders or throws an exception if something goes wrong.
    • Error Handling: Manages exceptions, logs details, and throws a user-friendly error message.
  • GetByAsync(Expression<Func<Order, bool>> predicate)

    • Description: Retrieves a single order based on a specified condition. Returns the order if found; otherwise, returns null.
    • Error Handling: Catches exceptions, logs them, and provides a user-friendly error message.
  • GetOrdersAsync(Expression<Func<Order, bool>> predicate)

    • Description: Fetches orders matching a specified condition. Returns a list of orders or throws an exception if an error occurs.
    • Error Handling: Handles exceptions, logs them, and returns a user-friendly error message.
  • UpdateAsync(Order entity)

    • Description: Updates an existing order in the database. If the order is found, it updates and saves the changes; otherwise, it returns a response indicating failure.
    • Error Handling: Catches exceptions, logs them, and provides a user-friendly error message.

Summary

The OrderRepository class provides essential data access functionalities for the Order API, managing Order entities with robust error handling and logging. By implementing the IOrder interface, it ensures consistent operations for creating, retrieving, updating, and deleting orders, while effectively managing exceptions and providing user-friendly error responses.


ServiceContainer Class

The ServiceContainer class is responsible for configuring and setting up dependency injection and middleware for the Order API. It ensures that all necessary services and policies are registered and available for use throughout the application.

Key Methods

  • AddInfrastructureService(IServiceCollection services, IConfiguration config)

    • Description: Configures and registers infrastructure-related services for the Order API. This includes:
      • Database Connectivity: Sets up the database context for the Order API using OrderDbContext.
      • Authentication Scheme: Integrates shared authentication services defined in the SharedServiceContainer.
      • Dependency Injection: Registers the OrderRepository as the implementation for the IOrder interface, ensuring that repository operations can be injected where needed.
    • Parameters:
      • services (IServiceCollection): The collection of services to which the infrastructure services will be added.
      • config (IConfiguration): Configuration settings used to configure services, including Serilog file names and database connection strings.
    • Returns: The modified IServiceCollection with infrastructure services added.
  • UserInfrastructurePolicy(IApplicationBuilder app)

    • Description: Configures middleware policies for the Order API. This includes:
      • Global Exception Handling: Adds middleware to handle global exceptions and ensure consistent error responses.
      • API Gateway Restrictions: Adds middleware to block unauthorized external API calls, allowing only requests from the API Gateway.
    • Parameters:
      • app (IApplicationBuilder): The application builder used to configure middleware.
    • Returns: The modified IApplicationBuilder with infrastructure policies applied.

Summary

The ServiceContainer class provides essential configuration and setup for the Order API's infrastructure layer. By integrating database connectivity, authentication services, and middleware policies, it ensures that the application is properly configured to handle data operations, security, and error management. This setup promotes clean separation of concerns and modular configuration within the Order API project.


Presentation Layer

OrdersController Class

The OrdersController class is an API controller that handles HTTP requests related to orders in the Order API. It provides endpoints for creating, retrieving, updating, and deleting orders, as well as retrieving order details and orders for a specific client.

Key Endpoints

  • GetOrders

    • Route: GET /api/orders
    • Description: Retrieves all orders from the database.
    • Response: Returns a list of OrderDTO objects if orders are found, otherwise returns NotFound.
  • GetOrder

    • Route: GET /api/orders/{id}
    • Description: Retrieves a single order by its ID.
    • Response: Returns the OrderDTO object if found, otherwise returns NotFound.
  • GetClientOrders

    • Route: GET /api/orders/client/{clientId}
    • Description: Retrieves all orders for a specific client by their ID.
    • Response: Returns a list of OrderDTO objects if found, otherwise returns NotFound.
  • GetOrderDetails

    • Route: GET /api/orders/details/{orderId}
    • Description: Retrieves detailed information about a specific order by its ID.
    • Response: Returns the OrderDetailsDTO object if found, otherwise returns NotFound.
  • CreateOrder

    • Route: POST /api/orders
    • Description: Creates a new order in the database.
    • Request Body: Accepts an OrderDTO object.
    • Response: Returns a Response object indicating success or failure.
  • UpdateOrder

    • Route: PUT /api/orders
    • Description: Updates an existing order in the database.
    • Request Body: Accepts an OrderDTO object.
    • Response: Returns a Response object indicating success or failure.
  • DeleteOrder

    • Route: DELETE /api/orders
    • Description: Deletes an existing order from the database.
    • Request Body: Accepts an OrderDTO object.
    • Response: Returns a Response object indicating success or failure.

Summary

The OrdersController class provides a comprehensive set of endpoints for managing orders within the Order API. It leverages the IOrder and IOrderService interfaces to perform CRUD operations and retrieve order details, ensuring that all necessary business logic is encapsulated within the appropriate services. This design promotes clean separation of concerns and makes the API easier to maintain and extend.


# Here's a follow-up section to encourage engagement and support for Netcode-Hub:

๐ŸŒŸ Get in touch with Netcode-Hub! ๐Ÿ“ซ

1. GitHub: [Explore Repositories] ๐ŸŒ

2. Twitter: [Stay Updated] ๐Ÿฆ

3. Facebook: [Connect Here]๐Ÿ“˜

4. LinkedIn: [Professional Network]๐Ÿ”—

5. Email: [business.netcodehub@gmail.com] ๐Ÿ“ง

# ☕️ If you've found value in Netcode-Hub's work, consider supporting the channel with a coffee!

1. Buy Me a Coffee: [Support Netcode-Hub] ☕️

Comments

Popular Posts

Complete Employee Management System | .NET 8 Blazor Wasm & Web API - Perform CRUD, Print, PDF etc..

.NET 8 Clean Architecture with Blazor CRUD, JWT & Role Authorization using Identity & Refresh Token๐Ÿ”ฅ

Employee Management System | .NET 8 Blazor Wasm- Profile & real-time data retrieval. Update 1