0% found this document useful (0 votes)
17 views19 pages

DotNet Report

This document is a lab report submitted to Tribhuvan University detailing various C# programming tasks, including creating a simple calculator, explaining abstract classes and interfaces, building an ASP.NET web form, connecting to a SQL database using ADO.NET, demonstrating LINQ, and creating a Web API for book details. Each task includes code examples and explanations of concepts such as exception handling with try-catch-finally. The report serves as a partial fulfillment of the requirements for a Bachelor's degree in Computer Application.

Uploaded by

dhakalshishir982
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)
17 views19 pages

DotNet Report

This document is a lab report submitted to Tribhuvan University detailing various C# programming tasks, including creating a simple calculator, explaining abstract classes and interfaces, building an ASP.NET web form, connecting to a SQL database using ADO.NET, demonstrating LINQ, and creating a Web API for book details. Each task includes code examples and explanations of concepts such as exception handling with try-catch-finally. The report serves as a partial fulfillment of the requirements for a Bachelor's degree in Computer Application.

Uploaded by

dhakalshishir982
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/ 19

TRIBHUVAN UNIVERSITY

FACULTY OF HUMANITIES AND SOCIAL SCIENCE

A Lab Report On
Dot Net Technology
Submitted to

Department of Computer Application


Southwestern State college, Basundhara, Kathmandu

In partial fulfillment of the requirements for the Bachelors in


Computer Application

Submitted By

Name: Shishir Dhakal


TU Roll no: 53002078

November 19, 2024


1. Write a C# program to create a simple calculator that performs
addition, subtraction, multiplication, and division based on user input.
Solution:
using System;

class Calculator
{
static void Main(string[] args)
{
Console.WriteLine("Simple Calculator");
Console.WriteLine("Enter two numbers:");

double num1 = Convert.ToDouble(Console.ReadLine());


double num2 = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Choose an operation: +, -, *, /");


char operation = Convert.ToChar(Console.ReadLine());

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");
}

public void Fly()


{
Console.WriteLine("Flying...");
}
}

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)
{

protected void btnSubmit_Click(object sender, EventArgs e)


{
if (Page.IsValid)
{
string name = txtName.Text;
string email = txtEmail.Text;

lblMessage.Text = $"Welcome, {name}! We'll send updates to {email}";


lblMessage.Visible = true;

// Clear the form


txtName.Text = "";
txtEmail.Text = "";
}
}
}
}
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebFormExample.Default" %>

<!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!!");
}

void SelectRecords(string sql)


{
command = new MySqlCommand(sql, conn);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows.Count != 0)
{
Console.WriteLine("ID\tName\tClass\tAddress");
for (int i = 0; i < dt.Rows.Count; i++)
{
int id = Convert.ToInt32(dt.Rows[i]["id"]);
string name = dt.Rows[i]["name"].ToString();
string address = dt.Rows[i]["address"].ToString();
int studentclass = Convert.ToInt32(dt.Rows[i]["class"]);
Console.WriteLine(id + "\t" + name + "\t" + studentclass + "\t" + address);
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Program started...");
Program obj = new Program();
obj.CreateConnection();
Console.WriteLine("Fetching data...");
obj.SelectRecords("SELECT * FROM student");
Console.WriteLine("Program ended.");
}
}
Output:
5. Write a C# program to demonstrate LINQ by filtering and displaying
a list of student names starting with the letter 'A'.
Solution:
using System;
using System.Linq;
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("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);

var filteredStudents = dt.AsEnumerable()


.Where(row => row["name"] != DBNull.Value &&
row["name"].ToString().StartsWith("A"))
.Select(row => new
{
ID = row["id"],
Name = row["name"],
Class = row["class"],
Address = row["address"]
});

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);
}
}

static void Main(string[] args)


{
Console.WriteLine("Program started...");
Program obj = new Program();
obj.CreateConnection();
obj.SelectAndFilterRecords();
Console.WriteLine("Program ended.");
}
}
Output:
6. What is the purpose of Web API in .NET? Create a simple Web API
that returns details about books (ID, Title, Author) in JSON format.
In .NET, a Web API is a framework for building HTTP-based services that allow clients
(like browsers, mobile apps, or other servers) to communicate with a server and perform
operations like CRUD (Create, Read, Update, Delete) over the web. A Web API typically
returns data in formats like JSON or XML, and it's often used to expose functionality to
other applications or services.
Solution:
Book.cs
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }

public Book(int id, string title, string author)


{
Id = id;
Title = title;
Author = author;
}
}
BooksController.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

[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;

public class Program


{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public class Startup


{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)


{
services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

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("Enter the denominator: ");


int denominator = Convert.ToInt32(Console.ReadLine());

// Perform the division


int result = numerator / denominator;

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:

You might also like