DotNet Report
DotNet Report
A Lab Report On
Dot Net Technology
Submitted to
Submitted By
class Calculator
{
static void Main(string[] args)
{
Console.WriteLine("Simple Calculator");
Console.WriteLine("Enter two numbers:");
double result = 0;
switch (operation)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0)
result = num1 / num2;
else
Console.WriteLine("Division by zero is not allowed.");
break;
default:
Console.WriteLine("Invalid operation.");
break;
}
Console.WriteLine($"Result: {result}");
}
}
Output:
2. What is the difference between an abstract class and an interface in
C#? Provide an example demonstrating their usage.
Solution:
Abstract Class
• Can have both abstract (unimplemented) and concrete (implemented) methods.
• Can have fields, properties, and constructors.
• Supports access modifiers (public, private, etc.).
• A class can inherit only one abstract class.
Interface
• Can only have method signatures (no implementation).
• Cannot have fields or constructors.
• All members are public by default.
• A class can implement multiple interfaces.
Example:
using System;
// Abstract Class
abstract class Animal
{
public abstract void Sound(); // Abstract method
public void Sleep() // Concrete method
{
Console.WriteLine("Sleeping...");
}
}
// Interface
interface IFlyable
{
void Fly();
}
// Derived Class
class Bird : Animal, IFlyable
{
public override void Sound()
{
Console.WriteLine("Chirp Chirp");
}
class Program
{
static void Main(string[] args)
{
Bird bird = new Bird();
bird.Sound();
bird.Fly();
bird.Sleep();
}
}
Output:
3. Create a basic ASP.NET web form that allows users to input their
name and email address and displays a welcome message when
submitted.
Solution:
Default.apsx.cs
using System;
namespace WebFormExample
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Welcome Form</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Welcome Form</h2>
<div>
<asp:Label ID="lblName" runat="server" Text="Name:"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvName" runat="server"
ControlToValidate="txtName"
ErrorMessage="Name is required"
ForeColor="Red">
</asp:RequiredFieldValidator>
</div>
<div>
<asp:Label ID="lblEmail" runat="server" Text="Email:"></asp:Label>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEmail" runat="server"
ControlToValidate="txtEmail"
ErrorMessage="Email is required"
ForeColor="Red">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revEmail" runat="server"
ControlToValidate="txtEmail"
ErrorMessage="Invalid email format"
ForeColor="Red"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
</div>
<div>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
</div>
<div>
<asp:Label ID="lblMessage" runat="server" Visible="false"></asp:Label>
</div>
</div>
</form>
</body>
</html>
4. Write a C# program using ADO.NET to connect to an SQL database
and fetch records from a table named ‘students’.
Solution:
using System;
using MySql.Data.MySqlClient;
using System.Data;
class Program
{
MySqlConnection conn;
MySqlCommand command;
void CreateConnection()
{
try
{
string constr =
"SERVER=localhost;DATABASE=std_db;UID=root;PASSWORD=";
conn = new MySqlConnection(constr);
conn.Open();
// Console.WriteLine("Db connected!!!");
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
void InsertUpdateDelete(string sql)
{
command = new MySqlCommand(sql, conn);
command.ExecuteNonQuery();
Console.WriteLine("Operation Performed successfully!!");
}
class Program
{
MySqlConnection? conn;
MySqlCommand? command;
void CreateConnection()
{
try
{
string constr =
"SERVER=localhost;DATABASE=std_db;UID=root;PASSWORD=";
conn = new MySqlConnection(constr);
conn.Open();
Console.WriteLine("Database connected successfully.");
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
void SelectAndFilterRecords()
{
if (conn == null)
{
Console.WriteLine("Database connection is not initialized.");
return;
}
try
{
string sql = "SELECT * FROM student";
command = new MySqlCommand(sql, conn);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
adapter.Fill(dt);
if (filteredStudents.Any())
{
Console.WriteLine("ID\tName\tClass\tAddress");
foreach (var student in filteredStudents)
{
Console.WriteLine($"{student.ID}\t{student.Name}\t{student.Class}\t{student.Address}
");
}
}
else
{
Console.WriteLine("No students found with names starting with 'A'.");
}
}
catch (Exception ex)
{
Console.WriteLine("Error fetching data: " + ex.Message);
}
}
[Route("api/[controller]")]
[ApiController]
public class BooksController : ControllerBase
{
private static List<Book> books = new List<Book>
{
new Book(1, "The Catcher in the Rye", "J.D. Salinger"),
new Book(2, "To Kill a Mockingbird", "Harper Lee"),
new Book(3, "1984", "George Orwell")
};
// GET api/books
[HttpGet]
public ActionResult<IEnumerable<Book>> GetBooks()
{
return Ok(books);
}
// GET api/books/{id}
[HttpGet("{id}")]
public ActionResult<Book> GetBook(int id)
{
var book = books.Find(b => b.Id == id);
if (book == null)
{
return NotFound();
}
return Ok(book);
}
}
Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Output:
7. Explain the try-catch-finally construct in C#. Write a program to
handle a division-by-zero exception gracefully.
In C#, the try-catch-finally construct is used to handle exceptions (errors) that may occur
during the execution of a program. It allows you to write error-handling code to handle
unexpected issues without crashing the program.
• try block: Contains the code that may throw an exception. If no exception occurs, the
code in the catch block is skipped.
• catch block: Contains the code that handles the exception. This block is executed if an
exception occurs in the try block.
• finally block: This block is optional and contains code that will always execute,
regardless of whether an exception occurs or not. It's typically used for cleanup (e.g.,
closing files or database connections).
Solution:
using System;
class Program
{
static void Main()
{
try
{
// Attempt to divide by zero
Console.WriteLine("Enter the numerator: ");
int numerator = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
// Handle division by zero exception
Console.WriteLine("Error: Cannot divide by zero.");
}
catch (FormatException ex)
{
// Handle invalid input (e.g., if the user enters non-numeric input)
Console.WriteLine("Error: Invalid input. Please enter valid integers.");
}
finally
{
// Code that will always execute, regardless of whether an exception occurred
Console.WriteLine("Execution completed.");
}
}
}
Output: