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

BCA III sem-C# & .NET Framework-Lab programs

The C# & .NET Framework Lab Manual for the academic year 2024-2025 provides a comprehensive guide for BCA III Sem students at Vidhyaashram First Grade College, detailing various practical applications and programming concepts in C#. It includes exercises on conditional statements, control statements, Windows controls, multithreading, subroutines, built-in functions in VB.NET, and creating an MDI application for employee payroll transactions. The manual is prepared by Evelin Jacob and consists of a structured curriculum with a total of 52 contact hours.

Uploaded by

eshkarthik
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

BCA III sem-C# & .NET Framework-Lab programs

The C# & .NET Framework Lab Manual for the academic year 2024-2025 provides a comprehensive guide for BCA III Sem students at Vidhyaashram First Grade College, detailing various practical applications and programming concepts in C#. It includes exercises on conditional statements, control statements, Windows controls, multithreading, subroutines, built-in functions in VB.NET, and creating an MDI application for employee payroll transactions. The manual is prepared by Evelin Jacob and consists of a structured curriculum with a total of 52 contact hours.

Uploaded by

eshkarthik
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

C# & .

NET FRAMEWORK LAB MANUAL

C# & .NET FRAMEWORK LAB MANUAL

Lab Manual for the Academic Year 2024-2025


BCA III Sem

Vidhyaashram First Grade


College
Mysore

In-charge

EVELIN JACOB

Prepared By: Evelin Jacob, Vidhyaashram First Grade College Page 1


Vidhyaashram First Grade College

BCA (Bachelor of Computer Applications)

Course Title: C# and .Net Technologies Lab


Course code: CAC08P
Total Contact Hours: 52
Hours/week : 04
Formative Assessment Marks: 25
Course Credits: 02
Exam Marks: 25
Duration of Exam: 03 Hours
Practicals:
1. Develop a C# .NET console application to demonstrate the conditional statements.

using System;

namespace ConditionalStatementsDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Conditional Statements Demo in C#");

// Prompt the user to enter a number


Console.Write("Enter an integer: ");
int number;
bool isNumber = int.TryParse(Console.ReadLine(), out number);

if (isNumber)
{
// if-else statement
if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else if (number < 0)
{
Console.WriteLine("The number is negative.");
}
else
{
Console.WriteLine("The number is zero.");
}

// Nested if-else statement


if (number % 2 == 0)
{
Console.WriteLine("The number is even.");
}
else
{
Console.WriteLine("The number is odd.");
}

// switch statement
switch (number)
{
case 1:
Console.WriteLine("The number is one.");
break;
case 2:
Console.WriteLine("The number is two.");
break;
case 3:
Console.WriteLine("The number is three.");
break;
default:
Console.WriteLine("The number is not one, two, or three.");
break;
}
}
else
{
Console.WriteLine("Invalid input! Please enter a valid integer.");
}

// End of program
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
2. Develop a C# .NET console application to demonstrate the control statements.

using System;

namespace ControlStatementsDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Control Statements Demo in C#");

// for loop example


Console.WriteLine("\nFor Loop Example:");
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Iteration: " + i);
}

// while loop example


Console.WriteLine("\nWhile Loop Example:");
int counter = 1;
while (counter <= 5)
{
Console.WriteLine("Counter: " + counter);
counter++;
}

// do-while loop example


Console.WriteLine("\nDo-While Loop Example:");
int number = 1;
do
{
Console.WriteLine("Number: " + number);
number++;
} while (number <= 5);

// break statement example


Console.WriteLine("\nBreak Statement Example:");
for (int i = 1; i <= 10; i++)
{
if (i == 6)
{
Console.WriteLine("Breaking the loop at i = " + i);
break; // Exit the loop when i equals 6
}
Console.WriteLine("i: " + i);
}

// continue statement example


Console.WriteLine("\nContinue Statement Example:");
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue; // Skip the even numbers
}
Console.WriteLine("i: " + i);
}

// foreach loop example


Console.WriteLine("\nForeach Loop Example:");
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int n in numbers)
{
Console.WriteLine("Number: " + n);
}

// End of program
Console.WriteLine("\nPress any key to exit.");
Console.ReadKey();
}
}
}
3. Develop an application in C#.NET that demonstrates the windows controls

Steps to Create the Application

1. Create a New Project:


o Open Visual Studio.
o Go to File > New > Project.
o Select Windows Forms App (.NET Framework) and give your project a name, such as
WindowsControlsDemo.
o Click Create.

2. Design the Form:


o Drag and drop the following controls from the Toolbox onto the form:
 Label: For displaying text.
 TextBox: For user input.
 Button: To trigger actions.
 CheckBox: For options that can be checked or unchecked.
 RadioButton: For selecting one option from a set.
 ListBox: For displaying a list of items.
 ComboBox: For a drop-down list of items.
 ProgressBar: To show progress.
 DateTimePicker: To pick a date.

3. Add Event Handlers:


o Double-click on the button to create an event handler for its Click event.
o Similarly, add event handlers for other controls as needed.

4. Write the Code:

using System;
using System.Windows.Forms;

namespace WindowsControlsDemo
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}

private void MainForm_Load(object sender, EventArgs e)


{
// Initialize ListBox items
listBoxItems.Items.Add("Item 1");
listBoxItems.Items.Add("Item 2");
listBoxItems.Items.Add("Item 3");

// Initialize ComboBox items


comboBoxOptions.Items.Add("Option 1");
comboBoxOptions.Items.Add("Option 2");
comboBoxOptions.Items.Add("Option 3");
// Initialize ProgressBar
progressBar.Value = 50;
}

private void buttonSubmit_Click(object sender, EventArgs e)


{
// Display input from TextBox
string userInput = textBoxInput.Text;
MessageBox.Show("You entered: " + userInput, "User Input");

// Display selected items in ListBox


if (listBoxItems.SelectedItem != null)
{
MessageBox.Show("Selected item: " + listBoxItems.SelectedItem.ToString(), "ListBox
Selection");
}

// Display selected option in ComboBox


if (comboBoxOptions.SelectedItem != null)
{
MessageBox.Show("Selected option: " + comboBoxOptions.SelectedItem.ToString(),
"ComboBox Selection");
}

// Check if CheckBox is checked


if (checkBoxAgree.Checked)
{
MessageBox.Show("You agreed to the terms.", "Checkbox Status");
}

// Check which RadioButton is selected


if (radioButtonOption1.Checked)
{
MessageBox.Show("You selected Option 1.", "RadioButton Selection");
}
else if (radioButtonOption2.Checked)
{
MessageBox.Show("You selected Option 2.", "RadioButton Selection");
}

// Display selected date


DateTime selectedDate = dateTimePicker.Value;
MessageBox.Show("Selected date: " + selectedDate.ToShortDateString(), "Date Selection");
}

private void buttonIncrementProgress_Click(object sender, EventArgs e)


{
// Increment ProgressBar value
if (progressBar.Value < progressBar.Maximum)
{
progressBar.Value += 10;
}
}
}
}
4. Demonstrate Multithreaded Programming in C#.NET

using System;
using System.Threading;

namespace MultithreadedProgrammingDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Multithreaded Programming Demo in C#");

// Create a thread using a ThreadStart delegate


Thread thread1 = new Thread(new ThreadStart(DoWork1));
thread1.Name = "Worker Thread 1";

// Create another thread using a lambda expression


Thread thread2 = new Thread(() =>
{
DoWork2();
});
thread2.Name = "Worker Thread 2";

// Start both threads


thread1.Start();
thread2.Start();

// Main thread work


for (int i = 0; i < 5; i++)
{
Console.WriteLine("Main thread: Working...");
Thread.Sleep(1000); // Simulate some work in the main thread
}

// Wait for both threads to complete


thread1.Join();
thread2.Join();

Console.WriteLine("Both worker threads have finished. Press any key to exit.");


Console.ReadKey();
}

// Method to be run by the first thread


static void DoWork1()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine(Thread.CurrentThread.Name + ": Working...");
Thread.Sleep(1500); // Simulate some work
}
}
// Method to be run by the second thread
static void DoWork2()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine(Thread.CurrentThread.Name + ": Working...");
Thread.Sleep(2000); // Simulate some work
}
}
}
}
5. Demonstrate subroutines and functions in C#.NET
using System;

namespace SubroutinesAndFunctionsDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Subroutines and Functions Demo in C#");

// Calling a subroutine (void method)


GreetUser();

// Calling a function with return value


int sumResult = AddNumbers(5, 10);
Console.WriteLine("Sum of 5 and 10 is: " + sumResult);

// Calling a function with an output parameter


int differenceResult;
CalculateDifference(15, 5, out differenceResult);
Console.WriteLine("Difference between 15 and 5 is: " + differenceResult);

// Calling an overloaded function


double productResult = MultiplyNumbers(2.5, 4);
Console.WriteLine("Product of 2.5 and 4 is: " + productResult);

Console.WriteLine("Press any key to exit.");


Console.ReadKey();
}

// Subroutine (void method) - Does not return a value


static void GreetUser()
{
Console.WriteLine("Hello! Welcome to the demo.");
}

// Function - Returns an integer value


static int AddNumbers(int num1, int num2)
{
return num1 + num2;
}

// Function with an output parameter


static void CalculateDifference(int num1, int num2, out int difference)
{
difference = num1 - num2;
}

// Overloaded function - Returns a double value


static double MultiplyNumbers(double num1, double num2)
{
return num1 * num2;
}
// Another overloaded function - Returns an integer value
static int MultiplyNumbers(int num1, int num2)
{
return num1 * num2;
}
}
}
6. Develop an application for deploying various built-in functions in VB.NET

Steps to Create the Application

1. Create a New Project:


o Open Visual Studio.
o Go to File > New > Project.
o Select Windows Forms App (.NET Framework) and give your project a name, such as
BuiltinFunctionsDemo.
o Click Create.

2. Design the Form:


o Drag and drop the following controls from the Toolbox onto the form:
 Label: To describe the purpose of each operation.
 TextBox: For user input.
 Button: To trigger the function and display the result.
 ListBox: To display results from some operations, like string splitting.
 DateTimePicker: For selecting a date.

3. Add Event Handlers:


o Double-click on the buttons to create event handlers for their Click events.

4. Write the Code:

Here is an example of the code that demonstrates various built-in functions in VB.NET:

VB.NET Code Example


Public Class MainForm
Private Sub btnStringManipulation_Click(sender As Object, e As EventArgs) Handles
btnStringManipulation.Click
' String Manipulation Functions
Dim input As String = txtInput.Text

' Convert to Upper Case


Dim upper As String = input.ToUpper()
MessageBox.Show("Upper Case: " & upper, "String Manipulation")

' Get String Length


Dim length As Integer = input.Length
MessageBox.Show("Length: " & length, "String Manipulation")

' Split String


Dim words() As String = input.Split(" "c)
lstResults.Items.Clear()
lstResults.Items.AddRange(words)
End Sub

Private Sub btnMathOperations_Click(sender As Object, e As EventArgs) Handles


btnMathOperations.Click
' Mathematical Functions
Dim number As Double = Convert.ToDouble(txtInput.Text)

' Square Root


Dim sqrt As Double = Math.Sqrt(number)
MessageBox.Show("Square Root: " & sqrt, "Math Operations")

' Round
Dim rounded As Double = Math.Round(number)
MessageBox.Show("Rounded Value: " & rounded, "Math Operations")

' Absolute Value


Dim abs As Double = Math.Abs(number)
MessageBox.Show("Absolute Value: " & abs, "Math Operations")
End Sub

Private Sub btnDateTimeOperations_Click(sender As Object, e As EventArgs) Handles


btnDateTimeOperations.Click
' Date and Time Functions
Dim selectedDate As DateTime = dateTimePicker.Value

' Current Date and Time


Dim now As DateTime = DateTime.Now
MessageBox.Show("Current Date and Time: " & now, "DateTime Operations")

' Add Days


Dim futureDate As DateTime = selectedDate.AddDays(10)
MessageBox.Show("Date After 10 Days: " & futureDate.ToShortDateString(), "DateTime
Operations")

' Format Date


Dim formattedDate As String = selectedDate.ToString("dddd, MMMM dd, yyyy")
MessageBox.Show("Formatted Date: " & formattedDate, "DateTime Operations")
End Sub

Private Sub btnTypeConversion_Click(sender As Object, e As EventArgs) Handles


btnTypeConversion.Click
' Type Conversion Functions
Dim input As String = txtInput.Text

' Convert String to Integer


Dim number As Integer
If Integer.TryParse(input, number) Then
MessageBox.Show("Converted to Integer: " & number, "Type Conversion")
Else
MessageBox.Show("Invalid Integer Input", "Type Conversion")
End If

' Convert String to Double


Dim dbl As Double
If Double.TryParse(input, dbl) Then
MessageBox.Show("Converted to Double: " & dbl, "Type Conversion")
Else
MessageBox.Show("Invalid Double Input", "Type Conversion")
End If

' Convert String to Boolean


Dim booleanValue As Boolean
If Boolean.TryParse(input, booleanValue) Then
MessageBox.Show("Converted to Boolean: " & booleanValue, "Type Conversion")
Else
MessageBox.Show("Invalid Boolean Input", "Type Conversion")
End If
End Sub
End Class
7. Develop an MDI application for Employee Pay-roll transactions in VB.NET

To develop an MDI (Multiple Document Interface) application for Employee Payroll transactions in
VB.NET, you can follow these steps. This example will create a basic MDI application where you can
manage employee information and payroll transactions.

### Steps to Create the MDI Application

1. **Create a New Project:**


- Open Visual Studio.
- Go to `File` > `New` > `Project`.
- Select `Windows Forms App (.NET Framework)` and give your project a name, such as
`EmployeePayrollMDI`.
- Click `Create`.

2. **Set Up the MDI Parent Form:**


- Rename the default `Form1` to `MDIParentForm` (right-click on the form in the Solution Explorer,
select `Rename`).
- Set the `IsMdiContainer` property of `MDIParentForm` to `True` (you can find this property in the
Properties window).
- Add a `MenuStrip` control to the form from the Toolbox.

3. **Design the Menu Strip:**


- Add the following menu items:
- **File**
- New Employee
- Payroll Transaction
- Exit
- **Help**
- About

4. **Create the Child Forms:**


- Add a new Windows Form for managing employees:
- Right-click on the project in Solution Explorer > `Add` > `Windows Form`.
- Name it `EmployeeForm.vb`.
- Design the form with controls such as `TextBox` for employee name, ID, etc., and `Button` controls for
saving or canceling.

- Add another form for payroll transactions:


- Repeat the steps above and name it `PayrollForm.vb`.
- Design the form with controls like `TextBox` for entering salary details, `ComboBox` for selecting the
employee, and `Button` controls for processing the payroll.

5. **Write Code to Open Child Forms:**

- In the `MDIParentForm` code, add event handlers for the menu items to open the child forms. Here’s an
example:

### VB.NET Code Example

```vb
Public Class MDIParentForm
Private Sub NewEmployeeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles
NewEmployeeToolStripMenuItem.Click
' Open the EmployeeForm as a child form
Dim empForm As New EmployeeForm()
empForm.MdiParent = Me
empForm.Show()
End Sub

Private Sub PayrollTransactionToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles


PayrollTransactionToolStripMenuItem.Click
' Open the PayrollForm as a child form
Dim payrollForm As New PayrollForm()
payrollForm.MdiParent = Me
payrollForm.Show()
End Sub

Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles


ExitToolStripMenuItem.Click
' Exit the application
Me.Close()
End Sub

Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles


AboutToolStripMenuItem.Click
' Display an About message box
MessageBox.Show("Employee Payroll MDI Application" & vbCrLf & "Version 1.0", "About")
End Sub

End Class
```

### Design the Child Forms

1. **EmployeeForm:**
- Design the form with labels and text boxes for employee details such as Employee ID, Name,
Department, etc.
- Add buttons for saving and closing the form.

2. **PayrollForm:**
- Design the form with labels, text boxes, and combo boxes for payroll details such as Employee ID,
Salary, Tax deductions, etc.
- Add buttons for processing the payroll and closing the form.

### Running the Application

1. **Compile and Run**:


- Press `F5` to build and run the application.
- The MDI parent form will open with the menu items for managing employees and payroll transactions.

2. **Use the Application**:


- Click on "File" > "New Employee" to open the Employee form.
- Click on "File" > "Payroll Transaction" to open the Payroll form.
- Each form opens within the MDI parent window, allowing you to manage multiple documents within
the same interface.
### Features to Add

- **Database Integration**: Implement database connectivity using ADO.NET or Entity Framework to


store and retrieve employee and payroll data.
- **Data Validation**: Add validation to ensure the correct input of employee and payroll information.
- **Reporting**: Create reports for payroll transactions, such as monthly salary reports.
- **Security**: Implement authentication and authorization to restrict access to payroll data.

This basic MDI application structure provides a foundation for developing a more complex Employee
Payroll system in VB.NET.
8. Construct a console application to demonstrate the OOP Concepts
To demonstrate Object-Oriented Programming (OOP) concepts in a C# console application, we'll create a
simple application that models an Employee and a Payroll system. The application will cover the four key
OOP concepts: **Encapsulation, Inheritance, Polymorphism,** and **Abstraction**.

### Step-by-Step Implementation

1. **Encapsulation**: We'll encapsulate the employee's data within the `Employee` class, making the data
accessible only through public methods.

2. **Inheritance**: We'll create a `FullTimeEmployee` and a `PartTimeEmployee` class that inherit from
the `Employee` base class.

3. **Polymorphism**: We'll use method overriding to demonstrate polymorphism, where the same
method behaves differently in derived classes.

4. **Abstraction**: We'll use an abstract class `Employee` to force derived classes to implement specific
methods.

### C# Code Example

```csharp
using System;

namespace OOPConceptsDemo
{
// Abstraction: Abstract class Employee
abstract class Employee
{
// Encapsulation: Private fields
private int id;
private string name;
private string department;

// Constructor
public Employee(int id, string name, string department)
{
this.id = id;
this.name = name;
this.department = department;
}

// Properties for encapsulation


public int Id
{
get { return id; }
set { id = value; }
}

public string Name


{
get { return name; }
set { name = value; }
}
public string Department
{
get { return department; }
set { department = value; }
}

// Abstract method to be implemented by derived classes


public abstract double CalculateSalary();

// Virtual method to demonstrate polymorphism


public virtual void DisplayEmployeeInfo()
{
Console.WriteLine("ID: " + Id);
Console.WriteLine("Name: " + Name);
Console.WriteLine("Department: " + Department);
}
}

// Inheritance: FullTimeEmployee class inheriting from Employee


class FullTimeEmployee : Employee
{
private double annualSalary;

// Constructor
public FullTimeEmployee(int id, string name, string department, double annualSalary)
: base(id, name, department)
{
this.annualSalary = annualSalary;
}

// Override abstract method


public override double CalculateSalary()
{
return annualSalary / 12; // Monthly salary
}

// Override virtual method


public override void DisplayEmployeeInfo()
{
base.DisplayEmployeeInfo();
Console.WriteLine("Annual Salary: " + annualSalary);
Console.WriteLine("Monthly Salary: " + CalculateSalary());
}
}

// Inheritance: PartTimeEmployee class inheriting from Employee


class PartTimeEmployee : Employee
{
private double hourlyRate;
private int hoursWorked;

// Constructor
public PartTimeEmployee(int id, string name, string department, double hourlyRate, int
hoursWorked)
: base(id, name, department)
{
this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
}

// Override abstract method


public override double CalculateSalary()
{
return hourlyRate * hoursWorked;
}

// Override virtual method


public override void DisplayEmployeeInfo()
{
base.DisplayEmployeeInfo();
Console.WriteLine("Hourly Rate: " + hourlyRate);
Console.WriteLine("Hours Worked: " + hoursWorked);
Console.WriteLine("Total Salary: " + CalculateSalary());
}
}

class Program
{
static void Main(string[] args)
{
// Create instances of FullTimeEmployee and PartTimeEmployee
FullTimeEmployee ftEmployee = new FullTimeEmployee(1, "John Doe", "Engineering", 120000);
PartTimeEmployee ptEmployee = new PartTimeEmployee(2, "Jane Smith", "Marketing", 40, 120);

// Demonstrate polymorphism: Different behaviors for the same method


Employee[] employees = new Employee[] { ftEmployee, ptEmployee };

foreach (var employee in employees)


{
Console.WriteLine("Employee Info:");
employee.DisplayEmployeeInfo();
Console.WriteLine();
}

Console.WriteLine("Press any key to exit.");


Console.ReadKey();
}
}
}
```

### Explanation

1. **Encapsulation**:
- The `Employee` class encapsulates data by making fields private and exposing them through
properties. This protects the data from unauthorized access and modification.

2. **Abstraction**:
- The `Employee` class is an abstract class that defines common properties and methods for all
employees. It forces derived classes to implement the `CalculateSalary` method, which is specific to the
type of employee.

3. **Inheritance**:
- The `FullTimeEmployee` and `PartTimeEmployee` classes inherit from the `Employee` base class. They
reuse the properties and methods defined in `Employee` and add their own specific logic.

4. **Polymorphism**:
- The `DisplayEmployeeInfo` method is overridden in both `FullTimeEmployee` and
`PartTimeEmployee`. Despite being called the same way on both classes, it behaves differently based on
the object type.

### Running the Application

1. **Compile and Run**:


- Press `F5` to build and run the console application.
- The program will display the details of a full-time and part-time employee, including their calculated
salaries.

2. **Output**:
- The output will display the employee details, showcasing the OOP concepts in action.

This application provides a clear demonstration of the key OOP concepts in C#. Each concept is applied in
a practical context, making it easier to understand how these principles can be used to structure and
organize code effectively.
9. Develop a web application in VB.NET for dynamic Login Processing

Creating a web application in VB.NET for dynamic login processing involves several steps, including
setting up the project, designing the user interface, and implementing the logic for authentication. Below
is a step-by-step guide to developing a simple login web application.

### Steps to Create the Web Application

1. **Create a New ASP.NET Web Application:**


- Open Visual Studio.
- Go to `File` > `New` > `Project`.
- Select `ASP.NET Web Application (.NET Framework)` and name your project, e.g., `DynamicLoginApp`.
- Choose the template "Empty" and click `Create`.

2. **Add Required Web Forms:**


- In Solution Explorer, right-click the project, select `Add` > `Web Form`, and name it `Login.aspx`.
- Add another Web Form named `Home.aspx` (this will be the landing page after successful login).

3. **Design the Login Page (`Login.aspx`):**


- Open `Login.aspx` in Design view.
- Add the following controls from the Toolbox:
- Two `TextBox` controls for username and password.
- Two `Label` controls for displaying text ("Username:" and "Password:").
- One `Button` control for submitting the login.
- One `Label` control for displaying error messages.

Here's how the HTML might look:

```html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Login</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Login</h2>
<asp:Label ID="lblUsername" runat="server" Text="Username:"></asp:Label>
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox><br /><br />
<asp:Label ID="lblPassword" runat="server" Text="Password:"></asp:Label>
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox><br
/><br />
<asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" /><br
/><br />
<asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>
</div>
</form>
</body>
</html>
```

4. **Write Code for Login Processing:**


- Double-click on the `Login.aspx` page to create a `btnLogin_Click` event handler in the `Login.aspx.vb`
code-behind file.
- Implement the login logic by checking the username and password against predefined values or a
database.

Here's a basic example that checks against hardcoded credentials:

```vb
Partial Class Login
Inherits System.Web.UI.Page

Protected Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click


' Hardcoded username and password for demonstration
Dim validUsername As String = "admin"
Dim validPassword As String = "password123"

If txtUsername.Text = validUsername AndAlso txtPassword.Text = validPassword Then


' Redirect to the Home page upon successful login
Response.Redirect("Home.aspx")
Else
' Display error message
lblMessage.Text = "Invalid username or password. Please try again."
End If
End Sub
End Class
```

5. **Design the Home Page (`Home.aspx`):**


- Open `Home.aspx` in Design view.
- Add a label to welcome the user.

Example `Home.aspx`:

```html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Home</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Welcome to the Home Page!</h2>
</div>
</form>
</body>
</html>
```

6. **Test the Application:**


- Press `F5` to run the application.
- The login page will appear. Enter the credentials (`admin`/`password123`).
- If the login is successful, you will be redirected to the `Home.aspx` page; otherwise, an error message
will be displayed.
### Adding a Database for Dynamic Authentication

To make the login dynamic, you should store usernames and passwords in a database. Here's a basic
outline of how to implement this:

1. **Set Up a Database:**
- Create a database (e.g., `UserDB`) in SQL Server.
- Create a table named `Users` with columns `Username` and `Password`.

2. **Connect to the Database:**


- In your `Web.config` file, add a connection string to connect to your database.

```xml
<connectionStrings>
<add name="UserDBConnectionString"
connectionString="Data Source=.;Initial Catalog=UserDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
```

3. **Modify the Login Code:**


- Use ADO.NET to check the entered credentials against the database.

```vb
Imports System.Data.SqlClient

Partial Class Login


Inherits System.Web.UI.Page

Protected Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click


' Connect to the database and verify credentials
Dim connectionString As String =
ConfigurationManager.ConnectionStrings("UserDBConnectionString").ConnectionString
Using con As New SqlConnection(connectionString)
Dim query As String = "SELECT COUNT(1) FROM Users WHERE Username=@Username AND
Password=@Password"
Dim cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("@Username", txtUsername.Text)
cmd.Parameters.AddWithValue("@Password", txtPassword.Text)
con.Open()
Dim count As Integer = Convert.ToInt32(cmd.ExecuteScalar())
If count = 1 Then
' Redirect to the Home page upon successful login
Response.Redirect("Home.aspx")
Else
' Display error message
lblMessage.Text = "Invalid username or password. Please try again."
End If
End Using
End Sub
End Class
```

### Conclusion
This guide provides a fundamental example of how to create a dynamic login processing web application
in VB.NET. You can expand upon this by implementing more advanced features such as password hashing,
user roles, session management, and more robust error handling.
10. Develop a Windows application with database connectivity for core-banking transactions
Creating a Windows application in VB.NET for core-banking transactions with database connectivity
involves several steps. Below is a step-by-step guide to help you build a simple banking application that
allows users to perform basic banking operations like depositing and withdrawing funds, and viewing
account balances.

### Project Overview

**Technologies Used:**
- VB.NET
- Windows Forms
- SQL Server (for database)

**Core Features:**
- User login
- Account balance inquiry
- Deposit funds
- Withdraw funds

### Step-by-Step Implementation

#### 1. Set Up the Database

1. **Create a Database:**
- Open SQL Server Management Studio (SSMS).
- Create a new database named `BankDB`.
- Create a table named `Accounts` with the following columns:
- `AccountID` (Primary Key, INT, Identity)
- `AccountNumber` (VARCHAR(20))
- `AccountHolderName` (VARCHAR(100))
- `Balance` (DECIMAL(18, 2))

Example SQL Script:


```sql
CREATE DATABASE BankDB;

USE BankDB;

CREATE TABLE Accounts (


AccountID INT PRIMARY KEY IDENTITY,
AccountNumber VARCHAR(20) NOT NULL,
AccountHolderName VARCHAR(100) NOT NULL,
Balance DECIMAL(18, 2) NOT NULL
);
```

#### 2. Create a New Windows Forms Application

1. **Create a New Project:**


- Open Visual Studio.
- Go to `File` > `New` > `Project`.
- Select `Windows Forms App (.NET Framework)` and name your project, e.g., `CoreBankingApp`.

2. **Add the Required Forms:**


- Add forms for login (`LoginForm`), main dashboard (`MainForm`), and transaction processing
(`TransactionForm`).

#### 3. Design the Login Form

1. **LoginForm Design:**
- Add `TextBox` controls for entering `AccountNumber`.
- Add a `Button` for login.
- Add a `Label` for displaying error messages.

Example `LoginForm` UI design:


```vb
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class LoginForm
Inherits System.Windows.Forms.Form

' ... Designer code for text boxes, labels, and buttons ...

End Class
```

2. **LoginForm Code-Behind:**
- Add code to authenticate the user based on the `AccountNumber`.

Example `LoginForm` code:


```vb
Imports System.Data.SqlClient

Public Class LoginForm


Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim accountNumber As String = txtAccountNumber.Text

Dim connectionString As String = "Data Source=.;Initial Catalog=BankDB;Integrated Security=True"


Using con As New SqlConnection(connectionString)
Dim query As String = "SELECT COUNT(1) FROM Accounts WHERE
AccountNumber=@AccountNumber"
Dim cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("@AccountNumber", accountNumber)
con.Open()
Dim count As Integer = Convert.ToInt32(cmd.ExecuteScalar())
If count = 1 Then
' Open the MainForm upon successful login
Dim mainForm As New MainForm(accountNumber)
Me.Hide()
mainForm.Show()
Else
lblMessage.Text = "Invalid Account Number. Please try again."
End If
End Using
End Sub
End Class
```

#### 4. Design the Main Form


1. **MainForm Design:**
- Add buttons for viewing the balance, depositing funds, and withdrawing funds.

Example `MainForm` UI design:


```vb
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class MainForm
Inherits System.Windows.Forms.Form

' ... Designer code for buttons and labels ...

End Class
```

2. **MainForm Code-Behind:**
- Implement the logic to handle button clicks, opening the transaction form, and displaying account
balance.

Example `MainForm` code:


```vb
Imports System.Data.SqlClient

Public Class MainForm


Private accountNumber As String

Public Sub New(accountNumber As String)


InitializeComponent()
Me.accountNumber = accountNumber
End Sub

Private Sub btnViewBalance_Click(sender As Object, e As EventArgs) Handles btnViewBalance.Click


Dim connectionString As String = "Data Source=.;Initial Catalog=BankDB;Integrated Security=True"
Using con As New SqlConnection(connectionString)
Dim query As String = "SELECT Balance FROM Accounts WHERE
AccountNumber=@AccountNumber"
Dim cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("@AccountNumber", accountNumber)
con.Open()
Dim balance As Decimal = Convert.ToDecimal(cmd.ExecuteScalar())
lblBalance.Text = "Current Balance: " & balance.ToString("C")
End Using
End Sub

Private Sub btnDeposit_Click(sender As Object, e As EventArgs) Handles btnDeposit.Click


Dim transactionForm As New TransactionForm(accountNumber, "Deposit")
transactionForm.ShowDialog()
btnViewBalance.PerformClick() ' Refresh the balance after deposit
End Sub

Private Sub btnWithdraw_Click(sender As Object, e As EventArgs) Handles btnWithdraw.Click


Dim transactionForm As New TransactionForm(accountNumber, "Withdraw")
transactionForm.ShowDialog()
btnViewBalance.PerformClick() ' Refresh the balance after withdrawal
End Sub
End Class
```

#### 5. Design the Transaction Form

1. **TransactionForm Design:**
- Add `TextBox` controls for entering the transaction amount.
- Add a `Button` to submit the transaction.

Example `TransactionForm` UI design:


```vb
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class TransactionForm
Inherits System.Windows.Forms.Form

' ... Designer code for text boxes, labels, and buttons ...

End Class
```

2. **TransactionForm Code-Behind:**
- Implement the logic for handling deposits and withdrawals.

Example `TransactionForm` code:


```vb
Imports System.Data.SqlClient

Public Class TransactionForm


Private accountNumber As String
Private transactionType As String

Public Sub New(accountNumber As String, transactionType As String)


InitializeComponent()
Me.accountNumber = accountNumber
Me.transactionType = transactionType
lblTransactionType.Text = transactionType & " Amount:"
End Sub

Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click


Dim amount As Decimal = Convert.ToDecimal(txtAmount.Text)
Dim connectionString As String = "Data Source=.;Initial Catalog=BankDB;Integrated Security=True"

Using con As New SqlConnection(connectionString)


Dim query As String

If transactionType = "Deposit" Then


query = "UPDATE Accounts SET Balance = Balance + @Amount WHERE
AccountNumber=@AccountNumber"
ElseIf transactionType = "Withdraw" Then
query = "UPDATE Accounts SET Balance = Balance - @Amount WHERE
AccountNumber=@AccountNumber"
End If

Dim cmd As New SqlCommand(query, con)


cmd.Parameters.AddWithValue("@Amount", amount)
cmd.Parameters.AddWithValue("@AccountNumber", accountNumber)
con.Open()
cmd.ExecuteNonQuery()

MessageBox.Show(transactionType & " successful!", "Success", MessageBoxButtons.OK,


MessageBoxIcon.Information)
Me.Close()
End Using
End Sub
End Class
```

#### 6. Run and Test the Application

1. **Compile and Run:**


- Press `F5` to build and run the application.
- Test the login, balance inquiry, deposit, and withdrawal functionalities.

2. **Test Scenarios:**
- Try logging in with a valid and invalid `AccountNumber`.
- Perform deposit and withdrawal transactions.
- Check if the balance updates correctly after each transaction.

### Conclusion

This Windows Forms application provides a basic implementation of core banking transactions. It
includes a login system, balance inquiry, deposit, and withdrawal functionality, all connected to a SQL
Server database. You can expand upon this by adding more features like transaction history, user
authentication, account creation, and more robust error handling.
Evaluation Scheme for Lab Examination:
Assessment Criteria Marks
Writing 2 Programs 10
Execution of 1 Program 10
Viva and Record 05
Total 25

You might also like