Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

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(){
Console.WriteLine("This is the display method of Class 1");
}
}
class Class2: Class1{
public override void Display(){
Console.WriteLine("This is the display method of Class 2");
}
}
class Program
{
static void Main()
{
Class2 obj2 = new Class2();
obj2.Display();
Console.ReadKey();
}
}

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
{
Console.Write("Enter the price: ");
price = Convert.ToInt32(Console.ReadLine());

}
catch (Exception e)
{
Console.WriteLine("Invalid input format. Please enter a valid price. ");
Console.WriteLine($"Error Message:{e.Message}");
}
finally{
Console.WriteLine($"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 System.Collections.Generic;
using System.Linq;

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 = students.Where(student => student.DepartmentId == 193);

foreach (var student in results)


{
Console.WriteLine($"ID: {student.Id}\nName: {student.Name}\nAddress:
{student.Address}");
}
}
}

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="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>

$(document).ready(function() {
$("#login-form").submit(function(event) {
var username = $("#username").val();
var password = $("#password").val();
if (username === "" ) {

event.preventDefault();
$("#username_msg").text("Username cannot be empty"); }
if(password === ""){
event.preventDefault();
$("#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 ASP.NET 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 Microsoft.AspNetCore.Mvc;

namespace WebApplication2.Controllers
{
[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 Player.cs


namespace PlayerValidation.Models
{
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 HomeController.cs


[HttpPost]
public IActionResult Privacy(Player players)
{
if (ModelState.IsValid)
{
return Content("Successfully validated");
}
else
{
return View(players);
}
}

Step 3: Add following code in privacy.cshtml which will be our form page
@model PlayerValidation.Models.Player

<h1>Player Validation</h1>

7
<p>Form for Player</p>
@using (Html.BeginForm())
{

<div class=" name">


@Html.LabelFor(m=>m.Id)
@Html.TextBoxFor(m=>m.Id)
@Html.ValidationMessageFor(m=>m.Id)
</div>
<br />
<div class=" name">
@Html.LabelFor(m=>m.Name)
@Html.TextBoxFor(m=>m.Name)
@Html.ValidationMessageFor(m=>m.Name)
</div>
<br />
<div class = "age">
@Html.LabelFor(m=>m.Age)
@Html.TextBoxFor(m=>m.Age)
@Html.ValidationMessageFor(m=>m.Age)
</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 System.Collections.Generic;

// 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[user.Username] = user.Role;
}

public bool IsAuthorized(User user, UserRole requiredRole)


{
if (userRoles.ContainsKey(user.Username))
{
return userRoles[user.Username] >= requiredRole;
}
return false;
}
}

class Program
{
static void Main(string[] args)
{
AuthorizationService authorizationService = new AuthorizationService();

9
// Create users
User adminUser = new User { Username = "admin", Role = UserRole.Admin };
User modUser = new User { Username = "moderator", Role = UserRole.Moderator };
User regUser = new User { Username = "user123", Role = UserRole.User };

// Add users to the authorization service


authorizationService.AddUser(adminUser);
authorizationService.AddUser(modUser);
authorizationService.AddUser(regUser);

// Simulate authorization checks


Console.WriteLine(authorizationService.IsAuthorized(adminUser, UserRole.Admin)); // true
Console.WriteLine(authorizationService.IsAuthorized(modUser, UserRole.Moderator)); // true
Console.WriteLine(authorizationService.IsAuthorized(regUser, UserRole.Admin)); // false
Console.WriteLine(authorizationService.IsAuthorized(regUser, UserRole.User)); // 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 ASP.NET Core MVC application to
store user login information for 5 days using cookies:

Step 1: Configure Cookie Authentication

In your `Startup.cs` file, configure cookie authentication:

using Microsoft.AspNetCore.Authentication.Cookies;

public void ConfigureServices(IServiceCollection services)

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)

.AddCookie(options =>

options.ExpireTimeSpan = TimeSpan.FromDays(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 (ModelState.IsValid)

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password,


model.RememberMe, false);

if (result.Succeeded)

return RedirectToAction("Index", "Home");

ModelState.AddModelError("", "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 `User.Identity`:

@if (User.Identity.IsAuthenticated)

<p>Welcome, @User.Identity.Name!</p>

<p>Your last login was: @User.Identity.AuthenticationTime</p>

Step 5: Run the Application

Run the application using `dotnet run` and navigate to `https://localhost:8805/Account/Login` 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 ASP.NET CORE MVC.
Solution

Creating a complete CRUD (Create, Read, Update, Delete) application in ASP.NET 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 ASP.NET 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 Microsoft.EntityFrameworkCore;

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 `Startup.cs`, configure routing to your `StudentsController`:

app.UseEndpoints(endpoints =>

endpoints.MapControllerRoute(

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 `https://localhost:8805/Students` to


access the CRUD interface for Student information.

15

You might also like