Practical 1
Practical 1
1.write a C# program to find if the give number is prime. (for the above programs use
the console as I/O first and then use ASP page as I/O).
NumberClass.cs
using System;
using System.Runtime.InteropServices;
namespace WebApplication1
{
internal class NumberClass
{
public NumberClass()
{
}
internal bool isPrime(int n)
{
int testLimit = (n / 2);
for(int i=2;i<=testLimit;i++)
{
if (n % i == 0) return false;
}
return true;
}
public static void Main()
{
Console.WriteLine("Enter a number:");
int N = 0;
N = Int32.Parse(Console.ReadLine());
NumberClass obj = new NumberClass();
if(obj.isPrime(N))
{
Console.WriteLine("This is a Prime Number.");
}
else
{
Console.WriteLine("This is NOt a Prime Number.");
}
}
}
}
Output:
Pract1.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<div>
<form id="form1" runat="server">
<asp:TextBox runat="server" ID="UserInput" Height="16px"></asp:TextBox>
<p>
<asp:Button runat="server" Text="Button" ID="Submit" Height="23px"
OnClick="Submit_Click" />
</p>
<p>
<asp:Label runat="server" ID="Message"></asp:Label>
</p>
</form>
</div>
</body>
</html>
Pract1.aspx.cs
using Microsoft.Ajax.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class Pract1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
NumberClass obj = new NumberClass();
int N = 0;
N = Int32.Parse(this.UserInput.Text);
if(obj.isPrime(N))
{
this.Message.Text += ("This is a Prime Number");
}
else
{
this.Message.Text += ("This is Not a Prime Number");
}
}
}
Output:
Practical 2
2.Write a C# program to find the vowels(count and the list)in a given string.
(for the above programs use the console as I/O first and then use ASP page as I/O).
Vowel.cs
using System;
namespace ConsoleApp1
{
internal class Vowels
{
public static void Main()
{
Console.WriteLine("Enter a String");
string input =Console.ReadLine();
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
var vowelList = input.Where(c => vowels.Contains(c)).ToList();
int vowelCount = vowelList.Count;
Console.ReadLine();
}
}
}
Output:
FindVowels.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FindVowels.aspx.cs"
Inherits="Practicles.FindVowels" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Vowel Checker</h2>
<label for="txtInput">Enter a string:</label>
<asp:TextBox ID="txtInput" runat="server"></asp:TextBox>
<br /><br />
<asp:Button ID="btnCheck" Text="Check Vowels" runat="server"
OnClick="btnCheck_Click" />
<br /><br />
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
<br />
<asp:Label ID="lblVowelList" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
FindVowels.aspx.cs
using System;
using System.Linq;
using System.Web.UI.WebControls;
namespace Practicles
{
public partial class FindVowels : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnCheck_Click(object sender, EventArgs e)
{
string input = txtInput.Text.ToLower();
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
var vowelList = input.Where(c => vowels.Contains(c)).ToList();
int vowelCount = vowelList.Count;
lblResult.Text = $"Number of vowels: {vowelCount}";
lblVowelList.Text = "Vowels found: " + string.Join(", ", vowelList);
}
}
}
Output:
Practical 3
3. Write a program to find the sum of the series of even numbers (2, 4, 6,....) up
to 50 numbers. Implement Exception handling using try-catch (Invalid data
type entered, Wrong Data, etc) for the above program.
(For the above programs use the console as I/O, then the ASP.NET page as I/O.)
SumOfEven.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
internal class SumOfEven
{
public static void Main(string[] args)
{
try
{
Console.WriteLine("Enter the total even number :");
int sum = 0;
int count = int.Parse(Console.ReadLine());
for (int i = 1; i <= count; i++)
{
int evenNumber = 2 * i;
sum += evenNumber;
}
Console.WriteLine($"The sum of {count} even numbers is: {sum}");
}
catch (FormatException ex)
{
Console.WriteLine("Invalid input. Please enter a valid number.");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
Output:
SumofEvenNumber.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="SumOfEvenNumber.aspx.cs" Inherits="Practicles.SumOfEvenNumber" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Sum of Even Numbers</h2>
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br/>
<asp:Button ID="btnCalculate" Text="Calculate Sum" runat="server"
OnClick="btnCalculate_Click" />
<br /><br />
<asp:Label ID="lblFinalSum" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
SumOfEvenNumber.aspx.cs
using System;
namespace Practicles
{
public partial class SumOfEvenNumber : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnCalculate_Click(object sender, EventArgs e)
{
try
{
int sum = 0;
int count = Int32.Parse(this.TextBox1.Text);
for (int i = 1; i <= count; i++)
{
int evenNumber = 2 * i;
sum += evenNumber;
}
lblFinalSum.Text = $"The final sum of the first {count} even numbers is: {sum}";
}
catch (FormatException ex)
{
lblMessage.Text = "Invalid input. Please enter a valid number.";
lblMessage.ForeColor = System.Drawing.Color.Red;
}
catch (Exception ex)
{
lblMessage.Text = "An unexpected error occurred.";
lblMessage.ForeColor = System.Drawing.Color.Red;
}
}
}
}
Output:
Practical 4
4. Write a program to implement add(+), sub(-), and mul(*) of two complex
Numbers . (For the above programs use the console as I/O then the ASP.NET page as
I/O.)
ComplexNumber.cs
namespace ConsoleApp1
{
internal class ComplexNumber
{
public double Real { get; set; }
public double Imaginary { get; set; }
public ComplexNumber(double real, double imaginary)
{
Real = real;
Imaginary = imaginary;
}
public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
{
return new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
public static ComplexNumber operator -(ComplexNumber c1, ComplexNumber c2)
{
return new ComplexNumber(c1.Real - c2.Real, c1.Imaginary - c2.Imaginary);
}
public static ComplexNumber operator *(ComplexNumber c1, ComplexNumber c2)
{
double realPart = c1.Real * c2.Real - c1.Imaginary * c2.Imaginary;
double imaginaryPart = c1.Real * c2.Imaginary + c1.Imaginary * c2.Real;
return new ComplexNumber(realPart, imaginaryPart);
}
public override string ToString()
{
return $"{Real} + {Imaginary}i";
}
}
class Program2
{
static void Main(string[] args)
{
Console.Write("Enter first 1st number: ");
double real1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter seconde 1st number: ");
double imaginary1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter first 2nd number: ");
double real2 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter second 2nd number: ");
double imaginary2 = Convert.ToDouble(Console.ReadLine());
ComplexNumber complex1 = new ComplexNumber(real1, imaginary1);
ComplexNumber complex2 = new ComplexNumber(real2, imaginary2);
ComplexNumber sum = complex1 + complex2;
ComplexNumber difference = complex1 - complex2;
ComplexNumber product = complex1 * complex2;
Console.WriteLine($"Result : Num1 + Num2 = ( {sum})i");
Console.WriteLine($"Result : Num1 - Num2 = ( {difference})i");
Console.WriteLine($"Result : Num1 * Num2 = ( {product})i");
Console.ReadLine();
}
}
}
Output:
ComplexNumber.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Complex Number Operations (Add, Subtract, Multiply)</h2>
Enter 1st Number :- <asp:TextBox ID="txtReal1" runat="server"></asp:TextBox> +
<asp:TextBox ID="txtImaginary1" runat="server"></asp:TextBox>i
<br /> <br/>
Enter 2nd Number :- <asp:TextBox ID="txtReal2" runat="server"></asp:TextBox> +
<asp:TextBox ID="txtImaginary2" runat="server"></asp:TextBox>i
<br /><br />
ComplexNumber.aspx.cs
using System;
namespace Practicles
{
public partial class ComplexNumber : System.Web.UI.Page
{
protected void btnAdd_Click(object sender, EventArgs e)
{
try
{
double real1 = Convert.ToDouble(txtReal1.Text);
double imag1 = Convert.ToDouble(txtImaginary1.Text);
double real2 = Convert.ToDouble(txtReal2.Text);
double imag2 = Convert.ToDouble(txtImaginary2.Text);
double realResult = real1 + real2;
double imagResult = imag1 + imag2;
lblResult.Text = $"Result : Num1 + Num2 = ( {realResult} + {imagResult})i";
}
catch (FormatException)
{
lblResult.Text = "Invalid input. Please enter valid numbers.";
}
}
protected void btnSubtract_Click(object sender, EventArgs e)
{
try
{
double real1 = Convert.ToDouble(txtReal1.Text);
double imag1 = Convert.ToDouble(txtImaginary1.Text);
double real2 = Convert.ToDouble(txtReal2.Text);
double imag2 = Convert.ToDouble(txtImaginary2.Text);
double realResult = real1 - real2;
double imagResult = imag1 - imag2;
lblResult.Text = $"Result : Num1 - Num2 = ( {realResult} - {imagResult})i";
}
catch (FormatException)
{
lblResult.Text = "Invalid input. Please enter valid numbers.";
}
}
protected void btnMultiply_Click(object sender, EventArgs e)
{
try
{
double real1 = Convert.ToDouble(txtReal1.Text);
double imag1 = Convert.ToDouble(txtImaginary1.Text);
double real2 = Convert.ToDouble(txtReal2.Text);
double imag2 = Convert.ToDouble(txtImaginary2.Text);
double realResult = (real1 * real2) - (imag1 * imag2);
double imagResult = (real1 * imag2) + (imag1 * real2);
lblResult.Text = $"Result : Num1 * Num2 = ( {realResult} * {imagResult})i";
}
catch (FormatException)
{
lblResult.Text = "Invalid input. Please enter valid numbers.";
}
}
}
}
Output:
Practical 5
5. Write a program to implement a stack of cards (the use of System.Collections
Library) – Two players are playing cards. Each has 6 cards in the beginning
(Randomly distributed). The players pull a card from one stack and then
throw a card into another stack.
(For the above programs use the console as I/O first and then use the ASP.NET
page as I/O)
(Test the programs given in Lab Note – 2 for the above concept demonstrations)
CardGame.cs
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class CardGame
{
static Random = new Random();
Console.WriteLine("\nGame Over");
Console.ReadLine();
}
static List<int> CreateDeck()
{
List<int> deck = new List<int>();
for (int i = 1; i <= 52; i++)
{
deck.Add(i);
}
return deck;
}
static List<int> ShuffleCards(List<int> deck)
{
for (int i = deck.Count - 1; i > 0; i--)
{
int randomIndex = random.Next(i + 1);
int temp = deck[i];
deck[i] = deck[randomIndex];
deck[randomIndex] = temp;
}
return deck;
}
static void DistributeCards(Stack<int> deck, List<int> player1, List<int> player2)
{
for (int i = 0; i < 6; i++)
{
player1.Add(deck.Pop());
player2.Add(deck.Pop());
}
}
static void PlayerDrawAndDiscard(Stack<int> mainDeck, Stack<int> discardPile,
List<int> playerHand, string playerName)
{
if (mainDeck.Count > 0)
{
int drawnCard = mainDeck.Pop();
Console.WriteLine($"{playerName} draws card {drawnCard}");
int cardToDiscard = playerHand[random.Next(playerHand.Count)];
playerHand.Remove(cardToDiscard);
discardPile.Push(cardToDiscard);
Console.WriteLine($"{playerName} discards card {cardToDiscard}");
playerHand.Add(drawnCard);
}
else
{
Console.WriteLine("Main deck is empty, no card drawn.");
}
DisplayPlayerCards(playerName, playerHand);
}
static void DisplayPlayerCards(string playerName, List<int> playerCards)
{
Console.WriteLine($"{playerName}'s hand: {string.Join(", ", playerCards)}");
}
}
}
Output:
CardGame.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CardGame.aspx.cs"
Inherits="Practicles.CardGame" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Card Game: Two Players</h2>
<asp:Button ID="btnStartGame" Text="Start Game" runat="server"
OnClick="btnStartGame_Click" />
<br /><br />
CardGame.aspx.cs
using System;
using System.Collections;
using System.Collections.Generic;
namespace Practicles
{
public partial class CardGame : System.Web.UI.Page
{
private Stack deck = new Stack();
private Stack discardPile = new Stack();
private List<int> player1Cards = new List<int>();
private List<int> player2Cards = new List<int>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
InitializeDeck();
}
}
private void InitializeDeck()
{
Random rnd = new Random();
List<int> allCards = new List<int>();
for (int i = 1; i <= 52; i++) allCards.Add(i);
allCards.Sort((a, b) => rnd.Next(-1, 2)); // Shuffle the cards
foreach (var card in allCards) deck.Push(card);
}
protected void btnStartGame_Click(object sender, EventArgs e)
{
DealCards();
btnPlayer1Draw.Enabled = true;
btnPlayer1Discard.Enabled = true;
btnPlayer2Draw.Enabled = true;
btnPlayer2Discard.Enabled = true;
UpdateUI();
}
private void DealCards()
{
if (deck.Count >= 12)
{
player1Cards.Clear();
player2Cards.Clear();
Practical 6
6. 1. Understanding different controls provided in ASP.Net Web UI:
a. Create a Student Registration Form using web form with the following
details;
1. Name of Student: (50 chars)
2. Date of Birth: dd/mm/yyyy format
3. Gender (Male, Female) - Use radio buttons
4. Email:
5. Address: (100 characters, allow multiline up to 3-lines)
6. Phone Number: Numeric(10)
7. Registration for: UG / PG (Use single list selection)
8. Branch: If UG, then display following options:
1. CSE, MECH, ECE, CIVIL, IT, ELEC
else If PG then display following options:
2. MCA, MBA, MTech-AI ML, MTech-DS, MTech-Mech
9.Accommodation Preference: Hostel / Own / Outside hostel (Select one)
- Use single list selection
10.Sports Preference: Basket ball, Cricket, Foot ball, Table tenis,
Swimming, and Hockey (select multiple) - Use check boxes
11. A "Save" button, and "Reset" button at the bottom
2. Understand the concept of code behind:
Write down the validations for the above student registration form as given
below.
• Following information is mandatory. Student Name, DoB, Address, and
Branch
• Student names cannot have numbers. Only space and "." are allowed. No
other special characters are allowed.
• The Date 0f Birth can not be >= current date. The year of birth should be
at least 12 years before the current year
• The default value of Gender is "Male"
• The default value of Registration is "UG"
• The phone number must be 0f 10 numbers
• Email should be well-formed
Use ASP.NET attributes to implement these. Create custom validations that can
be shared across applications.
StudentRegistration.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="StudentRegistration.aspx.cs" Inherits="Practicles.StudentRegistration" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Student Registration Form</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Student Registration Form</h2>
<div>
<label for="txtName">Name of Student:</label>
<asp:TextBox ID="txtName" runat="server" MaxLength="50"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvName" runat="server"
ControlToValidate="txtName"
ErrorMessage="Student Name is required." CssClass="error"
Display="Dynamic" />
<asp:RegularExpressionValidator ID="revName" runat="server"
ControlToValidate="txtName"
ErrorMessage="Invalid Name format." CssClass="error" Display="Dynamic"
ValidationExpression="^[A-Za-z\s.]+$" />
</div>
<br />
<div>
<label for="txtDOB">Date of Birth:</label>
<asp:TextBox ID="txtDOB" runat="server" MaxLength="10"
placeholder="dd/mm/yyyy"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvDOB" runat="server"
ControlToValidate="txtDOB"
ErrorMessage="Date of Birth is required." CssClass="error" Display="Dynamic"
/>
<asp:CustomValidator ID="cvDOB" runat="server" ControlToValidate="txtDOB"
ErrorMessage="Date of Birth must be at least 12 years before the current date."
CssClass="error" Display="Dynamic"
OnServerValidate="ValidateDOB" />
</div>
<br />
<div>
<label>Gender:</label>
<asp:RadioButtonList ID="rblGender" runat="server">
<asp:ListItem Value="Male" Selected="True">Male</asp:ListItem>
<asp:ListItem Value="Female">Female</asp:ListItem>
</asp:RadioButtonList>
</div>
<br />
<div>
<label for="txtEmail">Email:</label>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEmail" runat="server"
ControlToValidate="txtEmail"
ErrorMessage="Email is required." CssClass="error" Display="Dynamic" />
<asp:RegularExpressionValidator ID="revEmail" runat="server"
ControlToValidate="txtEmail"
ErrorMessage="Invalid email format." CssClass="error" Display="Dynamic"
ValidationExpression="^[^@\s]+@[^@\s]+\.[^@\s]+$" />
</div>
<br />
<div>
<label for="txtAddress">Address:</label>
<asp:TextBox ID="txtAddress" runat="server" TextMode="MultiLine" Rows="3"
MaxLength="100"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvAddress" runat="server"
ControlToValidate="txtAddress"
ErrorMessage="Address is required." CssClass="error" Display="Dynamic" />
</div>
<br />
<div>
<label for="txtPhone">Phone Number:</label>
<asp:TextBox ID="txtPhone" runat="server" MaxLength="10"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPhone" runat="server"
ControlToValidate="txtPhone"
ErrorMessage="Phone Number is required." CssClass="error"
Display="Dynamic" />
<asp:RegularExpressionValidator ID="revPhone" runat="server"
ControlToValidate="txtPhone"
ErrorMessage="Phone Number must be 10 digits." CssClass="error"
Display="Dynamic"
ValidationExpression="^\d{10}$" />
</div>
<br />
<div>
<label for="ddlRegistration">Registration for:</label>
<asp:DropDownList ID="ddlRegistration" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ddlRegistration_SelectedIndexChanged">
<asp:ListItem Value="UG" Selected="True">UG</asp:ListItem>
<asp:ListItem Value="PG">PG</asp:ListItem>
</asp:DropDownList>
</div>
<br />
<div>
<label for="ddlBranch">Branch:</label>
<asp:DropDownList ID="ddlBranch" runat="server"></asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvBranch" runat="server"
ControlToValidate="ddlBranch"
ErrorMessage="Branch is required." CssClass="error" Display="Dynamic" />
</div>
<br />
<div>
<label for="ddlAccommodation">Accommodation Preference:</label>
<asp:DropDownList ID="ddlAccommodation" runat="server">
<asp:ListItem Value="Hostel">Hostel</asp:ListItem>
<asp:ListItem Value="Own">Own</asp:ListItem>
<asp:ListItem Value="Outside">Outside hostel</asp:ListItem>
</asp:DropDownList>
</div>
<br />
<div>
<label>Sports Preference:</label><br />
<asp:CheckBoxList ID="cblSports" runat="server">
<asp:ListItem Value="Basketball">Basketball</asp:ListItem>
<asp:ListItem Value="Cricket">Cricket</asp:ListItem>
<asp:ListItem Value="Football">Football</asp:ListItem>
<asp:ListItem Value="Table Tennis">Table Tennis</asp:ListItem>
<asp:ListItem Value="Swimming">Swimming</asp:ListItem>
<asp:ListItem Value="Hockey">Hockey</asp:ListItem>
</asp:CheckBoxList>
</div>
<br />
<div>
<asp:Button ID="btnSave" runat="server" Text="Save"
OnClick="btnSave_Click" />
<asp:Button ID="btnReset" runat="server" Text="Reset"
OnClick="btnReset_Click" />
</div>
<br />
</div>
</form>
</body>
</html>
StudentRegistration.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Practicles
{
public partial class StudentRegistration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadBranches();
}
}
protected void ddlRegistration_SelectedIndexChanged(object sender, EventArgs e)
{
LoadBranches();
}
private void LoadBranches()
{
ddlBranch.Items.Clear();
if (ddlRegistration.SelectedValue == "UG")
{
ddlBranch.Items.Add(new ListItem("CSE"));
ddlBranch.Items.Add(new ListItem("MECH"));
ddlBranch.Items.Add(new ListItem("ECE"));
ddlBranch.Items.Add(new ListItem("CIVIL"));
ddlBranch.Items.Add(new ListItem("IT"));
ddlBranch.Items.Add(new ListItem("ELEC"));
}
else // PG
{
ddlBranch.Items.Add(new ListItem("MCA"));
ddlBranch.Items.Add(new ListItem("MBA"));
ddlBranch.Items.Add(new ListItem("MTech-AI ML"));
ddlBranch.Items.Add(new ListItem("MTech-DS"));
ddlBranch.Items.Add(new ListItem("MTech-Mech"));
}
}
protected void ValidateDOB(object source,
System.Web.UI.WebControls.ServerValidateEventArgs args)
{
if (DateTime.TryParse(txtDOB.Text, out DateTime dob))
{
int age = DateTime.Now.Year - dob.Year;
if (dob > DateTime.Now.AddYears(-age)) age--;
}
}
Practical 7
7. Creating Custom Controls and Components:
Create a custom Login Form as a user control with necessary validations that can
be shared between applications.
Inputs: User ID, Password, (Reenter Password), save and reset button. A message
box if it is a wrong Login (UserId / Password entered is wrong. Try again.)
Validations:
Userid - Mandatory(Required) - 8 Chars Long
Userid - Can not have special characters except underscore ( _ ), alphabets, and
numbers (0 to 9)
Password: Must be a min of 8 Characters. There should be at least one Uppercase
char, one number and one special char.
Password re-entered must be same as password.
LoginForm.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LoginForm.aspx.cs"
Inherits="Practicles.LoginForm" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
User id <asp:TextBox ID="TextBox1" runat="server"
OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
</div>
</form>
</body>
</html>
LoginForm.aspx.cs
using System;
namespace Practicles
{
public partial class LoginForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Focus();
}
}
}
}
Output:
Practical 8
8.Reading data from a data file and writing data to a data file:
Create a C# component to read student registration information from a data file
(text file .csv). Use this component to display data on an ASP page. Create a
component that writes student registration information from an ASP.Net web
form to a data file.
Use the “Read” and "Save" buttons for these operations.
Create a component to connect to the database using ADO.NET and access the
database tables for query, insert, and update. Use the database with tables of
Students, Courses, Subjects, and Marks. Use Web forms in ASP to demonstrate
the above operations.
ResgistrationForm2.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="RegistrationForm2.aspx.cs" Inherits="Practicles.RegistrationForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblID" runat="server" Text="Student ID: " />
<asp:TextBox ID="txtID" runat="server" />
<br/>
namespace Practicles
{
public partial class RegistrationForm2 : System.Web.UI.Page
{
_csvHelper.WriteToCSV(student);
lblMessage.Text = "Data saved successfully!";
}
Practical 9
9. Handling web page events and state tracking
Write an ASP web application (with two pages – login and home page) to
demonstrate user state and application state tracking.
Prac9.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Prac9.aspx.cs"
Inherits="Practicles.Prac9" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>TGPCET</h2>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Practicles
Pract9.aspx.cs
{
public partial class Prac9 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Application.Lock();
Application["visitcount"] = Convert.ToInt32(Application["visitcount"]) + 1;
Application.UnLock();
MsgApp.Text = "Application Visit Count = " + Application["visitcount"].ToString();
Session["number"] = Convert.ToInt32(Session["number"]) + 1;
MsgSession.Text = "Session Count = " + Session["number"].ToString();
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string username = TextBox1.Text;
string password = TextBox2.Text;
Response.Redirect("Prac9Part2.aspx");
}
else
{
Label1.Text = "Login faild pleass try again";
}
}
}
}
Prac9part2.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Prac9Part2.aspx.cs"
Inherits="Practicles.Prac9Part2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="MsgApp" runat="server" Text="Application Count"></asp:Label>
<asp:Label ID="MsgSession" runat="server" Text="Session Count"></asp:Label>
</div>
</form>
</body>
</html>
Prac9part2.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Practicles
{
public partial class Prac9Part2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Application.Lock();
Application["visitcount"] = Convert.ToInt32(Application["visitcount"]) + 1;
Application.UnLock();
MsgApp.Text = "Application Visit Count = " + Application["visitcount"].ToString();
Session["number"] = Convert.ToInt32(Session["number"]) + 1;
MsgSession.Text = "Session Count = " + Session["number"].ToString();
}
}
}
Output:
Practical 10
10. Multipage Navigation and Error Handling
1. Write a web application using ASP.Net that has the following pages.
a. A Login page (Authentication is managed in an “Authentication class
with different user-id and password.
b. A home page after successful login. With some static content. The
content is loaded from the home.txt file, in a specific folder
c. A “helpdesk” page with a form to input query and submit to generate
a ticket.
d. A ticket tracking page to find the status of submitted tickets.
Demonstrate the handling of different errors in the web application.
Login form:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Prac10.aspx.cs"
Inherits="Practicles.Prac10" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtUsername" runat="server"
placeholder="Username"></asp:TextBox><br />
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"
placeholder="Password"></asp:TextBox><br />
<asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />
<asp:Label ID="lblError" runat="server" ForeColor="Red"></asp:Label>
</div>
</form>
</body>
</html>
using System;
namespace Practicles
{
public partial class Prac10 : System.Web.UI.Page
{
protected void btnLogin_Click(object sender, EventArgs e)
{
string username = txtUsername.Text;
string password = txtPassword.Text;
if (Authentication.AuthenticateUser(username, password))
{
Response.Redirect("Prac10Home.aspx");
}
else
{
lblError.Text = "Invalid username or password.";
}
}
}
}
Output:
Home page:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Prac10Home.aspx.cs"
Inherits="Practicles.Prac10Home" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblContent" runat="server"></asp:Label>
<br/>
<a href="Helpdesk.aspx" >Helpdesk</a>
</div>
</form>
</body>
</html>
using System;
using System.IO;
namespace Practicles
{
public partial class Prac10Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
string filePath = Server.MapPath("~/NewFolder1/home.txt");
lblContent.Text = File.ReadAllText(filePath);
}
catch (FileNotFoundException)
{
lblContent.Text = "Error: Content file not found.";
}
catch (Exception ex)
{
lblContent.Text = "An error occurred: " + ex.Message;
}
}
}
}
Helpdesk
</div>
</form>
</body>
</html>
using System;
using System.IO;
namespace Practicles
{
public partial class Prac10Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
string filePath = Server.MapPath("~/NewFolder1/home.txt");
lblContent.Text = File.ReadAllText(filePath);
}
catch (FileNotFoundException)
{
lblContent.Text = "Error: Content file not found.";
}
catch (Exception ex)
{
lblContent.Text = "An error occurred: " + ex.Message;
}
}
}
}
Authentication
using System.Collections.Generic;
namespace Practicles
{
public class Authentication
{
private static Dictionary<string, string> users = new Dictionary<string, string>()
{
{ "admin", "password123" },
{ "user1", "pass1" }
};
TrackTicket:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtTicketNumber" runat="server" placeholder="Enter Ticket
Number"></asp:TextBox><br />
<asp:Button ID="btnTrack" runat="server" Text="Track Ticket"
OnClick="btnTrack_Click" />
<asp:Label ID="lblStatus" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
using System;
namespace Practicles
{
public partial class TrackTicket : System.Web.UI.Page
{
protected void btnTrack_Click(object sender, EventArgs e)
{
string ticketNumber = txtTicketNumber.Text;
string status = Session["Ticket_" + ticketNumber] as string;
if (status != null)
{
lblStatus.Text = $"Ticket {ticketNumber} Status: {status}";
}
else
{
lblStatus.Text = "Ticket not found.";
}
}
}
}
Output: