DotNet Framework
DotNet Framework
b) What is CTS?
The Common Type System (CTS) is a standard defined by .NET that specifies
how data types are declared, used, and managed. It ensures type compatibility
across different .NET languages, allowing them to work together seamlessly.
3
a) What is IDE?
IDE stands for Integrated Development Environment. It is a software application
that provides comprehensive facilities to computer programmers for software
development. Typically, an IDE consists of a source code editor, build
automation tools, and a debugger. Examples include Visual Studio, Eclipse, and
IntelliJ IDEA
g) Explain ADO.Net?
ADO.Net (ActiveX Data Objects .NET) is a set of classes in the .NET Framework
that provides a way for .NET applications to access and interact with various data
sources, such as databases, XML files, and spreadsheets. It provides a
disconnected data architecture for efficient data manipulation.
range. You set the MinimumValue and MaximumValue properties, and the
validator checks if the input is within these bounds.
i) What is ASP.NET?
ASP.NET is a web application framework developed by Microsoft for building
dynamic web pages, web applications, and web services. It is built on the .NET
Framework and provides a rich set of controls, libraries, and tools for developing
robust and scalable web solutions.
a) What is CTS?
CTS stands for Common Type System. It is a specification within the .NET
Framework that defines how data types are declared, used, and managed. It
provides a unified type system that allows different .NET languages to
interoperate seamlessly.
* Layout and Formatting: You can control the layout of columns (order, width,
visibility), apply formatting to cell values, and even display images within cells.In
essence, the DataGridView control provides a user-friendly interface for viewing,
including dynamic content from other pages. Overloads exist to preserve form
and query string parameters.
* HtmlDecode(string): Decodes an HTML-encoded string. It converts HTML
entities (like <, >, &) back to their original characters (<, >, &). This is
useful when displaying user-submitted data that might have been HTML-encoded
for security reasons.
* HtmlEncode(string): Encodes a string into HTML. It converts potentially
problematic characters (like <, >, &, ", ') into their corresponding HTML entities.
This is crucial for preventing cross-site scripting (XSS) attacks by ensuring that
user-provided data is rendered as plain text and not as executable HTML or
JavaScript.
* MapPath(path): Maps a virtual path (relative to the application's root directory)
to its corresponding physical path on the server's file system. This is essential for
accessing files and directories within your web application. For example,
Server.MapPath("~/Images/logo.gif") would return the full physical path to the
logo.gif file in the Images folder under your application's root.
* Transfer(path): Terminates the execution of the current page and redirects the
request to another ASP.Net page or handler on the server without sending a
redirect response to the client. The server directly executes the target page using
the same request context. This is more efficient than a client-side redirect
.
e) Explain the MessageBox function in detail.
The MessageBox is a static class (in Windows Forms and WPF under the
System.Windows.Forms and System.Windows namespaces, respectively) that
displays a modal message box to the user. A modal window prevents the user
from interacting with other parts of the application until the message box is
closed. It's commonly used to display information, warnings, or errors, or to ask
simple questions to the user.
Here's a breakdown of its key aspects:
Show() Method:
The core of the MessageBox functionality lies in its overloaded Show() method.
Here are some common signatures and what they allow you to do:
* MessageBox.Show(string text):
* Displays a simple message box with the specified text and an "OK" button.
* The title bar of the message box will typically display the application's name
or a default value.
* MessageBox.Show(string text, string caption):
13
* Displays a message box with the specified text and sets the title bar to the
provided caption.
* It still defaults to an "OK" button.
* MessageBox.Show(string text, string caption, MessageBoxButtons buttons):
* This overload allows you to specify which buttons will appear in the message
box using the MessageBoxButtons enumeration. Common values include:
* MessageBoxButtons.OK: Displays an "OK" button.
* MessageBoxButtons.OKCancel: Displays "OK" and "Cancel" buttons.
* MessageBoxButtons.YesNo: Displays "Yes" and "No" buttons.
* MessageBoxButtons.YesNoCancel: Displays "Yes", "No", and "Cancel"
buttons.
* MessageBoxButtons.AbortRetryIgnore: Displays "Abort", "Retry", and
"Ignore" buttons.
* MessageBox.Show(string text, string caption, MessageBoxButtons buttons,
MessageBoxIcon icon):
* This overload adds an icon to the message box to visually indicate the type of
message using the MessageBoxIcon enumeration. Common values include:
* MessageBoxIcon.Error: Displays a critical error icon (usually a red circle with
a white 'x').
* MessageBoxIcon.Warning: Displays a warning icon (usually a yellow triangle
with an exclamation mark).
* MessageBoxIcon.Information: Displays an informational icon (usually a blue
'i' in a circle).
* MessageBoxIcon.Question: Displays a question mark icon.
* MessageBoxIcon.Asterisk or MessageBoxIcon.Information: Another style for
information.
* MessageBoxIcon.Exclamation or MessageBoxIcon.Warning: Another style
for warning.
* MessageBoxIcon.Hand or MessageBoxIcon.Stop or MessageBoxIcon.Error:
Other styles for error.
* MessageBox.Show(string text, string caption, MessageBoxButtons buttons,
MessageBoxIcon icon, MessageBoxDefaultButton defaultButton):
* This allows you to specify which button should be the default button (the one
that is automatically selected when the user presses the Enter key) using the
MessageBoxDefaultButton enumeration (e.g.,
MessageBoxDefaultButton.Button1, MessageBoxDefaultButton.Button2).
14
a) VB.Net program to accept a character from the user and check whether it
is a vowel or not.
Module Module1
Sub Main()
Console.WriteLine("Enter a character: ")
Dim inputChar As String = Console.ReadLine()
End Module
}
}
c) VB.Net program to accept the details of an Employee (Eno, Ename,
salary).
Module Module1
Sub Main()
Console.WriteLine("Enter Employee Details:")
End Module
{
Console.WriteLine("Invalid input. Please enter an integer.");
}
}
}
Sub Main()
Dim today As Date = Date.Today
Console.WriteLine($"Today's date is: {today.ToLongDateString()}") ' Display
in long date format
End Module
* If set to true, the text is displayed but cannot be modified by the user. This is
useful for displaying read-only information.
* If set to false (the default), the user can freely type and edit the text.
* Example (C#): textBox1.ReadOnly = true;
* Example (VB.NET): TextBox1.ReadOnly = True
* Multiline: This boolean property specifies whether the TextBox can display and
accept multiple lines of text.
* If set to true, the TextBox can grow vertically to accommodate multiple lines,
and scroll bars may appear if the text exceeds the visible area. The user can
enter new lines by pressing the Enter key.
* If set to false (the default), the TextBox is limited to a single line of text. The
Enter key typically moves focus to the next control.
* Example (C#): textBox1.Multiline = true;
* Example (VB.NET): TextBox1.Multiline = True
* PasswordChar: This property allows you to mask the characters entered in the
TextBox, typically used for password input.
* You can set this property to a specific character (e.g., an asterisk '*') which
will be displayed instead of the actual characters typed by the user. The
underlying Text property still holds the actual typed characters.
* If this property is left empty (or set to its default null or empty character), the
entered text is displayed normally.
* Example (C#): textBox1.PasswordChar = '*';
* Example (VB.NET): TextBox1.PasswordChar = "*"
These properties are fundamental for controlling the behavior and appearance of
the TextBox control in user interfaces.
* Designing the Menu Items: Once you have a ContextMenuStrip control, you
can add menu items to it. This is usually done in the Visual Studio designer. You
can:
* Drag and drop the ContextMenuStrip from the Toolbox onto your form.
* Select the ContextMenuStrip in the component tray and use its Items property
in the Properties window to add ToolStripMenuItem objects (which represent
individual menu items).
* For each ToolStripMenuItem, you can set properties like Text (the text
displayed in the menu), Image (an optional icon), ShortcutKeys (keyboard
shortcuts), and an event handler for its Click event (the code that runs when the
menu item is selected).
* You can also add separators (ToolStripSeparator) to visually group related
menu items and submenus (ToolStripMenuItem can contain other
ToolStripMenuItem objects).
* Associating the Menu with a Control: To make a pop-up menu appear when a
user right-clicks on a specific control (like a TextBox, ListBox, PictureBox, or
even the form itself), you need to associate the ContextMenuStrip with that
control's ContextMenuStrip property. You can do this in the Properties window of
the target control by selecting the desired ContextMenuStrip from the dropdown
list.
* Handling Menu Item Clicks: When the user selects an item from the pop-up
menu, the Click event of the corresponding ToolStripMenuItem is raised. You
need to write event handler code for these Click events to perform the desired
actions. This code will typically access the control that the menu was invoked on
(you can often use the SourceControl property of the EventArgs in the Click
event handler to determine which control was right-clicked).
a) Event-Driven Programming
Event-driven programming is a paradigm where the flow of the program is
determined by events – actions or occurrences that happen, such as user
interactions (mouse clicks, key presses), system messages, or signals from other
23
c) Method Overloading
Method overloading is a feature in object-oriented programming that allows a
class to have multiple methods with the same name but different parameter lists.
The parameter lists must differ in either the number of parameters, the data types
of the parameters, or the order of the data types of the parameters. The compiler
determines which overloaded method to call based on the arguments passed
during the method invocation. This provides a way to create more flexible and
intuitive APIs where a single method name can perform similar operations on
different types or numbers of input.
a) What are Control Structures? Discuss any two control structures. 4 mark
Control structures are statements in a programming language that determine the
order in which instructions are executed. They allow for decision-making and
repetition within a program, enabling it to perform complex tasks based on
conditions and data. Without control structures, programs would simply execute
sequentially, one instruction after another.
Here are two common control structures:
* If...Then...Else (Selection Structure): This control structure allows a program to
execute different blocks of code based on whether a specified condition is true or
false.
24
Console.WriteLine("Excellent!")
ElseIf grade = "B" Then
Console.WriteLine("Good job.")
ElseIf grade = "C" Then
Console.WriteLine("Average.")
Else
Console.WriteLine("Needs improvement.")
End If
* for (C#):
26
Both examples above will print the numbers 1 through 5 to the console. The
For loop initializes a counter variable i, checks if it's less than or equal to the
upper limit (5), executes the code block, and then increments i. This process
continues until the condition is no longer true.
Control structures are fundamental building blocks of any programming
language, enabling the creation of programs that can make decisions and
perform repetitive tasks, making them much more powerful and versatile.
* Networking (System.Net)
* XML processing (System.Xml)
* Security (System.Security)
* Web development (ASP.NET in System.Web)
* Windows Forms for GUI development (System.Windows.Forms)
* Windows Presentation Foundation (WPF) for modern UI
(System.Windows.Presentation)
* Data access (ADO.NET in System.Data)
* Language Integrated Query (LINQ in System.Linq)
* Common Language Specification (CLS): As mentioned earlier, the CLS is a set
of rules that define a subset of the Common Type System (CTS) that all .NET
languages are expected to support. Adhering to the CLS ensures seamless
interoperability between code written in different .NET languages (like C#,
VB.NET, and F#).
* Common Type System (CTS): The CTS defines how data types are declared
and used in the .NET Framework. It provides a unified type system that is shared
by all .NET languages, enabling them to work with each other's data types. The
CTS includes value types (like integers and booleans) and reference types (like
objects and strings).
* Language Compilers: The .NET Framework includes language-specific
compilers (e.g., C# compiler csc.exe, VB.NET compiler vbc.exe, F# compiler
fsc.exe). These compilers translate the source code written in a specific .NET
language into Intermediate Language (IL), which is then executed by the CLR.
public Dog(string name, string breed) : base(name, "Woof") // Calling the base
class constructor
{
Breed = breed;
}
public Cat(string name, string color) : base(name, "Meow") // Calling the base
class constructor
{
FurColor = color;
}
' Add a PictureBox control named PictureBox1 to your form and set its Image
property.
End Class
{
Console.Write("Enter the first number: ");
int num1 = int.Parse(Console.ReadLine());
c) Design a VB.net form to pick a date from Date Time Picker control and
display day, month, and year in separate text boxes.
Public Class Form1
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As
EventArgs) Handles DateTimePicker1.ValueChanged
TextBoxDay.Text = DateTimePicker1.Value.Day.ToString()
TextBoxMonth.Text = DateTimePicker1.Value.Month.ToString()
TextBoxYear.Text = DateTimePicker1.Value.Year.ToString()
End Sub
End Class
' Add a TextBox control named TextBox1, a Button control named Button1,
' and a Label control named LabelResult to your form. Set the Text property
' of Button1 to "Check Palindrome" and clear the Text property of LabelResult.
End Class
// Parameterized constructor
public Student(int rollNo, string name, int age)
36
{
RollNo = rollNo;
Name = name;
Age = age;
Console.WriteLine("Parameterized constructor called.");
}
' Reset the label position when it goes off-screen to the right
If Label1.Left > Me.Width Then
Label1.Left = -Label1.Width
39
End If
End Sub
' Add a Label control named Label1 to your form and set its Text property to
"Pune university".
' Add a Timer control named Timer1 to your form.
' Ensure Timer1's Enabled property is initially False (it will be started in code).
End Class
a) Event-Driven Programming
Event-driven programming is a paradigm where the flow of the program is
determined by events – actions or occurrences that happen, such as user
interactions (mouse clicks, key presses), system messages, or signals from other
parts of the program or the operating system. Instead of a linear, predefined
execution path, the program waits for events to occur and then executes specific
code blocks (event handlers) associated with those events. This makes
applications more interactive and responsive to user actions. Common in GUI
applications.
and interfaces are key tools for achieving abstraction by defining contracts
without providing full implementation.
* BeginInit: The server controls on the page are initialized. Control properties
are set to their default values or values from the previous view state and control
state.
* OnInit: This event is raised after all server controls have been initialized and
any skin settings have been applied. It's a good place to perform early
initialization tasks that need to occur before view state is loaded.
* Page Load:
* LoadViewState: If the page is being posted back (i.e., the user submitted a
form), the view state information from the previous request is loaded and applied
to the controls. View state allows controls to remember their values between
postbacks.
* LoadControlState: Similar to view state, control state is loaded. Control state
is used for critical control data that must be maintained even if view state is
disabled.
* OnLoad: This event is raised after view state and control state have been
loaded. It's a common place to perform tasks that depend on control values or
view state, such as querying a database based on user input from the previous
postback. The IsPostBack property is useful here to differentiate between the
initial page load and subsequent postbacks.
* Control Events: If the request is a postback resulting from a control event (e.g.,
a button click), the relevant event handlers for the control are executed at this
stage. These events occur after the Load event and before the PreRender event.
For example, if a user clicks a button, the Click event handler for that button will
be executed here.
* Page PreRender:
* OnPreRender: This event is raised after all control events have been handled
and just before the page's content is rendered. It's the last chance to make
changes to the page and its controls before the output is generated. You might
perform final data binding or update UI elements based on the processing done
in earlier stages.
* SaveStateComplete: Before rendering, the view state and control state for the
page and its controls are saved. This information will be sent to the client as
hidden fields in the HTML and will be used to restore the state during the next
postback.
.
42
languages. The Common Language Runtime (CLR) and the Common Type
System (CTS) provide a unified environment where languages like C#, VB.NET,
and F# can work together, share code, and inherit from each other's classes.
This allows developers to choose the language best suited for a particular task
without sacrificing interoperability.
* Simplified Development: The .NET Framework provides a rich set of class
libraries (FCL/BCL) that offer pre-built components for a wide range of tasks,
such as data access (ADO.NET), web development (ASP.NET), GUI
development (Windows Forms, WPF), networking, security, and more. This
significantly reduces the amount of code developers need to write from scratch,
leading to faster development cycles and increased productivity.
* Platform Independence (Initially Focused on Windows): While the original .NET
Framework was primarily targeted at the Windows operating system, it aimed to
provide a consistent development experience across different versions of
Windows. Modern .NET (.NET Core and later) has significantly expanded this
objective to include cross-platform compatibility with macOS and Linux.
* Robust and Secure Applications: The .NET Framework incorporates features
designed to enhance the reliability and security of applications. Automatic
memory management (garbage collection) helps prevent memory leaks.
Exception handling provides a structured way to deal with runtime errors. Code
access security and other security features help protect applications from
malicious code.
* Simplified Deployment: The .NET Framework aimed to simplify the deployment
of applications. Features like assembly management and the Common Language
Infrastructure (CLI) contribute to easier deployment and versioning of software
components. XCOPY deployment (simply copying files) is possible for
many .NET applications.
* Integration with Existing Systems: The .NET Framework provides mechanisms
for interoperating with existing COM (Component Object Model) components and
native Windows APIs. This allows developers to leverage legacy code and
platform-specific functionalities when necessary, facilitating the migration to and
coexistence with older technologies.
* Support for Modern Application Development: The .NET Framework has
evolved to support modern development paradigms, including web services,
cloud computing, mobile development (through Xamarin, now .NET MAUI), and
more. Technologies like ASP.NET Core are designed for building scalable and
high-performance web applications and APIs.
45
}
else
{
Console.WriteLine("Invalid input. Please enter valid numbers.");
}
}
}
Sub Main()
Console.WriteLine("Enter a number:")
Dim input As String = Console.ReadLine()
47
If IsNumeric(input) Then
Dim number As Integer = Integer.Parse(input)
If IsPalindrome(number) Then
Console.WriteLine($"{number} is a palindrome.")
Else
Console.WriteLine($"{number} is not a palindrome.")
End If
Else
Console.WriteLine("Invalid input. Please enter a valid number.")
End If
End Module
Sub Main()
Dim yesterday As Date = Date.Today.AddDays(-1)
48
End Module
Sub Main()
Dim studentID As Integer = 12345
Dim studentName As String = "Alice Smith"
Dim studentCourse As String = "Computer Science"
Dim studentFees As Decimal = 15000.75D ' The 'D' suffix indicates a
Decimal literal
Console.WriteLine("Student Details:")
Console.WriteLine($"Student ID: {studentID}")
Console.WriteLine($"Student Name: {studentName}")
Console.WriteLine($"Student Course: {studentCourse}")
Console.WriteLine($"Student Fees: ${studentFees}") ' Added a dollar sign
for currency representation
Console.ReadKey()
End Sub
End Module
* Text Input (<input type="text">): Creates a single-line text field where users
can enter alphanumeric data.
* Example: <input type="text" name="username" placeholder="Enter your
username">
* Password Input (<input type="password">): Similar to text input, but it masks
the entered characters (usually with asterisks or dots) for security purposes.
* Example: <input type="password" name="password" placeholder="Enter your
password">
* Radio Buttons (<input type="radio">): Allow users to select only one option
from a predefined set. Radio buttons within the same group share the same
name attribute.
* Example:
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
* Textarea (<textarea>): Creates a multi-line text input field, useful for entering
larger amounts of text.
* Example: <textarea name="message" rows="5" cols="30" placeholder="Enter
your message"></textarea>
* C#:
try
{
connection.Open();
Console.WriteLine("Connection to the database established successfully!");
// Proceed with database operations
}
catch (Exception ex)
{
Console.WriteLine($"Error connecting to the database: {ex.Message}");
}
52
* VB.NET:
Try
connection.Open()
Console.WriteLine("Connection to the database established successfully!")
' Proceed with database operations
Catch ex As Exception
Console.WriteLine($"Error connecting to the database: {ex.Message}")
End Try
Sub Main()
Console.WriteLine("Prime numbers between 2 and 20 are:")
For number As Integer = 2 To 20
If IsPrime(number) Then
Console.Write($"{number} ")
End If
Next
Console.WriteLine() ' To move to the next line after printing primes
54
Console.ReadKey()
End Sub
End Module
a) Inheritance:
Inheritance is a fundamental concept in Object-Oriented Programming (OOP)
where a new class (derived or child class) inherits properties and methods from
an existing class (base or parent class). This promotes code reusability, as the
derived class can use the members of the base class without rewriting them.
Inheritance establishes an "is-a" relationship (e.g., a "Dog" is-a "Animal").
Derived classes can also add new members or override inherited ones to
specialize their behavior.
55
website visitors. These controls are defined using various HTML elements,
primarily the <input> element with different type attributes, as well as other
elements like <textarea>, <select>, and <button>.
Key characteristics of HTML controls:
* User Interaction: They enable users to interact with the web page by entering
text, selecting options, uploading files, and triggering actions.
* Data Input: They are designed to gather different types of data from users,
such as text, numbers, dates, selections, and files.
* Form Submission: When placed within a <form> element, the data entered or
selected in these controls can be submitted to a server for processing.
* Attributes for Configuration: HTML controls have various attributes that control
their appearance, behavior, and validation rules (e.g., type, name, value, size,
maxlength, required).
* Client-Side Rendering: They are rendered by the user's web browser based on
the HTML markup.
* Event Handling: They can be associated with JavaScript event handlers to
implement client-side interactivity and validation.
Examples of common HTML controls include: text boxes (<input type="text">),
password fields (<input type="password">), radio buttons (<input type="radio">),
checkboxes (<input type="checkbox">), dropdown lists (<select>), multi-line text
areas (<textarea>), buttons (<button> or <input type="submit">, <input
type="reset">, <input type="button">), and file upload controls (<input
type="file">).
Sub Main()
Dim num1 As Integer
Dim num2 As Integer
61
End Module
Sub Main()
Dim inputString As String
Dim reversedString As String = ""
Console.WriteLine("Enter a string:")
inputString = Console.ReadLine()
' Check if the original cleaned string is equal to the reversed string
If cleanedString = reversedString Then
Console.WriteLine($"'{inputString}' is a palindrome.")
Else
Console.WriteLine($"'{inputString}' is not a palindrome.")
End If
Console.ReadKey()
End Sub
End Module
' You would need to add a Button (Button1) and a ListBox (ListBox1)
63
End Class
VB.NET or the += operator in C#. This is often used for more dynamic scenarios
or custom controls. For example (VB.NET):
' In the Page_Load event or another appropriate place
AddHandler MyButton.Click, AddressOf MyButton_Click
' If the text goes completely off the right side, reset it to the left
If startX > Me.Width Then
startX = -textWidth
End If
' You would need to add a Timer control (Timer1) to your Form in the
' VB.NET Windows Forms Designer. Make sure its 'Enabled' property is
' initially set to 'False'. You don't need to explicitly handle the Tick
' event in the designer if you use 'WithEvents' as shown above.
End Class
68
Console.ReadKey();
}
}
a) Method Overloading in C#
Method overloading is a feature in C# that allows you to define multiple methods
within the same class that have the same name but different parameter lists. The
parameter lists must differ in either the number of parameters, the data types of
the parameters, or the order of the data types of the parameters.
* Compiler Decision: The C# compiler determines which overloaded method to
call based on the number and types of the arguments passed in the method call.
* Benefits:
* Provides flexibility and convenience by allowing you to perform similar
operations with different input.
* Improves code readability by using the same descriptive name for related
functionalities.
* Reduces the need for creating many distinct method names for conceptually
similar actions.
Example:
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
70
* Type Inference: VB.NET can sometimes infer the data type of a variable based
on its initial value when you use Option Infer On and don't explicitly declare the
type.
* Type Conversion: You can convert data from one type to another using
functions like CInt, CDbl, CStr, CType, etc. Implicit conversions can occur when
there's no risk of data loss.
* Strong Typing: Helps catch type-related errors at compile time, leading to more
robust and reliable code.