Dot Net
Dot Net
: 01
Course Name: Dot Net Framework (21BSIT501/21BCA501)
Academic year: 2023-24
Level A. Easy Questions (2 marks each)
1. System
2. System.Collections.Generic
Example:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
In this example:
System is a built-in namespace that contains commonly used classes like Console.
MyApplication is a custom namespace that defines where the Program class belongs.
Types of JIT:
1. Pre-JIT: Compiles the entire code into native code in a single cycle at the time of
application deployment.
2. Econo-JIT: Compiles methods when they are called but removes the compiled code
when it is not needed to optimize memory usage.
3. Normal JIT: Compiles methods when they are called and stores the compiled code
for future calls to avoid recompilation.
Code: The Intermediate Language (IL) code that is executed by the CLR.
Metadata: Describes the types, members, and references in the assembly.
Manifest: Contains information about the assembly's version, culture, and security
permissions.
Resources: Any additional files like images or strings used by the assembly.
1. Private Assembly:
o Accessible only by a single application.
o Stored in the application's folder.
o Used when the assembly is intended for a specific application and doesn't need
to be shared.
2. Public (or Shared) Assembly:
o Can be used by multiple applications.
o Stored in the Global Assembly Cache (GAC).
o Used when an assembly needs to be shared across multiple applications on the
same machine. Public assemblies require a strong name for identification.
Allows multiple applications to use the same assembly without each one maintaining
a separate copy.
Helps in managing different versions of assemblies.
Ensures that the correct version of an assembly is used by all applications.
Example:
Consider a library that provides logging functionality that is used by multiple applications.
Instead of each application having its own copy of the library, it can be installed in the GAC
as a public assembly.
sn -k keypair.snk
csc /target:library /keyfile:keypair.snk LoggingLibrary.cs
gacutil -i LoggingLibrary.dll
Example:
Imagine an application, MyApp, that includes a Utilities.dll for internal use. Since this
assembly is only relevant to MyApp and not to other applications, it is stored in the same
directory as the application:
MyApp/
├── MyApp.exe
├── Utilities.dll
2. The MyApp.exe will reference the Utilities.dll, but other applications won't have
access to it.
Q29: How does the .NET Framework provide interoperability among different
languages?
The .NET Framework supports interoperability among different programming languages
(like C#, VB.NET, F#) through the following mechanisms:
Through these mechanisms, .NET allows code written in one language (e.g., C#) to work
seamlessly with code written in another language (e.g., VB.NET).
Here’s how you can achieve interoperability between VB.NET and C#.NET:
Namespace MyNamespace
Public Class MyClass
Public Function SayHello() As String
Return "Hello from VB.NET"
End Function
End Class
End Namespace
Example of C# Code:
using MyNamespace;
class Program
{
static void Main()
{
MyClass vbClass = new MyClass();
Console.WriteLine(vbClass.SayHello());
}
}
This shows how VB.NET and C#.NET code can work together by referencing compiled
assemblies.
Overall Flow:
When a .NET application is executed, the CLR loads the assembly, compiles the IL code to
native machine code via JIT, and provides services like garbage collection and security. The
application accesses classes and methods from the FCL to perform its operations.
The Common Language Runtime (CLR) is the heart of the .NET Framework and provides
a range of important services and functionalities that enable the execution and management
of .NET applications.
1. Memory Management:
o The CLR automatically handles memory allocation and deallocation for
objects in .NET applications using a mechanism called Garbage Collection
(GC). This ensures efficient use of memory and prevents memory leaks.
2. Just-In-Time (JIT) Compilation:
o The JIT compiler in the CLR converts Intermediate Language (IL) code
into native machine code, which is executed by the underlying hardware. This
allows .NET applications to run on different platforms.
3. Type Safety:
o The CLR enforces type safety, ensuring that code cannot access memory that
it does not have permission to use. This prevents issues like buffer overflows
and type mismatches.
4. Exception Handling:
o The CLR provides a unified way to handle errors and exceptions across
all .NET languages using a common exception-handling model, which
enhances code reliability.
5. Security Management:
o The CLR provides code access security (CAS) and role-based security (RBS)
to control the permissions that .NET code can have based on the trust level of
the application or user.
6. Thread Management:
o The CLR manages multiple threads, allowing applications to run multiple
tasks concurrently. It ensures proper synchronization and efficient execution
of threads.
7. Interoperability:
o The CLR allows .NET code to interact with COM components and
unmanaged code (native Windows APIs or libraries). This enables legacy
systems to work with modern .NET applications.
8. Assembly Loading and Management:
o The CLR is responsible for loading assemblies, resolving assembly references,
and ensuring that the correct version of an assembly is used in an application.
The Common Type System (CTS) is a standard that defines how data types are declared,
used, and managed in the .NET Framework. It ensures that types used in different .NET
languages (like C#, VB.NET, and F#) are compatible and can interoperate with each other.
Working of CTS:
1. Type Definition:
o The CTS specifies the rules for defining types (classes, interfaces,
enumerations, etc.) in .NET. It ensures that each type in one .NET language is
compatible with and can be used in other .NET languages.
o Types in the CTS are categorized into two main categories:
Value Types: These types hold the data directly. Examples include
int, float, and struct.
Reference Types: These types store references to the actual data.
Examples include class, interface, and object.
2. Cross-Language Interoperability:
o The CTS allows code written in one language to create and use types defined
in another language. For example, a C# program can use a class written in
VB.NET without any issues because both languages conform to the CTS.
3. Type Safety and Consistency:
o CTS ensures type safety, meaning that type mismatches are avoided at
runtime. For example, you cannot assign an int type to a string type without
explicit conversion.
o The CTS enforces consistency in how types are used and stored, ensuring that
types have the same behavior across different .NET languages.
4. Unified Type System:
o All types, including primitive types like int and complex types like class,
inherit from the base class System.Object. This allows for a unified type
system where all types share common methods like ToString(),
GetHashCode(), and Equals().
5. Support for Language Features:
o The CTS enables various language-specific features like inheritance,
polymorphism, and encapsulation to be shared across languages. For instance,
a class in C# can inherit from a class written in F# because both languages
share the same type system.
By enforcing these rules, the CTS ensures that code written in different languages can work
together seamlessly in the .NET environment.
The Common Language Specification (CLS) is a set of guidelines and rules that define a
subset of features that all .NET languages must follow to ensure language interoperability.
The CLS enables code written in one .NET language to be used by code written in
another .NET language, ensuring a consistent development environment.
1. Interoperability: By following CLS rules, .NET languages can interact with each
other seamlessly. For example, a class created in VB.NET can be used in C# if both
adhere to the CLS.
2. Subset of the Common Type System (CTS): The CLS is a narrower specification
compared to the CTS. It defines the common types, methods, and features that are
guaranteed to be supported across all .NET languages.
3. Rules and Restrictions:
o Case Sensitivity: Some languages are case-insensitive (like VB.NET), so the
CLS requires that public identifiers (like class names or method names) not
differ only by case.
o Data Types: Only common data types that are CLS-compliant (like int,
string, bool) should be used in public methods or classes.
o Method Overloading: While supported, overloading based on differences in
parameters is allowed, but restrictions may apply to ensure compatibility
across languages.
Example:
In C#, you might have a method signature like this:
While this is valid in C#, if this class is to be used in a VB.NET project (which doesn’t
support case-sensitive overloading), you would have to modify it to comply with the CLS,
ensuring compatibility.
1. Platform Independence: Since all .NET languages compile to MSIL, it allows .NET
applications to be run on any platform supported by the CLR, regardless of the
original programming language used.
2. Security: MSIL contains metadata that helps in enforcing security policies.
3. Execution Model: MSIL code is executed by the CLR, which provides services such
as garbage collection, type safety, and exception handling.
Example:
Here is a simple C# program:
class Program
{
static void Main()
{
System.Console.WriteLine("Hello, World!");
}
}
When compiled, the C# code is translated into the following MSIL code:
This MSIL code is platform-independent and is converted to machine code at runtime by the
JIT compiler.
The .NET Framework Class Library (FCL) is a vast collection of reusable classes,
interfaces, and types that provide the functionality needed to build .NET applications. It is an
integral part of the .NET Framework and offers access to system functionality, basic data
structures, and a variety of tools to create desktop applications, web applications, and more.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = @"C:\example.txt";
In this example:
A .NET application is composed of several key components that play an essential role in
making the software modular, reusable, and maintainable. These components include
assemblies, namespaces, and classes.
1. Assemblies:
2. Namespaces:
Example:
namespace MyCompany.Logging
{
public class Logger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
}
Here, Logger is part of the MyCompany.Logging namespace, making it easy to find and
organize logging-related classes.
3. Classes:
Definition: A class is a blueprint for creating objects in .NET. It defines the structure and
behavior (methods, properties, fields) of an object.
Function: Classes encapsulate data and behavior, supporting object-oriented programming
(OOP) principles like inheritance, encapsulation, and polymorphism.
Role in Modular Software:
o Abstraction and Encapsulation: Classes allow for abstraction of functionality and
encapsulation of data, which leads to cleaner, modular code.
o Reusability and Maintainability: Classes can be reused across different projects and
can be extended through inheritance. This reduces code duplication and enhances
maintainability.
Example:
1. Modularity: Assemblies allow you to break down an application into independent, self-
contained modules that can be developed, tested, and maintained separately.
2. Reusability: Classes and namespaces can be organized into libraries (assemblies) that are
reusable across multiple applications.
3. Maintainability: Clear separation of code into namespaces and well-structured classes
ensures that code is easier to maintain and extend.
4. Versioning and Upgrades: Assemblies support versioning, allowing developers to update
parts of the system without affecting the entire application.
1. Object Allocation:
o When a new object is created in a .NET application, memory is allocated for it from a
reserved region of memory known as the managed heap.
2. Generations in the Managed Heap: The managed heap is divided into three
generations:
o Generation 0: Newly created objects are allocated here. This is the area where most
short-lived objects reside.
o Generation 1: Objects that survive a collection from Generation 0 are promoted to
Generation 1.
o Generation 2: Long-lived objects (like static variables) reside in this generation.
3. Garbage Collection Trigger: The Garbage Collector runs when the system runs low
on memory or when memory pressure increases. It can also be triggered manually via
GC.Collect(), though this is typically discouraged.
4. Mark-and-Sweep:
o Mark: The GC marks objects that are still in use by tracking all object references
from application roots (like static fields or active threads).
o Sweep: After marking, the GC frees memory occupied by objects that are no longer
referenced.
5. Compaction: After objects are collected, the GC compacts the remaining objects to
optimize memory usage and reduce fragmentation in the heap.
1. Simplifies Development: Developers don't have to manually manage memory allocation and
deallocation, which reduces memory leaks and dangling pointers.
2. Improves Reliability: The GC ensures that memory is automatically freed when objects are
no longer in use, preventing common memory-related bugs like use-after-free.
3. Optimized for Performance: The GC performs memory management efficiently and is
optimized for both throughput and latency, dynamically adjusting its behavior based on the
application's workload.
By following these best practices, developers can optimize memory usage and improve the
performance of .NET applications while relying on the automatic memory management
capabilities provided by the CLR.
Some IDEs also include features such as version control, design tools, and testing
environments.
Visual Studio is a widely used IDE developed by Microsoft for developing applications,
including console apps, Windows applications, web apps, mobile apps, and cloud services. It
supports multiple programming languages such as C#, VB.NET, F#, Python, JavaScript, and
more.
A solution file (.sln) in Visual Studio is a container that holds multiple projects and their
configurations in a single environment. It allows developers to manage multiple related
projects together, such as a web application with a backend API.
Q4: What is the Menu bar?
The Menu bar in Visual Studio is located at the top of the IDE and provides access to
various tools and commands needed for developing software. Common menus include File,
Edit, View, Build, and Debug.
Solution Explorer is a tool window in Visual Studio that shows all the files, folders, and
references within a solution and its projects. It allows you to navigate, add, remove, and
manage files and components within your solution.
The Toolbox is a panel that provides access to various controls and components that can be
dragged and dropped into a design surface (such as a web form or Windows form). For
example, it contains controls like text boxes, buttons, labels, and more.
Server Explorer is a tool in Visual Studio that allows you to view and manage databases,
servers, and other connected resources. It provides access to services like SQL Server
databases, event logs, and Azure services.
A Textbox is an HTML control used in web applications to allow users to input text data. In
ASP.NET web forms, it is represented by the <asp:TextBox> control, and it can accept text
input from users.
A Button is a control in web applications that users can click to trigger an action or event,
such as submitting a form. In ASP.NET, it is represented by the <asp:Button> control.
A List box in a web application is a user interface element that allows users to select one or more
items from a predefined list. It typically displays multiple options at once and can support single or
multiple selections, depending on its configuration.
A Combo box is a user interface element that combines a drop-down list with an editable field. Users
can either select an item from the list or enter a value manually. This allows for flexibility in data
input.
The Toolbox in development environments, like Visual Studio, contains a collection of controls,
tools, and components that developers can drag and drop into their design surface to build user
interfaces or define functionality in their applications.
The Server Explorer in an IDE (like Visual Studio) provides access to server-side resources such as
databases, services, event logs, and system resources. Developers use it to manage connections to
databases, explore database schema, and perform queries.
The Solution Explorer in Visual Studio shows the hierarchical view of the projects and files in a
solution. It helps developers manage and navigate through their codebase, assets, references, and
other resources associated with the project.
An IDE is used to streamline software development by providing a set of tools in one interface,
including a code editor, debugger, compiler, and sometimes version control. This allows developers
to write, test, and debug code more efficiently in one environment.
Q18: Which IDE is used to create projects using the .NET Framework? (CO2)
Visual Studio is the primary IDE used to create projects using the .NET Framework.
A Windows project involves the development of desktop applications designed to run on the
Windows operating system. In .NET, this can involve building applications using frameworks like
Windows Forms or Windows Presentation Foundation (WPF).
.NET is a software development platform developed by Microsoft, which provides tools, libraries,
and frameworks to build various types of applications such as web, desktop, mobile, cloud-based,
and IoT applications. It supports multiple languages like C#, VB.NET, and F#.
Visual Studio is the most widely used IDE for creating .NET projects.
In your code-behind (VB.NET), you can handle the button click event:
A Manifest is a part of the metadata in .NET assemblies that contains information about the
assembly's identity (name, version, culture), its dependencies, and the files that make up the
assembly. It helps the Common Language Runtime (CLR) to manage the assembly’s versioning,
security, and deployment. The manifest ensures that the correct versions of assemblies are loaded
and that all the necessary components are available when the application runs.
The Common Type System (CTS) is a standard in the .NET framework that defines how types are
declared, used, and managed in the runtime. It provides a framework for creating and using types,
ensuring that they can work together regardless of the programming language used. CTS includes
value types (such as integers and structures) and reference types (such as classes and interfaces),
enabling type safety and interoperability among different languages in the .NET ecosystem.
The Common Language Specification (CLS) is a subset of the Common Type System (CTS) that
defines a set of rules and guidelines for building .NET applications in a way that ensures
interoperability between different .NET languages. CLS specifies which features of the .NET
framework are available to all compliant languages, enabling developers to create components that
can be used across various languages in the .NET environment. It includes naming conventions, type
definitions, and other language interoperability requirements.
Q31: What do you mean by JIT Compilation and Common Type System? (CO2)
arduino
Copy code
.method public hidebysig static void Main() cil managed
{
// Method implementation
ldstr "Hello, World!"
call void [mscorlib]System.Console::WriteLine(string)
ret
}
FCL (Framework Class Library):
The Framework Class Library (FCL) is a comprehensive collection of reusable classes,
interfaces, and value types that developers can use to build applications in the .NET
framework. FCL provides a wide range of functionalities, including file handling, database
interaction, web application development, and more.
Example: When you use the System.IO namespace to read a file in C#:
csharp
Copy code
using System.IO;
class Program
{
static void Main()
{
string text = File.ReadAllText("example.txt");
System.Console.WriteLine(text);
}
}
Here, File is part of the FCL, allowing developers to easily interact with the file system
without having to write low-level code.
Q33: Create a registration form for student (add student name, admission no., course name, email
id, and contact no.) (CO2)
aspx
Copy code
<%@ Page Language="VB" AutoEventWireup="false" CodeBehind="RegistrationForm.aspx.vb"
Inherits="YourNamespace.RegistrationForm" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Student Registration Form</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Student Registration Form</h2>
<label for="TextBoxName">Student Name:</label>
<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox><br /><br />
Code-Behind (RegistrationForm.aspx.vb):
vb
Copy code
Imports System
' Here you can add code to save the data to a database or process it as needed
This code creates a simple registration form for students, including fields for their name, admission
number, course name, email ID, and contact number. The form handles submission and can be
extended to store data as needed.
Q34: What is the role of the JIT compiler in the .NET Framework? (CO2)
The Just-In-Time (JIT) compiler in the .NET Framework plays a crucial role in converting Microsoft
Intermediate Language (MSIL) code into native machine code at runtime. Here are the key roles of
the JIT compiler:
1. Runtime Compilation: The JIT compiler compiles MSIL to native code on demand, just
before the code is executed. This allows the .NET runtime to optimize the execution for the
specific architecture of the machine.
2. Performance Optimization: By compiling code at runtime, the JIT compiler can apply
optimizations that are relevant to the current execution environment, such as inlining
methods and optimizing loops.
3. Memory Management: The JIT compiler also manages memory allocation and ensures that
the native code can interact efficiently with the managed memory environment of the .NET
Framework.
4. Code Generation: It generates native code for the methods that are called, which improves
the performance of applications since the code does not need to be recompiled each time it
runs, only compiled once when it is called.
Q35: How to create a project in Visual Studio? Write steps to create a project. (CO2)
Q36: Write code to create a TextBox, Button, Label, ListBox, and ComboBox. (CO2)
Here’s an example of how to create a TextBox, Button, Label, ListBox, and ComboBox in an ASP.NET
Web Application using VB.NET:
ASPX Code (WebForm.aspx):
aspx
Copy code
<%@ Page Language="VB" AutoEventWireup="false" CodeBehind="WebForm.aspx.vb"
Inherits="YourNamespace.WebForm" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Form Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Form Elements Example</h2>
<label for="TextBoxName">Name:</label>
<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox><br /><br />
<label for="LabelInfo">Information:</label>
<asp:Label ID="LabelInfo" runat="server" Text="Enter your name above."></asp:Label><br
/><br />
Code-Behind (WebForm.aspx.vb):
vb
Copy code
Imports System
Public Class WebForm
Inherits System.Web.UI.Page
In this example:
You can run this form in an ASP.NET web application to see how it works!
2. Define constant.
A constant is a named value in a program that does not change during the execution
of the program.
vb.net
Copy code
Module Module1
Sub Main()
num1 = Convert.ToInt32(Console.ReadLine())
num2 = Convert.ToInt32(Console.ReadLine())
Console.ReadLine()
End Sub
End Module
Definition: Constants in VB.NET are values that cannot be changed during the execution of
the program.
Example:
vb.net
Copy code
Module Module1
Sub Main()
End Sub
End Module
o Explanation: PI and MaxCount are constants. Their values are fixed and cannot be
altered during runtime.
Example:
vb.net
Copy code
Enum Days
Sunday = 1
Monday = 2
Tuesday = 3
Wednesday = 4
Thursday = 5
Friday = 6
Saturday = 7
End Enum
Module Module1
Sub Main()
End Sub
End Module
o Explanation: The Days Enum defines constants for the days of the week.
Days.Monday represents the value 2.
Integer:
Double:
Boolean:
String:
Date:
Definition: Type conversion is the process of converting one data type to another, either
implicitly or explicitly.
Example:
vb.net
Copy code
Module Module1
Sub Main()
End Sub
End Module
Operators:
o + (Addition)
o - (Subtraction)
o * (Multiplication)
o / (Division)
o % (Modulus)
Example:
vb.net
Copy code
Module Module1
Sub Main()
Dim x As Integer = 10
Dim y As Integer = 5
End Sub
End Module
Operators:
o = (Equal to)
Example:
vb.net
Copy code
Module Module1
Sub Main()
Dim x As Integer = 10
Dim y As Integer = 20
End Sub
End Module
o Explanation: The program compares two integers using comparison operators and
prints the result (True/False).
Definition: Logical operators are used to perform logical operations on Boolean values.
Operators:
Example:
vb.net
Copy code
Module Module1
Sub Main()
End Sub
End Module
o Explanation: Logical operators are used to perform logical operations between two
Boolean values.
Operators:
o = (Simple assignment)
Example:
vb.net
Copy code
Module Module1
Sub Main()
Dim x As Integer = 10
x += 5 ' x = x + 5
Console.WriteLine(x) ' 15
End Sub
End Module
o Explanation: The += operator adds 5 to the current value of x and assigns the result
back to x.
vb.net
Copy code
Module Module1
Sub Main()
Dim num As Integer
num = Convert.ToInt32(Console.ReadLine())
For i As Integer = 1 To 10
Console.WriteLine(num & " x " & i & " = " & (num * i))
Next
Console.ReadLine()
End Sub
End Module
Syntax:
vb.net
Copy code
If condition Then
End If
Example:
vb.net
Copy code
Module Module1
Sub Main()
Dim number As Integer = 10
End If
End Sub
End Module
Explanation: If the number is greater than 5, the message "The number is greater than 5"
will be printed.
Syntax:
vb.net
Copy code
If condition Then
Else
End If
Example:
vb.net
Copy code
Module Module1
Sub Main()
Else
End If
End Sub
End Module
Explanation: If the number is greater than 5, the first block of code will execute; otherwise,
the second block will execute.
Definition: The Do Loop is used to repeat a block of code while a certain condition is true.
The condition is evaluated before or after the loop.
Syntax:
o Do While loop:
vb.net
Copy code
Do While condition
Loop
o Do Until loop:
vb.net
Copy code
Do Until condition
Loop
Example:
vb.net
Copy code
Module Module1
Sub Main()
count += 1
Loop
End Sub
End Module
Explanation: The loop will run as long as the condition (count <= 5) is true, printing the value
of count at each iteration.
Definition: The For Loop is used to execute a block of code a specific number of times. The
number of iterations is determined by the start, end, and step values.
Syntax:
vb.net
Copy code
Next
Example:
vb.net
Copy code
Module Module1
Sub Main()
For i As Integer = 1 To 5
Next
End Sub
End Module
Explanation: The loop iterates five times, printing the value of i in each iteration.
vb.net
Copy code
Module Module1
Sub Main()
Next
Console.ReadLine()
End Sub
End Module
Explanation: The program creates an array of integers and displays each element along with
its index.
Example:
vb.net
Copy code
Module Module1
Sub Main()
Console.WriteLine(greeting)
End Sub
End Module
Explanation: The program defines a string variable greeting and displays its value.
vb.net
Copy code
Module Module1
Sub Main()
Dim sentence As String = "Hello, how are you?"
Console.WriteLine(word)
Next
End Sub
End Module
Explanation: The Split method divides the string into words based on the space character
and displays each word.
vb.net
Copy code
Module Module1
Sub Main()
Console.WriteLine(extracted)
End Sub
End Module
Explanation: The Substring method extracts a part of the string starting from index 7 and
with a length of 5 characters.
vb.net
Copy code
Module Module1
Sub Main()
Console.WriteLine(sentence)
End Sub
End Module
Explanation: The Join method combines the elements of an array into a single string,
separating them with spaces.
vb.net
Copy code
Module Module1
Sub Main()
End Sub
End Module
Explanation: The Trim method removes leading and trailing spaces from the string text.
Methods like Split, Substring, Join, Trim: Used for manipulating and modifying strings.
Question Bank - Unit no.:04
Definition: A function is a block of code that performs a specific task and returns a value. In
VB.NET, functions are used to return a value after performing some operations.
Definition: A subroutine (also known as a Sub in VB.NET) is a block of code that performs a
task but does not return any value. Subroutines are used for executing operations without
the need to return a result.
Syntax:
vb.net
Copy code
Return value
End Function
Example:
vb.net
Copy code
End Function
Q4. Write syntax to create a subroutine in VB.NET. CO4
Syntax:
vb.net
Copy code
Sub SubroutineName()
End Sub
Example:
vb.net
Copy code
Sub DisplayMessage()
Console.WriteLine("Hello, World!")
End Sub
Syntax:
vb.net
Copy code
Return value
End Function
Example:
vb.net
Copy code
Return x * y
End Function
Syntax:
vb.net
Copy code
Return value
End Function
Example:
vb.net
Copy code
End Function
Syntax:
vb.net
Copy code
End Sub
Example:
vb.net
Copy code
End Sub
Q8. Write a syntax to create a Sub procedure with parameter in VB.NET. CO4
Syntax:
vb.net
Copy code
Sub ProcedureName(ByVal param1 As DataType, ByVal param2 As DataType)
End Sub
Example:
vb.net
Copy code
End Sub
Syntax:
vb.net
Copy code
Class ClassName
End Class
Example:
vb.net
Copy code
Class Car
Sub DisplayInfo()
End Sub
End Class
vb.net
Copy code
Example:
vb.net
Copy code
myCar.DisplayInfo()
Definition: A Function in VB.NET is a block of code that performs a task and returns a value.
Functions can accept parameters and are used to perform operations like calculations and
return results.
Definition: The term "Sub Function" is not a standard term in VB.NET. It seems to be a mix of
Sub and Function. A Sub does not return a value, whereas a Function does. They are both
used to organize code in VB.NET.
Syntax:
vb.net
Copy code
Class ClassName
Sub New()
End Sub
End Class
Example:
vb.net
Copy code
Class Person
name = personName
End Sub
End Class
Syntax:
vb.net
Copy code
Class ClassName
End Sub
End Class
Example:
vb.net
Copy code
Class Person
End Sub
End Class
Syntax:
vb.net
Copy code
Try
Catch ex As Exception
Finally
End Try
Example:
vb.net
Copy code
Try
Catch ex As DivideByZeroException
End Try
Answer: Exceptions are represented by objects of the Exception class or its derived classes.
Q19. Name of the base class of all exception classes ………………….. CO4
Answer: The Try keyword is used to define a block of code that might throw an exception. It
is followed by a Catch block to handle any exceptions that occur.
Level B. Intermediate Questions (5 marks each)
Program:
vb.net
Copy code
Module Module1
End Function
Sub Main()
Console.ReadLine()
End Sub
End Module
Program:
vb.net
Copy code
Module Module1
Console.WriteLine(message)
End Sub
Sub Main()
Console.ReadLine()
End Sub
End Module
Program:
vb.net
Copy code
Module Module1
Class Car
Sub DisplayDetails()
End Sub
End Class
Sub Main()
myCar.make = "Toyota"
myCar.model = "Camry"
myCar.DisplayDetails()
Console.ReadLine()
End Sub
End Module
Program:
vb.net
Copy code
Module Module1
Class Person
Me.Name = name
Me.Age = age
End Sub
Sub DisplayPersonDetails()
End Class
Sub Main()
person1.DisplayPersonDetails()
Console.ReadLine()
End Sub
End Module
Program:
vb.net
Copy code
Module Module1
Sub Main()
Try
Catch ex As DivideByZeroException
Finally
End Try
Console.ReadLine()
End Sub
End Module
Q26. What is the use of try, catch, finally blocks in VB.NET? CO4
Try Block: The Try block contains the code that might throw an exception.
Catch Block: The Catch block handles any exception that occurs in the Try block. It can
specify the type of exception to catch (e.g., DivideByZeroException).
Finally Block: The Finally block is optional and executes regardless of whether an exception
occurred or not. It is often used for cleanup operations (e.g., closing files or database
connections).
1. TextBox:
vb.net
Copy code
Me.Controls.Add(txtInput)
2. RadioButton:
vb.net
Copy code
Me.Controls.Add(radioButton)
3. CheckBox:
vb.net
Copy code
Me.Controls.Add(checkBox)
1. Label:
vb.net
Copy code
Me.Controls.Add(lblMessage)
2. Button:
vb.net
Copy code
btnSubmit.Text = "Submit"
Me.Controls.Add(btnSubmit)
3. ListBox:
vb.net
Copy code
lstItems.Items.Add("Item 1")
lstItems.Items.Add("Item 2")
Me.Controls.Add(lstItems)
Q31. Write a program to calculate the area of a circle using class and object in VB.NET. CO4
Program:
vb.net
Copy code
Module Module1
Class Circle
End Function
End Class
Sub Main()
circleObj.radius = 5.0
Console.WriteLine("The area of the circle with radius " & circleObj.radius & " is: " & area)
Console.ReadLine()
End Sub
End Module
Q32. What is class and object? How to create class and object in VB.NET? Write a program to print
factorial value in VB.NET. CO4
Class: A class is a blueprint or template that defines the properties and methods for objects.
Object: An object is an instance of a class. It holds the actual data and can call the methods
defined in the class.
vb.net
Copy code
Module Module1
Class FactorialCalculator
For i As Integer = 1 To n
factorial *= i
Next
Return factorial
End Function
End Class
Sub Main()
Console.WriteLine("Factorial of " & number & " is: " & result)
Console.ReadLine()
End Sub
End Module
Q33. Explain about Constructor and Destructors with an example in VB.NET. CO4
Example Program:
vb.net
Copy code
Module Module1
Class Car
make = carMake
End Sub
End Class
Sub Main()
' Creating an object of the Car class which invokes the constructor
' Destructor will be called when the object goes out of scope
Console.ReadLine()
End Sub
End Module
Try: Block where the code that might throw an exception is written.
Example:
vb.net
Copy code
Module Module1
Sub Main()
Try
Catch ex As DivideByZeroException
Catch ex As Exception
End Try
Console.ReadLine()
End Sub
End Module
Q36. What are basic controls? Explain any five basic controls in VB.NET. CO4
vb.net
Copy code
Me.Controls.Add(txtInput)
vb.net
Copy code
btnSubmit.Text = "Submit"
Me.Controls.Add(btnSubmit)
3. Label: Used to display text or information to the user.
vb.net
Copy code
Me.Controls.Add(lblMessage)
vb.net
Copy code
Me.Controls.Add(radioButton)
vb.net
Copy code
Me.Controls.Add(checkBox)
These are the basic controls used to create interactive forms in VB.NET. They handle user input,
trigger actions, and display information to users.
Question Bank - Unit no.:05
Course Name: Dot Net Framework
Academic year: 2023-24
Level A. Easy Questions (2 marks each)
Q1. What does ADO.NET stand for in VB.NET? CO5
Answer: ADO.NET stands for ActiveX Data Objects .NET. It is a data access technology that provides
a set of classes to interact with databases in VB.NET and other .NET languages.
Answer: A connection string is used to specify the necessary parameters for establishing a
connection to a database, such as the server name, database name, authentication details
(username and password), and other optional parameters like timeouts.
Q4. Which ADO.NET object is used to execute SQL commands against a database in VB.NET? CO5
Answer: The ADO.NET object used to execute SQL commands against a database is SqlCommand.
Q5. Which of the following is used to read data from a database in a forward-only, readonly
manner in VB.NET? CO5
Answer: The SqlDataReader is used to read data from a database in a forward-only, read-only
manner in VB.NET.
Q6. What is the primary purpose of using parameterized queries in database connectivity? CO5
Answer: The primary purpose of using parameterized queries is to prevent SQL injection attacks and
to ensure that the parameters passed to the SQL query are treated as values, not executable code.
Q7. Which ADO.NET object is used to store data retrieved from a database in a structured format
in VB.NET? CO5
Answer: The DataSet object is used to store data retrieved from a database in a structured format,
like a table or multiple related tables, in VB.NET.
Q8. Which of the following is used to iterate through a result set and read data retrieved from a
database in VB.NET? CO5
Answer: The SqlDataReader is used to iterate through a result set and read data retrieved from a
database.
Answer: A connection string is used to specify the configuration settings needed to connect to a
database, such as the server, database name, user credentials, and other optional parameters.
Q11. Which ADO.NET object is used to execute SQL commands against a database in VB.NET? CO5
Answer: The SqlCommand object is used to execute SQL commands against a database in VB.NET.
Q12. Which of the following is used to read data from a database in a forward-only, readonly
manner in VB.NET? CO5
Answer: The SqlDataReader is used to read data from a database in a forward-only, read-only
manner in VB.NET.
Q13. What is the primary purpose of using parameterized queries in database connectivity? CO5
Answer: The primary purpose of using parameterized queries is to avoid SQL injection, ensure
correct data types, and improve performance by reusing the query execution plan.
Q14. Which ADO.NET object is used to store data retrieved from a database in a structured format
in VB.NET? CO5
Answer: The DataSet object is used to store data retrieved from a database in a structured, in-
memory representation.
Q15. Which of the following is used to iterate through a result set and read data retrieved from a
database in VB.NET? CO5
Answer: The SqlDataReader is used to iterate through a result set and read data retrieved from a
database.
Answer: The SqlDataAdapter is an ADO.NET object used to retrieve data from a database and
populate a DataSet or DataTable with the result. It can also be used to update the database with
changes made to the DataSet.
Answer: The SqlConnection is an ADO.NET class that is used to establish and manage the connection
between an application and a SQL Server database.
Answer: The SqlCommand class in ADO.NET is used to execute SQL queries, commands, and stored
procedures against a SQL Server database.
1. SQL Server
2. Oracle Database
Q20. Which of the following is used to iterate through a result set and read data retrieved from a
database in VB.NET? CO5
Answer: The SqlDataReader is used to iterate through a result set and read data retrieved from a
database.
Q21. What is the difference between a SqlDataAdapter and a SqlCommand in ADO.NET? CO5
Answer:
1. SqlDataAdapter:
o It also provides the functionality to update the database with changes made in the
DataSet.
o Example:
vb.net
Copy code
adapter.Fill(dataSet)
2. SqlCommand:
o Example:
vb.net
Copy code
Q22. How do you retrieve data from a database using a DataReader in VB.NET? CO5
Example:
vb.net
Copy code
connection.Open()
While reader.Read()
Console.WriteLine(reader("ColumnName").ToString())
End While
reader.Close()
connection.Close()
Q23. How can you secure database connections and prevent SQL injection in your VB.NET
applications? CO5
Answer:
1. Use Parameterized Queries: Ensure queries use parameters to avoid direct concatenation of
user input in SQL queries.
vb.net
Copy code
command.Parameters.AddWithValue("@username", username)
2. Use Stored Procedures: Execute stored procedures with parameters instead of dynamic SQL
queries.
3. Validate User Input: Always validate and sanitize user input before passing it to SQL queries.
4. Use Least Privilege Principle: Limit database user permissions to only what's necessary.
Answer: ADO.NET (ActiveX Data Objects .NET) is a data access technology in the .NET framework
that allows VB.NET applications to interact with data sources such as SQL Server, Oracle, and other
databases. It provides classes like SqlConnection, SqlCommand, SqlDataReader, SqlDataAdapter,
and DataSet for managing and manipulating data in disconnected and connected modes. ADO.NET
enables efficient and secure database connectivity in VB.NET applications.
Q25. What is connection pooling, and how does it benefit database connectivity in VB.NET
applications? CO5
Answer: Connection pooling refers to the practice of maintaining a pool of database connections
that can be reused instead of opening a new connection for every database operation. This improves
performance and reduces the overhead of creating and destroying connections repeatedly. Benefits:
1. Improved Performance: Reduces the time spent opening and closing database connections.
2. Resource Optimization: Avoids creating excessive connections, which can exhaust system
resources.
Q26. What are stored procedures, and how can they be used in a VB.NET application for database
connectivity? CO5
Answer: Stored procedures are precompiled SQL statements stored in the database. They can
perform operations like data retrieval, insertion, and deletion. In VB.NET, stored procedures can be
called using SqlCommand objects, which can be executed using the ExecuteNonQuery(),
ExecuteReader(), or ExecuteScalar() methods depending on the operation.
Example:
vb.net
Copy code
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddWithValue("@EmployeeID", 1)
Q27. Discuss the advantages of using stored procedures over inline SQL queries. CO5
Answer:
1. Security: Stored procedures help prevent SQL injection by using parameters instead of
concatenating user input.
2. Performance: Stored procedures are precompiled, which makes execution faster since the
SQL Server already knows the execution plan.
3. Code Reusability: Stored procedures allow reusing SQL code in multiple applications,
ensuring consistency.
4. Maintainability: With stored procedures, the logic resides in the database, making
maintenance easier.
5. Reduced Bandwidth Usage: Stored procedures send only the procedure call, reducing the
amount of data exchanged between the application and the database.
Q28. Discuss the concept of data binding in VB.NET applications. How can you bind data from a
database to user interface controls, and what are the benefits of doing so? CO5
Answer: Data binding in VB.NET refers to the process of linking data from a data source (like a
database) to a UI control, such as a TextBox, GridView, or ComboBox. Data binding can be done in
two main ways: simple binding and complex binding.
vb.net
Copy code
vb.net
Copy code
DataGridView1.DataSource = dataSet.Tables("TableName")
Benefits:
1. Automatic Data Synchronization: Changes in the data source are automatically reflected in
the UI controls.
Q29. Explain how you can work with multiple database connections in a VB.NET application. For
example, how would you handle connections to multiple databases or multiple instances of the
same database? CO5
1. Multiple Databases: Create separate SqlConnection objects for each database and use them
independently.
vb.net
Copy code
2. Multiple Instances of Same Database: Create multiple SqlConnection objects with different
connection strings (for example, connecting to different server instances or using different
credentials).
3. Managing Connections: Ensure each connection is properly opened and closed to avoid
resource leaks.
Q30. Discuss the security considerations when working with database connectivity in VB.NET. How
can you prevent SQL injection and protect sensitive data during database interactions? CO5
Answer:
1. Use Parameterized Queries: Ensure all database queries use parameters, not concatenated
strings, to prevent SQL injection.
2. Use Stored Procedures: Avoid inline SQL queries and use stored procedures with
parameters to increase security.
3. Validate User Input: Always validate user inputs for correctness and sanitize inputs.
4. Encrypt Sensitive Data: Use encryption for sensitive data like passwords when storing them
in the database or transmitting over the network.
5. Use Secure Connection Strings: Encrypt connection strings and avoid hardcoding them in
the source code.
Q31. Explain the purpose of the Connection, Command, DataReader, and DataSet objects in
ADO.NET. CO5
Answer:
1. Connection:
o Example:
vb.net
Copy code
Dim connection As New SqlConnection("your_connection_string")
connection.Open()
2. Command:
o The SqlCommand object is used to execute SQL queries or stored procedures against
the database. It can be used for queries, updates, and database management
operations.
o Example:
vb.net
Copy code
3. DataReader:
o The SqlDataReader object is used to retrieve data from the database in a forward-
only, read-only manner. It is efficient for large result sets as it fetches data row-by-
row.
o Example:
vb.net
Copy code
While reader.Read()
Console.WriteLine(reader("EmployeeName"))
End While
4. DataSet:
o The DataSet object is an in-memory cache that can hold multiple tables of data. It is
used to retrieve data and store it in a disconnected manner, allowing you to work
with the data offline.
o Example:
vb.net
Copy code
adapter.Fill(dataSet, "Employees")
Q32. How can you establish a connection to a SQL Server database in VB.NET? CO5
Answer: To establish a connection to a SQL Server database, you need to use the SqlConnection
object and specify the connection string. The following steps are involved:
2. Provide the connection string, which includes the server name, database name, user
credentials (if required).
Example:
vb.net
Copy code
connection.Open()
Q33. What are the key components of a database connection string in VB.NET? CO5
1. Server: The address of the SQL Server instance (e.g., localhost, myServerAddress).
4. Password: The password associated with the database user (e.g., myPassword).
5. Integrated Security: Specifies whether Windows Authentication is used (set to True for
integrated security).
6. Connection Timeout: The amount of time before the connection attempt times out
(optional).
Example:
vb.net
Copy code
Q34. Explain the steps involved in establishing a database connection in a VB.NET application. CO5
1. Create a SqlConnection Object: Initialize a new SqlConnection object with the connection
string.
2. Open the Connection: Use the Open() method to open the connection to the database.
3. Execute Commands: Execute SQL commands or stored procedures using the SqlCommand
object.
4. Handle Exceptions: Use Try...Catch blocks to handle any errors that occur during connection.
5. Close the Connection: Use the Close() method to close the connection once the operation is
complete.
Example:
vb.net
Copy code
Try
connection.Open()
Catch ex As Exception
Finally
connection.Close()
End Try
Q35. Discuss the importance of parameterized queries in VB.NET database connectivity. Provide
an example of a parameterized query. CO5
1. Security: Prevents SQL injection by ensuring that user input is treated as data, not
executable code.
2. Performance: The SQL Server can cache execution plans for parameterized queries,
improving performance.
3. Data Integrity: Ensures that data types are validated and prevents errors due to incorrect
data types.
vb.net
Copy code
Dim command As New SqlCommand("SELECT * FROM Users WHERE Username = @Username AND
Password = @Password", connection)
command.Parameters.AddWithValue("@Username", username)
command.Parameters.AddWithValue("@Password", password)
Q36. Describe the differences between a SqlDataReader and a SqlDataAdapter in ADO.NET. When
would you use one over the other in a VB.NET application? CO5
Answer:
1. SqlDataReader:
o Purpose: Used to read data from the database in a forward-only, read-only manner.
o Usage: Suitable when you need to read data row-by-row and cannot afford to store
the data in memory.
o Efficiency: It is more efficient than SqlDataAdapter for large result sets because it
retrieves data as it is read, without loading it into memory.
Example:
vb.net
Copy code
While reader.Read()
Console.WriteLine(reader("ColumnName"))
End While
2. SqlDataAdapter:
o Usage: Suitable when you need to perform operations like sorting, filtering, or
updating the data offline.
o Advantages: Can update data back to the database using the Update() method.
Example:
vb.net
Copy code
adapter.Fill(dataSet, "Employees")
When to use:
Use SqlDataReader for fast, forward-only data retrieval when you don't need to update the
data and memory efficiency is crucial.
Use SqlDataAdapter when you need to work with disconnected data and perform operations
like sorting, updating, or binding to UI controls.