Editors Picked
Building a Basic open source E-Commerce Website with ASP.NET Core 8
Building a Basic eCommerce Website with ASP.NET Core 8: A Complete Guide to MLCart The evolution of eCommerce has transformed the way businesses operate and interact with customers. As companies continue to move their operations online, the demand for dynamic, scalable, and secure web applications has increased. ASP.NET Core 8, Microsoft's open-source web framework, is designed to meet these needs, allowing developers to build high-performance and feature-rich applications that can power online businesses. In this blog, we’ll explore how to build a basic eCommerce website using ASP.NET Core 8. We will use MLCart, an open-source project available on GitHub, to demonstrate key features and how to get started with building your own eCommerce platform. Table of Contents Introduction to ASP.NET Core 8 Overview of MLCart: Features and Architecture Setting Up the Development Environment Cloning and Running the MLCart Application Key Components of an eCommerce Website Product Management Shopping Cart Functionality User Authentication Payment Integration Exploring the Codebase of MLCart Models, Views, and Controllers Entity Framework Integration Customizing MLCart for Your Business Needs Adding Custom Features Improving the UI/UX Performance Optimization Best Practices for eCommerce Websites in ASP.NET Core Conclusion and Next Steps 1. Introduction to ASP.NET Core 8 ASP.NET Core 8 is the latest iteration of Microsoft’s web development framework. It is cross-platform, allowing developers to build applications for Windows, macOS, and Linux. ASP.NET Core is known for its performance, scalability, and the flexibility to integrate various tools and libraries. Key features that make ASP.NET Core 8 a strong choice for eCommerce platforms include: High Performance: ASP.NET Core has built-in performance optimization, making it one of the fastest web frameworks. Cross-Platform Support: Applications built with ASP.NET Core can run on multiple platforms, allowing businesses to deploy their websites on various operating systems. Built-in Security Features: ASP.NET Core offers built-in tools for authentication, authorization, and data protection, ensuring secure eCommerce transactions. Integration with Modern Frontend Frameworks: ASP.NET Core allows seamless integration with frontend technologies like Angular, React, and Vue.js. Scalability: The framework is designed to handle high traffic and complex workloads, making it perfect for growing eCommerce businesses. 2. Overview of MLCart: Features and Architecture MLCart is an open-source eCommerce project built using ASP.NET Core 8 and made available by the developer Mayur Lohite on GitHub. MLCart provides a basic structure for an online store with essential features like product listing, shopping cart management, and user authentication. Key Features of MLCart: Product Catalog: Displays available products with detailed descriptions and images. User Authentication: Implements user registration, login, and account management functionalities. Shopping Cart: Enables users to add products to their cart and manage the cart’s content. Order Processing: Manages order placement and history. Admin Dashboard: Provides an interface for administrators to manage products, categories, and user orders. Architecture Overview: MLCart follows the traditional Model-View-Controller (MVC) architecture of ASP.NET Core: Models: Represent the business logic and data structure of the eCommerce platform. Views: Define the user interface for both customers and admins. Controllers: Handle user requests and interactions, connecting the Models and Views. This modular architecture allows developers to easily extend the functionality of MLCart by adding new features or modifying existing ones. 3. Setting Up the Development Environment Before diving into the MLCart project, you need to set up your development environment to run ASP.NET Core 8 applications. Prerequisites: Install .NET SDK (Version 8): Download and install the latest version of the .NET SDK from the official website. Install Visual Studio: You can download Visual Studio 2022 or later. Ensure you select the ".NET Core cross-platform development" workload during installation. Install SQL Server: Since MLCart uses SQL Server for database management, ensure you have SQL Server installed. Alternatively, you can use SQL Server Express for local development. Cloning the MLCart Repository: Once the environment is set up, you can clone the MLCart repository from GitHub: git clone https://github.com/mayurlohite/MLCart.git After cloning the repository, open the solution in Visual Studio and restore the NuGet packages. 4. Cloning and Running the MLCart Application Once you have the MLCart repository cloned, follow these steps to run the application: Build the Project: Open the MLCart solution file (.sln) in Visual Studio and click on the "Build" option from the top menu. Configure the Database: MLCart uses SQL Server for the database. You may need to configure the connection string found in the appsettings.json file to point to your local SQL Server instance. Here’s an example of the configuration: "ConnectionStrings": { "DefaultConnection": "Server=YOUR_SERVER_NAME;Database=MLCartDb;Trusted_Connection=True;MultipleActiveResultSets=true" } Run Database Migrations: In the Package Manager Console, run the following command to create the necessary tables in the database: Update-Database Run the Application: After the database setup is complete, you can run the project by pressing F5 or clicking "Start" in Visual Studio. Once the application is running, you can access it in your browser at http://localhost:5000 (or the configured port). 5. Key Components of an eCommerce Website An eCommerce website needs several core features to function effectively. Let’s explore these features within the context of MLCart and how they are implemented using ASP.NET Core 8. Product Management Products are the heart of any eCommerce store. MLCart allows admins to add, edit, and manage product listings. Products are displayed in the frontend for customers to browse. Models: The Product model in MLCart defines the product’s attributes such as Name, Description, Price, ImageUrl, and Category. Controllers: The ProductController handles the business logic for managing products, including fetching products from the database and serving them to the views. Views: Razor views display product listings and details to users in an attractive and responsive layout. Shopping Cart Functionality The shopping cart is crucial for managing customer orders. In MLCart, the cart functionality is built into the CartController, allowing users to add, remove, and update product quantities. Cart Sessions: MLCart uses session storage to keep track of the items a user has added to their cart until they proceed to checkout. Order Summary: Once a user is ready to checkout, the order summary is generated and displayed, showing the total price and product details. User Authentication MLCart supports user authentication out of the box, enabling users to create accounts, log in, and manage their profiles. ASP.NET Core Identity is used to handle registration, authentication, and authorization. Identity Models: ASP.NET Core Identity provides predefined models for users, roles, and claims. Authentication Middleware: MLCart uses middleware to handle user sessions, authentication cookies, and role-based access control. Payment Integration While MLCart doesn’t include payment integration by default, adding it is straightforward with ASP.NET Core 8. Common payment gateways like Stripe or PayPal can be integrated using third-party libraries or APIs. 6. Exploring the Codebase of MLCart Let’s dive deeper into the MLCart codebase to understand how it’s structured and how you can modify it to suit your needs. Models, Views, and Controllers (MVC Pattern) MLCart follows the MVC pattern, which separates the application logic into three interconnected components: Models: Represent the data and business logic. For example, the Product model defines the properties of a product. Views: Razor Views (.cshtml files) display data to the user and collect input. Controllers: Handle user requests and interact with models to serve data to views. For instance, the OrderController processes customer orders and saves them in the database. Entity Framework Integration MLCart uses Entity Framework Core (EF Core) for database management. EF Core is an Object-Relational Mapping (ORM) framework that simplifies data access by allowing developers to work with databases using .NET objects. DbContext: The ApplicationDbContext class is the bridge between the database and the application. It defines the data models and configures database behavior. Migrations: EF Core migrations are used to update the database schema over time. 7. Customizing MLCart for Your Business Needs One of the major advantages of using an open-source project like MLCart is
Clean Structured Project – ASP.NET Core
This template is for a clean structured ASP.NET Core web project, follows the Clean Architecture principles, SOLID design principles, implements the Dependency Injection, Repository, and Unit of Work design pattern, and utilizes Entity Framework Core for data access. It provides a standardized structure and organization for building robust and maintainable ASP.NET Core web applications with complete CRUD (Create, Read, Update, Delete) operations. Project Structure The project structure is designed to promote separation of concerns and modularity, making it easier to understand, test, and maintain the application. ├── src │ ├── Core # Contains the core business logic and domain models, view models, etc. │ ├── Infrastructure # Contains infrastructure concerns such as data access, external services, etc. │ └── UI # Contains the user interface layer, including controllers, views, and extensions, etc. ├── tests │ ├── Core.Tests # Contains unit tests for the core layer │ ├── Infrastructure.Tests # Contains unit tests for the infrastructure layer │ └── UI.Tests # Contains unit tests for the UI layer └── README.md # Project documentation (you are here!) Getting Started To use this project template, follow the steps below: Ensure the .NET 7 SDK is installed on your machine. Clone or download this repository to your local machine. Open the solution in your preferred IDE (e.g., Visual Studio, Visual Studio Code). Build the solution to restore NuGet packages and compile the code. Configure the necessary database connection settings in the appsettings.json file of the Infrastructure project. Open the Package Manager Console, select Project.Infrastructure project and run the Update-Database command to create the database Run the application by starting the Project.UI project. Project Features This project template includes the following features: Clean Architecture: The project is structured according to the principles of Clean Architecture, which promotes the separation of concerns and a clear division of responsibilities. SOLID Design Principles: The code adheres to SOLID principles (Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion), making it easier to maintain and extend. Repository Pattern: The repository pattern abstracts the data access layer and provides a consistent interface for working with data. Unit of Work Pattern: The unit of work pattern helps manage transactions and ensures consistency when working with multiple repositories. Entity Framework Core: The project utilizes Entity Framework Core as the ORM (Object-Relational Mapping) tool for data access. ASP.NET Core Web: The project includes an ASP.NET Core web project that serves as the user interface layer, handling HTTP requests and responses. CRUD Operations: The project template provides a foundation for implementing complete CRUD (Create, Read, Update, Delete) operations on entities using Entity Framework Core. Dependency Injection: The project utilizes the built-in dependency injection container in ASP.NET Core, making it easy to manage and inject dependencies throughout the application. Unit Testing: The solution includes separate test projects for unit testing the core, infrastructure, and UI layers. Usage The project template provides a starting point for implementing CRUD operations on entities using Entity Framework Core. You can modify and extend the existing code to suit your specific application requirements. Here’s an overview of the key components involved in the CRUD operations: Models: The Core project contains the domain models representing the entities you want to perform CRUD operations on. Update the models or add new ones according to your domain. Repositories: The Infrastructure project contains repository implementations that handle data access operations using Entity Framework Core. Modify the repositories or create new ones to match your entity models and database structure. Services: The Core project contains services that encapsulate the business logic and orchestrate the operations on repositories. Update or create new services to handle CRUD operations on your entities. Controllers: The UI project contains controllers that handle HTTP requests and responses. Update or create new controllers to expose the CRUD endpoints for your entities. Make sure to update the routes, validation, and error-handling logic to align with your application requirements and best practices. Note: This article has been written by Kawser Hamid and republished on MudMatter with Author’s Permission. Please find the original link here – Clean Structured Project – ASP.NET Core.
Differences between IEnumerable and IQueryable in C#
In every .NET application we need to manipulate IEnumerable and IQueryable interfaces to hold collections. The basic use of IEnumerable and IQueryable is to hold the collection of data & perform Ordering, Grouping & Filtering of data based on project/application requirements. The first thing to keep in mind is that since the IQueryable interface is an inheritance of IEnumerable, it possesses all of IEnumerable's capabilities. Both are limited to process on C# collections. The important difference between IEnumerableand IQueryable is: IQueryable - The Filter is apply at server level/side and fetch only required results from source. So processing time is less. IEnumerable- It fetch all data from source first and later apply the filter at client level/side. Which can be result in fetching unnecessary data and it increase processing time. Lets understand this with an example. We have created Console application in .NET Core to fetch Books from SQL Server database and we are using Entity Framework Core to fetch the books (books table). We built it over Code-First approach. This is our Book.cs Entity [Table("Books")] public class Book { [Key] public int BookId { get; set; } [StringLength(255)] public string? Title { get; set; } public decimal Price { get; set; } } We have around 10 records added into database by using seed data method. Lets understand the differences by using below code. We have written both queries in LINQ. class Program { static void Main(string[] args) { using (var context = new BookDemoDbContext()) { var booksIEnumerable = (from book in context.Books select book) .AsEnumerable<Book>().Take(2).ToList(); var booksIQurable = (from book in context.Books select book) .AsQueryable<Book>().Take(2).ToList(); } Console.ReadKey(); } } In first query we are trying to fetch 2 books in IEnumerable interface. var booksIEnumerable = (from book in context.Books select book) .AsEnumerable<Book>().Take(2).ToList(); Lets see what above LINQ query has been executed in SQL Server with the help of SQL Server profiler (for IEnumerable). Below query is traced in profiler. The query is simple SELECT statement without any where clause or TOP statement. It means it selecting all rows from SQL server database and just pick 2 records on client side. SELECT [b].[BookId], [b].[Price], [b].[Title] FROM [Books] AS [b] The diagram shows graphical representation of how IEnumerableworks. In first query we are trying to fetch 2 books in IQueryableinterface. var booksIQurable = (from book in context.Books select book) .AsQueryable<Book>().Take(2).ToList(); Lets see what above LINQ query has been executed in SQL Server with the help of SQL Server profiler (for IQueryable). Below query is traced in profiler. The TOP filter has been applied with parameter and its value = 2, so it means it fetch only 2 records from Books table. So it avoids fetching unnecessary data from database. exec sp_executesql N'SELECT TOP(@__p_0) [b].[BookId], [b].[Price], [b].[Title] FROM [Books] AS [b]',N'@__p_0 int',@__p_0=2 The diagram shows graphical representation of how IQueryable works. Download Source Code https://github.com/mayurlohite/IEnumerableVsIQueryable See the difference in action, watch this video https://www.youtube.com/watch?v=1x7Pf5geDd4 Conclusion Hence, when working with in-memory collections—where data is kept locally in the memory of the application—select IEnumerable<T>. When working with huge data sets or querying external data sources, use IQueryable<T> as it enables effective server-side processing and query optimization. Your performance needs and the type of data source will determine which option is best. If you have any questions, Please connect me on LinkedIn. Explore more articles.
Chicken Marsala
Chicken Marsala is an Italian-American dish of golden pan-fried chicken cutlets and mushrooms in a rich Marsala wine sauce. Chicken Marsala is an Italian-American dish of golden pan-fried chicken cutlets and mushrooms in a rich Marsala wine sauce. It’s the most popular chicken recipe on this website, and though it’s a classic restaurant dish, it’s really easy to make at home. With just one pan, you can have it on the dinner table in 45 minutes. The recipe makes a lovely sauce that is delicious over pasta, polenta, rice, or mashed potatoes. If your family loves Italian food like mine does, once you master chicken Marsala, try your hand at other Italian restaurant favorites, such pasta e fagioli, eggplant parmesan, penne alla vodka, and lasagna. What You’ll Need To Make Chicken Marsala Marsala is a brandy-fortified wine from Sicily that is 100% worth adding to your pantry, if only to make this dish time and again. It will keep in a cool, dry spot for months.I buy boneless skinless chicken breasts and pound them thin myself, as opposed to using the ultra-thin sliced cutlets sold at the supermarket, since pounding tenderizes the meat. This adds an extra step but you can save time by using pre-sliced mushrooms. (Or you can skip all this hassle by using chicken tenderloins.) How To Make Chicken Marsala If your chicken breasts are large, like the ones in the photo above, it’s best to first cut them in half horizontally. (If you pound them without first halving them, they’ll be ginormous and oddly shaped.) Once you’ve got four flat filets, pound them each to an even 1/4-inch thickness. Place the flour, 3/4 teaspoon salt, and 1/4 teaspoon pepper in a ziplock bag. Add the chicken to the bag; seal the bag tightly and shake to coat chicken evenly. Set aside. Heat the oil and 2 tablespoons of the butter in a large skillet over medium-high heat. (Use a stainless steel pan for the best browning. Nonstick will work too, but you won’t get that nice golden color on the chicken.) Place the flour-dusted chicken in the pan, shaking off any excess first. Cook, turning once, until the chicken is golden and just barely cooked through, about 5 to 6 minutes total. Transfer the chicken to a plate and set aside. Melt the remaining tablespoon of butter in the pan. Add the mushrooms and cook, stirring frequently, until the mushrooms begin to brown, 3 to 4 minutes. Add the shallots, garlic, and ¼ teaspoon of salt. Cook for 1 to 2 minutes more. Add the broth, wine, heavy cream, thyme, 1/4 teaspoon salt, and 1/8 teaspoon of pepper; use a wooden spoon to scrape any brown bits from the pan into the liquid. Bring the liquid to a boil, then reduce the heat to medium. Gently boil, uncovered, until the sauce is reduced by about half, slightly thickened, and darkened in color, 10 to 15 minutes (you’re going for a thin cream sauce; it won’t start to thicken until the very end of the cooking time). Add the chicken back to the pan, along with any juices that accumulated on the plate. Reduce the heat to low and simmer until the chicken is warmed through and the sauce thickens a bit more, 2 to 3 minutes. Sprinkle with parsley, if using, and serve. Video Tutorial Note: This recipe has been written by Jenn Segal and republished on MudMatter with Author's Permission. Please find the original link here - Chicken Marsala.
Chicken Tikka Masala
Chicken tikka masala is a dish of yogurt-marinated broiled chicken in a creamy, spice-infused tomato sauce. Chicken tikka masala is a dish of yogurt-marinated and broiled chicken in a creamy, spice-infused tomato sauce. It’s surprisingly easy to make, and it’s a great intro to Indian food for kids, as it’s not too spicy. The sauce is seasoned with garam masala, a fragrant Indian spice blend typically made from peppercorns, mace, cinnamon, cloves, cardamom, and nutmeg. You can find it at most large supermarkets (McCormick makes it as part of their Gourmet Collection), but feel free to substitute curry powder if need be. Serve with basmati rice, buttered peas, and naan for a fabulous family feast. What you’ll need to make chicken tikka masala Step-by-Step Instructions Begin by chopping the chicken breasts into chunks. Feel free to substitute boneless skinless chicken thighs if you like, but I prefer white meat for this recipe since the sauce is quite rich. In a bowl large enough to hold the chicken, combine the yogurt, salt and spices. Whisk to combine. Then add the chicken and mix until it is evenly coated. Cover and marinate in the refrigerator for at least 1 hour or overnight. When you’re ready to cook the chicken, preheat the broiler and set an oven rack in the top position. Line a baking sheet with aluminum foil and set a wire rack on top; spray the rack with nonstick cooking spray. Place the chicken on the prepared rack, spooning any marinade left in the bowl over the chicken. Broil for 7 to 8 minutes, until browned on top. (The chicken does not need to be flipped over.) While the chicken cooks, start the sauce. Melt the butter over medium heat in a large pan. Add the onions and ginger and cook, stirring frequently, until softened, 5 to 7 minutes. Do not brown; reduce the heat if necessary. Add the spices and cook 2 minutes more. Add the tomatoes, heavy cream, salt, sugar, pepper and 1/2 cup water. Bring to a boil, then reduce the heat to medium-low and simmer, uncovered, until thickened, about 15 minutes. Add the broiled chicken to the sauce and simmer until the chicken is warmed through and fully cooked, a few minutes. Sprinkle the cilantro over the chicken and serve with buttered Indian basmati rice and/or naan. Enjoy! Video Tutorial Note: This recipe has been written by Jenn Segal and republished on MudMatter with Author’s Permission. Please find the original link here – Chicken Tikka Masala.