Dot Net Bicky
Dot Net Bicky
Lab Report
of
Net Centric Computing
(BIT 351)
Tribhuvan University
Institute of Science and Technology (Bachelor in Information Technology (BIT) Program)
1) Write a program to convert input strings from lower to upper and upper to lower
case.
using System;
namespace lab
{
internal class text_transform
{
static void Main(string[] args)
{
Console.WriteLine("Enter a string to convert to uppercase:");
string inputUpper = Console.ReadLine();
string upperCase = inputUpper.ToUpper();
Console.WriteLine("Uppercase: " + upperCase);
using System;
namespace lab
{
internal class _2_changestring
{
static void Main(string[] args)
{
Console.WriteLine("Enter a string:");
string input = Console.ReadLine();
string result = SwapFirstAndLastCharacters(input);
Console.WriteLine("Modified string: " + result);
}
using System;
namespace lab
{
internal class _3_classobj
{
class Person
{
public string? Name { get; set; }
public int Age { get; set; }
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}
class Program
{
static void Main(string[] args)
{
Person person1 = new Person();
person1.Name = "Alice";
person1.Age = 25;
Person person2 = new Person();
person2.Name = "Bob";
person2.Age = 30;
Console.WriteLine("Person 1:");
person1.DisplayInfo();
Console.WriteLine("\nPerson 2:");
person2.DisplayInfo();
}
}
}
}
4) Write a program to illustrate encapsulation with properties and indexers.
using System;
namespace lab
{
internal class encapsulation
{
class Student
{
private string[] subjects = new string[5];
public string this[int index]
{
get { return subjects[index]; }
set { subjects[index] = value; }
}
public int TotalSubjects
{
get { return subjects.Length; }
}
}
class Program
{
static void Main(string[] args)
{
Student student = new Student();
student[0] = "Math";
student[1] = "Science";
student[2] = "History";
student[3] = "English";
student[4] = "Computer Science";
Console.WriteLine("Subjects:");
for (int i = 0; i < student.TotalSubjects; i++)
{
Console.WriteLine($"Subject {i + 1}: {student[i]}");
}
}
}
}
}
5) Write a program that reflects the overloading and overriding of constructor and
function.
using System;
namespace lab
{
internal class _5_overloading
{
class Shape
{
public string Name { get; }
public Shape(string name)
{
Name = name;
}
public virtual void Display()
{
Console.WriteLine($"This is a {Name}");
}
}
class Rectangle : Shape
{
public double Width { get; }
public double Height { get; }
public Rectangle(string name, double width, double height) : base(name)
{
Width = width;
Height = height;
}
public override void Display()
{
base.Display();
Console.WriteLine($"It has width: {Width} and height: {Height}");
}
}
using System;
namespace lab
{
internal class _6_mul_inheritance
{
interface IShape
{
double CalculateArea();
}
interface IColor
{
string GetColor();
}
class Program
{
static void Main(string[] args)
{
Circle redCircle = new Circle(5, "Red");
using System;
namespace lab
{
internal class _7_exception
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Enter a number:");
int num = int.Parse(Console.ReadLine());
using System;
namespace lab
{
internal class _8_delegate
{
public delegate void EventHandler(string message);
class Publisher
{
public event EventHandler Notify;
public void DoSomething()
{
Console.WriteLine("Doing something...");
Notify?.Invoke("Something was done.");
}
}
class Subscriber
{
public void Subscribe(Publisher publisher)
{
publisher.Notify += HandleEvent;
}
public void Unsubscribe(Publisher publisher)
{
publisher.Notify -= HandleEvent;
}
private void HandleEvent(string message)
{
Console.WriteLine($"Event handled: {message}");
}
}
class Program
{
static void Main(string[] args)
{
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
subscriber.Subscribe(publisher);
publisher.DoSomething();
subscriber.Unsubscribe(publisher);
publisher.DoSomething();
}
}
}
}
using System;
namespace lab
{
internal class _9_generic
{
class Box<T>
{
private T contents;
public Box(T item)
{
contents = item;
}
public T GetContents()
{
return contents;
}
}
class MathHelper
{
public static T Max<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) > 0 ? a : b;
}
}
class Program
{
static void Main(string[] args)
{
Box<int> intBox = new Box<int>(42);
int intContents = intBox.GetContents();
Console.WriteLine($"Integer Contents: {intContents}");
using System;
using System.Linq;
namespace lab
{
internal class _10_linq
{
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Person> people = new List<Person>
{
new Person { Name = "Alice", Age = 25 },
new Person { Name = "Bob", Age = 30 },
new Person { Name = "Charlie", Age = 22 }
};
var result = from person in people
where IsAdult(person.Age)
select person;
Console.WriteLine("Adults:");
foreach (var person in result)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
static bool IsAdult(int age)
{
return age >= 18;
}
}
}
}
11) Demonstrate Asynchronous programming with async, await, Task in C#.
using System;
namespace lab2
{
internal class program
{
static void Main(string[] args)
{
Method1();
Method2();
Console.ReadKey();
}
Controllers/WeatherController.cs
using dependency2.Services;
using Microsoft.AspNetCore.Mvc;
namespace dependency2.Controllers
{
public class WeatherController : Controller
{
private readonly IWeatherService _weatherService;
public WeatherController(IWeatherService weatherService)
{
_weatherService = weatherService;
}
public IActionResult Index()
{
string forecast = _weatherService.GetForecast();
return View((object)forecast);
}
}
}
Services/WeatherService.cs
namespace dependency2.Services
{
public class WeatherService : IWeatherService
{
public string GetForecast()
{
return "Today's weather is sunny!";
}
}
}
Services/IWeatherService.cs
namespace dependency2.Services
{
public interface IWeatherService
{
string GetForecast();
}
}
Index.cshtml
@model string
<h1>Weather Forecast</h1>
<p>@Model</p>
Program.cs
using dependency2.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddScoped<IWeatherService, WeatherService>();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
13) Create an ASP.NET Core application to perform CRUD operation using ADO.NET
Controllers/ProductController.cs
using lab13_2.Models;
using Microsoft.AspNetCore.Mvc;
using System.Data.SqlClient;
namespace lab13_2.Controllers
{
public class ProductController : Controller
{
private string _connectionString = "Server=DESKTOP-
OVRP8KV\\SQLEXPRESS;Database=Lab;Integrated Security=true;Encrypt=false";
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(Product product)
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
string query = "INSERT INTO Products (Name, Price, Description) VALUES
(@Name, @Price, @Description)";
using SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Name", product.Name);
command.Parameters.AddWithValue("@Price", product.Price);
command.Parameters.AddWithValue("@Description", product.Description);
command.ExecuteNonQuery();
}
return RedirectToAction("Index");
}
[HttpPost]
public IActionResult Edit(Product product)
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
string query = "UPDATE Products SET Name = @Name, Price = @Price,
Description = @Description WHERE Id = @Id";
using SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Id", product.Id);
command.Parameters.AddWithValue("@Name", product.Name);
command.Parameters.AddWithValue("@Price", product.Price);
command.Parameters.AddWithValue("@Description", product.Description);
command.ExecuteNonQuery();
}
return RedirectToAction("Index");
}
Views/Product/Edit.cshtml
@model lab13_2.Models.Product
<h2>Edit Product</h2>
<form asp-action="Edit">
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Price"></label>
<input asp-for="Price" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Description"></label>
<input asp-for="Description" class="form-control" />
</div>
<button type="submit" class="btn btn-primary">Save Changes</button>
</form>
Views/Product/Index.cshtml
@model IEnumerable<lab13_2.Models.Product>
<h2>Product List</h2>
<p>
<a asp-action="Create" class="btn btn-primary">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Price</th>
<th>Description</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var product in Model)
{
<tr>
<td>@product.Id</td>
<td>@product.Name</td>
<td>@product.Price</td>
<td>@product.Description</td>
<td>
<a asp-action="Details" asp-route-id="@product.Id">Details</a> |
<a asp-action="Edit" asp-route-id="@product.Id">Edit</a> |
<a asp-action="Delete" asp-route-id="@product.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
14) Write a program to store and display employee information using DbContext.
Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc;
using PurpleStore.Models;
namespace PurpleStore.Controllers
{
public class HomeController : Controller
{
ApplicationContext context;
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger, ApplicationContext
_context)
{
_logger = logger;
context = _context;
}
//Add data
public void Add()
{
var cat1 = new Category { Name = "Toy", Description = "This is a Car Toy!" };
context.Categories.Add(cat1);
context.SaveChanges();
}
//Read data
public IActionResult Index()
{
//return context.Categories.ToList();
List<Category> categorylist = context.Categories.ToList();
return View(categorylist);
}
}
}
Models/ApplicationContext.cs
using Microsoft.EntityFrameworkCore;
namespace PurpleStore.Models
{
public class ApplicationContext : DbContext
{
private readonly IConfiguration configuration;
public ApplicationContext(IConfiguration _configuration)
{
configuration = _configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if(!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(configuration.GetConnectionString("test"));
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
public DbSet<Category> Categories { get; set; }
}
}
Models/Product.cs
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
namespace PurpleStore.Models
{
public class Category
{
[Key]
public int Id { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
}
}
Views/Home/Index.cshtml
@model List<PurpleStore.Models.Category>
<h2>Categories</h2>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
@foreach (var category in Model)
{
<tr>
<td>@category.Id</td>
<td>@category.Name</td>
<td>@category.Description</td>
</tr>
}
</tbody>
</table>
appsettings.json
{
"ConnectionStrings": {
"test": "server=DESKTOP-OVRP8KV\\SQLEXPRESS; database=Sharad; Integrated
Security=True; encrypt=False;"
}
}
Program.cs
using Microsoft.EntityFrameworkCore;
using PurpleStore.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationContext>(options =>
{
options.UseSqlServer(
builder.Configuration.GetConnectionString("test"));
}
);
builder.Services.AddSession(options => { options.IdleTimeout =
TimeSpan.FromMinutes(10); });
var app = builder.Build();
Controller/StateController.cs
using Microsoft.AspNetCore.Mvc;
namespace lab15.Controllers
{
public class StateController : Controller
{
public IActionResult Add()
{
return View();
}
[HttpPost]
public IActionResult SetUserData(string username, string message)
{
// Session state example
HttpContext.Session.SetString("Username", username);
// TempData example
TempData["Message"] = message;
return RedirectToAction("Display");
}
Controllers/StateController.cs
using Microsoft.AspNetCore.Mvc;
namespace lab16.Controllers
{
public class StateController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult SetCookie(string data)
{
// Set a cookie with the user-provided data
CookieOptions option = new CookieOptions();
option.Expires = DateTime.Now.AddMinutes(30); // Cookie expiration time
Response.Cookies.Append("UserData", data, option);
return RedirectToAction("Index");
}
Views/State/Index.cshtml
@page
@model lab16.Controllers.StateController
<form method="post" asp-action="SetCookie">
<label for="data">Enter data:</label>
<input type="text" name="data" required />
<button type="submit">Submit</button>
</form>
Views/State/GetCookie.cshtml
@page
@model lab16.Controllers.StateController
<h2>Stored User Data:</h2>
<p>@ViewBag.UserData</p>