0% found this document useful (0 votes)
4 views

SRIJAN_BASNET_ DOTNET_LAB

The document provides an overview of the C# programming language, covering its syntax, basic constructs, flow control statements, arrays, classes, methods, and exception handling. It includes source code examples demonstrating key concepts such as variable declaration, control structures, and object-oriented programming principles like inheritance. The document concludes with practical experiments showcasing the application of these concepts in C#.

Uploaded by

gbot98318
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

SRIJAN_BASNET_ DOTNET_LAB

The document provides an overview of the C# programming language, covering its syntax, basic constructs, flow control statements, arrays, classes, methods, and exception handling. It includes source code examples demonstrating key concepts such as variable declaration, control structures, and object-oriented programming principles like inheritance. The document concludes with practical experiments showcasing the application of these concepts in C#.

Uploaded by

gbot98318
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

LAB - 1: ​

LANGUAGE PRELIMINARIES

OBJECTIVE: ​
TO LEARN ABOUT THE VARIOUS PRELIMINARIES FOR THE C#
PROGRAMMING LANGUAGE

C# SYNTAX:

THEORY:
C# is a high level, general-purpose, object-oriented programming language
developed by Microsoft. A C# Program may consists of the following parts:
• Namespace Declaration
• Class
• Class Methods
• Class Attributes
• Main Method
• Statements and Expressions
• Comments

A new console app for The C# can be created using :


dotnet new console -o preliminary

The C# Program can be run in the program directory using the


command: dotnet run
The entry Point for C# Console app is given by Program.cs.

SOURCE PROGRAM:
using System;
namespace SyntaxLearning
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}

OUTPUT:

CONCLUSION:
Hence, from the above experiment, we were able to demonstrate a basic C# console application
that utilizes essential programming elements for basic C# Syntax.


BASIC LANGUAGE CONSTRUCTS (VARIABLES AND DATA TYPES):​

THEORY:
Variables are special containers that hold the data at specific memory locations. Variables can
Either Be Numeric, String, Characters , Booleans , Decimal , Date and so on. The syntax for the
declaration of variables in C# is given as:
data_type variable_name;
e.g.
int age;
Different Data Types in a C# program are:
Data Types Keywords

Integer int

Floating float

Character char

Boolean bool

Decimal decimal

C# also has the Reference data type which stores reference to the value in the managed heap.
Some of The Reference Data Types are:
• Class Type
• String Type
• Delegate Type
• Interface Type
• Array Type

SOURCE PROGRAM:
using System;

namespace DataTypeShowcase
{
class Program
{
static void Main(string[] args)
{
int yearsOfExperience = 5;
float averageScore = 85.6f;
string firstName = "Alice";
bool hasDrivingLicense = false;
decimal accountBalance = 2500.75m;
char grade = 'A';
int[] attendanceDays = { 1, 3, 5, 7, 9, 11, 13, 15 };
if (hasDrivingLicense)
{
Console.WriteLine("You have a driving license.");
}
else
{
Console.WriteLine("You do not have a driving license.");
}
Console.WriteLine($"Name: {firstName}, Experience: {yearsOfExperience} years, Average
Score: {averageScore}, Grade: {grade}, Account Balance: {accountBalance}");
Console.WriteLine("Attendance Days:");
foreach (int day in attendanceDays)
{
Console.Write(day + " ");
}
}
}
}

OUTPUT:

CONCLUSION:
Hence, from the above experiment, we were able to showcase the various data types in the C#
programming language.
FLOW CONTROL STATEMENTS:

THEORY:​
Flow Control Statement is the programming construct that determines which part of the code is
to be executed next using conditions and loops. The two Types of flow control statements are
Conditional Statements and Loop Statements.

if/else statements: In C#, if-else statements are control structures that enable the program to
execute specific blocks of code based on evaluated boolean conditions.
Syntax:
if (condition)
{
// Code to execute if condition is true
}
else
{
// Code to execute if condition is false
}

switch case statements: C# also provides switch statements for multi-case comparisons, which
can be seen as a form of nested if-else constructs optimized for value-based comparisons.
Syntax:
switch (expression)
{
case value1:
// Code block 1
break;
case value2:
// Code block 2
break;
...
default:
// Default code block
}

looping statements: Loops in C# allows you to execute the statements or group of statements
repeatedly until a certain condition is met. C# has the following types of looping statements. -
for loop
- while loop
- do/while loop
- foreach loop

SOURCE PROGRAM:
using System;
namespace ConditionalShowcase
{
class Program
{
static void Main(string[] args)
{
int age = 20;
if (age >= 18)
{
Console.WriteLine("You can vote.");
}
else
{
Console.WriteLine("You cannot vote.");
}
}
}
}

OUTPUT:

SOURCE PROGRAM:
using System;
namespace ConditionalShowcase
{
class Program
{
static void Main(string[] args)
{
int dayOfWeek = 1;

switch (dayOfWeek)
{
case 1:
Console.WriteLine("Sunday");
break;
case 2:
Console.WriteLine("Monday");
break;
case 3:
Console.WriteLine("Tuesday");
break;
case 4:
Console.WriteLine("Wednesday");
break;
case 5:
Console.WriteLine("Thursday");
break;
case 6:
Console.WriteLine("Friday");
break;
case 7:
Console.WriteLine("Saturday");
break;
default:
Console.WriteLine("Invalid day of the week");
break;
}
}
}
}

OUTPUT:

SOURCE PROGRAM:
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("For Loop Example");
for (int i = 0; i < 5; i++)
{
Console.Write(i + " ");
}
Console.WriteLine("\n");
Console.WriteLine("While Loop Example");
string sentence = "The fox Jumps over the world";
int j = 0;
int countWords = 0;
while (j < sentence.Length)
{
if (sentence[j] == ' ')
{
countWords++;
}
j++;
}
Console.WriteLine("Number of words in the sentence: " + (countWords +
1)); Console.WriteLine("\n");
Console.WriteLine("Do While Loop Example");
int age;
do
{
Console.Write("Enter your age: ");
age = Convert.ToInt32(Console.ReadLine());
if (age < 18)
{
Console.WriteLine("Not Allowed to vote");
}

} while (age < 18);


Console.WriteLine("Allowed to vote");
Console.WriteLine("\n");
Console.WriteLine("foreach Loop Example");
string[] names = { "John", "Doe", "Jane" };
foreach (string name in names)
{
Console.Write(name + " ");
}
}
}

OUTPUT:

CONCLUSION:
Hence, from the above experiment, we are able to demonstrate various flow control
statements in C# programming language.
ARRAYS: ​

THEORY:
An Array is the collection of the same type of variable.
Syntax for array Declaration is given as:
data_type[] arr_name;

e.g.
string[] strarr=new string[5] //this is how we allocate along with size

Jagged Arrays:
In C#, a jagged array is an array of arrays, where each element of the main array is itself an array.
Unlike a multidimensional array, the sub-arrays in a jagged array can be of different lengths,
hence the term "jagged."

Syntax for Jagged Arrays Declaration


// Declare a jagged array
int[][] jaggedArray;

// Initialize the main array with a specific number of rows


jaggedArray = new int[3][];

// Initialize each sub-array with different lengths


jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };

SOURCE PROGRAM:
using System;
namespace ArrayShowcase
{
class Program
{
static void Main(string[] args)
{
int[] regularArray = { 1, 2, 3, 4, 5 };
Console.WriteLine("Regular array:");
for (int i = 0; i < regularArray.Length; i++)
{
Console.Write(regularArray[i] + " ");
}
Console.WriteLine();

int[][] jaggedArray = new int[3][];


jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };

Console.WriteLine("Jagged array:");
for (int i = 0; i < jaggedArray.Length; i++)
{
Console.Write($"Row {i + 1}: ");
for (int j = 0; j < jaggedArray[i].Length; j++)
{
Console.Write(jaggedArray[i][j] + " ");
}
Console.WriteLine();
}
}
}
}

OUTPUT:


CONCLUSION:
Hence, from the above experiment, we are able to demonstrate the use of both a simple string
array and a jagged array in C# programming language.
CLASS, METHODS:​

THEORY:
In C# a class is a blueprint or template for creating objects (instances) that encapsulate data
(fields or properties) and behavior (methods or functions). It is a fundamental concept in object
oriented programming (OOP) and serves as the foundation for defining custom data types. Key
Features of a Class Are:
1. Fields: Variables That Hold the Data
2. Properties: Special methods that provide controlled access to Fields
4. Methods: Functions that define the behavior of the class.
5. Constructors: Special Methods that Helps to initialize the Object
6. Access Modifiers: Keywords like public private protected that control the visibility of the class
members.
7. Inheritance: A Class can inherit fields and methods from another class (base class) to promote
code reuse.

Syntax for class Definition is given as:


class ClassName{
AccessModifier DataType Variable;
public ClassName(parameters){
//Constructor Body
}
}

In C#, a method is a block of code that performs a specific task or operation. It is a fundamental
building block of a program and is used to encapsulate reusable logic. Methods are defined
within a class or struct and can be called (invoked) to execute their code.

Syntax for method declaration in C# is given as:


AccessModifier return_type MethodName(parameters){
//Method Body
return value;
}

SOURCE PROGRAM:
using System;
namespace ClassShowcase
{
class Program
{
static void Main(string[] args)
{
Person person = new Person("Ana", 25);
person.DisplayInfo();
person.Greet();
}
}
class Person
{
private string name;
private int age;
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
public void DisplayInfo()
{
Console.WriteLine($"Name: {name}, Age: {age}");
}
public void Greet()
{
Console.WriteLine($"Hello, {name}.");
}
}
}

OUTPUT:

CONCLUSION:
Hence, from the above experiment, we are able to demonstrate the use of a class and methods
in C# programming language with fields, properties, a constructor, .
EXCEPTION HANDLING:​

THEORY:
The Exceptional Handling in C# is done using try, catch and finally blocks. This is the
Mechanism to detect and handle the runtime errors in code. The .NET framework provides the
built-in classes for common exceptions. The exceptions can be because of user, logic or system
errors.
Syntax for Exception Handling is given as:
try{
// Statement which can cause an exception
}
catch(Type x){
//Statement for handling the exception
}
finally{
// Final Code After The Exception Handling i.e. cleanup code
}

- The try block contains the code that might throw an exception.
- The catch block handles the exception if it occurs.
- The finally block contains code that will always execute, whether an exception occurs or
not. It is typically used for cleanup tasks (e.g., closing files or releasing resources). - The
throw statement is used to explicitly throw an exception.

SOURCE PROGRAM :
using System;
namespace ExceptionHandlingShowcase
{
class Program
{
static void Main(string[] args)
{
try
{
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
Console.Write("Enter another number: ");
int divisor = int.Parse(Console.ReadLine());
int result = number / divisor;
Console.WriteLine($"Result: {result}");
}
catch (FormatException ex)
{
Console.WriteLine($"Error: Invalid input. {ex.Message}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: Cannot divide by zero. {ex.Message}");
}
finally
{
Console.WriteLine("Execution completed.");
}
}
}
}

OUTPUT :

CONCLUSION:
Hence, from the above experiment, we are able to demonstrate exception handling in C# by
attempting to divide two user-input numbers, catching specific exceptions like
DivideByZeroException and ensuring the finally block executes to indicate completion.
LAB - 2:​
OOP CONCEPTS

OBJECTIVE: TO LEARN ABOUT THE VARIOUS OOP


CONCEPTS IN C# PROGRAMMING LANGUAGE

INHERITANCE:​

THEORY:
Inheritance is a key feature of Object-Oriented Programming (OOP) that allows a class
(child/derived) to inherit members (fields, methods, properties) from another class (parent/base).
i. Single Level Inheritance: In single-level inheritance, a child class inherits from a single parent
class.
Syntax:
class Parent{
//methods and properties
}

class Children:Parent{
//Children methods and properties
}

ii. Multi-Level Inheritance: In multi-level inheritance, a class is derived from another derived
class, forming a chain of inheritance.
Syntax:
class GranParent{
//methods and properties
}

class Parent: GrandParent{


//Parent Methods and Properties
}

class Children: Parent{


//Children Methods and Properties
}

iii. Multi-Level Inheritance with Interface:


Interfaces in C# provide a way to achieve multiple inheritances since a class can inherit multiple
interfaces but only one class.
Syntax:
interface Iname{
//methods and properties
}

SOURCE PROGRAM:
using System;
namespace InheritanceShowcase
{
interface IGreet
{
void Greet();
}
class Person : IGreet
{ protected string name;
public Person(string name)
{
this.name = name;
}
public virtual void DisplayInfo()
{Console.WriteLine($"Name: {name}");
}
public void Greet()
{ Console.WriteLine($"Hello, my name is {name}.");
}
}
class Employee : Person
{
protected int employeeId;
public Employee(string name, int employeeId) : base(name)
{
this.employeeId = employeeId;
}
public override void DisplayInfo()
{
base.DisplayInfo();
Console.WriteLine($"Employee ID: {employeeId}");
}
}
class Manager : Employee
{
private string department;
public Manager(string name, int employeeId, string department) : base(name, employeeId)
{
this.department = department;
}
public override void DisplayInfo()
{
base.DisplayInfo();
Console.WriteLine($"Department: {department}");
}
}
class Program
{
static void Main(string[] args)
{
Manager manager = new Manager("Srijan", 777, "Automations");
manager.DisplayInfo();
manager.Greet();
}
}
}

OUTPUT:

CONCLUSION:
Hence, from the above experiment, we are able to demonstrate multilevel inheritance and
interface in the C# programming language.
CONSTRUCTOR, PROPERTIES AND METHODS: ​

THEORY:

A constructor is a special method that initializes objects of a class. It is automatically called


when an instance of the class is created.

i. Default Constructor
A constructor without parameters.
Syntax:
class ClassName
{
public ClassName()
{
// Constructor logic
}
}

ii. Parameterized Constructor


A constructor that takes arguments to initialize values.
Syntax:
class ClassName
{
public ClassName(string param)
{
// Constructor logic using param
}
}
iii. Constructor Overloading
Multiple constructors with different parameters in the same class.
Syntax:
class ClassName
{
public ClassName() { }
public ClassName(int value) { }
public ClassName(string name, int age) { }
}

Methods define the behavior of a class and perform specific tasks.


Syntax:
class ClassName{
accessModifier returnType methodName (args){
//Method Body
}
}

Properties in C# act as getters and setters to encapsulate class fields.

SOURCE PROGRAM:
using System;

namespace PropertyAndConstructorShowcase
{
class Person
{
public string Name { get; set; }
public int Age { get; set; }

public Person()
{
Name = "Unknown";
Age = 0;
}

public Person(string name, int age)


{
Name = name;
Age = age;
}
public Person(Person person)
{
Name = person.Name;
Age = person.Age;
}
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}

class Program
{
static void Main(string[] args)
{
Person person1 = new Person();
person1.DisplayInfo();
Person person2 = new Person("Zephyr", 25);
person2.DisplayInfo();
Person person3 = new Person(person2);
person3.DisplayInfo();
}
}
}

OUTPUT:

CONCLUSION:
Hence, from the above experiment, we are able to demonstrates the use of constructors,
methods, and properties in C# programming language.
METHOD OVERLOADING AND OVERRIDING:​

THEORY:
Method Overloading allows multiple methods in the same class to have the same name but
different parameters. The method signature must differ in:
1. Number of parameters
2. Type of parameters
3. Order of parameters

Key Characteristics of Method Overloading


• It occurs within the same class.
• The return type may or may not be different.
• It improves code readability and usability.
• It is an example of Compile-time Polymorphism (Static Binding) since the method to be
called is determined at compile time.

Method Overriding allows a subclass to provide a specific implementation of a method that is


already defined in its superclass. The method in the subclass must have the same name, return
type, and parameters as the method in the parent class.
Key Characteristics of Method Overriding
• It occurs in two different classes (parent and child class).
• The method in the parent class must be marked as virtual, abstract, or override. •
The method in the child class must use the override keyword.
• It is an example of Runtime Polymorphism (Dynamic Binding) since the method to be
called is determined at runtime.

SOURCE PROGRAM:
using System;
namespace MethodOverloadingShowcase
{
class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
public int Add(int a, int b, int c)
{
return a + b + c;
}
public double Add(double a, double b)
{
return a + b;
}
}

class Program
{
static void Main(string[] args)
{
Calculator calculator = new Calculator();
Console.WriteLine("Add two integers: " + calculator.Add(1, 2));
Console.WriteLine("Add three integers: " + calculator.Add(1, 2, 3));
Console.WriteLine("Add two doubles: " + calculator.Add(1.1, 2.2));
}
}
}

OUTPUT:

CONCLUSION:
Hence, from the above experiment,This program demonstrates Method Overloading by
defining multiple Add methods with different parameters and Method Overriding by
allowing the Dog class to override the Eat method of the Animal class, showcasing both
compile-time and runtime polymorphism in C#.​

LAMBDA EXPRESSIONS: ​

THEORY:
Lambda expressions are a concise way to represent anonymous functions in C#. They are
primarily used in LINQ queries and delegate-based programming. The term "lambda" comes
from lambda calculus, a formal system for defining functions.
Syntax:
(parameters) => expression
OR
(parameters) => { statement(s) }

e.g.
y => y * y
This expression takes a parameter y and returns its square (y * y).
• Expression Lambdas:
Lambda expressions that contain only a single expression on the right-hand side are
known as expression lambdas.
• Async Lambdas:
Lambda expressions can also be used with asynchronous programming by incorporating
the async keyword:

Func<Task<string>> getWordAsync = async () => "hello";

This makes the lambda function return a Task<string> asynchronously.

SOURCE PROGRAM:
using System;
using System.Collections.Generic;
using System.Linq;
namespace LambdaExpressionShowcase
{
class Program
{
static void Main(string[] args)
{
Func<int, int> triple = (a) => a * 3;
Console.WriteLine("Tripling a number using lambda: " + triple(7));

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };


List<int> evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
Console.WriteLine("Even numbers:");
evenNumbers.ForEach(n => Console.WriteLine(n));
List<Person> people = new List<Person>
{
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 25 },
new Person { Name = "Charlie", Age = 35 }
};
List<Person> olderThan30 = people.Where(p => p.Age > 30).ToList();
Console.WriteLine("People older than 30:");
olderThan30.ForEach(p => Console.WriteLine(p.Name));
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
}

OUTPUT:


CONCLUSION:
Hence, from the above experiment, we are able to demonstrate various lambda
expressions in C# programming language.
LAB - 3:​
ASP .NET MVC

OBJECTIVE: TO LEARN ABOUT ASP .NET WEB FRAMEWORK AND


MVC APPROACH

MVC ASP.NET CORE WEB APP:​



THEORY:
ASP.NET is a server-side web-application framework designed for web development
to produce dynamic web pages. It was developed by Microsoft to allow programmers to build
dynamic web sites, applications and services. The name stands for Active Server Pages Network
Enabled Technologies.
The Model-View-Controller (MVC) architecture within the ASP.NET MVC framework
provides a robust and efficient way to build web applications by separating concerns into three
main layers: model, view, and controller.
1. Model: Model Represents the shape of the data. A class in C# is used to describe a model.
Model Objects store data retrieved from the database. Model represents the data.

2. View: View in MVC represents the interface of the program . View display model data to
the user and enables them to modify them. View in ASP.NET is HTML,CSS and some
specific syntax (Razor) that makes it easy to communicate with the model and controller.
View is the user Interface.

3. Controller: Controller Handles The User Request . Typically, the user uses the view and
raises the HTTP Request, which will be handled by the controller. The controller process
the request and returns the appropriate view as a response. Controller is the request
handler.

SOURCE PROGRAM:
//Models/Person.cs
namespace SimpleMvcApp.Models
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
}

//Controllers/PersonController.cs
using Microsoft.AspNetCore.Mvc;
using SimpleMvcApp.Models;
using System.Collections.Generic;

namespace SimpleMvcApp.Controllers
{
public class PersonController : Controller
{
public IActionResult Index()
{
var people = new List<Person>
{
new Person { Id = 1, Name = "Alice", Age = 30 },
new Person { Id = 2, Name = "Bob", Age = 25 },
new Person { Id = 3, Name = "Charlie", Age = 35 }
};

return View(people);
}
}
}

Views/Person/Index.cshtml
@model IEnumerable<SimpleMvcApp.Models.Person>

<h1>People</h1>

<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
@foreach (var person in Model)
{
<tr>
<td>@person.Id</td>
<td>@person.Name</td>
<td>@person.Age</td>
</tr>
}
</tbody>
</table>​

OUTPUT:

CONCLUSION:
Hence, from the above experiment, we are able to demonstrate the Model View Controller
concept in an ASP.NET Core web app .
RAZOR SYNTAX AND HTML TAG HELPER:​

THEORY:
Razor is a lightweight and powerful syntax used for embedding server-side code into HTML in
ASP.NET Core MVC and Razor Pages. It allows developers to mix C# code with HTML in a
clean and readable way.

Basic Razor Syntax :


Razor Code Blocks:(@{})
@{
var message = "Hello, Razor!";
var year = DateTime.Now.Year;
}
<p>@message The year is @year.</p>

Inline Expressions:(@expressions)
<p>Current Year: @DateTime.Now.Year</p>

Conditional Statements:
@{
int age = 20;
}
@if (age >= 18)
{
<p>You are an adult.</p>
}
else
{
<p>You are a minor.</p>
}

Loop:
@{
var fruits = new List<string> { "Apple", "Banana", "Cherry" };
}
<ul>
@foreach (var fruit in fruits)
{
<li>@fruit</li>
}
</ul>

Working With Models:


@model Student

<p>Name: @Model.Name</p>
<p>Age: @Model.Age</p>

Razor Comments:
@*
This is a Comment for The Razor cshtml
*@

Tag Helpers enable the server-side code to participate in creating and rendering HTML Elements
in Razor files. There are many built-in tag helpers for some common tasks, such as creating
forms, links, loading assets, etc. Tag Helpers are authorized in C# and they Target HTML
elements based on the element name, the attribute name, or the parent tag.
Tag Helpers must be enabled in Razor Views. By default, they are available in ASP.NET
Core MVC.
If not already enabled, add this line at the top of _ViewImports.cshtml
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Some of the Most Commonly Used Tag Helpers Are:


asp-for (Model Binding)
<input asp-for="FirstName" class="form-control" />

asp-action or asp-controller (Form Submission or Link Redirecting)


<a asp-controller="Home" asp-action="Index">Go to Home</a>

asp-route (Passing Routing Parameters Dynamically):


<a asp-controller="Products" asp-action="Details" asp-route-id="5">View Product</a>

asp-validation-for (Form Validation)


<span asp-validation-for="Email" class="text-danger"></span>

SOURCE PROGRAM:
// Controllers/PersonController.cs
using Microsoft.AspNetCore.Mvc;
using SimpleMvcApp.Models;
using System.Collections.Generic;
namespace SimpleMvcApp.Controllers
{
public class PersonController : Controller
{
private static List<Person> people = new List<Person>
{
new Person { Id = 1, Name = "Alice", Age = 23 },
new Person { Id = 2, Name = "Bob", Age = 24 },
new Person { Id = 3, Name = "Charlie", Age = 25 }
};

public IActionResult Index()


{
return View(people);
}

public IActionResult Create()


{
return View();
}

[HttpPost]
public IActionResult Create(Person person)
{
person.Id = people.Count + 1;
people.Add(person);
return RedirectToAction("Index");
}
}
}

//Person/Index.cshtml

@model IEnumerable<SimpleMvcApp.Models.Person>
@{

ViewData["Title"] = "People List";

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

<table class="table">

<thead>

<tr>

<th>ID</th>

<th>Name</th>

<th>Age</th>

</tr>

</thead>

<tbody>

@foreach (var person in Model)

<tr>

<td>@person.Id</td>

<td>@person.Name</td>

<td>@person.Age</td>
</tr>

</tbody>

</table>

<p>

<a asp-controller="Person" asp-action="Create" class="btn btn-primary">Create New


Person</a>

</p>

//Person/Create.cshtml

@model SimpleMvcApp.Models.Person

@{

ViewData["Title"] = "Create Person";

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

<form asp-action="Create" method="post">

<div class="form-group">

<label asp-for="Name" class="control-label"></label>

<input asp-for="Name" class="form-control" />

<span asp-validation-for="Name" class="text-danger"></span>


</div>

<div class="form-group">

<label asp-for="Age" class="control-label"></label>

<input asp-for="Age" class="form-control" />

<span asp-validation-for="Age" class="text-danger"></span>

</div>

<div class="form-group">

<input type="submit" value="Create" class="btn btn-primary" />

</div>

</form>

OUTPUT:


CONCLUSION:
Hence, from the above experiment, we are able to demonstrate the Razor Syntax and HTML
Tag Helpers used in ASP.NET Core MVC Web App.​

LAB - 4:​
​ ​ ADO.NET

OBJECTIVE: TO LEARN ABOUT THE ADO.NET AND


DATABASE INTEGRATION IN DOTNET APPLICATION

THEORY:
ADO.NET (ActiveX Data Objects for .NET) is a core component of the .NET Framework,
introduced in the early 2000s, designed for efficient data access and manipulation. It enables
applications to interact with databases, XML, and other data sources, offering both connected
and disconnected architectures.
Different Classes in The ADO NET are:
Connection Classes
• Purpose: Establish and manage a connection to a data source.
• Common Implementations:
o SqlConnection (for SQL Server)
o OleDbConnection (for OLE DB providers, e.g., Excel, Access)
o OdbcConnection (for ODBC drivers)
o OracleConnection (for Oracle databases)
• Key Methods:
o Open(): Opens the connection.
o Close(): Closes the connection.
o BeginTransaction(): Starts a database transaction.

Command Classes
• Purpose: Execute SQL queries, stored procedures, or commands against a data source. •
Common Implementations:
o SqlCommand, OleDbCommand, OdbcCommand, etc.
• Key Methods:
o ExecuteNonQuery(): Executes non-query commands (e.g., INSERT, UPDATE,
DELETE).
o ExecuteScalar(): Returns a single value (e.g., result of COUNT(*)).
o ExecuteReader(): Returns a DataReader for read-only, forward-only data access.
• Properties:
o CommandText: The SQL query or stored procedure name.
o CommandType: Text (default), StoredProcedure, or TableDirect.
DataReader Classes
• Purpose: Read data in a fast, forward-only, read-only stream. Ideal for large datasets. •
Common Implementations:
o SqlDataReader, OleDbDataReader, etc.
• Key Methods:
o Read(): Advances to the next record.
o GetValue(), GetString(), etc.: Retrieve column values.

Transaction Classes
• Purpose: Ensure atomicity and consistency in database operations. •
Common Implementations:
o SqlTransaction, OleDbTransaction, etc.
• Key Methods:
o Commit(): Saves changes to the database.
o Rollback(): Reverts changes.

SOURCE PROGRAM:
using System;
using System.Data.SqlClient;

namespace StudentAdmissionApp
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Server=localhost;Database=master;Trusted_Connection=True;";

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

string createTableQuery = @"


CREATE TABLE Student_Admission (
RollNo INT PRIMARY KEY,
StudentName NVARCHAR(50),
ElectiveI NVARCHAR(50)
)";
using (SqlCommand command = new SqlCommand(createTableQuery, connection))
{
command.ExecuteNonQuery();
Console.WriteLine("Table Student_Admission created successfully.");
}

string insertQuery = @"


INSERT INTO Student_Admission (RollNo, StudentName, ElectiveI)
VALUES (1, 'John Doe', 'Mathematics')";
using (SqlCommand command = new SqlCommand(insertQuery, connection))
{
command.ExecuteNonQuery();
Console.WriteLine("Data inserted successfully.");
}

string readQuery = "SELECT * FROM Student_Admission";


using (SqlCommand command = new SqlCommand(readQuery, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine($"RollNo: {reader["RollNo"]}, StudentName:
{reader["StudentName"]}, ElectiveI: {reader["ElectiveI"]}");
}
}
}

string deleteQuery = "DELETE FROM Student_Admission WHERE RollNo = 1";


using (SqlCommand command = new SqlCommand(deleteQuery, connection))
{
command.ExecuteNonQuery();
Console.WriteLine("Data deleted successfully.");
}
}
}
}
}
OUTPUT:

CONCLUSION:
Hence, from the above experiment, we are able to demonstrate database integration in a .NET
application using ADO.NET by performing basic insert, delete and read operations.
LAB - 5:​
ENTITY FRAMEWORK

OBJECTIVE: TO LEARN ABOUT EF CORE FOR CREATING THE


CONSOLE APP WITH DATABASE INTEGRATION​

THEORY:
Entity Framework Core (EF Core) is a lightweight, extensible, and cross-platform version
of the popular Entity Framework data access technology. It is an Object-Relational Mapper
(ORM) that enables .NET developers to work with a database using .NET objects,
eliminating the need for most of the data-access code that developers usually need to write.
EF Core supports a variety of database engines, making it a versatile tool for .NET
applications.

Basic Workflow with EF Core:

Define Your Data Model:


Create your entity classes that represent the data you want to store in the database. These
classes are typically simple C# classes with properties that map to database columns.

Create a DbContext: The DbContext is the bridge between your entity classes and the
database. It manages the entities, tracks changes, and performs database operations. You define
a DbContext class that includes DbSet<TEntity> properties for each entity.

Configure the Database Connection: In your application’s configuration, you specify the
database provider (e.g., SQL Server, SQLite, PostgreSQL) and the connection string.

Apply Migrations: If you’re using the Code-First approach, you can create and apply
migrations to create or update the database schema based on your entity classes.

Query and Save Data: Use LINQ or raw SQL to query the database and retrieve data. Modify
the entities as needed and save changes back to the database using the SaveChanges or
SaveChangesAsync method.

SOURCE PROGRAM:
//Student.cs
namespace StudentAdmissionAppEF
{
public class Student
{
public int Id { get; set; }
public string? StudentName { get; set; }
public string? Elective { get; set; }
}
}

//StudentContext.cs
using Microsoft.EntityFrameworkCore;
namespace StudentAdmissionAppEF
{
public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)


{

optionsBuilder.UseSqlServer("Server=localhost;Database=StudentDB;Trusted_Connection=True;Tr
ustServerCertificate=True;");
}
}
}

//Program.cs​
using System;
using System.Linq;
namespace StudentAdmissionAppEF
{
class Program
{
static void Main(string[] args)
{
using (var context = new StudentContext())
{
// Ensure database is created
context.Database.EnsureCreated();
// Insert data
var student = new Student { StudentName = "John Doe", Elective = "Mathematics" };
context.Students.Add(student);
context.SaveChanges();
Console.WriteLine("Data inserted successfully.");

// Read data
var students = context.Students.ToList();
Console.WriteLine("Students:");
foreach (var s in students)
{
Console.WriteLine($"Id: {s.Id}, StudentName: {s.StudentName}, Elective: {s.Elective}");
}

// Delete data
var studentToDelete = context.Students.FirstOrDefault(s => s.StudentName == "John
Doe");
if (studentToDelete != null)
{
context.Students.Remove(studentToDelete);
context.SaveChanges();
Console.WriteLine("Data deleted successfully.");
}
}
}
}
}

OUTPUT:

CONCLUSION:
Hence, from the above experiment, we are able to demonstrate database integration in a .NET
application using entity framework by performing basic insert, delete and read operations.
LAB - 6:
STATE MANAGEMENT

OBJECTIVE: TO LEARN ABOUT THE VARIOUS STATE


MANAGEMENT TECHNIQUES IN THE ASP.NET CORE

THEORY:​
HTTP is a stateless protocol. HTTP requests are independent messages that
don’t retain user values or app states. We need to take additional steps to manage states
between the requests.

Some of The Approach for State Management in ASP .NET Core App

Session State:
Session state is an ASP.NET Core mechanism to store user data while the user browses
the application. We should store the critical application data in a database and we should cache it
in the session only as a performance optimization if required.
ASP .NET Core maintains the session state by providing a cookie to the client that
contains a sessionID. The browser sends this cookie to the application with each request. The
application uses the sessionID to fetch the session data.
While working with Session State, we should keep the following things in mind:

- A Session Cookie is specific to the browser session


- When a Browser session ends, it deletes the session cookie
- If The Application receives a cookie for an expired session, it creates a new session that
uses the same session cookie
- An application doesn’t retain empty sessions
- An application deletes the data stored in session either when we call the ISession. Clear
Implementation or When the session expires

TempData:

TempData persists data between requests, but only until it is read. Once accessed, the data is
removed automatically unless it is explicitly kept using:

- TempData.Keep("key") – Keeps the data for subsequent requests.


- TempData.Peek("key") – Reads the data without removing it.

SOURCE PROGRAM:

// Controllers/StateController.cs
namespace StateManagementApp.Controllers

public class StateController : Controller

public IActionResult Index()

// Set session data

HttpContext.Session.SetString("SessionData", "This is session data.");

// Set temp data

TempData["TempData"] = "This is temp data.";

return View();

public IActionResult ShowSessionData()

// Get session data

var sessionData = HttpContext.Session.GetString("SessionData");

ViewBag.SessionData = sessionData;

// Get additional session values

ViewBag.SessionValue1 = HttpContext.Session.GetString("SessionValue1");

ViewBag.SessionValue2 = HttpContext.Session.GetString("SessionValue2");

return View();

public IActionResult ShowTempData()


{

// Get temp data using Peek (does not mark for deletion)

var tempData = TempData.Peek("TempData");

ViewBag.TempData = tempData;

// Keep TempData for the next request

TempData.Keep("TempData");

return View();

public IActionResult SetSessionValues()

// Set session values

HttpContext.Session.SetString("SessionValue1", "Value1");

HttpContext.Session.SetString("SessionValue2", "Value2");

return RedirectToAction("Index");

public IActionResult ClearSession()

// Clear session

HttpContext.Session.Clear();

return RedirectToAction("Index");

//State/Index.cshtml
@{

ViewData["Title"] = "Index";

<h1>Index</h1>

<p>

<a asp-controller="State" asp-action="ShowSessionData">Show Session Data</a>

</p>

<p>

<a asp-controller="State" asp-action="ShowTempData">Show Temp Data</a>

</p>

<p>

<a asp-controller="State" asp-action="SetSessionValues">Set Session Values</a>

</p>

<p>

<a asp-controller="State" asp-action="ClearSession">Clear Session</a>

</p>

//ShowTempData.cshtml

@{

ViewData["Title"] = "Show Temp Data";

<h1>Show Temp Data</h1>

<p>Temp Data: @ViewBag.TempData</p>


//ShowSessionData.cshtml

@{

ViewData["Title"] = "Show Session Data";

<h1>Show Session Data</h1>

<p>Session Data: @ViewBag.SessionData</p>

<p>Session Value 1: @ViewBag.SessionValue1</p>

<p>Session Value 2: @ViewBag.SessionValue2</p>

OUTPUT:
CONCLUSION:
Hence, from the above experiment, we are able to demonstrate various state management
techniques in ASP.NET Core.

You might also like