European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFE.eu :: Stripe Payment Gateway Integration with ASP.NET Core MVC

clock February 10, 2025 07:09 by author Peter

We'll go over every step of integrating the Stripe Payment Gateway into an ASP.NET Core MVC application in this post. After completing this tutorial, you will have a complete payment system that enables customers to use Stripe's safe checkout to make purchases.

Stripe is a popular payment gateway that allows businesses to accept payments online. It supports credit cards, debit cards, and other payment methods. Stripe provides a secure and easy-to-integrate API for developers. In this article, we’ll use Stripe Checkout, which is a pre-built payment page hosted by Stripe. This approach is secure and requires minimal setup.

Introduction
Before starting, ensure you have the following.

  • Stripe Account: Sign up at Stripe.
  • .NET SDK: Install the latest .NET SDK from here.
  • IDE: Use Visual Studio, Visual Studio Code, or any preferred IDE.
  • Stripe API Keys: Retrieve your Publishable Key and Secret Key from the Stripe Dashboard.

Step 1. Create a Stripe Account

  1. Go to Stripe and sign up for an account.
  2. Once logged in, navigate to Developers > API Keys.
  3. Copy your publishable key and secret key. These will be used in your ASP.NET Core application.

Step 2. Set Up an ASP.NET Core MVC Project

  • Open Visual Studio or your preferred IDE.
  • Create a new ASP.NET Core Web App (Model-View-Controller) project.
    • Name the project (e.g., StripePaymentDemo).
    • Select .NET 6.0 or later as the framework.
  • Build and run the project to ensure it’s set up correctly.

Step 3. Install Stripe.NET NuGet Package
Stripe provides an official .NET library to interact with its API. Install it via the Package Manager Console.
Install-Package Stripe.net

Step 4. Configure Stripe in appsettings.json
Add your Stripe API keys to the appsettings.json file.
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "Stripe": {
    "PublishableKey": "YOUR_STRIPE_PUBLISHED_KEY",
    "SecretKey": "YOUR_SECRET_KEY"
  },
  "AllowedHosts": "*"
}

Step 5. Configure Stripe in the Program.cs
Configure Stripe in the Program.cs file.
using Stripe;

namespace StripePaymentDemoApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            // Add services to the container
            builder.Services.AddControllersWithViews();
            StripeConfiguration.ApiKey = builder.Configuration["Stripe:SecretKey"];
            var app = builder.Build();
            // Configure the HTTP request pipeline
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios,
                // see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            app.Run();
        }
    }
}

Step 6. Create a Payment Controller
Create a new controller named: PaymentController.cs.using Microsoft.AspNetCore.Mvc;
using Stripe.Checkout;

namespace StripePaymentDemoApp.Controllers
{
    public class PaymentController : Controller
    {
        private readonly IConfiguration _configuration;
        public PaymentController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        public IActionResult Checkout()
        {
            // Pass the Stripe Publishable Key to the view
            ViewBag.StripePublishableKey = _configuration["Stripe:PublishableKey"];
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> CreateCheckoutSession()
        {
            // Create a Stripe Checkout Session
            var options = new SessionCreateOptions
            {
                PaymentMethodTypes = new List<string> { "card" },
                LineItems = new List<SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        PriceData = new SessionLineItemPriceDataOptions
                        {
                            Currency = "usd",
                            ProductData = new SessionLineItemPriceDataProductDataOptions
                            {
                                Name = "Test Product",
                            },
                            UnitAmount = 2000, // $20.00 (in cents)
                        },
                        Quantity = 1,
                    },
                },
                Mode = "payment",
                SuccessUrl = Url.Action("Success", "Payment", null, Request.Scheme),
                CancelUrl = Url.Action("Cancel", "Payment", null, Request.Scheme),
            };
            var service = new SessionService();
            var session = await service.CreateAsync(options);
            // Redirect to Stripe Checkout
            return Redirect(session.Url);
        }
        public IActionResult Success()
        {
            return View();
        }
        public IActionResult Cancel()
        {
            return View();
        }
    }
}
Step 7. Create Views
Checkout View (Views/Payment/Checkout.cshtml).
@{
ViewData["Title"] = "Checkout";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Checkout</h1>
<form asp-action="CreateCheckoutSession" method="post">
<button type="submit" class="btn btn-primary">Pay with Stripe</button>
</form>


Success View (Views/Payment/Success.cshtml).
@{
ViewData["Title"] = "Payment Successful";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Payment Successful</h1>
<p>Thank you for your payment!</p>

Cancel View (Views/Payment/Cancel.cshtml).
@{
ViewData["Title"] = "Payment Canceled";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Payment Canceled</h1>
<p>Your payment was canceled.</p>

Step 8. Run and Test the Application

  • Run the application using dotnet run or your IDE’s run command.
  • Navigate to /Payment/Checkout in your browser.
  • Click the "Pay with Stripe" button to be redirected to the Stripe Checkout page.
  • Use the following test card details.
    • Card Number: 4242 4242 4242 4242.
    • Expiration Date: Any future date.
    • CVC: Any 3 digits.
    • ZIP Code: Any value.

Let's run the application and start the payments with Stripe.

Click the Pay with Stripe Button.


Fill in the payment details with test credentials and click the pay button.

Let's look at our most recent transactions on the Stripe dashboard.


Step 9. Handle Webhooks (Optional)
To handle payment confirmation and other events, set up a webhook endpoint.

Create a Webhook Endpoint in the Stripe Dashboard.

  • Go to Developers > Webhooks in the Stripe Dashboard.
    • Add a new endpoint with your server's URL (e.g., https://yourdomain.com/Payment/Webhook).
    • Add Webhook Secret to:appsettings.json.

{
  "Stripe": {
    "WebhookSecret": "your_webhook_secret_here"
  }
}


Add Webhook Handler in:PaymentController.cs.
[HttpPost]
public async Task<IActionResult> Webhook()
{
    var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

    try
    {
        var stripeEvent = EventUtility.ConstructEvent(
            json,
            Request.Headers["Stripe-Signature"],
            _configuration["Stripe:WebhookSecret"]
        );
        // Handle events
        if (stripeEvent.Type == Events.CheckoutSessionCompleted)
        {
            var session = stripeEvent.Data.Object as Session;
            // Handle successful payment
        }
        return Ok();
    }
    catch (StripeException e)
    {
        return BadRequest();
    }
}



ASP.NET MVC Hosting - HostForLIFE.eu :: Scalable ASP.NET MVC Application Design Patterns

clock February 3, 2025 06:14 by author Peter

Design patterns are tried-and-true fixes for typical program design issues. Implementing these principles can enhance the scalability, testability, and maintainability of code in ASP.NET MVC projects. This article examines important design patterns seen in ASP.NET MVC projects and offers real-world examples of how to use them.

1. Repository Pattern
The repository pattern abstracts data access logic, providing a clean separation between the business logic and the data layer.

Benefits

  • Promotes loose coupling between the application and data storage.
  • Simplifies unit testing by allowing mocking of the data layer.

Implementation
// IRepository Interface
public interface IRepository<T> where T : class
{
    IEnumerable<T> GetAll();
    T GetById(int id);
    void Insert(T entity);
    void Update(T entity);
    void Delete(int id);
}

// Repository Implementation
public class Repository<T> : IRepository<T> where T : class
{
    private readonly ApplicationDbContext _context;
    private DbSet<T> entities;

    public Repository(ApplicationDbContext context)
    {
        _context = context;
        entities = context.Set<T>();
    }

    public IEnumerable<T> GetAll() => entities.ToList();
    public T GetById(int id) => entities.Find(id);
    public void Insert(T entity) => entities.Add(entity);
    public void Update(T entity) => _context.Entry(entity).State = EntityState.Modified;
    public void Delete(int id) => entities.Remove(GetById(id));
}


2. Unit of Work Pattern
The unit of work pattern helps manage transactions by coordinating changes across multiple repositories in a single transaction.

Benefits

  • Ensures consistency across repositories.
  • Reduces redundant calls to the database.

Implementation
public class UnitOfWork : IDisposable
{
    private readonly ApplicationDbContext _context;
    private IRepository<Product> _productRepository;

    public UnitOfWork(ApplicationDbContext context)
    {
        _context = context;
    }

    public IRepository<Product> ProductRepository
    {
        get
        {
            return _productRepository ??= new Repository<Product>(_context);
        }
    }

    public void Save()
    {
        _context.SaveChanges();
    }

    public void Dispose()
    {
        _context.Dispose();
    }
}


3. Dependency Injection (DI)
Dependency injection (DI) injects dependencies into controllers or classes instead of creating them directly.

Benefits

  • Reduces tight coupling.
  • Simplifies testing by allowing dependency substitution.

Implementation
Configure DI in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IRepository<Product>, Repository<Product>>();
    services.AddScoped<UnitOfWork>();
    services.AddControllersWithViews();
}


Inject Dependencies in Controller
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int StockQuantity { get; set; }
}

Products Controller
using System.Linq;
using System.Web.Mvc;
using MVCDesignPatternsApp.Models;
using MVCDesignPatternsApp.Repositories;

public class ProductsController : Controller
{
    private readonly UnitOfWork _unitOfWork;

    public ProductsController(UnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    // GET: Products
    public ActionResult Index()
    {
        var products = _unitOfWork.ProductRepository.GetAll().ToList();
        return View(products);
    }

    // GET: Products/Details/5
    public ActionResult Details(int id)
    {
        var product = _unitOfWork.ProductRepository.GetById(id);
        if (product == null)
        {
            return HttpNotFound();
        }
        return View(product);
    }

    // GET: Products/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Products/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Product product)
    {
        if (ModelState.IsValid)
        {
            _unitOfWork.ProductRepository.Insert(product);
            _unitOfWork.Save();
            return RedirectToAction("Index");
        }
        return View(product);
    }

    // GET: Products/Edit/5
    public ActionResult Edit(int id)
    {
        var product = _unitOfWork.ProductRepository.GetById(id);
        if (product == null)
        {
            return HttpNotFound();
        }
        return View(product);
    }

    // POST: Products/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Product product)
    {
        if (ModelState.IsValid)
        {
            _unitOfWork.ProductRepository.Update(product);
            _unitOfWork.Save();
            return RedirectToAction("Index");
        }
        return View(product);
    }

    // GET: Products/Delete/5
    public ActionResult Delete(int id)
    {
        var product = _unitOfWork.ProductRepository.GetById(id);
        if (product == null)
        {
            return HttpNotFound();
        }
        return View(product);
    }

    // POST: Products/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        _unitOfWork.ProductRepository.Delete(id);
        _unitOfWork.Save();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _unitOfWork.Dispose();
        }
        base.Dispose(disposing);
    }
}

Views
Ensure you have corresponding views in the Views/Products/ folder:

  • Index.cshtml: Display the product list.
  • Details.cshtml: Show product details.
  • Create.cshtml: Form to add a new product.
  • Edit.cshtml: Form to update product information.
  • Delete.cshtml: Confirm product deletion.

View Example for Index.cshtml
@model IEnumerable<YourNamespace.Models.Product>

<h2>Product List</h2>

<p>
    @Html.ActionLink("Create New Product", "Create")
</p>

<table class="table">
    <thead>
        <tr>
            <th>Name</th>
            <th>Price</th>
            <th>Stock Quantity</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
    @foreach (var item in Model) {
        <tr>
            <td>@item.Name</td>
            <td>@item.Price</td>
            <td>@item.StockQuantity</td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })
            </td>
        </tr>
    }
    </tbody>
</table>

4. Factory Pattern
The factory pattern centralizes object creation logic.

Benefits

  • Decouples object creation from usage.
  • Promotes flexibility for varying object requirements.

Implementation
Factory Implementation

public interface IProductService
{
    void ProcessOrder();
}

public class PhysicalProductService : IProductService
{
    public void ProcessOrder() => Console.WriteLine("Processing physical product order.");
}

public class DigitalProductService : IProductService
{
    public void ProcessOrder() => Console.WriteLine("Processing digital product order.");
}

public class ProductServiceFactory
{
    public IProductService GetProductService(string productType)
    {
        return productType switch
        {
            "Physical" => new PhysicalProductService(),
            "Digital" => new DigitalProductService(),
            _ => throw new ArgumentException("Invalid product type")
        };
    }
}

Usage in Controller
public class OrdersController : Controller
{
    private readonly ProductServiceFactory _factory;

    public OrdersController(ProductServiceFactory factory)
    {
        _factory = factory;
    }

    public void CreateOrder(string productType)
    {
        var service = _factory.GetProductService(productType);
        service.ProcessOrder();
    }
}

5. Singleton Pattern
The singleton pattern ensures only one instance of a class is created and shared.

Benefits

  • Ideal for shared resources like logging or caching.
  • Ensures a single point of control.

Implementation
Singleton Class
public sealed class LogManager
{
    private static readonly Lazy<LogManager> instance = new(() => new LogManager());

    private LogManager() { }

    public static LogManager Instance => instance.Value;

    public void Log(string message) => Console.WriteLine($"Log: {message}");
}


6. Command Pattern
The command pattern encapsulates a request as an object, allowing for more complex request handling.

Benefits

  • Supports undoable operations.
  • Decouples request handling from request execution.

Implementation
Command Interface and Implementation
public interface ICommand
{
    void Execute();
}

public class SaveOrderCommand : ICommand
{
    public void Execute() => Console.WriteLine("Order saved.");
}

public class CancelOrderCommand : ICommand
{
    public void Execute() => Console.WriteLine("Order canceled.");
}

Invoker Class
public class CommandInvoker
{
    private readonly List<ICommand> _commands = new();

    public void AddCommand(ICommand command) => _commands.Add(command);

    public void ExecuteCommands()
    {
        foreach (var command in _commands)
        {
            command.Execute();
        }
        _commands.Clear();
    }
}

Output

 



ASP.NET MVC Hosting - HostForLIFE.eu :: Generic Repository Pattern With MVC

clock January 24, 2025 07:21 by author Peter

In this article, I am going to explain the generic repository pattern. We are going to start the concept and implementation of the repository pattern, so first, let's try to understand what it is.


Why go with the repository pattern?

Enterprise applications such as web-based enterprise applications, order management systems, payroll, accounting applications, etc., are large-scale data flow applications. Along with data flow, they have some other features too.

  • Large amount of data: These types (accounting, payroll, order management) of applications handle quite a large amount of data. And this amount of data is not fixed. It may vary day by day and get more and more than the previous day.
  • Separation of database and application: Handling of data for an application is a major undertaking that needs some persistent storage. We usually separate the database engine from the application. The data object is a multiuser environment. At a given point in time, the data should be overwritten and given a concurrency feature.
  • Modification in business rules is always acceptable: Enterprise applications will always have new rules, so our application should be ready to accept those changes without affecting the past code and logic. These rules can change at any time. At the time of business upgrade, our application should be ready to accept all the changes. Sometimes, business rules have operations that usually deal with the size (data) and display the data on many pages or one page, we may have to display the data from different tables.

We come across these scenarios daily and reach one conclusion, that is,

Enterprise applications function in three different areas

  • Data Access: This layer deals with the data storage and retrieval, such as CRUD (Create, Read, Update, Delete)
  • Business Rule: This layer deals with data access such as reading and writing data and encapsulation with business-specific rules
  • User Interface: Displays the data to the end user and also accepts input from the end user.

We use a repository pattern when the scenario is dealing with a complex set of queries from multiple tables, to avoid duplication so that we will not write the same code at multiple places.

In these scenarios, we use a layer between our domain class and the data access layer. This layer will take care of all operations that can be reused again and again. In short, we can say that "Repository pattern plays a mediator's role in between the data-access layer and all the system."

Once the repository pattern is implemented, the client code won’t invoke the data access directly. Instead, we will invoke the repository to get the job done. The repository offers a collection interface by providing methods to add, modify, remove, and fetch domain objects.

Let’s try to implement a generic repository pattern in the ASP MVC application. Before going to the implementation part, it is a very common question usually asked by many developers - Entity Framework is already developed in a repository pattern. Then, why will we again create a repository pattern?

I am trying to answer that.

In a small application, it is not required at all, but in enterprise applications, it is beneficial.

  • Promoting loose coupling: In the repository pattern, all query code is isolated from the Entity Framework objects, so that it gives a good way to implement loose coupling with other model classes.
  • Preventing Entity Framework objects from business logic layers: Giving all data access (Entity Framework objects) to the business layer is not a good idea. All LINQ queries get embedded inside it, these things are not desirable.

Steps to implement generic repository in ASP.NET MVC

Step 1. Add a new MVC template

Choose an MVC template.

Step 2. Add Entity Framework

Step 3. We are going to choose code first approach for creating a database and respective tables.

After defining the model class for students, now, we are now going to make a schema class for the code-first approach.
[Table("Students")]
public class Student
{
    [Key]
    [Display(Name = "Student Id")]
    public int StId { get; set; }

    [Required]
    [Display(Name = "Student Name")]
    public string StName { get; set; }

    [Display(Name = "Address")]
    public string StAddress { get; set; }

    [Required]
    [Display(Name = "Mobile No.")]
    public string MobileNo { get; set; }
}

Step 4. Create studentConext


Step 5. Add database set Initializer
Usually, in Entity Framework, there are four different ways to create an Initializer.

  • CreateDatabaseIfNotExists: This is the default initializer and it will create the database if it does not exist already, as per the configuration. One more thing; it will throw an exception if the model class is changed and will try to run the application with this initializer.
  • DropCreateDatabaseIfModelChanges: According to this initializer, it drops an existing database and creates a new database if model classes (entity classes) are changed.
  • DropCreateDatabaseAlways: According to this initializer, it drops an existing database every time when we run the application. It doesn’t worry about the model class changes. This is useful when we want a fresh database every time we run the application.
  • Customer db Initializer: We can create our own custom initializer.

Syntax
public class SchoolDataBaseInitializer : CreateDatabaseIfNotExists<StudentContext>
{
    protected override void Seed(StudentContext context)
    {
        base.Seed(context);
    }
}


For this application, I am implementing the “DropCreateDatabaseIfModelChanges” database initializer method, globally.aspx file.
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        Database.SetInitializer<StudentContext>(new DropCreateDatabaseIfModelChanges<StudentContext>());
    }
}


Step 6. Now working with Generic Repository
Add an Interface.
public interface IGenericRepo<T> where T : class
{
    IEnumerable<T> GetAll();
    T GetById(int id);
    void Insert(T obj);
    void Update(T obj);
    void Delete(int id);
    void Save();
}


As we can see Interface is very simple and easy to understand here, Here <T> I took to incorporate with any classes whoever needed.
Inside Interface, we are implementing two type parameters - T1, (type parameter is a concept which is taken in C++ for making the generic concept). Here, I am not saying both are the same. The T1 type parameter specifies the class type, which means that we pass the class while implementing the generic interface to any class, and on the other hand, I haven’t specified the T2 with any data, the reason is that - it might be any class having unique id in different type (might be int, string or all).

Implement the generic repository with Entity Framework.
public class GenericRepo<T> : IGenericRepo<T> where T : class
{
    private StudentContext _context = null;
    private DbSet<T> table = null;

    public GenericRepo()
    {
        this._context = new StudentContext();
        table = _context.Set<T>();
    }

    public GenericRepo(StudentContext _context)
    {
        this._context = _context;
        table = _context.Set<T>();
    }

    public IEnumerable<T> GetAll()
    {
        return table.ToList();
    }

    public T GetById(int id)
    {
        return table.Find(id);
    }

    public void Insert(T obj)
    {
        table.Add(obj);
    }

    public void Update(T obj)
    {
        table.Attach(obj);
        _context.Entry(obj).State = EntityState.Modified;
    }

    public void Delete(int id)
    {
        T existing = table.Find(id);
        table.Remove(existing);
    }

    public void Save()
    {
        _context.SaveChanges();
    }
}


Now, it is very easy to implement the controller class to play with CRUD operation with the Repository class. As the code stated first we are creating a private member of our context class, and assigning it to null. same as with the Dbset.

Two constructors I created, as default and parameterized for initializing the context. As the context is get initilize we will able to call implemented Generic methods.

Have a look at the fetch and insert records using the Controller class.
public class HomeController : Controller
{
    private IGenericRepo<Students> repository = null;

    public HomeController()
    {
        this.repository = new GenericRepo<Students>();
    }

    public HomeController(IGenericRepo<Students> repository)
    {
        this.repository = repository;
    }

    public ActionResult Index()
    {
        var obj = repository.GetAll();
        return View(obj);
    }

    [HttpGet]
    public ActionResult AddStudent()
    {
        return View();
    }

    [HttpPost]
    public ActionResult AddStudent(Students obj)
    {
        repository.Insert(obj);
        return RedirectToAction("Index");
    }
}

Summary
This article explained the generic repository pattern, this approach where we can handle multiple databases with a single implemented class, only we have to pass the respective class to operate the desired result. We have also seen the pros and cons of the generic repository pattern.



ASP.NET MVC Hosting - HostForLIFE.eu :: Knowing EF Core MVC's Connected Disconnected Scenarios

clock January 7, 2025 06:56 by author Peter

Working with data is essential in contemporary online applications, and Entity Framework Core (EF Core) offers a productive method of interacting with databases through the use of Object-Relational Mapping (ORM). The Connected and Disconnected scenarios are the two main methods that EF Core provides for handling data in an application. Both situations differ in how data is recorded, accessed, and stored in the database, and they are crucial in distinct use cases. Both of these ideas are examined in this article along with workable solutions in a.NET Core MVC application.

What is a Connected Scenario?
In a Connected scenario, the DbContext is directly connected to the entity instances and actively tracks changes made to the data. This is the default behavior of EF Core when entities are retrieved using a context and modified within the scope of the context.

  • Key Characteristics of a Connected Scenario
  • Change Tracking: EF Core automatically tracks changes made to the entities. When SaveChanges() is called, it updates the database with those changes.
  • Short-lived Context: The DbContext instance is created, used, and disposed of within a limited scope, often tied to a single HTTP request in a web application.
  • Automatic State Management: EF Core keeps track of the state of entities, such as Added, Modified, Deleted, and Unchanged.

Practical Example
Let’s create a simple CRUD operation in a Connected scenario for managing a list of users.

Create the Model
namespace EFCoreConnectedDisconnectedDemo.Model
{
    public class User
    {
        public int Id { get; set; }
        public string? Name { get; set; }
        public string? Email { get; set; }
    }
}

Set Up DbContext
using EFCoreConnectedDisconnectedDemo.Model;
using Microsoft.EntityFrameworkCore;

namespace EFCoreConnectedDisconnectedDemo.ApplicationContext
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }

        public DbSet<User> Users { get; set; }
    }
}

Create the controller

using EFCoreConnectedDisconnectedDemo.ApplicationContext;
using EFCoreConnectedDisconnectedDemo.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace EFCoreConnectedDisconnectedDemo.Controllers
{
    public class UserController : Controller
    {
        private readonly ApplicationDbContext _context;

        public UserController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: User
        public IActionResult Index()
        {
            var users = _context.Users.ToList();
            return View(users);
        }

        // GET: User/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: User/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create([Bind("Id, Name, Email")] User user)
        {
            if (ModelState.IsValid)
            {
                _context.Add(user);
                _context.SaveChanges(); // Save the changes in the connected scenario
                return RedirectToAction(nameof(Index));
            }
            return View(user);
        }

        // GET: User/Edit/5
        public IActionResult Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var user = _context.Users.Find(id);
            if (user == null)
            {
                return NotFound();
            }
            return View(user);
        }

        // POST: User/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(int id, [Bind("Id, Name, Email")] User user)
        {
            if (id != user.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(user);
                    _context.SaveChanges(); // EF Core automatically tracks changes and updates the database
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!_context.Users.Any(e => e.Id == user.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(user);
        }

        // GET: User/Delete/5
        public IActionResult Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var user = _context.Users
                .FirstOrDefault(m => m.Id == id);
            if (user == null)
            {
                return NotFound();
            }

            return View(user);
        }

        // POST: User/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteConfirmed(int id)
        {
            var user = _context.Users.Find(id);
            _context.Users.Remove(user);
            _context.SaveChanges(); // EF Core will automatically track the deletion
            return RedirectToAction(nameof(Index));
        }
    }
}


Create the Views
Index.cshtml, Create.cshtml, Edit.cshtml, and Delete.cshtml are Razor views for handling the respective CRUD actions.

How it Works in a Connected Scenario?

  • Tracking Changes: EF Core tracks changes made to User entities in the database automatically.
  • Saving Changes: Calling SaveChanges() saves the changes (whether added, updated, or deleted) to the database.

What is a Disconnected Scenario?
In a Disconnected scenario, the DbContext is not available to track changes once the data is retrieved from the database. This scenario is common in applications where the DbContext is disposed of after the entity data is fetched, such as in web APIs where entities are transferred over HTTP.

Key Characteristics of a Disconnected Scenario

  • No Change Tracking: Entities are not tracked once the DbContext is disposed of, meaning changes must be manually managed.
  • Manual State Management: In disconnected scenarios, the entity must be explicitly attached to the context and marked with its state (e.g., Modified) when changes are saved.
  • Common in Web APIs: Commonly used in Web API scenarios where entities are transferred to and from clients and must be handled after detaching from the context.

Practical Example
Let’s handle a simple scenario where data is fetched in a disconnected manner, then updated and saved.

Create a Web API Controller for Disconnected Scenario
using EFCoreConnectedDisconnectedDemo.ApplicationContext;
using EFCoreConnectedDisconnectedDemo.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace EFCoreConnectedDisconnectedDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ApiUserController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public ApiUserController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: api/ApiUser/5
        [HttpGet("{id}")]
        public ActionResult<User> GetUser(int id)
        {
            var user = _context.Users.Find(id);
            if (user == null)
            {
                return NotFound();
            }
            return user;
        }

        // PUT: api/ApiUser/5
        [HttpPut("{id}")]
        public IActionResult PutUser(int id, User user)
        {
            if (id != user.Id)
            {
                return BadRequest();
            }

            // In disconnected scenario, we must attach the entity back to the context and mark it as modified
            _context.Users.Attach(user);
            _context.Entry(user).State = Microsoft.EntityFrameworkCore.EntityState.Modified;

            try
            {
                _context.SaveChanges(); // Save changes to the database manually
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!_context.Users.Any(e => e.Id == user.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }
    }
}


How it Works in a Disconnected Scenario?
The data is fetched and passed to the client (e.g., as JSON).

When the client sends an updated version of the entity, the entity must be explicitly attached to the DbContext.

The entity is marked as modified, and the changes are saved by calling SaveChanges().

When to Use Each Scenario?

  • Connected Scenario: Best suited for web applications or APIs where the DbContext remains active throughout the request lifecycle. It simplifies the development process since EF Core automatically handles change tracking.
  • Disconnected Scenario: Ideal for web APIs and scenarios where the DbContext is not available after data is retrieved. It requires explicit management of entity states and is suitable for distributed systems or client-server models.

Conclusion
In this post, we looked at how to use Entity Framework Core in an ASP.NET Core MVC application to manage connected and disconnected circumstances. Knowing the distinctions between these two methods can help you decide whether your application needs manual state management (disconnected) or automatic change monitoring (connected) for data management. Both situations are necessary for developing effective and reliable data-driven applications and are crucial in various use cases.



ASP.NET MVC Hosting - HostForLIFE.eu :: Action Method In ASP.NET MVC

clock December 20, 2024 08:02 by author Peter

ASP.NET MVC action methods are responsible to execute the request and generate a response to it. All the public methods of the MVC Controller are action methods. If we want the public method to be a  non-action method, then we can decorate the action method by “NonAction” attribute. It will restrict the action method to render on the browser.

 
To work with action method we need to remember the following points.

  • The action method is the public non-static method.
  • Action method can not be the private or protected method.
  • Action method can not contain ref and out parameters.
  • Action method can not be an extension method.
  • Action method can not be overloaded.

Example of an action method in ASP.NET MVC 5 is as below.

    public class HomeController : Controller  
        {  
            // GET: Home  
            public ActionResult Index()  
            {  
                return View();  
            }  
    }  


You can see in the above action method example that the Index() method is a public method which is inside the HomeController class. And the return type of the action method is ActionResult. It can return using the “View()” method. So, every public method inside the Controller is an action method in MVC.
 
Action Method can not be a private or protected method.
    public class HomeController : Controller  
        {  
            // GET: Home  
            private ActionResult Index()  
            {  
                return "This is Index Method";          
            }  
    }  


If you provide the private or protected access modifier to the action method, it will provide the error to the user, i.e., “resource can not be found” as below.

Action method can not be overloaded.
    public string Index()  
           {            
               return "This is Index Method";  
           }  
      
           public string Index(int id)  
           {  
               return "This is Index overloaded Method";  
           }  

If you try to overload the action method, then it will throw an ambiguous error.

An action method cannot contain ref and out parameters.
    public string Index(ref int id)  
            {  
                return "This is Index Method" +id;  
            }  

    public string Index(out int id)  
           {  
               id = 0;  
               return "This is Index Method" +id;  
           }  


We can not provide the ref and out parameters to the action method. If you try to provide the ref and out parameters to the action method, then it will throw an error as below.



Action method can not be overloaded.
    public string Index()  
           {            
               return "This is Index Method";  
           }  
      
           public string Index(int id)  
           {  
               return "This is Index overloaded Method";  
           }  


If you try to overload the action method, then it will throw an ambiguous error.


 
Types of Action Method.

  • Action Method
  • Non Action Method

How to restrict the public action method in MVC?
To restrict the public action method in MVC, we can use the “NonAction” attribute. The “NonAction” attribute exists in the “System.Web.MVC” namespace.
 
Example of NonAction attribute in ASP.NET MVC.
    [NonAction]  
      public string GetFullName(string strFirstName, string strLastName)  
      {  
              return strFirstName + " " + strLastName;  
      }  

How to call Action Method?
Syntax

YourDomainName/ControllerName/ActionMethodName
 
Example
 
localhost/Home/Index

How to change default Action Method?
The default Action method is configured in the RouteConfig.cs class. By default, the Action Method is the “Index” action method. Change the “Index” action method name as per our requirement.
    public static void RegisterRoutes(RouteCollection routes)  
            {  
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
      
                routes.MapRoute(  
                    name: "Default",  
                    url: "{controller}/{action}/{id}",  
                    defaults: new { controller = "Home", action = "Message", id = UrlParameter.Optional }  
                );  
            }  

You can see in the above code that we have changed the action method name to “Message” instead of “Index” by default.
 
How does the default action get executed?
Default controller and action method are configured in RouteConfig.cs class. By default, Controller is the Home Controller and default Action Method is the “Index” action method.
 
Example of default action method
    public static void RegisterRoutes(RouteCollection routes)  
            {  
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
      
                routes.MapRoute(  
                    name: "Default",  
                    url: "{controller}/{action}/{id}",  
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
                );  
            }  



ASP.NET MVC Hosting - HostForLIFE.eu :: Session in ASP.NET Core MVC .NET 8

clock December 11, 2024 06:09 by author Peter

What is a Session?
Session is KEY-VALUE structure to store the user specific data. In Asp.Net Core .NET 8 session is not enable by default, we have to enable it. Session data persists across multiple HTTP requests.


How many ways for Session storage?

In-Memory Cache: Server base storage. Storage capacity is depend upon server’s available memory. Best for single server base environment.
Distributed Cache: Session storage not on one server its store on multiple server. Distributed cache work with Redis, Sql Server etc. .

How to Enable Session in .Net 8 Asp.Net Core MVC Application?

builder.Services.AddSession();

Add another line just after app declaration line:
app.UseSession();

How to set or store the value in session?
Create or Setting Session value.

Syntax
HttpContext.Session.SetString(KEY,VALUE);
HttpContext.Session.SetInt22(KEY,VALUE);


Example
HttpContext.Session.SetString(“USERNAME”, UserName);
HttpContext.Session.SetString(“USERID”,Convert.ToString(UserID));

How to get or retrieve the value of session?
Getting Session value.

Syntax
HttpContext.Session.GetString(KEY);

HttpContext.Session.GetInt22(KEY);


Example
HttpContext.Session.GetString(“USERNAME”);

HttpContext.Session.GetString(“USERID”);


How to remove particular session key?
You can easily remove a specific session key.

Syntax
HttpContext.Session.Remove(KEY);

Example
HttpContext.Session.Remove(“UESERNAME”);

How to remove all session keys?
You can delete/remove/clear all sessions in one go.

HttpContext.Session.Clear();


Clear: It remove all the current session entries from the server.

OR

HttpContext.SignOutAsync();

SignOutAsync: It end the current user session and remove or clear the user’s authentication cookie from the server.
Walk-through on session implementation

In this article I had used Visual Studio 2022. After follow step by step you are able to implement SESSION in your Asp.Net Core project.

 

 

Above screenshot is a view of default project structure of Asp.Net Core .NET 8.

Now open program.cs file to add following line:
builder.Services.AddSession(); //

app.UseSession(); //after app declaration.


Update Program.cs file Code:
var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddControllersWithViews();

// Configure session service for the application
builder.Services.AddSession();

var app = builder.Build();

// Enable the Session Middleware
app.UseSession();

// Configure the HTTP request pipeline
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Open the HomeController.cs file from CONTROLLERS folder.

Update HomeController.cs file code:
using LearnCore.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace LearnCore.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            // Create SESSION called USERNAME and store value "Peter Scott"
            HttpContext.Session.SetString("USERNAME", "
Peter Scott");
            return View();
        }

        public IActionResult Privacy()
        {
            // Get value from SESSION
            string UserValName = HttpContext.Session.GetString("USERNAME")?.ToString();
            ViewBag.UserName = UserValName;
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Open the Privacy.cshtml file from VIEWS àHOME.

Update the Privacy.cshtml file code :
@{
    ViewData["Title"] = "Privacy Policy";
}

<h1>@ViewData["Title"]</h1>

<p>Use this page to detail your site's privacy policy.</p>

<h2>
    User Name: <i><u>@ViewBag.UserName</u></i>
</h2>

Now press F5 to run the project. Happy Coding!



ASP.NET MVC Hosting - HostForLIFE.eu :: Application Using Backbone.js with ASP.NET MVC

clock December 3, 2024 07:37 by author Peter

This article shows the use of Backbone.js with ASP.NET MVC with a simple MVC application using backbone.js. Before this article we used backbone with HTML but here we will use with cshtml.



Use the following procedure to create the sample.

Step 1

  • Create a Web API application with the following:
  • Start Visual Studio 2013.
  • From Start window Select "New Project".
  • Select "Installed" -> "Template" -> "Visual C#" -> "Web" -> "Visual Studio 2012" and select "ASP.NET MVC4 Web Application".
  • Click the "OK" button.

From the MVC4 project window select "Empty application".

Click on the "OK" button.

Step 2
Now add a MVC controller class in the Controller folder.

  • In the Solution Explorer.
  • Right-click on the Controller folder.
  • Select "Add" -> "Controller" then select "Empty MVC Controller" and click on the "Add" button.

Add the "Person Action method".
public class HomeController : Controller
{
    //
    // GET: /Home/
    public ActionResult Index()
    {
        return View();
    }
    public ActionResult Person()
    {
        return View();
    }
}


Now we need to add a "index.cshtml" view in the Home folder. Right-click on the "Person()" action method, select "Add view" then open an "Add View" window then click on the "Add" button.

Add the following code in this view:
@{
    ViewBag.Title = "Person";
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Backbone.js Web App</title>
    <link href="~/Content/style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
    <div id="persons"></div>
    <script id="personTemplate" type="text/template">
        <img src="<%= photo %>" alt="<%= name %>" />
        <h1><%= name %><span><%= type %></span></h1>
        <div><%= address %></div>
        <dl>
            <dt>Tel:</dt>
            <dd><%= tel %></dd>
            <dt>Email:</dt>
            <dd><a href="mailto:<%= email %>"><%= email %></a></dd>
        </dl>
    </script>
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/Scripts/json2.js"></script>
    <script src="~/Scripts/underscore-min.js"></script>
    <script src="~/Scripts/backbone-min.js"></script>
    <script src="~/Scripts/main.js" type="text/javascript"></script>
    </div>
</body>
</html>

Step 3
Now we create a JavaScript file as "main.js".

  • In the Solution Explorer.
  • Right-click on the "Scripts" folder select "Add" -> "JavaScript".

Click on the "Add" button.

Add the following code;
(function ($) {
    //demo data
    var persons = [       { name: "Person 1", address: "Address 1", tel: "0123456789", email: "[email protected]", type: "family" },       { name: "Person 2", address: "Address 2", tel: "0123456789", email: "[email protected]", type: "family" },
    ];
    //define product model
    var Person= Backbone.Model.extend({
        defaults: {
            photo: "img/placeholder.png"
    }
    });
//define directory collection
var Directory = Backbone.Collection.extend({
    model: Person
});
//define individual person view
var PersonView = Backbone.View.extend({
    tagName: "article",
    className: "person-container",
    template: $("#personTemplate").html(),
    render: function () {
        var tmpl = _.template(this.template);
        $(this.el).html(tmpl(this.model.toJSON()));
        return  this;
    }
});
//define master view
var DirectoryView = Backbone.View.extend({
    el: $("#persons"),
    initialize: function () {
        this.collection = new Directory(persons);
        this.render();
    },
    render: function () {
        var that = this;
        _.each(this.collection.models, function (item) {
            that.renderPerson(item);
        }, this);
    },
    renderPerson: function (item) {
        var personView = new PersonView({
            model: item
        });
        this.$el.append(personView.render().el);
    }
});
//create instance of master view
var directory = new DirectoryView();
} (jQuery));

There is were we need the other scripting files "backbone.js","underscore.js", "json2.js" and "jquery-1.8.2.min.js".

Step 4
Now execute the application:



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: ASP.NET MVC With Knockout.Js

clock November 21, 2024 07:36 by author Peter

Fundamentals of MVVM
Developers will soon find the MVVM design pattern in Silverlight and WPF necessary. Martin Fowler's Presentation Model, which gathers strength from MVC and MVP flexible structures, serves as the foundation for the MVVM architecture. The UI design patterns with Code-Behind are meant to be entirely or partially distinct from one another.


 
The three primary components of MVVM are Model, View, and ViewModel. When the View is totally ignorant of the model, ViewModel makes reference to it. This eliminates the developer's need to interact with the business logic interface.


The diagram above describes the situation in the best way. The Model may vary throughout the project. The View is unaware of this situation. The Model is isolated from the View. The ViewModel is a middle man for managing the binding and commands.
 
With Only jQuery on MVC
Let's talk about jQuery. jQuery has a strong binding mechanism that uses HTML tag ids, a CSS class and a HTML tag name. Values are pushed from the source object into the HTML elements, thus requiring a line of code for each mapping from the source value to the target element. It's much easier with KO. It lets you scale up in complexity without fear of introducing inconsistencies. jQuery is simple to bind with values and tags.
 
jQuery cannot serve us in the following ways:
Any source object changes will not reflected on HTML elements. (You can push values and call again.)
Any changes in the HTML elements won't be reflected on source objects.

Code:
    <h2>Using Jquery  
        Without Knockout</h2>  
    <span>StudentNumber:</span><span id="StudentNumber"></span>  
    <br />  
    <span>Surname:</span><input id="StudentSurName" />  
    <span>Name:</span><input id="StudentName" />  
    <script type="text/javascript">  
    $(document).ready(function() {  
        var student = {  
            Number: "A123456",  
            Surname: "Leon",  
            Name: "Alexander"  
        };  
        $("#StudentNumber").text(student.Number);  
        $("#StudentSurName").val(student.Surname);  
        $("#StudentName").val(student.Name);  
    });  
    </script>  

You can bind your values to HTML tags using the HTML tag's id and CSS classes. jQuery is an excellent low-level way to manipulate elements and event handlers on a web page. jQuery doesn't have a concept of an underlying data model. If you bind the values of any object like above, you will not observe any changes in the UI after any change of the Model. You must refresh web pages to observe View changes. On the other hand; if you change the HTML element's value then your model won't be fired.

What is knockout.js?

KO is not an alternative to jQuery or other js libraries (Prototype, MooTools). KO focuses on MVVM to manipulate the Model to the View from AJAX calls. KO manages between the ViewModel and View the automatic relation that is triggered by user interface calls.
 
Model: Business Logic.
View:   HTML/CSS. If you change the ViewModel's objects, the View will be effected automatically.
ViewModel: He is a middle man to observable connection Model and View because the Model doesn't have any knowledge of the View.
 
Observable and Binding: KO's focus is on the Data-Driven js concepts; in other words, any changes in the View will fire the model; also the model's changes will automatically fire the View's updates. KO is on the alert to communicate between them in both directions.

Code:
<h2>With Knockout</h2>  
<span>Student Number:</span><span data-bind="text: Number"></span>  
<br />  
<span>Surname:</span><input data-bind="value: Surname" />  
<span>Name:</span><input data-bind="value: Name" />  
<script type="text/javascript">  
var student = {  
    Number: "A123456",  
    Surname: "Leon
",  
    Name: "Alexander"  
}  
// Activates knockout.js  
ko.applyBindings(student);  
</script>  

The HTML tag binding is unable to observe the Data-Bind structure. KO concentrates on data-binding via the data-bind tag. But the preferred usage is the following. It is useful to control the View's changes for values of the Model's objects. Observable property is one of the most important things. MVVM needs to observe any changes in UI. KO will consider any changes to the View. Actually, when you edit one of those text boxes, it does update the underlying ViewModel data.

Update your ViewModel to make the Name and Surname properties observable using ko.observable:

<script type="text/javascript">  
var student = {  
    Number: ko.observable("A123456"),  
    Surname: ko.observable("Leon"),  
    Name: ko.observable("Alexander")  
}  
// Activates knockout.js  
ko.applyBindings(student);  
</script>  


Now re-run the application and edit the text boxes. This time you'll see not only that the underlying ViewModel data is being updated when you edit, but that all associated UI is updating in sync with it too.

Simple Usage Knockout on MVC
Real-World applications need to be fed from a database. So, the Model would be your application's stored data that would be implemented using a server-side technology. The View is always interested in the UI requests. The Viewmodel contains objects to manage any responses from the View. A programmer must be able to imagine how to generate a ViewModel, not only WPF but also data-driven HTML pages. Data-driven means that the implementation of the ViewModel uses JavaScript.
 
Sometimes, we don't need to implement the ViewModel with JavaScript. We can bind the server-side Model to the View. "@Html.Raw(Json.Encode(Model));" is an effective way to bind the Server-side Model to the View.

Model: public class Student {  
        public string Number {  
            get;  
            set;  
        }  
        public string Name {  
            get;  
            set;  
        }  
        public string Surname {  
            get;  
            set;  
        }  
    }  
    //Controller:  
      
    [HttpGet]  
    publicActionResult StudentMvcWithKnockout() {  
        Student student = new Student();  
        student.Number = "B123456";  
        student.Name = "Peter";  
        student.Surname = "Scott";  
        return View(student);  
    }  
    //View:  
      
    @using System.Web.Script.Serialization;  
    @model MvcAppWithJquery.Models.Student  
    @ {  
        ViewBag.Title = "StudentMvcWithKnockout";  
        Layout = "~/Views/Shared/_Layout.cshtml";  
    }  
    <h2>StudentMvcWithKnockout</h2> <  
    scriptsrc = "../../Scripts/knockout-2.1.0.js"  
    type = "text/javascript" > < /script> <  
    scriptsrc = "../../Scripts/knockout.mapping-latest.js"  
    type = "text/javascript" > < /script> <  
    p > Name: < strongdata - bind = "text: Name" > < /strong></p >  
        <p>SurName:<strongdata-bind="text: Surname"></strong></p> <  
        scripttype = "text/javascript" >  
        $(function() {  
            var model = @Html.Raw(Json.Encode(Model));  
            ko.applyBindings(model);  
        }); <  
    /script>  


By calling ko.mapping in the view, we can access JSON data. But we must pass the JSON data from the controller by "return Json(StudentList,JsonRequestBehavior.AllowGet);". So we need a number of collections on ViewModel. We call "ko.applyBindings(viewModel) - so" simply using:
$(document).ready(function () { ko.applyBindings(viewModel); });
 
The $.ajax and $.getJSON methods are appropriate to get the JSON data. (Controller/Action) You can find two methods in the source code.


Code:
    // Controller  
    public JsonResult GetStudents()  
    {  
    List<Student> StudentList = newList<Student>(){new Student(){ Number="A123456", Name="Alexander", Surname="Leon"},  
            new Student(){ Number="B123456", Name="Peter", Surname="Scott"},  
            new Student(){ Number="C123456", Name="Michael", Surname="Leroy"},  
            new Student(){ Number="D123456", Name="Frank", Surname="Mill"}};  
            return Json(StudentList,JsonRequestBehavior.AllowGet);  
            }  
            // View  
            <tbody data-bind="foreach: Students">  
                <tr style="border-bottom: 1px solid #000000;">  
                    <td>  
                        <span data-bind="text: Number"></span>  
                    </td>  
                    <td>  
                        <span data-bind="text: Name"></span>  
                    </td>  
                    <td>  
                        <span data-bind="text: Surname"></span>  
                    </td>  
                </tr>  
            </tbody>  
            </table>  
            </div>  
            </form>  
            <script type="text/javascript">  
            var AppViewModel = function() {  
                var self = this;  
                self.Students = ko.mapping.fromJS([]);  
                $.getJSON('/Student/GetStudents/', function(data) { ko.mapping.fromJS(data, {}, self.Students); });  
            }  
            $(document).ready(function() {  
                var viewModel = new AppViewModel();  
                ko.applyBindings(viewModel);  
            });  
            </script>  

Review of Codes
"self.Students = ko.mapping.fromJS([]);" is an important one because "mapping from What?" is necessary. Mapping is controlled by Js. Calling'/Student/GetStudents/' we can feed the ViewModel.
You should use "$.getJSON" and "$.ajax" to get the JSON data.
Using "ko.mapping.fromJS(data, {}, self.Students);" you can fill the "self.Students" ViewModel using data that is in the JSON format.

Summary
KO can help you implement it easier and improve maintainability. Model Changes are observed by the ViewModel and updated UI parts. KO is a simple way to connect the UI from the Data Model. You can charge data procedures on KO so other js events (Click, Mouseover, Grid etc.) can be developed by using jQuery. KO is a pure JavaScript library that works with any server and client-side technology. KO provides a way to use MVVM on MVC technology. KO provides a complimentary, high-level way to link a data model to a UI.



ASP.NET MVC Hosting - HostForLIFE :: The Pipeline and Architecture of MVC

clock November 11, 2024 07:09 by author Peter

MVC is merely a design pattern used to create applications; it is not a programming language. The MVC design pattern was first used for creating Graphical User Interface (GUI) programs, but it is now also widely used for constructing desktop, mobile, and web apps. This technique is used in many programming languages, but we'll talk about it in relation to ASP.NET.

Last week one of my friends asked this question: "What is the MVC Architecture & its Pipeline?" and I am dedicating this article to him. I hope he will like this.

What does MVC mean?
In ASP.NET, model-view-controller (MVC) is the name of a methodology or design pattern for efficiently relating the user interface to underlying data models.

Understanding MVC

Model
It is responsible for maintaining the data and behavior of the application or it can be called the Business Layer. The classes in Models have properties and methods that represent the application state and rules and are called Entity classes or Domain classes, as well as these are independent of the User Interface (UI).

Models also contain the following types of logic.

  • Business logic
  • Data access logic
  • Validation logic

Model classes are used to perform the validation logic and business rules on the data. These are not dependent on the UI so we can use these in different kinds of applications. Simply, these are Plain Old CLR Objects (POCOs).

What is POCO?

The classes that we create in the Model folder, are called POCOs. These classes contain only the state and behavior of the application and they don’t have the persistence logic of the application. That’s why these are called persistent ignorant objects. POCO class is,

public class Student
{
}


The main benefits of POCOs are really used when you start to use things like the repository pattern, forms, and dependency injection. In other words – when we create an ORM (let's say EF) that pulls back data from somewhere (DB, web service, etc.), then passes this data into objects (POCOs). Then if one day we decide to switch over to NHibernate from EF, we should not have to touch your POCOs at all, the only thing that should need to be changed is the ORM.

View

This layer represents the HTML markup that we display to the user. This can be called the Display Layer. View is the user interface in which we render the Model in the form of interaction. The Views folder contains the .cshtml or .vbhtml files which clearly shows that these files are the combination of HTML and C#/VB code. In the Views folder, for every Controller there is a single view folder and for each action method in the controller, there is a view in that view folder, having the same name as that of the controller and action method respectively. There is also a Shared folder in the Views folder which represents the existence of Layout and Master Page in ASP.NET MVC.

Controller

When the user interacts with the user interface; i.e. View, then an HTTP request is generated which is in the MVC architectural pattern, handled by the Controller. So we can say that the Controller’s responsibility is to handle the HTTP request. This layer can also handle the input to the database or fetch the data from the database records. So it can be called the Input layer.

The Controllers folder contains the classes that are responsible for handling HTTP requests. The name of the controller ends with the word Controller to differentiate it from other classes, for example, AccountController, and HomeController. Every controller inherits from the ControllerBase class which implements the IController interface which is coming from the System.Web.Mvc namespace. The IController interface's purpose is to execute some code when the request comes to the controller. The look and feel of the controller is like this.
using System.Web.Routing;

namespace System.Web.Mvc
{
    {
        void Execute(RequestContext requestContext);
    }
}


There is an Execute method in the IController class that gets executed when the request comes to the controller. This method takes an object of the RequestContext class, and this class encapsulates the information about the HTTP request that matches the defined route, with the help of HttpContext and RouteData properties. The look and feel of the RequestContext class is like this.
using System.Runtime.CompilerServices;
namespace System.Web.Routing
{
    // Encapsulates information about an HTTP request that matches a defined route.
    public class RequestContext
    {
        // Initializes a new instance of the System.Web.Routing.RequestContext class.
        public RequestContext();

        // Initializes a new instance of the System.Web.Routing.RequestContext class.
        // Parameters:
        // httpContext:
        // An object that contains information about the HTTP request.
        // routeData:
        // An object that contains information about route that matched the current
        // request.
        public RequestContext(HttpContextBase httpContext, RouteData routeData);

        // Summary:
        // Gets information about the HTTP request.
        // Returns:
        // An object that contains information about the HTTP request.
        public virtual HttpContextBase HttpContext
        {
            get;
            set;
        }

        // Summary:
        // Gets information about the requested route.
        // Returns:
        // An object that contains information about the requested route.
        public virtual RouteData RouteData
        {
            get;
            set;
        }
    }
}


The code is very self-explanatory with the help of comments.

How does this architecture work?
The workflow of MVC architecture is given below, and we can see the request-response flow of an MVC web application.

The figure is very self-explanatory and shows the workflow of MVC architecture. The client, which is the browser, sends a request to the server (internet information server) and the Server finds a Route specified by the browser in its URL and through Route. The request goes to a specific Controller and then the controller communicates with the Model to fetch/store any records. Views are populated with model properties, and the controller gives a response to the IIS7 server, as a result server shows the required page in the browser.

As we know, in MVC there are three layers that are interconnected to each other such as in the figure.

Here, in MVC there is complete separation in each layer, referred to as Separation of Concerns. Now, what exactly does Separation of Concerns mean?

What is the Separation of Concerns?
Separation of concerns (SoC) is a design principle for separating a computer program into distinct sections, such that each section addresses a separate concern. A concern is a set of information that affects the code of a computer program. (Wikipedia)

MVC implements the principle of SoC as it separates the Model, View, and Controller. Following is the table that depicts the implementation of SoC and Violation of SoC in ASP.NET MVC.

Implementation of SoC Violation of SoC
Views are only for displaying the HTML markup to the browser.

When we use business logic in View then it is a violation because its sole purpose is to display the page not to execute the logic.

@if (user.Role == "Admin") { }
else { }


Controllers are just to handle the incoming HTTP request.

When we use business logic in the Controller like when the controller executes the database logic to fetch/store the information in the database, it is a violation of single responsibility principle as well.

public ActionResult Index()
{
    if (ModelState.IsValid)
    {
        dbContext.Employees.Add(model);
    }
    return RedirectToAction("Saved");
}

Use the Service layer to implement this business logic in the web application.

Models contain classes of the domain or business.

When we use ViewBag and ViewData to pass the data from controller to view instead of using ViewModels to display data in view. ViewModels are classes that bind strongly typed views. Use the Repository pattern to access the data from the database.

public ActionResult Contact()
{
    ViewBag.Message = "Your contact page.";
    return View();
}

Characteristics of MVC
These are the main characteristics of ASP.NET MVC,

  • Enables clean separation of concerns (SoC).
  • Follows the design of the stateless nature of the web.
  • Provides Test Driven Development (TDD).
  • Easy integration with JavaScript frameworks.
  • Provides full control over the rendered HTML.
  • No ViewState and PostBack events

Pipeline in MVC
We can say that the pipeline of MVC contains the following processes.

  • Routing
  • Controller Initialization
  • Action Execution
  • Result Execution
  • View Initialization and Rendering

 

Let’s understand them one by one!

Routing

Routing is the first step in the ASP.NET MVC pipeline. In fact, it is a pattern-matching system that matches the incoming request to the registered URL patterns which reside in the Route Table.

Routing is a system in which URL patterns are matched with the URL patterns defined in the RouteTable by using the MapRoute method. The process of Routing comes into action when the application starts, firstly it registers the routes in the RouteTable. This registration of routes in the RouteTable is essential because it is the only thing that tells the Routing Engine how to treat the requested URL requests. The routes are registered in the RouteConfig class App_Start file of the application. Let's have a look at it.
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new
            {
                controller = "Home",
                action = "Index",
                id = UrlParameter.Optional
            }
        );
    }
}

The Global. asax file looks like.
protected void Application_Start()
{
    // Some other code is removed for clarity.
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

The Routing Engine is the module whose responsibility is to treat the HTTP request. When an HTTP request comes, the UrlRoutingModule starts matching the perfect URL pattern from the RouteTable, when found successfully, the Routing Engine forwards the request to RouteHandler.

In RouteHandler its interface IRouteHandler comes into action and calls its GetHttpHandler method. This method looks as below.
public interface IRouteHandler
{
    IHttpHandler GetHttpHandler(RequestContext requestContext);
}


After finding the route successfully, the ProcessRequest() method is invoked, as shown in the figure above, otherwise, user will receive an HTTP 404 error page.

Controller Initialization
While the ProcessRequest() method is invoked, it uses the IControllerFactory instance to create the controller for the URL request. The IContollerFactory is responsible to instantiate and return an appropriate controller and this created controller will become the subclass of the Controller base class.Then the Execute() method is invoked.

ProcessRequest() method looks like this.
protected internal virtual void ProcessRequest(HttpContextBase httpContext)
{
    SecurityUtil.ProcessInApplicationTrust(delegate
    {
        IController controller;
        IControllerFactory factory;
        this.ProcessRequestInit(httpContext, out controller, out factory);
        try
        {
            controller.Execute(this.RequestContext);
        }
        finally
        {
            factory.ReleaseController(controller);
        }
    });
}


Action Execution
Action Execution starts with Action Invoker. So, after the initialization of controller, it has the information about the action method, this detail of the action method is passed to the controller’s InvokeAction() method. This InvokeAction() implements the interface IActionInvoler and hence the action is selected for invoking.

public virtual bool InvokeAction(ControllerContext controllerContext, string actionName)

After ActionInvoker, Model Binders come into action. Model binders are used to retrieve the data from the HTTP request and after taking data from it, it applies the validation, and data type conversion rules on that data. For example, it checks its validity by comparing its data type with the data type of action parameters, etc. Model Binders are present in the System.Web.Mvc.DefaultModelBinder namespace.

When Model Binders take data from the requested URL then it is time to apply restrictions on the use of that data. So for this purpose, we have an Authentication filter that comes into action and authenticates the user whether that user is valid or not. You can apply authentication by using the Authenticate attribute. This authentication is done with the help of the IAuthenticationFilter interface. So you can create your own by implementing it.

After authentication after checking it the user is valid or not, the Authorization Filter comes into action and checks the user access, which means who can use the data in which way. Authorization Filter applies to the authenticated user, it doesn’t apply to unauthenticated users. So authorization filter sets the user access for the authenticated user. You can use the authorization filter by applying the Authorize attribute at the top of the action method. And this authorization is done with the help of the IAuthorizationFilter interface. So you can implement it to create your own.

After collecting data from HTTP requests, and performing authorization on any authenticated user, now is the time to execute the action. So our Action Filters come into play. Action Filters execute with the help of the IActionFilter interface. This interface has two methods that are executed before and after the action is executed, named OnActionExecuting and OnActionExecuted respectively. I’ll post another article on “How can we create a custom action filter?”

After the execution of the Action, the ActionResult is generated. Hence the process of Action Execution is completed.


Result Execution
The “Result Execution” module executes after the execution of the module “Action Execution”, in this module Result Filters come into action and execute before and after the ActionResult is executed. Result Filters are also implemented by IResultFilter, so you can create your own result filters by implementing this interface.

As you saw in the action execution section, you have Action Result as a result. There are many types of Action Results such as ViewResult, PartialViewResult, RedirectToRoute, RedirectResult, JsonResult, ContentResult, and Empty Result. These types are all categorized into two main categories named as ViewResult and Non-ViewResult types.

ViewResult type: ViewResult is a type of result in which the View of MVC part uses means by which an HTML page is rendered.
NonViewResult type: NonViewResult is a type of result that deals with only data. Data may be in text format, JSON format, or binary format.

View Initialization and Rendering

View Engine takes the ViewResult type and renders it as a View and shows it by using IView. The IView interface looks like as below,
public interface IView
{
    void Render(ViewContext viewContext, TextWriter writer);
}

After rendering the View, it is time to make HTML Helpers that are used to write input files, create links, forms, and much more. These helpers are extension methods of the HTML helper class. Validation rules can also be applied, for example, view should use HtmlHelpers and render a form having client-side validations.


Hence this is the pipeline of MVC. We have discussed each part very thoroughly.

Conclusion

This article included the basic and foremost things to understand about MVC architectural pattern and its pipeline. If you have any query then feel free to contact me in the comments. Also give feedback, either positive or negative, it will help me to make my articles better and increase my enthusiasm to share my knowledge.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Dependency Injection & EF Migrations in ASP.NET MVC with Autofac

clock October 31, 2024 07:13 by author Peter

This post will demonstrate how to integrate Entity Framework for database operations, including migration setup, and use Autofac to create Dependency Injection (DI) in an ASP.NET MVC application. Code modularity, testability, and maintainability are all enhanced by this method.

Configuring Dependency Injection with Autofac
1. Install the Autofac packages first.
To install Autofac and its integration package for MVC, launch the Package Manager Console and execute the subsequent commands.

Install-Package Autofac
Install-Package Autofac.Mvc5

Step 2. Configure Autofac
Open Global.asax.cs and configure Autofac in the Application_Start method.
using Autofac;
using Autofac.Integration.Mvc;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WebApplication2.Data;
using WebApplication2.IRepository;
using WebApplication2.Service;
namespace WebApplication2
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            var builder = new ContainerBuilder();
            // Register MVC controllers
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            // Register DbContext for DI
            builder.RegisterType<MyDbContext>().AsSelf().InstancePerRequest();
            // Register your services here
            builder.RegisterType<ProductService>().As<IProductService>();
            // Build the Autofac container
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            // Regular MVC application start
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}


Implementing Entity Framework and Migrations

Step 1. Install Entity Framework
Run the following command in the Package Manager Console to install Entity Framework:
Install-Package EntityFramework

Step 2. Create MyDbContext

In the WebApplication2.Data namespace, create a class named MyDbContext to represent your database context:

Create Model Class for Product.
using System.ComponentModel.DataAnnotations;
namespace WebApplication2.Models
{
    public class Product
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}

Step 2. Create MyDbContext

In the WebApplication2.Data namespace, create a class named MyDbContext to represent your database context:
using System.Data.Entity;
using WebApplication2.Models;
namespace WebApplication2.Data
{
    public class MyDbContext : DbContext
    {
        public MyDbContext() : base("SqlServerConnection")
        {

        }
        // Define your entities here
        public DbSet<Product> Products { get; set; }
    }
}

Step 3. Enable Migrations

In the Package Manager Console, run the following command to enable migrations.
Enable-Migrations

Step 4. Create Initial Migration
Create an initial migration based on your current model.
Add-Migration InitialCreate

Step 5. Update Database

Apply the migration to the database:
Update-Database

Step 6. Add Connection String

Add a connection string for MyDbContext in the Web.config file.
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="SqlServerConnection" connectionString="Server=MUD\SQLEXPRESS2022;Database=DIAndMigInNetFrameWord;User Id=sa;Password=123456;" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Web.Infrastructure" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.9.0" newVersion="5.2.9.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-8.0.0.1" newVersion="8.0.0.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-8.1.1.0" newVersion="8.1.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.1" newVersion="4.2.0.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Bcl.AsyncInterfaces" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=&quot;Web&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <!-- Removed SQLite and Npgsql providers -->
    </providers>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SQLite.EF6" />
      <remove invariant="System.Data.SQLite" />
      <remove invariant="Npgsql" />
      <add name="SQL Server" invariant="System.Data.SqlClient" description=".NET Framework Data Provider for SQL Server" type="System.Data.SqlClient.SqlClientFactory, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </DbProviderFactories>
  </system.data>
</configuration>


Creating the Service and Repository Layers

Step 1. Create IProductService Interface

In the WebApplication2.IRepository namespace defines an interface for the product service.
using System.Collections.Generic;
using WebApplication2.Models;
namespace WebApplication2.IRepository
{
    public interface IProductService
    {
        IEnumerable<Product> GetAllProducts();
        void AddProduct(Product product);
    }
}

Step 2. Implement ProductService
In the WebApplication2.Service namespace, implement the ProductService class.
using System.Collections.Generic;
using System.Linq;
using WebApplication2.Data;
using WebApplication2.IRepository;
using WebApplication2.Models;
namespace WebApplication2.Service
{
    public class ProductService : IProductService
    {
        private readonly MyDbContext _context;
        public ProductService(MyDbContext context)
        {
            _context = context;
        }
        public IEnumerable<Product> GetAllProducts()
        {
            return _context.Products.ToList();
        }
        public void AddProduct(Product product)
        {
            _context.Products.Add(product);
            _context.SaveChanges();
        }
    }
}


Step 3. Create the Product Model
In the WebApplication2.Data namespace, create a Product model class.
using System.ComponentModel.DataAnnotations;
namespace WebApplication2.Models
{
    public class Product
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}


Creating the MVC Controller
Create a controller to handle requests related to products.

Step 1. Create ProductController

In the Controllers folder, create a ProductController
using System.Web.Mvc;
using WebApplication2.IRepository;
using WebApplication2.Models;
namespace WebApplication2.Controllers
{
    public class ProductController : Controller
    {
        private readonly IProductService _productService;
        public ProductController(IProductService productService)
        {
            _productService = productService;
        }
        public ActionResult Index()
        {
            var products = _productService.GetAllProducts();
            return View(products);
        }
        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(Product product)
        {
            if (ModelState.IsValid)
            {
                _productService.AddProduct(product);
                return RedirectToAction("Index");
            }
            return View(product);
        }
    }
}


Step 2. Create the View
In the Views/Product folder, create a view named Index. cshtml.
@model IEnumerable<WebApplication2.Models.Product>
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
        <th></th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}
</table>


Step 3. Create the View

In the Views/Product folder, create a view named Create. cshtml.
@model WebApplication2.Models.Product
@{
    ViewBag.Title = "View";
}
<h2>View</h2>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Product</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


Step 3. Create the View
Add the controller and Actions link in Layout Files.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-dark bg-dark">
        <div class="container">
            @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            <button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" title="Toggle navigation" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse d-sm-inline-flex justify-content-between">
                <ul class="navbar-nav flex-grow-1">
                    <li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                    <li>@Html.ActionLink("About", "About", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                    <li>@Html.ActionLink("Product", "Index", "Product", new { area = "" }, new { @class = "nav-link" })</li>
                </ul>
            </div>
        </div>
    </nav>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>


Database Creation
After doing all of this, just run the migration.

Create Initial Migration
After enabling migrations, generate the initial migration based on your current model:
Add-Migration InitialCreate

This command creates a migration class in the Migrations folder that defines the initial schema for your database based on the Product model and the MyDbContext.

Update Database
Now, apply the migration to the database with the following command.
Update-Database

This command will create the database and tables defined in your MyDbContext. If your connection string is set up correctly, the database will be created in your SQL Server instance.

Running the Application

  • Run the application in Visual Studio.
  • Navigate to http://localhost:8081/Product/Index
  • You should see the products displayed in a table.

Output


 

Conclusion
In this article, we successfully implemented Dependency Injection using Autofac and integrated Entity Framework for data access in an ASP.NET MVC application. This setup allows for better separation of concerns, making the application easier to maintain and test. By following these steps, you can extend this architecture to accommodate more complex business logic, additional services, and different data operations as needed. Happy coding!



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in