LAB 1
Write a program to achieve the run time polymorphism.
Ans:
Runtime polymorphism in .NET is a fundamental concept in object-oriented programming (OOP) that
allows you to invoke methods on objects at runtime, and the specific method that gets executed is
determined by the actual type of the object rather than the declared type of the reference variable.
This is also known as method overriding and is achieved through inheritance and the use of the
override keyword in C#.
using System;
class Class1{
public virtual void Display(){
[Link]("This is the display method of Class 1");
}
}
class Class2: Class1{
public override void Display(){
[Link]("This is the display method of Class 2");
}
}
class Program
{
static void Main()
{
Class2 obj2 = new Class2();
[Link]();
[Link]();
}
}
Output:
1
LAB 2.
Write a program to handle exception when User put character in price field.
using System;
class Program
{
static void Main(string[] args)
{
int price = 0;
try
{
[Link]("Enter the price: ");
price = Convert.ToInt32([Link]());
}
catch (Exception e)
{
[Link]("Invalid input format. Please enter a valid price. ");
[Link]($"Error Message:{[Link]}");
}
finally{
[Link]($"The value for price is {price} "); }
}
}
Output:
2
LAB 3
Write a program to display student list filter by department Id using Lambda
expression. Student has attributes(Id, DepartmentId, Name and Address) and
take any number of students.
using System;
using [Link];
using [Link];
class Student
{
public int Id { get; set; }
public int DepartmentId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Student> students = new List<Student>
{
new Student { Id = 102, DepartmentId = 301, Name = "Aaron", Address = "Thamel" },
new Student { Id = 32, DepartmentId = 702, Name = "Steven", Address = "Lainchaur"
},
new Student { Id = 35, DepartmentId = 121, Name = "Maxwell", Address = "Lazimpat"
},
new Student { Id = 44, DepartmentId = 193, Name = "David", Address = "Sorhakhutte"
}
};
var results = [Link](student => [Link] == 193);
foreach (var student in results)
{
[Link]($"ID: {[Link]}\nName: {[Link]}\nAddress:
{[Link]}");
}
}
}
3
Output:
LAB 4
Write a program to validate the Login form when user submit empty value
using JQuery.
<!DOCTYPE html>
<html>
<head>
<title>Login Form Validation using JQuery</title>
<script src="[Link]
<script>
$(document).ready(function() {
$("#login-form").submit(function(event) {
var username = $("#username").val();
var password = $("#password").val();
if (username === "" ) {
[Link]();
$("#username_msg").text("Username cannot be empty"); }
if(password === ""){
[Link]();
$("#password_msg").text("Password cannot be empty"); }
});
});
</script>
4
</head>
<body>
<fieldset style="text-align: center; ">
<legend>Login Form</legend>
<form id="login-form" action="#" method="post">
<input type="text" id="username" placeholder = "Enter Username">
<p id = "username_msg" style="color: red;"> </p>
<input type="password" id="password" placeholder="Enter Password">
<p id = "password_msg" style="color: red;"> </p>
<input type="submit" value="Login">
</form>
</fieldset>
</body>
</html>
Output:
5
LAB 5
Write a program to get the list of products in json format using [Link] Web
API.
a.) Define the Product model:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
b.) Define the controller:
using [Link];
namespace [Link]
{
[ApiController]
[Route("[controller]")]
public class ProductsController : ControllerBase
{
private static List<Product> products = new List<Product>
{
new Product { Id = 1, Name = "Product 1", Price = 10.99M },
new Product { Id = 2, Name = "Product 2", Price = 20.49M },
};
[HttpGet(Name = "GetProduts")]
public IActionResult GetProducts()
{
return Ok(products); //be default, "Ok" method returns in JSON format.
}
}
}
c.) Build the project.
6
Output:
LAB 6
Write a program to program to validate Player Information when click on
save button using MVC pattern.
Step1: Create a model [Link]
namespace [Link]
{
public class Player
{
[Required]
public int Id { get; set; }
[Range(10, 20)]
public string Name { get; set; }
[Required]
public int Age { get; set; }
}
}
Step 2: Add Following code in [Link]
[HttpPost]
public IActionResult Privacy(Player players)
{
if ([Link])
{
return Content("Successfully validated");
}
else
{
return View(players);
}
}
Step 3: Add following code in [Link] which will be our form page
@model [Link]
<h1>Player Validation</h1>
7
<p>Form for Player</p>
@using ([Link]())
{
<div class=" name">
@[Link](m=>[Link])
@[Link](m=>[Link])
@[Link](m=>[Link])
</div>
<br />
<div class=" name">
@[Link](m=>[Link])
@[Link](m=>[Link])
@[Link](m=>[Link])
</div>
<br />
<div class = "age">
@[Link](m=>[Link])
@[Link](m=>[Link])
@[Link](m=>[Link])
</div>
<br />
<br />
<button type = "submit"> Submit </button>
Then run the app,
Output:
8
LAB 7
Write a program to implement Authorization using User Roles.
using System;
using [Link];
// Define user roles
enum UserRole
{
Admin,
Moderator,
User
}
// Simulate a user class
class User
{
public string Username { get; set; }
public UserRole Role { get; set; }
}
// Authorization service
class AuthorizationService
{
private Dictionary<string, UserRole> userRoles = new Dictionary<string, UserRole>();
public void AddUser(User user)
{
userRoles[[Link]] = [Link];
}
public bool IsAuthorized(User user, UserRole requiredRole)
{
if ([Link]([Link]))
{
return userRoles[[Link]] >= requiredRole;
}
return false;
}
}
class Program
{
static void Main(string[] args)
{
AuthorizationService authorizationService = new AuthorizationService();
9
// Create users
User adminUser = new User { Username = "admin", Role = [Link] };
User modUser = new User { Username = "moderator", Role = [Link] };
User regUser = new User { Username = "user123", Role = [Link] };
// Add users to the authorization service
[Link](adminUser);
[Link](modUser);
[Link](regUser);
// Simulate authorization checks
[Link]([Link](adminUser, [Link])); // true
[Link]([Link](modUser, [Link])); // true
[Link]([Link](regUser, [Link])); // false
[Link]([Link](regUser, [Link])); // true
}
}
Output:
10
LAB 8
Write a program to store User login information for 5 days using Cookie
Solution:
Certainly! Here's an example of how you can create a simple [Link] Core MVC application to
store user login information for 5 days using cookies:
Step 1: Configure Cookie Authentication
In your `[Link]` file, configure cookie authentication:
using [Link];
public void ConfigureServices(IServiceCollection services)
[Link]([Link])
.AddCookie(options =>
[Link] = [Link](5); // Cookie expiration time
});
Step 2: Create Login and Logout Actions
Create login and logout actions in your `AccountController`:
public class AccountController : Controller{
private readonly SignInManager<IdentityUser> _signInManager;
public AccountController(SignInManager<IdentityUser> signInManager)
_signInManager = signInManager;
[HttpGet]
public IActionResult Login()
11
return View();
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
if ([Link])
var result = await _signInManager.PasswordSignInAsync([Link], [Link],
[Link], false);
if ([Link])
return RedirectToAction("Index", "Home");
[Link]("", "Invalid login attempt");
return View(model);
public async Task<IActionResult> Logout()
await _signInManager.SignOutAsync();
return RedirectToAction("Index", "Home");
Step 3: Use Authentication in Controllers
Use the `[Authorize]` attribute in controllers to require authentication
[Authorize]
public class HomeController : Controller
12
}
Step 4: Display User Information in Views**
You can access user information in views using `[Link]`:
@if ([Link])
<p>Welcome, @[Link]!</p>
<p>Your last login was: @[Link]</p>
Step 5: Run the Application
Run the application using `dotnet run` and navigate to `[Link] to
log in. After logging in, the user's login information will be stored in a cookie for 5 days, and you
can access it in views.
LAB 9
Write a crud operation to display, insert, update and delete Student
information using [Link] CORE MVC.
Solution
Creating a complete CRUD (Create, Read, Update, Delete) application in [Link] Core MVC
involves multiple steps and requires creating controllers, views, models, and setting up database
access. CRUD operations for displaying, inserting, updating, and deleting Student information in
an [Link] Core MVC application.
Step 1: Create a Model
Create a `Student` class representing the model in your project:
public class Student
public int Id { get; set; }
13
public string Name { get; set; }
public string Address { get; set; }
Step 2: Create a DbContext
Create a `DbContext` class to manage database operations:
using [Link];
public class ApplicationDbContext : DbContext
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
public DbSet<Student> Students { get; set; }
Step 3: Create Controllers and Views
Generate controllers and views using scaffolding. Open the terminal and navigate to your project
folder:
dotnet aspnet-codegenerator controller -name StudentsController -m Student -dc
ApplicationDbContext --relativeFolderPath Controllers --useDefaultLayout
This command generates a `StudentsController` with CRUD actions and views.
Step 4: Configure Routing
In `[Link]`, configure routing to your `StudentsController`:
[Link](endpoints =>
[Link](
14
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
Step 5: Perform Migrations
In the terminal, run the following commands to perform migrations and create the database:
dotnet ef migrations add InitialCreate
dotnet ef database update
Step 6: Run the Application
Run the application using `dotnet run` and navigate to `[Link] to
access the CRUD interface for Student information.
15