Download as pdf or txt
Download as pdf or txt
You are on page 1of 207

Page |1

Visual Programming C#

Visual Programming C#
Introduction to c-sharp:
C# is a programming language of .Net Framework.
Our C# tutorial includes all topics of C# such as first example, control statements,
objects and classes, inheritance, constructor, destructor, this, static, sealed,
polymorphism, abstraction, abstract class, interface, namespace, encapsulation,
properties, indexer, arrays, strings, regex, exception handling, multithreading, File
IO, Collections etc.
What is C#:
C# is pronounced as "C-Sharp". It is an object-oriented programming language
provided by Microsoft that runs on .Net Framework.
By the help of C# programming language, we can develop different types of
secured and robust applications:
• Window applications
• Web applications
• Distributed applications
• Web service applications
• Database applications etc.
C# is approved as a standard by ECMA and ISO. C# is designed for CLI (Common
Language Infrastructure). CLI is a specification that describes executable code and
runtime environment.
C# programming language is influenced by C++, Java, Eiffel, Modula-3, Pascal etc.
languages.

.NET Framework:
.NET is a framework to develop software applications. It is designed and
developed by Microsoft and the first beta version released in 2000.
Page |2
Visual Programming C#

It is used to develop applications for web, Windows, phone. Moreover, it provides


a broad range of functionalities and support.
This framework contains a large number of class libraries known as Framework
Class Library (FCL). The software programs written in .NET are executed in the
execution environment, which is called CLR (Common Language Runtime). These
are the core and essential parts of the .NET framework.
This framework provides various services like memory management, networking,
security, memory management, and type-safety.
The .Net Framework supports more than 60 programming languages such as C#,
F#, VB.NET, J#, VC++, JScript.NET, APL, COBOL, Perl, Oberon, ML, Pascal, Eiffel,
Smalltalk, Python, Cobra, ADA, etc.
Following is the .NET framework Stack that shows the modules and components
of the Framework.
The .NET Framework is composed of four main components:
• Common Language Runtime (CLR)
• Framework Class Library (FCL),
• Core Languages (WinForms, ASP.NET, and ADO.NET), and
• Other Modules (WCF, WPF, WF, Card Space, LINQ, Entity Framework,
Parallel LINQ, Task Parallel Library, etc.)

CLR (Common Language Runtime):


It is a program execution engine that loads and executes the program. It converts
the program into native code. It acts as an interface between the framework and
operating system. It does exception handling, memory management, and garbage
collection. Moreover, it provides security, type-safety, interoperability, and
Page |3
Visual Programming C#

portability. A list of CLR components are given below:

FCL (Framework Class Library):


It is a standard library that is a collection of thousands of classes and used to build
an application. The BCL (Base Class Library) is the core of the FCL and provides
basic functionalities.
Page |4
Visual Programming C#

Win Forms:
Windows Forms is a smart client technology for the .NET Framework, a set of
managed libraries that simplify common application tasks such as reading and
writing to the file system.

ASP.NET:
ASP.NET is a web framework designed and developed by Microsoft. It is used to
develop websites, web applications, and web services. It provides a fantastic
integration of HTML, CSS, and JavaScript. It was first released in January 2002.

Advantages of visual programming language:

• Easy to convert ideas into reality for example you don’t know how to code so
you can start with VPL (Visual Programming Language). and then switch to
actual coding.
• Visuals are easy to grasp i.e. to develop something in visual programming
language requires less efforts.
• It includes a variety of built in objects that are required while creating
something using VPL.
• It is a beginner-friendly also anyone will be able to derive the logic without
worrying about writing lines of code.
• Adding a user-specific code is also available and simple as it allows to create
of blocks as per the convenience of the user.

Disadvantages of visual programming language:

• These languages require more memory as they use graphics, as a result, their
execution is also slow and a large amount of memory is occupied by them.
• They can only work in an operating system like windows, mac, or any other
operating system which supports graphics.
• As the inbuilt functions are not sufficient so you have to add your custom code
as a result it is cumbersome.
• Only limited functions are present in these languages.
• Adding our custom code as a block requires coding knowledge or else you
have to work with limited functions which are provided with the language.
Page |5
Visual Programming C#

• As a computer engineer, it is not a good idea to use VPL as most of the tech
giants like FAANG or other tech companies work on textual languages like
JAVA, HTML, etc, rather than VPL.
• For the long run VPL might not be that much useful as in a regular language
you can explore more in it but in VPL at one point you will get bored by using
the same it.
Difference between regular programming languages and visual programming
languages:
Sr.
No Regular Languages Visual Programming Language
It is a programming It is a programming language that uses
1.
language that only uses text. graphics or blocks in place of text.
It is not beginner-friendly
2. It is a beginner-friendly language
language
There are not that much customizable as
Customization and flexible
the blocks or graphics that contain the
3. applications can be created
codes are limited and after that, we need
using regular languages
to add our custom code as a block.
This is not fast and efficient as every
These are quite fast and
4. block has some code with it so it takes
efficient
time and also it has graphics with it.
The interface is not good i.e.
The interface is great as the user has to
only text and syntax of
5. just join the blocks and frame the logic
language we have to get
without writing the code
familiar with it.
requires time to learn as the
user has to get familiar with any school student will be able to grasp
6
the language syntax then the VPL and create the applications
code in it
Doesn’t require a lot of effort and also
Requires lot of efforts as a
the main targeted user of VPL is school
7. beginner to start with the
level students so that they can love the
language
coding
These are quite fast as
These are slow as compared to regular
8. compared to VPL as they
languages as it has graphics.
don’t have graphics.
This requires more memory as it has
These require less memory
9. graphics so to store them more memory
as compared to VPL
is used.
Page |6
Visual Programming C#

Examples: Javascript, C, Examples: M block, Blockly, Scratch


10.
C++, Java, Python Etc. Etc.

C# Features:
C# is object oriented programming language. It provides a lot of features that are
given below.
• Simple

• Modern programming language

• Object oriented

• Type safe

• Interoperability

• Scalable and Updateable

• Component oriented

• Structured programming language

• Rich Library

• Fast Speed
Page |7
Visual Programming C#

1) Simple:
C# is a simple language in the sense that it provides structured approach (to break
the problem into parts), rich set of library functions, data types etc .
2) Modern Programming Language:
C# programming is based upon the current trend and it is very powerful and simple
for building scalable, interoperable and robust applications.
3) Object Oriented:
C# is object oriented programming language. OOPs makes development and
maintenance easier where as in Procedure-oriented programming language it is not
easy to manage if code grows as project size grow.
4) Type Safe:
C# type safe code can only access the memory location that it has permission to
execute. Therefore, it improves a security of the program.
5) Interoperability:
Interoperability process enables the C# programs to do almost anything that a
native C++ application can do.
6) Scalable and Updateable:
C# is automatic scalable and updateable programming language. For updating our
applications, we delete the old files and update them with new ones.
7) Component Oriented:
C# is component-oriented programming language. It is the predominant software
development methodology used to develop more robust and highly scalable
applications.
8) Structured Programming Language:
C# is a structured programming language in the sense that we can break the
program into parts using functions. So, it is easy to understand and modify.
9) Rich Library:
C# provides a lot of inbuilt functions that makes the development fast.
Page |8
Visual Programming C#

10) Fast Speed:


The compilation and execution time of C# language is fast.

C# Example: Hello World


In C# programming language, a simple "hello world" program can be written by
multiple ways. Let's see the top 4 ways to create a simple C# example:
• Simple Example

• Using System

• Using public modifier

• Using namespace

C# Simple Example:
• class Program

• {

• static void Main(string[] args)

• {

• System.Console.WriteLine("Hello World!");

• }

• }

Output:
Hello World!

Description
class: is a keyword which is used to define class.
Program: is the class name. A class is a blueprint or template from which objects
are created. It can have data members and methods. Here, it has only Main method.

static: is a keyword which means object is not required to access static members.
So it saves memory.
Page |9
Visual Programming C#

void: is the return type of the method. It doesn’t return any value. In such case,
return statement is not required.
Main: is the method name. It is the entry point for any C# program. Whenever we
run the C# program, Main() method is invoked first before any other method. It
represents start up of the program.
string[] args: is used for command line arguments in C#. While running the C#
program, we can pass values. These values are known as arguments which we can
use in the program.
System.Console.WriteLine("Hello World!"): Here, System is the namespace.
Console is the class defined in System namespace. The WriteLine() is the static
method of Console class which is used to write the text on the console.
C# Example: Using System:
If we write using System before the class, it means we don't need to specify System
namespace for accessing any class of this namespace. Here, we are using Console
class without specifying System.Console.
• using System;
• class Program
• {
• static void Main(string[] args)
• {
• Console.WriteLine("Hello World!");
• }
• }
Output:
Hello World!
C# Example: Using public modifier:
We can also specify public modifier before class and Main() method. Now, it can
be accessed from outside the class also.
• using System;
• public class Program
• {
P a g e | 10
Visual Programming C#

• public static void Main(string[] args)


• {
• Console.WriteLine("Hello World!");
• }
• }
Output:
Hello World!
C# Example: Using namespace:
We can create classes inside the namespace. It is used to group related classes. It is
used to categorize classes so that it can be easy to maintain.
• using System;
• namespace ConsoleApplication1
• {
• public class Program
• {
• public static void Main(string[] args)
• {
• Console.WriteLine("Hello World!");
• }
• }
• }
Output:
Hello World!

Events in C#
Events are user actions such as key press, clicks, mouse movements, etc., or some
occurrence such as system generated notifications. Applications need to respond
to events when they occur. For example, interrupts. Events are used for inter-
process communication.
Using Delegates with Events:
P a g e | 11
Visual Programming C#

The events are declared and raised in a class and associated with the event
handlers using delegates within the same class or some other class. The class
containing the event is used to publish the event. This is called the publisher class.
Some other class that accepts this event is called the subscriber class. Events use
the publisher-subscriber model.
A publisher is an object that contains the definition of the event and the delegate.
The event-delegate association is also defined in this object. A publisher class
object invokes the event and it is notified to other objects.
A subscriber is an object that accepts the event and provides an event handler.
The delegate in the publisher class invokes the method (event handler) of the
subscriber class.
Declaring Events
To declare an event inside a class, first of all, you must declare a delegate type for
the even as:
public delegate string BoilerLogHandler(string str);
then, declare the event using the event keyword −
event BoilerLogHandler BoilerEventLog;
The preceding code defines a delegate named BoilerLogHandler and an event
named BoilerEventLog, which invokes the delegate when it is raised.
Example:
using System;

namespace SampleApp {
public delegate string MyDel(string str);

class EventProgram {
event MyDel MyEvent;

public EventProgram() {
this.MyEvent += new MyDel(this.WelcomeUser);
}
public string WelcomeUser(string username) {
P a g e | 12
Visual Programming C#

return "Welcome " + username;


}
static void Main(string[] args) {
EventProgram obj1 = new EventProgram();
string result = obj1.MyEvent("BSCS 5th");
Console.WriteLine(result);
}
}
}
When the above code is compiled and executed, it produces the following result

Welcome BSCS 5th

Event-Driven Programming:
Definition: Event-driven programming is a programming paradigm in which
program execution is determined by new user events (mouse clicks, keypresses),
sensor outputs, or message passing from other programs. Programmers use Event
driven programming in graphical user interfaces and other applications that focus
on performing user actions in response to user input (user clicks). We can also
define event-driven programming as a way of building a computer program, in
which, in the essential function of the program, the main event loop of the
application is explicitly highlighted in the code, the body of which consists of two
parts: fetching the event and event handling. In an event-driven application, the
main loop listens for events and triggers a callback function when one of those
events is detected. Event Handlers is a function that handles or responds to a
specific event. Event-driven programming uses this feature in software
development. As a reminder, we provide economics homework help - with our
experts, all numbers become easy to understand. So let's take a closer look at the
event handler.
P a g e | 13
Visual Programming C#

Important Properties of Button:

Description
Properties
BackColor Using BackColor property you can set the background
color of the button.
BackgroundColor Using BackgroundImage property you can set the
background image on the button
Autoellipsis Using AutoEllipsis property you can set a value which
shows that whether the ellipsis character (…) appears
at the right edge of the control which denotes that the
P a g e | 14
Visual Programming C#

button text extends beyond the specified length of the


button.
Autosize Using AutoSize property you can set a value which
shows whether the button resizes based on its
contents.
Enabled Using Enabled property you can set a value which
shows whether the button can respond to user
interaction.
Events Font Using Events property you can get the list of the event
handlers that are applied on the given button.
Using Font property you can set the font of the button.
Font Height Using FontHeight property you can set the height of
the font.
ForeColor Using ForeColor property you can set the foreground
color of the button.
Height Using Height property you can set the height of the
button.
Image Using Image property you can set the image on the
button
Margine Name Using Name property you can set the name of the
button
Padding Using Padding property you can set the padding within
the button
Visible Using Visible property you can set a value which shows
whether the button and all its child buttons are
displayed.

Important Events on Buttons:

Events Description
Click This event occurs when the button is clicked.
Double Click This event occurs when the user double clicked the
button.
Enter This event is occured when the control is entered.
P a g e | 15
Visual Programming C#

KeyPress This event is occured when the character, or space, or


backspace key is pressed while the control has focus.
Leave This event occurs when the input focus leave the
control.
MouseClick This event occur when you click the mouse poiter on
the button.
MouseDoubleClick This event occur when you double click the mouse
pointer on the button.
MouseHover This event occur when the mouse printer placed on
the button.
MouseLeave This events occurs when the mouse pointer leaves the
button.
Mouse Up This event occurs when the mouse is over the control
and mouse button released.
Mouse Move This event occurs when the mouse moves over
controls.
Mouse Wheel When mouse wheel moves and the control has
focused.
Mouse Down When mouse button is pressed.

Program example:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp8 {
P a g e | 16
Visual Programming C#

public partial class Form1 : Form {

public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Creating and setting the properties of label

Label l = new Label();


l.AutoSize = true;
l.Text = "Do you want to submit this project?";
l.Location = new Point(222, 145);
l.Font = new Font("French Script MT", 18);

// Adding this label to form

this.Controls.Add(l);
// Creating and setting the properties of Button

Button Mybutton = new Button();


Mybutton.Location = new Point(225, 198);
Mybutton.Text = "Submit";
P a g e | 17
Visual Programming C#

Mybutton.AutoSize = true;
Mybutton.BackColor = Color.LightBlue;
Mybutton.Padding = new Padding(6);
Mybutton.Font = new Font("French Script MT", 18);

// Adding this button to form

this.Controls.Add(Mybutton);

// Creating and setting the properties of Button

Button Mybutton1 = new Button();


Mybutton1.Location = new Point(360, 198);
Mybutton1.Text = "Cancel";
Mybutton1.AutoSize = true;
Mybutton1.BackColor = Color.LightPink;
Mybutton1.Padding = new Padding(6);
Mybutton1.Font = new Font("French Script MT", 18);
// Adding this button to form

this.Controls.Add(Mybutton1);
}
}
}
P a g e | 18
Visual Programming C#

Complete Code For Click Event:


The complete code is listed in the following code, where CreateDynamicButton
methods creates a Button control to a Form at run-time, attaches a click event
handler of the button and adds Button control to the Form by calling
Form.Controls.Add() method.
/// This method creates a Button control at runtime
1. private void CreateDynamicButton()
2. {
3. // Create a Button object
4. Button dynamicButton = new Button();
5.
6. // Set Button properties
7. dynamicButton.Height = 40;
8. dynamicButton.Width = 300;
9. dynamicButton.BackColor = Color.Red;
10. dynamicButton.ForeColor = Color.Blue;
11. dynamicButton.Location = new Point(20, 150);
12. dynamicButton.Text = "I am Dynamic Button";
13. dynamicButton.Name = "DynamicButton";
14. dynamicButton.Font = new Font("Georgia", 16);
15.
16. // Add a Button Click Event handler
17. dynamicButton.Click += new EventHandler(DynamicButton_Click);
18.
19. // Add Button to the Form. Placement of the Button
20. // will be based on the Location and Size of button
P a g e | 19
Visual Programming C#

21. Controls.Add(dynamicButton);
22. }
23. /// <summary>
24. /// Button click event handler
25. /// </summary>
26.
27. /// <param name="sender"></param>
28. /// <param name="e"></param>
29.
30. private void DynamicButton_Click(object sender, EventArgs e)
31. {
32. MessageBox.Show("Dynamic button is clicked");
33. }
You need to make sure to call CreateDynamicButton() method on the Form's
constructor just after InitializeComponent() method, listed as following.

1. public Form1()
2. {
3. InitializeComponent();
4. CreateDynamicButton();
5. }

Drawing Graphics in C Sharp:


GDI+ consists of the set of .NET base classes that are available to control custom
drawing on the screen. These classes arrange for the appropriate instructions to be
sent to the graphics device drivers to ensure the correct output is placed on the
P a g e | 20
Visual Programming C#

screen. GDI provides a level of abstraction, hiding the differences between


different video cards. You simply call on the Windows API function to do the
specific task, and internally the GDI figures out how to get the client's particular
video card to do whatever it is you want
when they run your particular piece of code. Not only this, but the client has
several display devices - for example - monitors and printers - GDI achieves the
task of making the printer look the same onscreen as far as the application is
concerned. If the client wants to print something instead of displaying
it, your application will simply inform the system that the output device is the
printer and then call the same API functions in exactly the same way. As you can
see, the devicecontext (DC) object is a very powerful mechanism. Having said that,
we can also use this layer of abstraction to draw onto a Windows Form. This paper
will therefore begin with an example of a basic Windows Forms development in
order to demonstrate how to draw graphics onto a Windows Form, or a control on
that form. The focus of this article will be on graphics.
Creating a Graphics Object:
The first step in this tutorial is to create a new Visual Studio project called
CSharpGraphics. With the new project created select the Form in the design area
,click on the lightning bolt at the top of the Properties panel to list the events
available for the Form. Double click the Paint event to display the code editing
page.
Graphics Objects are created by calling the CreateGraphics() method of the
component on which the drawing is to performed. For example, a Graphics Object
can be created on our Form called Form1 by calling CreateGraphics() method as
follows in the Paint() method:
private void Form1_Paint(object sender, PaintEventArgs e)
{
System.Drawing.Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
}
Creating a Pen In C#:
P a g e | 21
Visual Programming C#

A Graphics Object is of little use without a Pen object with which to draw (much
as a sheet of paper is no good without a pen or pencil). A Pen object may be quite
easily created as follows:
Pen variable_name = new Pen (color, width);
where variable_name is the name to be assigned to the Pen object, color is the
color of the pen and width is the width of the lines to be drawn by the pen.
For example, we can create red pen that is 5 pixels wide as follows:
private void Form1_Paint(object sender, PaintEventArgs
e)
{
System.Drawing.Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Red, 5);
}
Once a Pen object has been created other properties may be changed. For
example, the DashStyle property can be modified to change the style of line (i.e
Dash, DashDot, DashDotDot, Dot, Solid or Custom). Properties such as the color
and width may similarly be changed after a Pen has been created:
myPen.DashStyle =System.Drawing.Drawing2D.DashStyle.DashDotDot;
myPen.Color = System.Drawing.Color.RoyalBlue;
myPen.Width = 3;
Now that we have a Paint() event handler, a Graphics Object and Pen we can now
begin to draw.
Drawing Lines in C#:
Lines are drawn in C# using the DrawLine() method of the Graphics Object. This
P a g e | 22
Visual Programming C#

method takes a pre-instantiated Pen object and two sets of x and y co-ordinates
(thestart and end points of the line) as arguments. For example, to draw a line from
coordinates (20, 20) to (200, 210) on our sample form:
private void Form1_Paint(object sender, PaintEventArgs
e)
{
System.Drawing.Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Red, 5);
graphicsObj.DrawLine(myPen, 20, 20, 200, 210);
}
The above code, when compiled and executed will result in the form appearing as
follows:

Drawing Squares and Rectangles in C#:


For the purposes of drawing rectangles and squares in C# the GraphicsObject
provides the DrawRectangle() method. There are two ways to use the
DrawRectangle() method. One is to pass through a Rectangle object and Pen
and the other is to create an instance of a Rectangle object and pass that through
P a g e | 23
Visual Programming C#

along with the Pen. We will begin by looking at drawing a rectangle without a
precreated Rectangle object. The syntax for this is:
graphicsobj.DrawRectangle(pen, x, y, width, height);
The alternative is to pass through a Rectangle object in place of the co-ordinates
and dimensions. The syntax for creating a Rectangle object in C# is as follows:
Rectangle rectangleObj = new Rectangle (x, y, width, height);
Once a Rectangle object has been instantiated the syntax to call DrawRectangle()
is
as follows:
graphicsobj.DrawRectangle(pen, x, y, rectangleobj);
The following example creates a Rectangle which is then used as an argument
to DrawRectangle():
private void Form1_Paint(object sender, PaintEventArgs
e)
{
System.Drawing.Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Red, 5);
Rectangle myRectangle = new Rectangle(20, 20, 250, 200);
graphicsObj.DrawRectangle(myPen, myRectangle);
}
When an application containing the above code is compiled and executed the
following graphics will appear in the form:
P a g e | 24
Visual Programming C#

If multiple rectangles of different shapes need to be drawn it is not necessary to


create a new Rectangle object for each call to the DrawRectangle(); method.
Instead the shape of an existing Rectangle object may be altered by calling
the Inflate() method of the Rectangle class. This method accepts two arguments,
the amount by which the width is to be changed and the amount by which the
height is to be changed. If a dimension is to be left unchanged 0 should be passed
through as the change value.
To reduce a dimension pass through the negative amount by which the dimension
is to be changed:
Rectangle myRectangle = new Rectangle(20, 20, 250, 200);
myRectangle.Inflate(10, -20); Increase width by 10.
Reduce height by20
Drawing Ellipses and Circles in C#:
Ellipses and circles are drawn in C# using the DrawEllipse() method of the
GraphicsObject class. The size of the shape to be drawn is defined by specifying a
rectangle into which the shape must fit. As with the DrawRectangle() method,
there are two ways to use the DrawEllipse() method. One is to pass through
P a g e | 25
Visual Programming C#

a Rectangle object and Pen and the other is to create an instance of a Rectangle
object and pass that through along with the Pen.
To draw an ellipse without first creating a Rectangle object use the following
syntax:
graphicsobj.DrawEllipse(pen, x, y, width, height);
The alternative is to pass through a Rectangle object in place of the co-ordinates
and dimensions. The syntax for creating a Rectangle object in C# is as follows:
Rectangle rectangleObj = new Rectangle (x, y, width, height);
Once a Rectangle object has been instantiated the syntax to call DrawRectangle()
is as follows:
graphicsobj.DrawEllipse(pen, x, y, rectangleobj);
The following example creates a Rectangle which is then used as an argument
to DrawEllipse():
private void Form1_Paint(object sender, PaintEventArgs
e)
{
System.Drawing.Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Green,5);
Rectangle myRectangle = new Rectangle(20, 20, 250,200);
graphicsObj.DrawEllipse(myPen, myRectangle);
}
When compiled and executed the above code creates the following graphics
outputon the form:
P a g e | 26
Visual Programming C#

Drawing Text with C#:


Text is drawn onto a Graphics Object using the DrawText() method. The syntax for
this method is as follows:
graphicsobj.DrawString(string, font, brush, x, y);
The string argument specifies the text to be drawn. Font defines the font to be used
to display the text and requires the creation of a Font object. The brush object is
similar to the Pen object used to draw shapes with the exception that it specifies a
fill pattern. Finally, the x and y values specify the top left hand corner of the text.
In order to create a Font object a font size, font family and font style may be
specified. For example to create a Helvetica, 40 point Italic font:
Font myFont = new System.Drawing.Font("Helvetica", 40,
FontStyle.Italic);
A brush object is created by specifying by calling the appropriate constructor for
the brush type and specifying a color:
Brush myBrush = newSolidBrush(System.Drawing.Color.Red);
Having created the necessary objects we can incorporate these into our example C#
application to draw some text:
private void Form1_Paint(object sender, PaintEventArgs
e)
P a g e | 27
Visual Programming C#

{
System.Drawing.Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
Font myFont = new System.Drawing.Font("Helvetica",40, FontStyle.Italic);
Brush myBrush = new SolidBrush(System.Drawing.Color.Red);
graphicsObj.DrawString("Hello C#", myFont,myBrush, 30, 30);
}

C# Interface:
Interface in C# is a blueprint of a class. It is like abstract class because all the
methods which are declared inside the interface are abstract methods. It cannot
have method body and cannot be instantiated.It is used to achieve multiple
inheritance which can't be achieved by class. It is used to achieve fully abstraction
because it cannot have method body.Its implementation must be provided by class
or struct. The class or struct which implements the interface, must provide the
implementation of all the methods declared inside the interface.

C# interface example:
Let's see the example of interface in C# which has draw() method. Its
implementation is provided by two classes: Rectangle and Circle.

using System;
P a g e | 28
Visual Programming C#

public interface Drawable

void draw();

public class Rectangle : Drawable

public void draw()

Console.WriteLine("drawing rectangle...");

public class Circle : Drawable

public void draw()

Console.WriteLine("drawing circle...");

public class TestInterface

public static void Main()

Drawable d;
P a g e | 29
Visual Programming C#

d = new Rectangle();

d.draw();

d = new Circle();

d.draw();

Output:

drawing ractangle...

drawing circle...

C# Graphical User Interface:


Windows Forms is a Graphical User Interface(GUI) class library which is bundled
in .Net Framework. Its main purpose is to provide an easier interface to develop
the applications for desktop, tablet, PCs. It is also termed as the WinForms. The
applications which are developed by using Windows Forms or WinForms are
known as the Windows Forms Applications that runs on the desktop computer.
WinForms can be used only to develop the Windows Forms Applications not web
applications. WinForms applications can contain the different type of controls like
labels, list boxes, tooltip etc.

Creating a Windows Forms Application Using Visual Studio 2022

First, open the Visual Studio then Go to File -> New -> Project to create a new
project and then select the language as Visual C# from the left menu. Click on
Windows Forms App(.NET Framework) in the middle of current window. After
that give the project name and Click OK.
P a g e | 30
Visual Programming C#

Here the solution is like a container which contains the projects and files that may
be required by the program.
After that following window will display which will be divided into three parts as
follows:
1.Editor Window or Main Window: Here, you will work with forms and code
editing. You can notice the layout of form which is now blank. You will double
click the form then it will open the code for that.
2.Solution Explorer Window: It is used to navigate between all items in solution.
For example, if you will select a file form this window then particular information
will be display in the property window.
3.Properties Window: This window is used to change the different properties of
the selected item in the Solution Explorer. Also, you can change the properties of
components or controls that you will add to the forms.
Now to add the controls to your WinForms application go to Toolbox tab
P a g e | 31
Visual Programming C#

present in the extreme left side of Visual Studio. Here, you can see a list of
controls. To access the most commonly used controls go to Common Controls
present in Toolbox tab.

• Now drag and drop the controls that you needed on created Form. For
example, if you can add TextBox, ListBox, Button etc. as shown below. By
clicking on the particular dropped control you can see and change its
properties present in the right most corner of Visual Studio.
P a g e | 32
Visual Programming C#

In the above image, you can see the TextBox is selected and its properties like
TextAlign, MaxLength etc. are opened in right most corner. You can change its
properties’ values as per the application need. The code of controls will be
automatically added in the background. You can check the Form1.Designer.cs file
present in the Solution Explorer Window.
• To run the program you can use an F5 key or Play button present in the
toolbar of Visual Studio. To stop the program you can use pause button
present in the ToolBar. You can also run the program by going to Debug-
>Start Debugging menu in the menubar.
P a g e | 33
Visual Programming C#

C# Windows Forms is a graphical user interface (GUI) framework that enables


developers to create desktop applications for the Windows operating system.
Windows Forms applications are created using the C# programming language and
the .NET framework. They are built by dragging and dropping controls such as
buttons, text boxes, labels, and other user interface elements onto a form.

1.The Windows Forms framework provides a rich set of controls that developers
can use to build applications with. These controls are designed to provide a
consistent and familiar user interface for Windows users. Developers can
customize the appearance and behavior of these controls by setting various
properties and handling events.

2.To create a Windows Forms application in C#, you can use Microsoft Visual
Studio, which is an integrated development environment (IDE) that provides a
visual designer to create and layout the user interface elements. The visual designer
is a drag-and-drop interface for building your UI, and you can easily configure
each control’s properties through a user-friendly interface.

3.In addition to the visual designer, Visual Studio also provides a code editor that
enables developers to write the C# code for the application’s logic. Developers can
handle events and perform tasks such as data validation, data manipulation, and
P a g e | 34
Visual Programming C#

business logic implementation.

4.Windows Forms applications are versatile and can be used to create various types
of applications such as data entry, management, and reporting applications, as well
as games and multimedia applications.

Overall, Windows Forms applications provide an easy-to-use and familiar


graphical user interface for Windows users, making it an ideal choice for building
desktop applications that require a high degree of interactivity and user
engagement.

Graphic device interface:


The graphical device interface(GDI) is the legacy component of microsoft
windows which is responsible for representing graphical objects and transmitting
them to output devices such as monitor and printer.

Window applications uses windows API to interact with GDI, for such tasks as
drawing lines and curves rendering fonts and handling palletes.

Usage:

Simple games that does not requires fast graphics rendering may use GDI.Modern
games usually use DirectX,vulkan(3D games,3D graphics) or OpenGL(open
graphics library).

GDI+: Evolution of GDI which represents in System.Drawing.dll(dynamic link


library).with better changes.

• Improved colors.

• Improved scalability.

• GDI+ draw lines ,rectangles, other shapes on coordinate system.


P a g e | 35
Visual Programming C#

Graphic class used in GDI+:

Pen class: to draw lines and curves.

C# code:

Pen mypen= new pen(color.red,21);

mygraphics.Drawline(mypen,4,2,12,6);

mygraphics.DrawRectangle(mypen,100,50,80,40);

Message Handling in C#:


Software applications user interact with windows application through the main
enternal devices like keyboard and mouse. In MFC(microsoft foundation class
library introduced by microsoft in1992) hardware events from these devices seen
as "windows messgae". An MFC application program respond to these windows
messages are called message handling.

Visual interfaces are user interfaces that make extensive use of graphical objects
(icons,diagram,form). The graphical user interface is a interface that allow user to
interact with technology via the use of graphical icons rather than complex code.
P a g e | 36
Visual Programming C#

MessageBoxes:

To deal with messages we use message boxes to display some message.

To Display Message box style Name

Ok
Ok only

Ok Cancel Ok Cancel

Abort Retry Ignore AbortRetryIgnore

Cancel
No
Yes YesNoCancel

Icons of Message Box:


To display Message Box Style
Information.

Exclaimation.

Critical.

Question.
C# code to use these styles:
{
P a g e | 37
Visual Programming C#

If(messagebox.show(“Hello World”, “My Form1”, messageBoxButton.yesNo,


messageBoxicon.Exclaimation)==DialogResult.yes)
{
//code to execute if yes is selected
MessageBox.show(“You clicked yes”);
}
Else
//code to execute if no is selected
MessageBox.show(“You clicked no”);
}
NETWORK PROGRAMMING:
Network programming is the act of using computer code to write programs or processes that
can communicate with other programs or processes across a network. Programmers use
various programming languages, code libraries, and protocols to do the work.

What is infrastructure as code (IaC)?


IaC is a method to define and provision network infrastructure by using definition files
that contain code. It's necessary for automating networks and making them
programmable.

IaC is enabled through application programming interfaces (APIs). It makes the tasks of
unifying separate processes and automating infrastructure provisioning simpler, faster,
and more reliable.

What is network programmability?


Networking programmability generally refers to tools and best practices for deploying,
managing, and troubleshooting network devices.

More precisely, network programmability is the process of using code, concepts based
on the software development lifecycle, and other tools to make networks perform
actions.

How is a network "programmable"?


A modern network is more than just routers and switches. It's a collection of
interconnected systems that include applications and other software, virtual machines,
cloud instances, containers, and more.
P a g e | 38
Visual Programming C#

A programmable network has APIs in its infrastructure that developers can use to
program applications and other components to interact directly with the network.

What are some network programmability use cases?


Network programmability, combined with task automation, helps businesses deploy new
apps and services faster, even at the network edge. Services also can be orchestrated
centrally instead of provisioned separately.

Another use case for network programmability is mitigating security threats. Using APIs,
a network can be programmed to block malware or other malicious traffic without
disrupting users as network security engineers diagnose and remediate the issue.

Do programmable networks demand new skills?


Yes—or at least an expansion of core skill sets for network programming. It's becoming
increasingly important for network engineers to become familiar with network
programmability basics.

The programmable network is taking center stage in today's application-centric


organizations, which are embracing software-defined networking, 5G connectivity,
Internet of Things (IoT) applications, and more.
IT professionals who want to advance their network programming skills and
programmability knowledge can earn certifications, attend education programs, or
engage in other learning opportunities.

Key network-programming skills and knowledge


Main types of networks to program
Network programming is a rapidly evolving discipline. However, engineers programming
networks still need traditional skills and other knowledge. That knowledge includes
understanding the main types of networks that many of today's businesses use, such as the
following:

LAN (local-area network)


A LAN is a collection of devices connected in one location, such as a building, an office, or a
home. A LAN can be small or large, ranging from a home network with one user to an
enterprise network with thousands of users and devices.

MAN (metropolitan-area network)


A MAN is a network that may serve a town, city, university campus, or a small geographic
region. A MAN is typically larger than a LAN.

WAN (wide-area network)


In its simplest form, a WAN is a collection of LANs or other networks that communicate
with one another. A WAN is essentially a network of networks. The internet is the world's
largest WAN.
P a g e | 39
Visual Programming C#

WLAN (wireless LAN)


A WLAN implements a flexible data communication system, frequently augmenting rather
than replacing a wired LAN within a building or campus. WLANs use radio frequency to
transmit and receive data over the air, reducing the need for wired connections.

VPN (virtual private network)


A VPN is an encrypted internet connection between a user device and a network. The
encrypted connection helps to ensure that sensitive data is transmitted safely. It prevents
unauthorized people from accessing the traffic.

VPN technology is widely used in corporate environments, often to support remote


workers and hybrid work models.
SAN (storage-area network)
A SAN is a dedicated high-speed network that makes storage devices accessible to servers
by attaching storage directly to an operating system. It centralizes storage devices, so they
are easier to manage and communicate faster over media.

C# Socket Programming:
Introduction:
C# is a powerful and popular programming language that has been used to develop
a wide variety of applications. One of its main strengths is its ability to perform Socket
programming, which enables developers to create applications that can communicate
with other devices or applications over a Network. In this article, we will dive deep
into the basics of C# Socket programming and how it can be used to create
Networked applications.

What are Sockets?


If two programs are running on the same Network and if they share a two-
way Communication Link, then their endpoint will be denoted by Socket. A
Socket is characterized by its IP Address, Port Number, and Protocol. It is used to
set up the connection, send and receive the information and close the
connection.

Types of Sockets:
There are generally two types of Sockets: one is Stream Sockets and the second
one is Datagram Sockets. Stream Sockets are connection-oriented and provide
reliable, two-way Communication between devices. They make sure the order
of data should be the same as it was sent. Datagram Sockets are connectionless
and provide an unreliable, one-way Communication between devices. They do
not make sure that the order of received data is the same as the order of sent.
P a g e | 40
Visual Programming C#

What is Socket Programming?


Socket programming is a technique used to establish Communication between
two applications over a Network. It involves creating a Socket, which is
essentially a software endpoint that can send and receive data over the
Network. The two applications communicate by sending data through their
respective Sockets, which are connected via a Network.

C# Socket Programming Basics:


Before diving into the specifics of C# Socket Programming, it's important to
understand some basic concepts of Socket programming in general. A Socket
is a type of software endpoint that symbolizes one end of a two-way
Communication channel between two Network-based programs. A Socket is
defined by an IP Address and a Port Number, and these two values uniquely
identify the Socket.

In C#, the Socket class provides a way to create and manipulate Sockets. The
Socket class is part of the System.Net.Sockets namespace, and it provides a set
of methods and properties that enable you to create, configure, connect, send,
and receive data over a Network.

To use Sockets in C#, you must first import the System.Net.Sockets namespace.
The Socket class is used to create and manipulate Sockets

The following code represents how to create a new Socket in C#:

1. Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, P

rotocolType.Tcp);

The AddressFamily parameter specifies the addressing scheme used by the


Socket. The type of the Socket is represented by the SocketType parameter.
The ProtocolType parameter describes the protocol used by the Socket.

Connect() method is taken into consideration for setup the connection between
two devices. The following code shows how to connect to a remote device
using C# Socket Programming:

2. IPAddress ipAddress = IPAddress.Parse("192.168.1.1");

3. IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, 80);


P a g e | 41
Visual Programming C#

4. socket.Connect(remoteEndPoint);
The IPAddress parameter specifies the IP Address of the remote device. The IPEndPoint parameter
specifies the endpoint of the remote device.

To send data over a Socket, the Send() method is used. The following code shows how to send data over
a Socket using C# Socket Programming:

5. byte[] data = Encoding.ASCII.GetBytes("Hello World");

6. socket.Send(data);

The byte[] parameter specifies the data to be sent.


The Encoding.ASCII.GetBytes() method is used to convert the string "Hello World"
to a byte array.

To receive data over a Socket, the Receive() method is used. The following code
shows how to receive data over a socket using C# Socket Programming:

7. byte[] data = new byte[1024];

8. int receivedBytes = socket.Receive(data);

9. string receivedData = Encoding.ASCII.GetString(data,0,recievedBytes);


The byte[] parameter specifies the buffer that receives the data. The int parameter specifies the
maximum number of bytes to receive. The Encoding.ASCII.GetString() method is used to convert the
byte array to a string.

To close a connection, the Close() method is used. The following code shows how to close a connection
using C# Socket Programming:

10. socket.Close();
C# Socket Programming Example
C# Code:

1. // Server code

2. Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Str

eam, ProtocolType.Tcp);

3. serverSocket.Bind(new IPEndPoint(IPAddress.Any, 1234));

4. serverSocket.Listen(10);

5. Socket clientSocket = serverSocket.Accept();


P a g e | 42
Visual Programming C#

6. byte[] data = new byte[1024];

7. int receivedBytes = clientSocket.Receive(data);

8. string receivedMessage = Encoding.ASCII.GetString(data, 0, receivedBytes);

9. Console.WriteLine("Received message: " + receivedMessage);

10. clientSocket.Send(Encoding.ASCII.GetBytes("Hello from server!"));

11. clientSocket.Close();

12. serverSocket.Close();

13.

14. // Client code

15. Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Str

eam, ProtocolType.Tcp);

16. clientSocket.Connect(new IPEndPoint(IPAddress.Loopback, 1234));

17. clientSocket.Send(Encoding.ASCII.GetBytes("Hello from client!"));

18. byte[] data = new byte[1024];

19. int receivedBytes = clientSocket.Receive(data);

20. string receivedMessage = Encoding.ASCII.GetString(data, 0, receivedBytes);

21. Console.WriteLine("Received message: " + receivedMessage);

22. clientSocket.Close();

23. In this example, the server listens for incoming connections on


port 1234, and the client connects to the server on the loopback address
(localhost) and port 1234. Once the connection is established, the client
sends information to the server, and the server responds with a
message. Finally, both the client and server close their Sockets.
24. Creating class libraries in visual C#:
A class library file is a collection of classes and namespaces in C# without any entry point method
like Main. Once we create a class library file it can be used in the C# project and classes inside it can be
P a g e | 43
Visual Programming C#
used as required. Class Library makes it convenient to use functionalities by importing DLL inside the
program rather than redefining everything. So, Let’s make our own class library in C#.

Terminologies

Class Library: It is a package or file that contains different namespaces and class definitions that are
used by other programs.

Create and use a class library


Step 1

Start Microsoft Visual Studio

Step 2

On the Menu Bar, click File -> New Project.

Step 3

In the left list, click Windows under Visual C#.

Step 4

In the right list, click ClassLibrary

Step 5

Change the Name to SampleLibrary and click OK

Step 6
Click Ok.
P a g e | 44
Visual Programming C#

When you click OK, C# will create a Namespace with the Name you've just used,
and you'll be looking at the code window.

Step 7

Change the class name to say "Algebra" and create any methods of your wish under
Algebra template file opened.

using System;
using System.Collections.Generic;
using System.Text;
namespace SampleLibrary
{
public class Algebra
{
public double Addition(double x, double y)
{
return x + y;
}
public double Subtraction(double x, double y)
{
return x - y;
}
public double Multiplication(double x, double y)
{
P a g e | 45
Visual Programming C#

return x * y;
}
public double Division(double x, double y)
{
return x / y;
}
}
}

Step 8

Build the Library: Since you would be creating a library and not an executable, to
compile the project:

25. On the main menu, you can click Build -> Build ProjectName

26. In the Solution Explorer, you can right-click the name of the project and click
Build

27. In the Class View, you can right-click the name of the project and click Build

Step 9

Create an ASP.NET WebApplication Project : After building the project, you can use
it. You can use it in the same project where the library was built or you can use it in
another project. If you are working in Microsoft Visual Studio, you can start by
creating a new project. To use the library, you would have to reference the library.
To do this:
P a g e | 46
Visual Programming C#

On the Menu bar, you would click Project -> Add Reference or In the Solution
Explorer, you would right-click References and click Add Reference.

You can click the Browse tab, locate the folder where the library resides and select
it.

Step 10

Call the Library class methods in your application : After selecting the library, you
can click OK. You can then use the classes and methods of the library like you
would use those of the .NET Framework. Here is an example:
P a g e | 47
Visual Programming C#

using System;
using SampleLibrary;
public class Exercise
{
static void Main()
{
Algebra alg = new Algebra();
double number1 = 100;
double number2 = 50;
double result = alg.Addition(number1, number2);
Console.Write(number1);
Console.Write(" + ");
Console.Write(number2);
Console.Write(" = ");
Console.WriteLine(result);
}
}
Step 11

Build and run the project.

What is a DLL:

A dynamic link library (DLL) is a collection of small programs that larger programs can load
when needed to complete specific tasks. The small program, called a DLL file, contains
instructions that help the larger program handle what may not be a core function of the original
program.

An example of those tasks might be communicating with a specific device, such as a printer or
scanner to process a document. DLL files that support specific device operations are known as
device drivers. DLL contains bits of code and data, like classes and variables, or other resources
such as images that the larger program can use. In addition to being a generic term for dynamic
link libraries, Dynamic Link Library is also the name of Microsoft's version of the shared library
concept for Windows. A shared library can exist in any operating system (OS).

How does a dynamic link library work? Computer programs are rarely written in a one file. They
often are composed of multiple files that are linked together. When a program is run, it must be
compiled from its source code, which is human readable code that the programmer writes. It's
turned into an executable file, which is binary code, or machine code, that the computer can read.
The computer goes through several intermediate steps for this to occur. During those steps,
multiple files are linked to one. There are two types of linking -- static and dynamic -- and two
types of corresponding link libraries:
P a g e | 48
Visual Programming C#

Object code contains placeholder symbols that tell the operating system which
libraries to link to at runtime to create the final executable file.
Static links: These are linked earlier in the process and are embedded into the
executable. Static libraries are linked to the executable when the program is
compiled. Dynamic libraries are linked later, either at runtime or at load time.
Static libraries are not shared between programs because they are written into
the individual executable.
Dynamic links: DLLs contain the files that a program links to. The libraries already
are stored on the computer, external to the program that the user writes. They are
called dynamic because they are not embedded in the executable -- they just link
to it when needed. An import library, which is a type of static library, replaces all
placeholder symbols with actual links to the necessary DLL data in the main
program at load time, pulling those functions from the DLL library. Programs
provide the name of the library, and the OS creates a path to the link library.
Different programs have their own language-specific calling conventions for linking
to DLLs. Because dynamic libraries are not written into the executable, the same
shared library can be used by more than one program at the same time. They can
also be modified without changing the entire program that is using it.
P a g e | 49
Visual Programming C#

More than one application can access a dynamic library at once, because they are
not embedded with the executable at compile time. Static libraries are embedded
into programs, which lead to duplicates among the multiple programs using them.
A dynamically linked program has a small virtual memory.
In the Windows operating systems, dynamic files have a ".dll" file extension, and
static files have a ".lib" extension. DLL files may also have ".ocx" (ActiveX), ".cpl"
(Control Panel) or ".drv" (driver) suffixes, depending on the DLL function.
Programs do not always need dynamic libraries. In some cases, static linking is
preferable. However, some programs specify DLLs that are needed to run and will
return an error message if they cannot be accessed.

C# Thread Synchronization:
Synchronization is a technique that allows only one thread to access the resource for the
particular time. No other thread can interrupt until the assigned thread finishes its task. In
multithreading program, threads are allowed to access any resource for the required execution
time. Threads share resources and executes asynchronously. Accessing shared resources (data)
is critical task that sometimes may halt the system. We deal with it by making threads
synchronized. It is mainly used in case of transactions like deposit, withdraw etc.

Advantage of Thread Synchronization.


o Consistency Maintain
o No Thread Interference
P a g e | 50
Visual Programming C#

C# Lock :
We can use C# lock keyword to execute program synchronously. It is used to get lock for the
current thread, execute the task and then release the lock. It ensures that other thread does not
interrupt the execution until the execution finish.
SQL CREATE TABLE Here; we are creating two examples that executes asynchronously and
synchronously. C# Example:
Without Synchronization:

In this example, we are not using lock. This example executes asynchronously. In other words,
there is context-switching between the threads.
1. using System;
2. using System.Threading;

3. class Printer
4. {
5. public void PrintTable()
6. {
7. for (int i = 1; i <= 10; i++)

8. {
9. Thread.Sleep(100);
10. Console.WriteLine(i);
11. }

12. }
13. }
14. class Program
15. {

16. public static void Main(string[] args)


17. {
18. Printer p = new Printer();
19. Thread t1 = new Thread(new ThreadStart(p.PrintTable));
P a g e | 51
Visual Programming C#

20. Thread t2 = new Thread(new ThreadStart(p.PrintTable));


21. t1.Start();
22. t2.Start();

23. }
24. }

Output:

1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
10
10
C# Thread Synchronization Example

In this example, we are using lock. This example executes synchronously. In other words,
there is no context-switching between the threads. In the output section, we can see that
second thread starts working after first threads finishes its tasks.

1. using System;
2. using System.Threading;
3. class Printer
4. {
5. public void PrintTable()
6. {
7. lock (this)
8. {
9. for (int i = 1; i <= 10; i++)
P a g e | 52
Visual Programming C#

10. {
11. Thread.Sleep(100);
12. Console.WriteLine(i);
13. }
14. }
15. }
16. }
17. class Program
18. {
19. public static void Main(string[] args)
20. {
21. Printer p = new Printer();
22. Thread t1 = new Thread(new ThreadStart(p.PrintTable));
23. Thread t2 = new Thread(new ThreadStart(p.PrintTable));
24. t1.Start();
25. t2.Start();
26. }
27. }

Output:

1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
P a g e | 53
Visual Programming C#

VP.NET Controls:
Visual basic controls are the columns that aid in creating GUI Based
Applications in VB.Net quickly as well as easily. These are things that you can
drag to the Type using the Control tool kit in the IDE. Each VB.NET Control has
some buildings, events, and techniques that can be made use of to modify
and customize the form to our liking.

– Properties explain the things


– Methods are used to make the item do something
– Events explain what takes place when the user/Object takes any action.

When you have actually added Visual basic controls to the kind, you can
transform its appearance, its text, its default values, setting, size, etc. utilizing
its buildings. The homes can be transformed by means of the Pre events pane
or by including the certain values of residential or commercial properties into
the code editor.

Visual Programming controls:

• Text Box
• Label
• Button
• ListBox
• Combo Box
• Radio Button
• Checkbox
• Checklistbox
• PictureBox
• ScrollBar
• Date Time Picker
• Progress Bar
• TreeView
• ListView

VB.NET TextBox Control:

A TextBox control is used to display, accept the text from the user as an input, or a single
line of text on a VB.NET Windows form at runtime. Furthermore, we can add multiple text
P a g e | 54
Visual Programming C#

and scroll bars in textbox control. However, we can set the text on the textbox that displays
on the form.

Let's create a TextBox control in the VB.NET Windows form by using the following steps:

Step 1: We have to drag the TextBox control from the Toolbox and drop it on the
Windows form, as shown below.

Step 2: Once the TextBox is added to the form, we can set various properties of the
TextBox by clicking on the TextBox control.

VB.NET TextBox Properties:

There are following properties of the TextBox control.


P a g e | 55
Visual Programming C#

Properties Description

AutoCompleteMode It is used to get or set a value that indicates how the automatic completion works for the
textbox control.
P a g e | 56
Visual Programming C#

Font It is used to set the font style of the text displayed on a Windows form.

Lines It is used to set the number of lines in a TextBox control.

CharacterCasing It is used to get or set a value representing whether the TextBox control can modify the
character's case as they typed.

Multiline It is used to enter more than one line in a TextBox control, by changing the Multiline
property value from False to True.

AcceptsReturn It is used to get or set a value that indicates whether pressing the enter button in a
multiline textbox; it creates a new line of text in control.

PasswordChar It is used to set the password character that can be a mask in a single line of a TextBox
control.

PreferredHeight It is used to set the preferred height of the textbox control in the window form.

ScrollBars It is used to display a scrollbar on a multiline textbox by setting a value for a Textbox
control.

Text It is used to get or set the text associated with the textbox control.

Visible The Visible property sets a value that indicates whether the textbox should be displayed
on a Windows Form.

WordWrap The WordWrap properties validate whether the multiline Textbox control automatically
wraps words to the beginning of the next line when necessary.

VB.NET TextBox Events:


Events Description

Click When a textbox is clicked, a click event is called in the textbox control.
P a g e | 57
Visual Programming C#

CausesValidationChanged It occurs in the TextBox Control when the value of CauseValidation property is
changed.

AcceptTabsChanged It is found in the TextBox control when the property value of the AcceptTab is
changed.

BackColorChanged It is found in the TextBox Control when the property value of the BackColor is
changed.

BorderStyleChanged It is found in the TextBox Control when the value of the BorderStyle is changed.

ControlAdded It is found when the new control is added to the Control.ControlCollection.

CursorChanged It is found in TextBox, when the textbox control is removed from the
Control.ControlCollection.

FontChanged It occurs when the property of the Font is changed.

GetFocus It is found in TextBox control to get the focus.

MouseClick A MouseClick event occurs when the mouse clicks the control.

MultilineChanged It is found in a textbox control when the value of multiline changes.

Furthermore, we can also refer to the VB.NET Microsoft documentation to get a complete
list of TextBox properties and events.

VB.NET Label Control:


In VB.NET, a label control is used to display descriptive text for the form in control. It does
not participate in user input or keyboard or mouse events. Also, we cannot rename labels
at runtime. The labels are defined in the class System.Windows.Forms namespace.
P a g e | 58
Visual Programming C#

Let's create a label in the VB.NET Windows by using the following steps:

Step 1: We have to drag the Label control from the Toolbox and drop it on the Windows
form, as shown below.

Step 2: Once the Label is added to the form, we can set various properties to the Label
by clicking on the Label control.

VB.NET Label Properties:


Description Properties

As the name defines, an AutoSize property of label control is used to set or get a value if it is AutoSize
automatically resized to display all its contents.

It is used to set the style of the border in the Windows form. Border Style

It is used to set or get the preferred width for the Label control. PreferredWidth

It is used to get or set the font of the text displayed on a Windows form. Font

It is used to set the height for the Label Control. PreferredHeight


P a g e | 59
Visual Programming C#

It is used to set the alignment of text such as centre, bottom, top, left, or right. TextAlign

It is used to set the color of the text. ForeColor

It is used to set the name of a label in the Windows Form. Text

It is used to get or sets the shortcut menu associated with the Label control. ContextMenu

It is used to get the default size of the Label control. DefaultSize

It is used to set the image to a label in Windows Form. Image

It is used to set the index value to a label control displayed on the Windows form. ImageIndex

VB.NET Label Events:


Description Events

An AutoSizeChanged event occurs in the Label control when the value of AutoSize AutoSizeChanged
property is changed.

Click event is occurring in the Label Control to perform a click. Click

When a user performs a double-clicked in the Label control, the DoubleClick event occurs. DoubleClick

It occurs when the Label Control receives focus on the Window Form. GotFocus

The Leave event is found when the input focus leaves the Label Control. Leave

It occurs when the value of Tabindex property is changed in the Label control. TabIndexChanged

When the control is removed from the Control.ControlCollection, a ControlRemoved event, ControlRemoved
occurs.

It occurs when the property of TabStop is changed in the Label Control. TabStopChanged
P a g e | 60
Visual Programming C#

A BackColorChanged event occurs in the Label control when the value of the BackColor BackColorChanged
property is changed.

When a new control is added to the Control.ControlCollection, a ControlAdded event ControlAdded


occurs.

A DragDrop event occurs in the Label control when a drag and drop operation is DragDrop
completed.

Furthermore, we can also refer to the VB.NET Microsoft documentation to get a complete
list of Label properties and events.

VB.NET Button Control:


Button control is used to perform a click event in Windows Forms, and it can be clicked
by a mouse or by pressing Enter keys. It is used to submit all queries of the form by clicking
the submit button or transfer control to the next form. However, we can set the buttons
on the form by using drag and drop operation.

Let's create a Button in VB.NET Windows form by using the following steps:

Step 1: We have to drag the Button control from the Toolbox and drop it on the Windows
form, as shown below.
P a g e | 61
Visual Programming C#

Step 2: Once the button is added to the form, we can set various properties of the
Button by clicking on the Button control.

VB.NET Button Properties:


Description Properties

It is used to get or set the auto mode value through which the button can automatically AutoSizeMode
resize in the Windows form.

It is used to set the background color of the Button in the Windows form. BackColor

It is used to set the background image of the button control. BackgroundImage

It is used to set or get the foreground color of the button control. ForeColor

It is used to set or gets the image on the button control that is displayed. Image

It is used to set the upper-left of the button control's coordinates relative to the upper-left Location
corner in the windows form.

It is used to set the name of the button control in the windows form. Text

It is used to set or get a value representing whether the button control can accept data that AllowDrop
can be dragged by the user on the form.

It is used to set or get the tab order of the button control within the form. TabIndex

VB.NET Button Events:


A BackColorChaged event is found in button control when the Background BackColorChanged
property is changed.

A BackgoundImageChanged event is found in button control when the value of BackgroundImageChanged


the BackgoundImage property is changed.
P a g e | 62
Visual Programming C#

A Click event is found in the button control when the control is clicked. Click

It is found in button control when the value of the ContextMenu property is ContextManuChanged
changed.

A ControlAdded event is found in button control when a new control is added ControlAdded
to the Control.ControlCollection.

A CursorChanged event is found in button control when the value of the control CursorChanged
is changed.

When the user makes a double click on the button, a double click event is found DoubleClick
in the button control.

It is found in the button control when the value of the text property is changed. TextChanged

The DragDrop event is found in the button control when the drag and drop DragDrop
operation is completed in the Form.

Furthermore, we can also refer to the VB.NET Microsoft documentation to get a complete
list of Button properties and events.

VB.NET ListBox Control:


The ListBox control is used to display a list of items in Windows form. It allows the user to
select one or more items from the ListBox Control. Furthermore, we can add or design the
list box by using the properties and events window at runtime.

Let's create a ListBox control in the VB.NET Windows by using the following steps.

Step 1: Drag the ListBox control from the Toolbox and drop it to the Windows form, as
shown below.
P a g e | 63
Visual Programming C#

Step 2: Once the ListBox is added to the Form, we can set various properties of the
Listbox by clicking on the ListBox control.

ListBox Properties:
There are following properties of the ListBox control.

Description Properties
Name

It takes a value that defines whether the list box allows the user to select the item from the AllowSelection
list.

It obtains a value that determines whether the Listbox control can be selected. CanSelect

It is used to get or set the width of the columns in a multicolumn Listbox. ColumnWidth

As the name defines, a container gets the IContainer that stores the component of ListBox Container
control.

It is used to get the collection of controls contained within the control. Controls

It takes a value that determines whether the control is created or not. Created
P a g e | 64
Visual Programming C#

It is used to set the width of the ListBox control. Width

It takes a value that determines whether the ListBox control and all its child are displayed Visible
on the Windows Form.

It is used to get or set the method that determines which items are selected in the ListBox. SelectionMode

It allows multiple columns of the item to be displayed by setting the True value in the MultiColumn
Listbox.

ListBox Methods:
Description Method Name

The Add() method is used to add items to an item collection. Add()

It is used to remove an item from an item collection. However, we can remove items using Remove
the item name.

It is used to remove all items from the item collection at the same time. Clear

It is used to check whether the particular item exists in the ListBox or not. Contains

It is used to display the control to the user. Show()

As the name suggests, a Sort() method is used to arrange or sort the elements in the ListBox. Sort()

A ResetText() method is used to reset ListBox's text property and set the default value. ResetText()

It is used to reset the backColor property of the ListBox and set the default value. ResetBackColor()

It is used to notify the message of the ListBox to Windows. OnNotifyMessage

The GetSelected method is used to validate whether the specified item is selected. GetSelected
P a g e | 65
Visual Programming C#

Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list
of ListBox properties, and methods.

Example:

VB.NET ComboBox Control:


The ComboBox control is used to display more than one item in a drop-down list. It is a
combination of Listbox and Textbox in which the user can input only one item.
Furthermore, it also allows a user to select an item from a drop-down list.

Let's create a ComboBox control in the VB.NET Windows by using the following steps.

Step 1: We need to drag the combo box control from the toolbox and drop it to
the Windows form, as shown below.
P a g e | 66
Visual Programming C#

Step 2: Once the ComboBox is added to the form, we can set various properties of the
ComboBox by clicking on the ComboBox control.

ComboBox Properties:
There are following properties of the ComboBox control.
P a g e | 67
Visual Programming C#

Description Property

The AllowSelection property takes the value that indicates whether the list allows AllowSelection
selecting the list item.
P a g e | 68
Visual Programming C#

It takes a value that represents how automatic completion work for the ComboBox. AutoCompleteMode

It takes a value that determines whether the control is created or not. Created

It is used to bind the data with a ComboBox Control. DataBinding

The BackColor property is used to set the background color of the combo box control. BackColor

It is used to get or set the data source for a ComboBox Control. DataSource

It is used to set the style or appearance for the ComboBox Control. FlatStyle

The MaxDropDownItems property is used in the combo box control to display the MaxDropDownItems
maximum number of items by setting a value.

It is used by the user to enter maximum characters in the editable area of the combo MaxLength
box.

It is used to set or get the selected item in the ComboBox Control. SelectedItem

The Sorted property is used to sort all the items in the ComboBox by setting the value. Sorted

ComboBox Events:
Description Events

It occurs when the property of the font value is changed. FontChanged

When the data is bound with a combo box control, a format event is called. Format

It occurs when the property value of SelectIndexChanged is changed. SelectIndexChanged

When the user requests for help in control, the HelpRequested event is called. HelpRequested

It occurs when the user leaves the focus on the ComboBox Control. Leave
P a g e | 69
Visual Programming C#

It occurs when the property of margin is changed in the ComboBox control. MarginChanged
P a g e | 70
Visual Programming C#

RadioButton Control:
The RadioButton is used to select one option from the number of choices. If we want to
select only one item from a related or group of items in the windows forms, we can use
the radio button. The RadioButton is mutually exclusive that represents only one item is
active and the remains unchecked in the form.

Let's create a RadioButton control in the VB.NET Windows by using the following steps.

Step 1: Drag the RadioButton control from the toolbox and drop it to
the Windows form, as shown below.

Step 2: Once the RadioButton is added to the form, we can set various properties of the
RadioButton by clicking on the Radio control.

RadioButton Properties:
There are following properties of the VB.NET RadioButton control.

Description Property
P a g e | 71
Visual Programming C#

It is used to set or get a value representing whether the RadioButton allows the user to drag AllowDrop
on the form.

It is used to get or set a value that represents the appearance of the RadioButton. Appearance

It is used to get or set the radio control in ScrollControlIntoView(Control). AutoScrollOffset

The AutoCheck property is used to check whether the checked value or appearance of control AutoCheck
can be automatically changed when the user clicked on the RadioButton control.

The AutoSize property is used to check whether the radio control can be automatically resized AutoSize
by setting a value in the RadioButton control.

A CanSelect property is used to validate whether a radio control can be selected by setting a CanSelect
value in the RadioButton control.

It is used to obtain or set a value that indicates the location of the check portion in the CheckAlign
radioButton control.

The Text property is used to set the name of the RadioButton control. Text

RadioButton Methods:
Description Method Name

The Contains() method is used to check if the defined control is available in the Contains(Control)
RadioButton control.

It is used to send the specified message to the Window procedure. DefWndProc(Message)

It is used to destroy the handle associated with the RadioButton Control. DestroHandle()

The Focus() method is used to set the input focus to the window form's RadioButton Focus()
control.
P a g e | 72
Visual Programming C#

It is used to return a value that represents how the control will operate when the GetAutoSizeMode()
AutoSize property is enabled in the RadioButton control of the Window form.

As the name suggests, a ResetText() method is used to reset the property of text to its ResetText()
default value or empty.

It is used to reroute an invalid field, which causes control in the client region. Update()

We can also refer to Microsoft documentation to get a complete list of RadioButton


Control properties and methods in the VB .NET.

Example:

VB.NET CheckedListBox Control:


The CheckedListBox is similar to Listbox except that it displays all items in the list with a
checkbox that allows users to check or uncheck single or multiple items.

Let's create a CheckedListBox control in the VB.NET Windows form using the following
steps.
P a g e | 73
Visual Programming C#

Step 1: Drag the CheckedListBox control from the Toolbox and drop it to
the Windows form, as shown below.

Step 2: Once the CheckedListBox is added to the Form, we can set various properties of
the CheckedListbox by clicking on the CheckedListBox control.

CheckedListBox Properties:
There are following properties of the CheckedListBox control.

Description Properties

It obtains a value that determines whether the AccessibilityObject is assigned to the AccessibilityObject
CheckedListBox control.

It gets or sets a value that tells if the accessible client application has used the name of AccessibleName
the checkedlistbox control.

It gets a value that indicates whether the ListBox allows for the item to be selected from AllowSelection
the list.

It gets or sets a value representing whether the CheckedListBox control is scrolled in AllowScollOffset
ScrollControlIntoView(Control).
P a g e | 74
Visual Programming C#

It is used to set the type of border around the CheckedListBox by getting or setting a value. BorderStyle

It is used to store a collection of checked items in the CheckedListBox. CheckedItems

It is used to set or get a value that indicates if the vertical scroll bar appears in Windows ScrollAlwaysVisible
Forms at all times.

It is used to get all selected items from CheckedListBox. SelectedItems

It is used to get or set a value representing the items' selection mode in the SelectionMode
CheckedListBox.

It is used to set the first visible item at the top of the index in the CheckedListBox. TopIndex

CheckedListBox Methods:
Description Methods

It is used to unselect all the selected items in the CheckedListBox. ClearSelected()

It is used to create new accessibility of the object in the CheckedListBox Control. CreateAccessibilityInstance()

It is used to create a new instance for the collected item in the list box. CreateItemCollection()

It is used to destroy the handle associated with CheckedListBox. DestroyHandle()

It is used to validate whether the specified object is equal to the current object Equals(Object)
in the CheckedListBox or not.

It is used to obtain the form in which CheckedListBox has control. FindForm()

It is used to get the text of the specified item in the CheckedListBox. GetItemText(Object)

It is used to get the current item type in the CheckedListBox. GetType()


P a g e | 75
Visual Programming C#

A Show() method is used to display the CheckedListBox Control to the user. Show()

A Sort() method is used to sort or organize all the items available in Sort()
CheckedListBox.

Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list
of CheckedListBox properties and methods.

Example:
P a g e | 76
Visual Programming C#

VB.NET PictureBox Control:


PictureBox control is used to display the images on Windows Form. The PictureBox
control has an image property that allows the user to set the image at runtime or design
time.

Let's create a PictureBox control in the VB.NET Windows form using the following steps.

Step 1: We have to find the PictureBox control from the toolbox and then drag and drop
the PictureBox control onto the window form, as shown below.
P a g e | 77
Visual Programming C#

Step 2: Once the PictureBox is added to the form, we can set various properties of the
image by clicking on the PictureBox control.

Properties of the PictureBox:


There are following properties of the VB.NET PictureBox control.

Description Property

It is used to set the background color for the PictureBox in the window form. BackColor

It is used to set the background image of a window form by setting or getting value in the BackgroundImage
picture box.

The ErrorImage property is used to display an image if an error occurs while loading an ErrorImage
image on a window form.

The initial image is used to display an image on the PictureBox when the main image is InitialImage
loaded onto a window form by setting a value in the PictureBox control.

It represents whether the particular image is synchronized or not in the PictureBox control. WaitOnLoad

It is used to set text for the picture box controls in the window form. Text

The image property is used to display the image on the PictureBox of a Windows form. Image

It is used to set the border style for the picture box in the windows form. BorderStyle

It is used to set or get the path or URL of the image displayed on the picture box of the ImageLocation
window form.

It obtains a value that determines whether the picture box control is mirrored. IsMirrored
P a g e | 78
Visual Programming C#

Methods of the PictureBox Control:


Description Method

The CancelAsync method is used to cancel an asynchronous image load in a PictureBox CancelAysnc()
control.

It is used to create handles for the picture box controls in window form. CreateHandle()

It is used to destroy all the handles that are associated with the picture box control. DestroyHandle()

The GetStyle() method is used to get values for the specified bit style in the PictureBox GetStyle()
control.

The Load() method is used to load the specified image from the control using the Load()
ImageLocation property.

It is used to asynchronous load the image at the specified position of the picture box LoadAsync(String)
control.

Events of the PictureBox Control:


There are some Events of the VB.NET PictureBox control.

Description Events

It occurs when the property of the backcolor is changed in the PictureBox BackColorChanged
control.

It occurs when the property value of the BackgroundImage is changed in BackgroundImageLayoutChanged


the PictureBox control.

It occurs when the property of the ContextMenu is changed in the ContextMenuChanged


PictureBox control.

The resize event occurs when the picture box control is changed. Resize
P a g e | 79
Visual Programming C#

Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list
of PictureBox control properties, methods, and events in the VB.NET.

Example:
P a g e | 80
Visual Programming C#

VB.NET ScrollBars Control:


A ScrollBar control is used to create and display vertical and horizontal scroll bars on the
Windows form. It is used when we have large information in a form, and we are unable to
see all the data. Therefore, we used VB.NET ScrollBar control. Generally, ScrollBar is of two
types: HScrollBar for displaying scroll bars and VScrollBar for displaying Vertical Scroll
bars.

Let's create a ScrollBar control in the VB.NET Windows form using the following steps.

Step 1: The first step is to drag the HScrollBar and VScrollBar control from the toolbox
and drop it on to the form.

Step 2: Once the ScrollBar is added to the form, we can set various properties of the
ScrollBar by clicking on the HScrollBar and VScrollBar control.

Properties of the ScrollBar Control:


There are following properties of the VB.NET ScrollBar control.
P a g e | 81
Visual Programming C#

Description Property

The BackColor property is used to set the back color of the scroll bar. BackColor

It is used to set or get the maximum value of the Scroll Bar control. By default, it is 100. Maximum

It is used to get or set the minimum value of the Scroll bar control. By default, it is 0. Minimum

It is used to obtain or set a value that will be added or subtracted from the property of the SmallChange
scroll bar control when the scroll bar is moved a short distance.

As the name suggests, the AutoSize property is used to get or set a value representing AutoSize
whether the scroll bar can be resized automatically or not with its contents.

It is used to obtain or set a value that will be added or subtracted from the property of the LargeChange
scroll bar control when the scroll bar is moved a large distance.

It is used to obtain or set a value in a scroll bar control that indicates a scroll box's current Value
position.

It is used to get the default input method Editor (IME) that are supported by ScrollBar DefaultImeMode
controls in the Windows Form.

Methods of the ScrollBar Control:


Description Method

It is used to update the ScrollBar control using the Minimum, maximum, and UpdateScrollInfo
the value of LargeChange properties.

It is used to raise the Scroll event in the ScrollBar Control. OnScroll(ScrollEventArgs)

It is used to raise the EnabledChanged event in the ScrollBar control. OnEnabledChanged

It is used to activate or start the ScrollBar control. Select


P a g e | 82
Visual Programming C#

It is used to raise the ValueChanged event in the ScrollBar control. OnValueChanged(EventArgs)

Events of the ScrollBar Control:


Description Event

The AutoSizeChanged event is found in the ScrollBar control when the value of the AutoSizeChanged
AutoSize property changes.

The Scroll event is found when the Scroll control is moved. Scroll

It occurs in the ScrollBar control when the value of the text property changes. TextChangedEvent

A ValueChanged event occurs when the property of the value is changed programmatically ValueChanged
or by a scroll event in the Scrollbar Control.

Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list
of ScrollBar control properties, methods, and events in the VB.NET.

VB.NET DateTimePicker Control:


The DateTimePicker control allows the user to select or display date and time values with
a specified format in Windows Forms. Furthermore, we can determine the current date
and time using the Value property of the DateTimePicker control. By default, the Value
property returns the current date and time in the DateTimePicker.

Let's create a DateTimePicker control in the VB.NET Windows form using the following
steps.

Step 1: The first step is to drag the DateTimePicker control from the toolbox and drop it
on to the form.
P a g e | 83
Visual Programming C#

Step 2: Once the DateTimePicker is added to the form, we can set various properties of
the DateTimePicker by clicking on the DateTimePicker control.

Properties of the DateTimePicker Control:


There are some properties of the VB.NET DateTimePicker control.

Description Property

It is used to set the background image for the DateTimePicker control. BackgroundImage

It is used to set the font style for the calendar in the DateTimePicker control. CalendarFont

The CustomFormat property is used to set the custom date and time format string in the CustomFormat
DateTimePicker control.

It is used to obtain the collection of controls that are stored within the DateTimePicker Controls
control.

A checked property is used to check whether the value property is checked with a valid Checked
date and time in the DateTimePicker control.
P a g e | 84
Visual Programming C#

The Format property of the DateTimePicker is used to set the format for the Date and time Format
displayed in the Windows Form.

The MaxDate property of the DateTimePicker is used to set the max data and time in MaxDate
control selected by the user.

The Name property of the DateTimePicker control allows the user to set the name of the Name
control.

It is used to set the minimum date value that can be allowed by control. MinimumDateTime

Methods of the DateTimePicker Control:


There are some Methods of the VB.NET DateTimePicker control.

Description Method

It is used to validate whether the specified control is a child of the DateTimePicker control Contains(Control)
or not.

It is used to force the creation of visible control to handle the creation and any visible CreateControl()
child controls.

The GetAutoSizeMode() method is used to check the behavior of the DateTimePicker GetAutoSizeMode()
control when the AutoAize property is enabled.

It is used to reset the back color of the DateTimePicker control. ResetBackColor()

The Select() method is used to start or activate the DateTimePicker control. Select()

The Show() method is used to display the control to the user. Show()

The ToString() method is used to return a string that represents the current ToString()
DateTimePicker control.
P a g e | 85
Visual Programming C#

Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list
of DateTimePicker control properties, and methods in the VB.NET.

Examples:
P a g e | 86
Visual Programming C#

VB.NET ProgressBar Control:


The Window ProgressBar control is used by the user to acknowledge the progress status
of some defined tasks, such as downloading a large file from the web, copying files,
installing software, calculating complex results, and more.

Let's create a ProgressBar by dragging a ProgressBar control from the toolbox and
dropping it to the Windows form.

Step 1: The first step is to drag the ProgressBar control from the toolbox and drop it on
to the Form.
P a g e | 87
Visual Programming C#

Step 2: Once the ProgressBar is added to the Form, we can set various properties of the
ProgressBar by clicking on the ProgressBar control.

Properties of the ProgressBar Control:


There are following properties of the VB.NET ProgressBar control.

Description Property

The BackgroundImage property is used to set the background image in the BackgroundImage
progressbar control.

It is used to determine the progress status for a progress bar in milliseconds. MarqueeAnimationSpeed

The padding property is used to create a space between the edges of the progress Padding
bar by setting the value in the progressbar control.

It is used to get or set a value in control that calls the PerformStep method to Step
increase the current state of the progress bar by adding a defined step.

It is used to set the maximum length of the progress bar control in the windows Maximum
form.

It is used to set or get the minimum value of the progress bar control in the windows Minimum
form.

It obtains a value representing whether the progress bar control enables the user AllowDrop
to be dragged onto the form.

It is used to set a value that represents how types the progress bar should be Style
displayed on the Windows Form.
P a g e | 88
Visual Programming C#

Methods of the ProgressBar Control


Description Event

The ForeColor method is used to reset the forecolor to its default value. ForeColor

The ToString method is used to display the progress bar control by returning the string. ToString

It is used to increase the current state of the progress bar control by defining the specified time. Increment

The PerformStep method is used to increase the progress bar by setting the step specified in the PerformStep
ProgressBar property.

Events of the ProgressBar Control:


Description Events

The Leave event occurs when the focus leaves the progress bar control. Leave

A MouseClick event occurred when the user clicked on the progress bar control MouseClick
by the mouse.

When the background property changes to the progress bar control, the BackgroundImageChanged
BackgroundImageChanged event changes.

It occurs when the property of the text is changed in the progress bar control. TextChanged

It occurs when the padding property is changed in the progress bar control. PaddingChanged

Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list
of ProgressBar control properties, methods, and events in the VB.NET.
P a g e | 89
Visual Programming C#

VB.NET TreeView Control:


The TreeView control is used to display a hierarchical representation of the same data in
a tree structure. The top-level in the tree view is the root node with one or more child
nodes. In addition, the root node can be contracted or expanded by clicking on the plus
sign (+) button. It is also useful to provide the full path of the root node to the child node.

Let's create a TreeView control in the VB.NET Windows form using the following steps.
P a g e | 90
Visual Programming C#

Step : We have to find the TreeView control from the toolbox and then drag and drop
the TreeView control onto the window form, as shown below.

Properties of the TreeView Control:


There are following properties of the TreeView control.

Description Properties

The nodes property of the tree view control is used to gather all the nodes used in the tree. Nodes

It is used to obtain or set the tree node that is selected in the tree view control. SelectedNode

It gets or sets a value that represents whether you want to draw lines between the tree nodes ShowRootLines
connected with the root of the tree view.

The Path Separator property of the Tree View Control is used to set a delimiter string between Path Separator
the tree node paths.

It is used to get or set a value representing whether you want to display the plus (+) or minus ShowPlusMinus
sign button next to tree nodes containing the child nodes.
P a g e | 91
Visual Programming C#

It takes a value representing whether you want to draw lines between the tree nodes of the ShowLines
tree view control.

It is used to get or set full visible tree nodes on top of other nodes in the tree view control. TopNode

It is used to obtain the fully visible tree node in the tree view control. VisibleCount

The ItemHeight property is used to set the height of each tree node in control. ItemHeight

The Scrollable property is used in the tree-view to display the scroll bar by setting the value Scrollable
in control.

Methods of the TreeView Control:


Description Method

A GetNodeAt() method is used to get a node at the specified location of the tree view control. GetNodeAt

A Sort method is used to sort the tree nodes that are available in the tree view control. Sort()

As the name suggests, an ExpandAll method is used to expand all the tree nodes. ExpandAll()

It is used to count the number of nodes that are available in the tree view control. GetNodeCount

It is used to collapse all tree nodes, including all child nodes in the tree view control. CollapseAll

ToString method is used to return the name of the string that is in the tree view control. ToString

Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list
of TreeView control properties and methods.

Examples:
P a g e | 92
Visual Programming C#
P a g e | 93
Visual Programming C#

VB.NET ListView Control:


The ListView Controls are used to display a collection of items in the Windows Forms. It
uses one of the view lists, such as LargeIcon, SmallIcon, Details, List, and Tile. Furthermore,
the ListView allows the user to add or remove icons from the ListView Control.

Let's create a ListView control in the VB.NET Windows form by using the following steps.

Step 1: We have to find the ListView control from the toolbox and then drag and drop
the ListView control onto the window form, as shown below.
P a g e | 94
Visual Programming C#

Step 2: Once the ListView is added to the form, we can set various properties of the List
by clicking on the ListView control.

Properties of the ListView Control


There are following properties of ListView control.

Properties Description

Alignment The Alignment property is used to set the alignment for the item in the ListvVew Control.

Activation The Activation property is used to get or set a user-requested action to activate an item.

CheckBoxes The CheckBoxes property sets a value to display the checkbox that appears next to each item
in the list view control.

Columns The Columns property is used to display the collection of columns header in the ListVie
Control.

CheckIndices The CheckIndices property is used to get all checked items in the ListView Control.
P a g e | 95
Visual Programming C#

GridLines The GridLines Property is used to display the gridlines between the rows and columns tha
contain the items and subitems in the ListView Control.

Items It is used to collect the collection of the items that are in the ListView Control.

LargeImageList It is used to set or get ImageList to display it as a large icon in the ListView Control.

HeaderStyle It is used to set or get the column header style in the ListView control.

MultiSelect The MultiSelect property is used to set a value that allows selecting more than items in th
ListView control.

SelectedItems It is used to obtain all selected items in the ListView control.

ShowGroups The ShowGroups property set a value that represents whether the ListView items are displaye
in groups.

SmallImageList It is used to set or get ImageList to display the image as a small icon in the ListView control.

TopItem The TopItem property is used to set or get the first item in control.

View The View property is used to set the items displayed in the List view. The View property ha
the following value
SmallIcon: It is used to display small size icon
List: It is used to display items in a list, and it only shows caption
LargeIcon: It is used to display large size icon
Report: It is used to display items and its sub-items.

Methods of the ListView Control


Method Description

ArrangeIcons() The ArrangeIcons method is used to arrange all the items displayed as icons in th
ListView control.

FindItemWithText() It is used to search the first ListViewItem that started with the given text value.
P a g e | 96
Visual Programming C#

GetItemAt() The GetItemAt method is used to get an item at the specified location of the ListVie
control.

Clear() The Clear method is used to clear all the items and columns from the ListView control.

Sort() The Sort method is used to sort items of the ListView.

Events of the ListView Control

There are following events of the ListView control.

Events Description

ItemActivate The ItemActivate event occurred when an item activated in the ListView control.

ItemChecked The ItemChecked event is found in the ListView control when the checked state of an item
changes.

TextChanged The TextChanged event is found in the ListView control when the property of the te
changes.

ItemCheck When the status of a check item changes, the ItemCheck event is found in the list vie
control.

AfterLabelEditEvent It occurs when the user in the ListView control edits the label for an item.

Examples:
P a g e | 97
Visual Programming C#
P a g e | 98
Visual Programming C#
P a g e | 99
Visual Programming C#

VB.NET Dialog Box:


A Dialog box is a temporary Window for an application that accepts user response
through mouse or keyboard to open a file, save a file, notifications, alert messages, color,
print, openfile dialog box, etc. It is also useful to create communication and interaction
between the user and the application. Furthermore, the dialog box appears in a form when
the program needs to interact with users, such as when an error occurs, an alert message,
acknowledgment from the user or when the program requires immediate action or
whether the decision is to be saved based on the changes.

All VB.NET Dialog box inherits the CommonDialog class and overrides
the RunDialog() method of the base class to create the OpenFileDialog box,
PrintDialogbox, Color, and Font Dialog box. The RunDialog() method is automatically
called in a Windows form when the dialog box calls its ShowDialog() method.

There are following functions of the ShowDialog() method that can be called at run time
in the Windows Form.

o Abort: The Abort Dialog box is used when a user clicks on the Abort button to return the
DialogResult.Abort value.
o Ignore: The Ignore Dialog box is used when a user clicks on the Ignore button to return
the DialogResult.Ignore.
o None: It is used to return nothing when the user clicks on the None button, and the dialog
box is continued running.
o OK: When the user clicks the OK button of the Dialog box, it returns a DialogResult.OK,
o Cancel: When a user clicks on the Cancel button of the Dialog Box, it returns
DialogResult.Cancel,
o Yes: When a user clicks the Yes button of the dialog box, it returns DialogResult.Yes.
o Retry: When a user clicks on the Dialog Box Retry button, it returns a DialogResult.Retry,
o No: When a user clicks on the No button of the Dialog box, it returns DialogResult.No,

There are the commonly used dialog box controls in the VB.NET Windows Form.

1. Color Dialog Box: It is used to display the color dialog box that allows the user to select
a color from the predefined colors or specify the custom colors.
P a g e | 100
Visual Programming C#

2. Font DialogBox: It is used to create a Font dialog box that allows the user to select the
font, font size, color, and style to be applied to the current text selection.
3. OpenFile Dialog Box: It is used to create a prompt box that allows the users to select a
file to open and allows the selection of multiple files.
4. Print Dialog Box: It is used to create a print dialog box that allows the user to print
documents by selecting the printer and setting of the page printed through the Windows
application.

Let's create a simple program to display the dialog box in the VB.NET Windows Forms.

Dialog.vb:

1. Public Class Dialog


2. Private Sub Dialog_Load(sender As Object, e As EventArgs) Handles MyBase.Load
3. Button1.Text = "Click Me" 'Set the name of button
4. Me.Text = "csharp.com" ' Set the title name for the Windows Form
5. Button1.BackColor = Color.Green ' Background color of the button
6. End Sub
7.
8. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
9. Dim result1 As DialogResult = MessageBox.Show("Is VB.NET programming l
anguage easy to learn?",
10. "Important Question",
11. MessageBoxButtons.YesNo)
P a g e | 101
Visual Programming C#

12. End Sub


13. End Class

Output:

Now, click on the Click Me button of the Windows Form, it displays the dialog box, as
shown below.

VB.NET Color Dialog Box:


The Color Dialog box is used to display the Color dialog box and the selection of colors
on the Microsoft Windows Application. It allows users to set or change the color of an
P a g e | 102
Visual Programming C#

object, such as the background color of a control or the color used to paint an object.
Furthermore, the control dialog box also allows the facility to the user to create a new
color by mixing all other colors of the Color Dialog Box.

Let's create a Color Dialog in the VB.NET Windows form by using the following steps.

Step 1: Drag the Color Dialog from the toolbox and drop it to the Windows form, as
shown below.

Step 2: Once the Color Dialog is added to the form, we can set various properties of the
Color by clicking on the Color Dialog.

Properties of Color DialogBox:


There are following properties of the Color Dialog Box in the Windows Form.

Description Properties

The AllowFullOpen property enables the user to set custom colors in Windows Forms by setting AllowFullOpen
values in the color dialog box.
P a g e | 103
Visual Programming C#

The Color property is used to set or get the user's selected color from the Color Dialog box. Color

The FullOpen property is used to set a value representing whether the custom colors will be FullOpen
displayed when the dialog box is opened.

The AnyColor property takes a value that is used to display all available colors in the Color AnyColor
dialog box with a set of basic colors.

ShowHelp property enables the user to display the help button in the Color Dialog box by ShowHelp
setting a value in the dialog box.

It is used to set the custom colors that are displayed on the dialog box. CustomColors

The SolidColorOnly property is used to set a value representing whether the dialog box restricts SolidColorOnly
the user from selecting only solid colors.

Events of Color DialogBox:


Description Events

When control or component is terminated by calling the Dispose method, a Dispose event occurs. Disposed

When a user clicks the help button of the Color dialog box, the HelpRequest event is called. HelpRequest

Methods of Color DialogBox:


Description Method

The ShowDialog () method is used to run a common dialog box with the default setting. ShowDialog()

The Dispose() method is used to free all resources used by the Control or component in the Dispose()
Color Dialog Box.

The Equals() method is used to check whether the current or defined object is the same. Equals()
P a g e | 104
Visual Programming C#

It is used to call the HelpRequest event in the dialog box. OnHelpRequest()

The Reset() method is used to reset all changes to their default values. For example, the last Reset()
selected color to be black, and the custom color to be their default values.

It is used to override a derived class to create a common dialog box. RunDialog()

Let's create a simple program to display the Color dialog box in the VB.NET Windows
Forms.

ColorDialog.vb

1. Public Class ColorDialog


2. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.C
lick
3. ColorDialog1.FullOpen = True
4. If ColorDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
5. RichTextBox1.ForeColor = ColorDialog1.Color
6. RichTextBox1.BackColor = ColorDialog1.Color
7. End If
8. End Sub
9. Private Sub ColorDialog_Load(sender As Object, e As EventArgs) Handles MyBa
se.Load
10. Me.Text = "Mycsharpcode" 'set the title for the Windows form
11. Button1.Text = "Change TextBox Color"
12. Button2.Text = "Change Form Color"
13. Button3.Text = "Change Label Color"
14. End Sub
15. Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.C
lick
16. ColorDialog1.FullOpen = False
17. If ColorDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
18. Me.BackColor = ColorDialog1.Color 'Change Background color of the for
m
19. End If
P a g e | 105
Visual Programming C#

20. End Sub


21. Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.C
lick
22. ColorDialog1.FullOpen = True
23. If ColorDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
24. Label1.ForeColor = ColorDialog1.Color 'set the color of the Label
25. End If
26. End Sub
27. End Class

When we click on the any of the three buttons, it opens the Color popup window, as
shown below.
P a g e | 106
Visual Programming C#

Click the OK button to display the colored Windows Form, as shown below.
P a g e | 107
Visual Programming C#

VB.NET Font Dialog Box:


The Font Dialog Box allows the user to select the font family, style, and size for the text in
an application. However, a user can also select the font color and apply the current setting
to the selected text of the control by clicking the Apply button.

Let's create a Font Dialog box in the VB.NET Windows form using the following steps.

Step 1. We need to drag the Font Dialog box from the toolbox and drop it to
the Windows form, as shown below.

Step2: Once the Font Dialog is added to the form, we can set various properties of the
Font by clicking on the Font Dialog box.

Properties of Font Dialog:


There are following properties of the Font Dialog Box in the VB.NET.

Description Properties
P a g e | 108
Visual Programming C#

The ShowApply property sets a value representing whether you want to display the Apply ShowApply
button on the dialog box.

The ShowEffects property is used to set various effects on the text such as strikethrough, ShowEffects
text color, and underline options by setting values on the FontDialog box.

The Font property is used to get or set the selected font to display changes. Font

The Container property is used to get the IContainer that contains the Component of the Container
Font Dialog Box.

The AllowverticalFonts property is used to set or get a value that represents whether the AllowVerticalFonts
Font dialog box displays the horizontal and vertical fonts or displays only horizontals fonts.

The AllowScriptChange property is used to set a value that allows the user to change the AllowScriptChange
character specified in the Script combo box to show a character set other than the currently
displayed character.

The ScriptOnly property is used to set a value that allows the user to select only the font, ScriptOnly
the character set of the symbol, and the ANSI character from the dialog box.

The ShowHelp property is used to set a value representing whether the Help button should ShowHelp
be displayed in the dialog box.

The MaxSize property gets or sets a value that allows the user to select only the maximum MaxSize
point size character.

It is used to initialize FontDialog by obtaining values. Options

Methods of Font Dialog:


Description Method

The Equals() method is used to check whether the current or defined object is the same. Equals()

It is used to call the HelpRequest event in the dialog box. OnHelpRequest()


P a g e | 109
Visual Programming C#

The Reset() method is used to reset all changes to their default values. Reset()

The Dispose() method is used to free all resources used by the Control or the component in Dispose()
the Dialog Box.

It is used to override a derived class to create a common dialog box. RunDialog()

The ShowDialog () method is used to run a common dialog box with the default setting. ShowDialog()

The CreateObjRef () method is used to create an object that contains all related information CreateObjRef()
to initialize a proxy that can communicate with a remote object.

Events of Font Dialog:


Description Events

When control or component is terminated by calling the Dispose() method, a Dispose event Disposed
occurs.

When a user clicks the Help button of the dialog box, the HelpRequest event is called. HelpRequest

When a user clicks on the Apply button of the Font dialog box, an apply event occurs. Apply

Let's create a simple program to display the Font dialog box in the VB.NET Windows
Forms.

FontDialog.vb

1. Public Class FontDialog


2. Private Sub FontDialog_Load(sender As Object, e As EventArgs) Handles MyBase.Load

3. Me.Text = "mydialogform" 'set the title name for the Windows form.
4. Button1.Text = "Change Font" 'Set the name of button1
5. Button2.Text = "Exit" 'name of button2
6. Label1.Text = "Uses of Font"
7. End Sub
P a g e | 110
Visual Programming C#

8. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


9. FontDialog1.ShowColor = True
10. If FontDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
11. TextBox1.Font = FontDialog1.Font 'Change the font of the selected string
12. TextBox1.ForeColor = FontDialog1.Color 'Change the color of selected string
13. End If
14. End Sub
15. Private Sub Button2_Click(sender As Object, e As EventArgs) Handles
Button2.Click
16. Me.Dispose() 'Terminate the program
17. End Sub
18. End Class

Output:

Write some text in TextArea, as shown below.


P a g e | 111
Visual Programming C#

Select the string and click the 'Change Font' button; it opens the Font window. In the Font
window, we can change the size, font, and font style of the selected string.
P a g e | 112
Visual Programming C#

After setting the font, font style, size, and color, etc. on the Font dialog box, it shows the
formatted string, as shown below.

VB.NET OpenFile Dialog Box


It is used to display the OpenFileDialog box that allows the user to select and open a file.
It also facilitates the user to select multiples files from the dialog box. However, the
OpenFileDialog box contains a list of files and folders from which the user can choose the
required files to process the form.

Let's create an OpenFileDialog control in the VB.NET Windows form by using the
following steps.

Step 1: Drag the OpenFileDialog control from the toolbox and drop it to the Windows
form, as shown below.
P a g e | 113
Visual Programming C#

Step 2: Once the OpenFileDialog is added to the form, we can set various properties of
the OpenFileDialog by clicking on the OpenFileDialog.

OpenFile Dialog Properties:


There are following properties of the OpenFileDialog Box in the VB.NET.

Description Properties

The CheckFileExists property is used to get or set a value that confirms whether the dialog CheckFileExists
box displays a warning message when the particular file does not exist.

The property is used to get the specific file name and extension for the selected file in the SafeFileName
dialog box. However, it does not include the file path for the file name.

The ShowReadOnly property is used to obtain or set a value that confirms whether the ShowReadOnly
dialog box provides only the read checkbox to read the file.

The ReadOnlyChecked property is used to obtain or set a value that validates whether the ReadOnlyChecked
read-only checkbox is selected in the OpenFileDialog box.
P a g e | 114
Visual Programming C#

The ShowHelp property is used to set a value that represents whether the Help button ShowHelp
should be displayed in the dialog box.

The MultiSelect property is used to set a value that allows the user to select multiple files Multiselect
from the OpenFileDialog box.

The AddExtension property is used to set a value that validates whether the dialog box AddExtension
automatically adds an extension to a file if the user forgets to add the extension.

The DefaultExt property is used to set or get the default extension of a file. DefaultExt

The FileName property represents the selected file name as a string in the file dialog box. FileName

It is an important property of the OpenFileDialog box, which is used to filter the files. It is Filter
also used to display files in a dialog box by specifying a file type. For example, we have to
set "Text|*.txt" in a filter to display only text files in the dialog box.

Methods of OpenFile Dialog Control:


Description Method

The OpenFile method is used to open the selected file by the user with reading only permission. OpenFile()
The selected file is specified by the FileName property of the dialog box.

The Reset() method is used to reset all changes to their default values. Reset()

Let's create a simple program to display the OpenFileDialog box in the VB.NET Windows
Forms.

OpenDialog.vb

1. Public Class OpenDialog


2. Private Sub OpenDialog_Load(sender As Object, e As EventArgs) Handles MyBase.Load

3. Me.Text = "csharp.com" 'Set the title of the Windows Form.


4. Button1.Text = "Click Me"
P a g e | 115
Visual Programming C#

5. Label1.Text = "Click the button below to open the file"


6. Label1.ForeColor = Color.Green
7. Label2.Text = "File Path"
8. End Sub
9. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.C
lick
10. If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
11. OpenFileDialog1.InitialDirectory = "C:\" 'Set the directory name
12. OpenFileDialog1.Title = "Open an Image File" 'Set the title name of the OpenDialog
Box
13. OpenFileDialog1.Filter = "Image|*.jpg" 'Set the filter to display only image.

14. PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)


15. Label2.Text = OpenFileDialog1.FileName 'Path of selected file
16. End If
17. End Sub
18. End Class

Output:

Now, click on the Click Me button, it opens the OpenDialog box to select an image, as
shown below.
P a g e | 116
Visual Programming C#

After selecting the image, click the Open button to display the selected image in
Windows Form, as shown below.
P a g e | 117
Visual Programming C#

VB.NET Print Dialog Box:


It is used to display the PrintDialog box in an application. It is an important dialog control
that allows the user to select sections of a document and then select a printer to print
pages from the Windows Forms application. Furthermore, a user can specify the range of
pages to print, printer to use, number of copies in the PrintDialog box. And we can display
the PrintDialog control in a Windows form using the ShowDialog() method.

Let's create a PrintDialog control in the VB.NET Windows form using the following steps.

Step 1: We have to find the PrintDialog, PrintDocument, PrintPreviewDialog


control from the toolbox. Drag and drop the PrintDialog, PrintDocument,
PrintPreviewDialog control onto the window form, as shown below.

Step 2: Once the Dialog is added to the form, we can set various properties of the
PrintDialog by clicking on the PrintDialog, PrintDocument, PrintPreviewDialog control.

Print Dialog Properties:


There are following properties of the Print Dialog Dialog Box.
P a g e | 118
Visual Programming C#

Description Properties

The AllowPrintToFile property is used to set a value in the control box representing whether AllowPrintToFile
the Print to File checkbox is enabled in the dialog box.

The Document property is used to set a value in the dialog box representing whether the Document
PrintDocument is capable of receiving PrintSettings.

The AllowCurrentPage property is used to set a value representing whether the Current AllowCurrentPage
Page option button is displayed in the PrintDialog box.

The PrintToFile property is used to set or get a value in the control that represents whether PrintToFile
the Print to File checkbox is selected in the dialog box.

The ShowHelp property is used to set a value that represents whether the Help button ShowHelp
should be displayed in the dialog box.

It is used to set the printer setting property in the PrintDialog box. PrinterSetting

The AllowSelection property is used to set a value in the control that represents whether AllowSelection
the Selection option button is enabled in the PrintDialog box.

Methods of Print Dialog Control:


Description Method

The ShowDialog () method is used to run a common dialog box with the default setting. ShowDialog()

The Reset() method is used to reset all changes to their default values. Reset()

The Dispose() method is used to free all resources used by the Control or component in the Dispose()
Dialog Box.

It is used to override a derived class to create a common dialog box. RunDialog()


P a g e | 119
Visual Programming C#

Events of PrintDialog Control:


Description Events

When control or component is terminated by calling the Dispose() method, a Dispose event Disposed
occurs.

When a user clicks the Help button of the dialog box, the HelpRequest event is called. HelpRequest

Let's create a simple program to print and preview the document in the VB.NET Windows
Forms.

Printbox.vb

1. Public Class Printbox


2. Private Sub Printbox_Load(sender As Object, e As EventArgs) Handles MyBase.Load
3. Me.Text = "csharpcode.com" 'Set the title for the Windows form
4. Button1.Text = "Print"
5. Button2.Text = "Print Preview"
6. Button1.BackColor = Color.SkyBlue
7. Button2.BackColor = Color.SkyBlue
8. PrintPreviewDialog1.Document = PrintDocument1
9. End Sub
10. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
11. If PrintDialog1.ShowDialog = DialogResult.OK Then 'Open the print dialog b
ox
12. PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings
13. PrintDocument1.Print() 'print a document
14. End If
15. End Sub
16. Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEvent
Args) Handles PrintDocument1.PrintPage
17. Dim font As New Font("Times New Roman", 24, FontStyle.Bold) 'set the font
to display
P a g e | 120
Visual Programming C#

18. e.Graphics.DrawString(RichTextBox1.Text, font, Brushes.Red, 100, 100) 'The DrawStrin


g() function is used to print letters.
19. End Sub
20. Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
21. If RichTextBox1.Text = " " Then
22. MsgBox("Please write some text...")
23. Else
24. PrintPreviewDialog1.ShowDialog()
25. End If
26. End Sub
27. End Class

Output:

Write some text in the textbox. We have written the following text in the text box, as
shown below.
P a g e | 121
Visual Programming C#

After writing the text, click the Print button to print the document and set printer settings,
as shown below.
P a g e | 122
Visual Programming C#

Even we can check the preview of the document by clicking on the Print Preview button;
it shows the below image.

Assemblies:
Type of Assembly in C#
Introduction:
Assembly is an important concept in C#. It is a collection of code files that are compiled
into an executable or a Dynamic Link Library (DLL). Depending on their location and
intended use, assemblies can be divided into many categories. We will examine the
various assembly types in C# in this article.

Private Assemblies:
An Assembly that is solely used by one application is referred to as a Private Assembly. It
is typically found in the directory for the application or a subdirectory of the directory for
the programme. Private Assemblies are not intended to be shared with other applications.
They are used to store application-specific code and resources.

Private Assemblies are created when an application is compiled. When an application is


compiled, all the code files and resources that are used by the application are compiled
P a g e | 123
Visual Programming C#

into a single assembly.The application's directory or a subdirectory of the application's


directory will thereafter contain this assembly.

Private Assemblies are simple to deploy and use. They don't need any extra installation or
setting. They are automatically loaded by the .NET runtime when the application starts.

Shared Assemblies:
An assembly that is used by several programmes is referred to as a shared assembly. It is
typically found in the Global Assembly Cache (GAC) or a common directory. Multiple
applications are supposed to share a shared assembly. They are used to store resources
and code that are shared by various applications.

Shared Assemblies are created using the strong name tool (sn.exe). A digital signature
for the assembly is applied using the strong name tool. The digital signature guarantees
that the assembly is genuine and unaltered.

The Global Assembly Cache (GAC) houses shared assemblies. Shared assemblies are
kept in the GAC, which serves as a central repository. The GAC location is in the Windows
directory (C:\Windows\assembly). Shared assemblies are registered with the GAC using
the gacutil.exe tool.

Shared assemblies require special configuration and installation. They cannot be simply
copied to the application's directory. They need to be registered with the GAC using
the gacutil.exe tool.

Satellite Assemblies:
An assembly used to store regional resources is referred to as a Satellite Assembly. It is
typically found in a subdirectory of the directory for the application or a subdirectory of
the directory for the Shared Assembly. Localized resources like strings, pictures, and audio
files are kept in satellite assemblies.

Satellite Assemblies are created using the resgen.exe tool. The resgen.exe tool is used to
create a resource file (.resx) from a text file. The resource file is then compiled into a
satellite assembly using the al.exe tool.

Satellite Assemblies are named using a specific naming convention. The naming
convention for satellite assemblies is as follows:

1. <AssemblyName>.resources.dll
P a g e | 124
Visual Programming C#

The <AssemblyName> part of the name is the name of the main assembly that the
satellite assembly is associated with. The.NET runtime automatically loads satellite
assemblies when the application first launches. The .NET runtime automatically selects the
appropriate satellite assembly based on the user's culture settings.

Dynamic Link Libraries (DLLs):


A Dynamic Link Library (DLL) is a type of assembly that contains code that can be used by
multiple applications. Similar to shared assemblies, DLLs are created with the intention of being
used by numerous applications. DLLs, however, differ from shared assemblies in that they do not
have a distinctive name.

DLLs are kept in the directory of the application or a subdirectory of the directory of the
application. They can be used by multiple applications by simply copying the DLL to the
application's directory.

DLLs are created using the same tools that are used to create shared assemblies.
However, DLLs do not require a strong name. They can be signed with a digital signature, but
this is optional.

Conclusion:
Assemblies are an important part of the .NET framework and are used to store code files and
resources that can be used by one or more applications. There are four main types of assemblies
in C#: Private Assemblies, Shared Assemblies, Satellite Assemblies, and Dynamic
Link Libraries (DLLs). Each type of assembly has its own purpose and usage.

Application-specific code and resources that are only needed by a single application are
kept in private assemblies. They don't need any extra installation or configuration and are
simple to deploy. They are automatically loaded by the .NET runtime when the application
starts.

A configuration file (web.config) is used to manage various settings that define a website.
The settings are stored in XML files that are separate from your application code. In this
way you can configure settings independently from your code. Generally a website
contains a single Web.config file stored inside the application root directory. However there
can be many configuration files that manage settings at various levels within an
application.
P a g e | 125
Visual Programming C#

Usage of configuration file

ASP.NET Configuration system is used to describe the properties and behaviors of various
aspects of ASP.NET applications. Configuration files help you to manage the many settings
related to your website. Each file is an XML file (with the extension .config) that contains a
set of configuration elements. Configuration information is stored in XML-based text files.

Benefits of XML-based Configuration files


• ASP.NET Configuration system is extensible and application specific
information can be stored and retrieved easily. It is human readable.
• You need not restart the web server when the settings are changed in
configuration file. ASP.NET automatically detects the changes and applies them
to the running ASP.NET application.
• You can use any standard text editor or XML parser to create and edit ASP.NET
configuration files.
What Web.config file contains?

There are number of important settings that can be stored in the configuration file. Some
of the most frequently used configurations, stored conveniently inside Web.config file are:

• Database connections
• Caching settings
• Session States
• Error Handling
• Security
Configuration file looks like this
1. <configuration>
2. <connectionStrings>
3. <add name="myCon" connectionString="server=MyServer;d
atabase=puran;uid=puranmehra;pwd=mydata1223" />
4. </connectionStrings>
5. </configuration/>
Different types of Configuration files
•Machine.config - Server or machine-wide configuration file
•Web.config - Application configuration files which deal with a single application
Machine.config File

Configuration files are applied to an executing site based on a hierarchy. There is a global
configuration file for all sites in a given machine which is called Machine.config. This file is
P a g e | 126
Visual Programming C#

typically found in the C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG


directory.

The Machine.config file contains settings for all sites running on the machine provided
another .config further up the chain does not override any of these settings. Although
Machine.config provides a global configuration option, you can use .config files inside
individual website directories to provide more granular control. Between these two poles
you can set a number of other .config files with varying degree of applicable scope.

Application Configuration file (Web.config)

Each and Every ASP.NET application has its own copy of configuration settings stored in a
file called Web.config. If the web application spans multiple folders, each sub folder has its
own Web.config file that inherits or overrides the parent's file settings.

Processing of a Web.config file

When you initially run your web application, the runtime builds a cache of the configuration
settings for your web application by flattening the layer of configuration files as below,

1. The Machine.config file settings are retrieved.


2. The settings from the root Web.config files are added to the caches,
overwriting any conflicting settings that were earlier while reading the
Machine.config file.
3. If there is a Web.config file at the root of the website, this file is read into the
cache, all overwriting any existing settings. The resulting cache contains the
setting for this website.
4. If you have subdirectories in your web application, each subdirectory can have
a Web.config file that includes settings that are specific to the files and folders
that are contained within the subdirectory. To calculate the effective setting for
the folders, the website settings are read (step 1-4) and then this Web.config
file is read into cache for this folder, overwriting (and thereby overriding) any
existing settings.
P a g e | 127
Visual Programming C#

ASP.NET Multilayered Configuration system:


ASP.NET uses a multilayered configuration system that allows for using different settings
for different parts of an application. For this, we must have an additional subdirectory
inside the virtual directory, and these subdirectories will contain their own config files
with additional settings. ASP.NET uses configuration inheritance so that each
subdirectory acquires the settings from the parent directory.

Let's take an example. We have a web request http://localhost/X/Y/Z/page.aspx,


where X is the root directory of the application. In this case, multiple levels of settings
come into the picture.

1. The default machine.config settings are applied first.


2. Next, the web.config of the root level is applied. This web.config resides in the same
config directory as the machine.config file.
3. Now, if there is any config file in the application root X, these settings are applied.
4. If there is any config file in the subdirectory Y, these settings are now applied.
P a g e | 128
Visual Programming C#

5. If there is any config file in the application root Z, those settings are then applied.

But here, there is a limitation: we can have unlimited number of subdirectories having
different settings, but the configuration at step 1 and 2 are more significant because
some of the settings can not be overridden, like the Windows account that is to be used
to execute the code, and other settings can be only overridden at the application root
level, like the type of authentication to be used etc.

Different config files are useful when we apply different security settings to different
folders. The files that need to be secured would then be placed in a separate folder with
a separate web.config file that defines the more stringent security settings to these files
and vice versa.

In the web.config, under the <configuration> element, there is another


element <system.web>, which is used for ASP.NET settings and contains separate
elements for each aspect of the configuration.

Important Configuration Tags


There are a lot of configuration tags that are provided by the web.config file,
like authentication, authorization, browserCaps, clientTarget etc., but all of these
don't have that much importance (and also can't be covered in a single article ), so here,
I have only concentrated on the main tags of the config file.

<authentication>
This element is used to verify the client's identity when the client requests a page from
the server. This is set at the application level. We have four types of authentication
modes: “None”, “Windows”, “Forms”, and “Passport”.

If we don't need any authentication, this is the setting we use:

XML

<authentication mode="None"/>

Normally, Windows authentication is used, for which, we need to check the checkbox:
Integrated Windows Authentication.

XML
P a g e | 129
Visual Programming C#

<authentication mode="Windows"/>

This authentication is handled by IIS. When the user sends a request to the server, IIS
authenticates it and sends the authentication identity to the code.

IIS gives us four choices for the authentication modes: Anonymous, Basic, Digest, and
Windows Integrated. If the user selects Anonymous, then IIS doesn't perform any
authentication. For Basic authentication, the user has to provide a username and
password. This authentication is very unsecure, because the user credentials are sent in
clear text format over the network. Digest authentication is same as Basic, except it
hashes the user's password and transmits the hashed version over the wire. So, it is
more secure than Basic. For Windows Integrated authentication, passwords never cross
the network. The user must still have a username and password, but the application uses
either the Kerberos or a challenge/response protocol to authenticate the user.
P a g e | 130
Visual Programming C#

Forms authentication uses web application forms to collect user credentials, and on
the basis of the credential, it takes action on a web application.

XML

<authentication mode="Forms">
<forms name="Form" loginUrl="index.asp" />
</authentication>

Passport authentication is provided by Microsoft. A redirect URL should be specified,


and is used when the requested page is not authenticated, and then it redirects to this
URL.

XML

<authentication mode="Passport">
<passport redirectUrl="internal" />
</authentication>

Here, users are authenticated using the information in Microsoft's Passport database.
The advantage is, we can use existing user credentials (such as an email address and
password) without forcing users to go through a separate registration process. The
disadvantage is we need to go through the licensing agreement with Microsoft and pay
a yearly fee based on the use.

For using Passport authentication, you first install the Passport Software Development
Kit (SDK) on your server. The SDK can be downloaded from here. It includes full details
of implementing passport authentication in your own applications.

<authorization>
The <authorization> tag controls client access to web page resources. This element
can be declared at any level (machine, site, application, subdirectory, or page).

XML

<authorization>
<allow users="comma-separated list of users"
roles="comma-separated list of roles"
verbs="comma-separated list of verbs"/>
<deny users="comma-separated list of users"
roles="comma-separated list of roles"
verbs="comma-separated list of verbs"/>
P a g e | 131
Visual Programming C#
</authorization>

<allow>: Using this tag, we can control access to resources on the basis of the following
verbs. In these attributes, we use symbols: ? and *.? means for anonymous
users/resources, and * means for all users.

• users: This contains the list of user names (comma separated) that are allowed to access
the resources.
• roles: This contains the list of roles (comma separated) that are allowed to access the
resources.
• verbs: This contains the list of HTTP verbs to which the action applies (comma
separated). It is used to create a rule that applies to a specific type of HTTP request (GET,
POST, HEAD, OR DEBUG).

<deny>: Using this tag, we can control access to resources on the basis of the following
verbs:

• users: This contains the list of users names (comma separated) that are denied access to
the resources.
• roles: This contains the list of roles (comma separated) that are denied access to the
resources.
• verbs: This contains the list of HTTP verbs to which the action applies (comma
separated). It is used to create a rule that applies to a specific type of HTTP request (GET,
POST, HEAD, OR DEBUG).

<compilation>
In this section, we can configure the settings of the compiler. Here, we can have lots of
attributes, but the most common ones are debug and defaultLanguage.
Setting debug to true means we want the debugging information in the browser, but it
has a performance tradeoff, so normally, it is set as false. And, defaultLanguage tells
ASP.NET which language compiler to use: VB or C#.

<customErrors>
This tags includes the error settings for the application, and is used to give custom error
pages (user-friendly error pages) to end users. In the case that an error occurs, the
website is redirected to the default URL. For enabling and disabling custom errors, we
need to specify the mode attribute.

XML
P a g e | 132
Visual Programming C#

<customErrors defaultRedirect="url" mode="Off">


<error statusCode="403" redirect="/accesdenied.html" />
<error statusCode="404" redirect="/pagenotfound.html" />
</customErrors>
• "On" means this settings is on, and if there is any error, the website is redirected to the
default URL.
• "Off" means the custom errors are disabled.
• "RemoteOnly" shows that custom errors will be shown to remote clients only.
XML

<error statusCode="403" redirect="/accesdenied.html" />


<error statusCode="404" redirect="/pagenotfound.html" />

This means if there is an error of 403, then the website will redirected to the custom
page accessdenied.html. Similarly for 404 as defined above.

Note: If an error occurs in the custom error page itself, ASP.NET won't able to handle it. It
won't try to reforward the user to the same page. Instead, it'll show the normal default
client error page with a generic message.

<globalization>
This section is used when we want to use encoding or specify a culture for the
application. This is a very vast topic, and can take an article itself for explaining it. Here,
we define the character set for the server to send the response to the client, which is by
default is UTF-8, and the settings of which the server should use to interpret and display
culturally specific strings, such as numbers and dates.

XML

<globalization requestEncoding="utf-8" responseEncoding="utf-8" />

<httpRuntime>
This section can be used to configure the general runtime settings of the application.
The main two are:

XML

<httpRuntime appRequestQueueLimit="50" executionTimeout="300" />


P a g e | 133
Visual Programming C#

As the name suggests, the attribute appRequestQueueLimit defines the number of


requests that can be queued up on the server for processing. If there are 51 or more
requests, then server would return the 503 error ("Server too busy").

The attribute executionTimeout defines the number of minutes ASP.NET will process a
request before it gets timeout.

<trace>
As the name suggestz, it is used for tracing the execution of an application. We have
here two levels of tracing: page level and application level. Application level enables the
trace log of the execution of every page available in the application.
If pageOutput="true", trace information will be displayed at the bottom of each page.
Else, we can view the trace log in the application root folder, under the name trace.axd.

XML

<trace enabled="false" requestLimit="10" pageOutput="false"


traceMode="SortByTime" locaOnly="true" />

Set the attribute localOnly to false for not viewing the trace information from the
client.

For enabling trace at page level, set Trace="True" in the Page tag (on the top of the
page).

<identity>
Using this tag, we can control the identity of the application. By
default, Impersonation is disabled. Using Impersonation, an ASP.NET application can
execute optionally with the identity of a client on whose behalf they are operating.

XML

<identity impersonate="false" userName="domain\username" password="password" />

<sessionState>
In this section, we tell ASP.NET where to store the session. By default, it's inproc which
means storing the session values on the server. But we have four options:
P a g e | 134
Visual Programming C#

• "Off" means session is not enabled for the application.


• "inproc" means storing the session values on the server.
• "StateServer" means session states are stored in a remote server.
• "SQLServer" means session states are stored in a SQL Server database. For this, we
need to install the InstallSQLState.sql script in the SQL Server database. It is mainly used
when the we use web farms (an application deployed on multiple servers), but it makes
the performance slow as compared to "inproc".

Here are the other settings:

• "cookieless": when it is true, it means the session used is without cookies.


• “timeout” specifies after how much time the session would expire if the application is
not accessed during that period.
• "stateConnectionString " needs to be specified when the session mode
is StateServer.
• "sqlConnectionString" is the connection string of the SQL Server database if the
session mode is sqlserver.
• "stateNetworkTimeout" attribute, when using the StateServer mode to store
session state, specifies the number of seconds the TCP/IP network connection between
the web server and the state server can be idle before the session is abandoned. The
default is 10.
XML

<sessionState mode="Off"
cookieless="true"
timeout="100"
stateConnectionString="tcpip=server:port"
sqlConnectionString="sql connection string"
stateNetworkTimeout="number of seconds"/>

<appSettings>
This section is used to store custom application configuration like database connection
strings, file paths etc. This also can be used for custom application-wide constants to
store information over multiple pages. It is based on the requirements of the
application.

XML

<appSettings>
<add key="Emailto" value="me@microsoft.com" />
<add key="cssFile" value="CSS/text.css" />
</appSettings>
P a g e | 135
Visual Programming C#

It can be accessed from code like:

C#

ConfigurationSettings.AppSettings("Emailto");

All the values returned from it are strings.

Custom Configuration Sections


We might need some custom configuration sections based on the requirements. One of
the simplest ways we can do this is to create our own named sections, and we can use
existing NameValueSectionHandler components to parse them, and they can be used
as key/value pairs to be accessed at run-time.

This can be read very easily accessed from the code-behind as:

C#

private string ReadCustomSection()


{
string strKey = "mySectionKey1";
NameValueCollection nvcmySection = (NameValueCollection)
ConfigurationSettings.GetConfig("mySection");
string strValueofKey = nvcmySection[strKey];
return strValueofKey;
}
P a g e | 136
Visual Programming C#

There are more ways for using custom configuration sections. Check this
article: CustomConfigurationSection.

Encrypting Configuration Sections


Some times, we put some sensitive data in the web.config file like connection strings,
user specific details etc. It is recommended to encrypt these sections. ASP.NET supports
two encryption techniques.

• RSA
• DPAPI

The way the operations perform is very simple. When retrieving information from a
config file, ASP.NET automatically decrypts it and gives the plain text to the code.
Similarly, if we do any updates on the config file from code, it is done the same way. We
cannot update a config file directly. But, we can use WAT for updating it.

Programmatic encryption techniques: If we want to do encryption programmatically,


then we need to retrieve the
corresponding ConfigurationSection.SectionInformation object and call
the ProtectSection() method. If we want to decrypt a section, then we can call the
method UnprotectSetion(). Sample code is shown here:

C#

Configuration myConfig =
WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection mySettings = myConfig.GetSection("mySection");
if (mySettings.SectionInformation.IsProtected)
{
mySettings.SectionInformation.UnprotectSection();
}
else
{

mySettings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider
"); ;
}
myConfig.Save();

Command line utilities: We can also use a command line utility


like aspnet_regiis.exe for encryption of a config file, which is a CAB file found
in C:\[WinDir]\Microsoft.NET\Framework\[Version]. For using this tool, we must create a
P a g e | 137
Visual Programming C#

virtual directory for the application. You can refer my article, Deploying Website at IIS,
for more information.

When using aspnet_regiis to protect some sections of a config file, we need to specify
some command line arguments such as:

• The -pe switch specifies the configuration section to encrypt.


• The -app switch specifies our web application virtual path.
• The -prov switch specifies the provider name.

Here is the command line for an application located at http://localhost/MyApp:

A Few Important Points


• Some settings can not be encrypted because they are used outside ASP.NET (mainly by
the IIS web server), like <httpruntime>.
• Config files are case sensitive.
• The web.config file is protected by IIS, so it won't be accessible by a client system. So, if a
user tries to access it, anaccess denied message will be shown.
• If we change the config file at the server, we don't need to restart the web server
because IIS monitors the changes in the web.config, and for performance measures, it
cache it.
• Microsoft also provides a tool known as Website Administration Tool (WAT) that lets us
configure various part of the web.config using a web interface. To run it, select Website-
>ASP.NET Configuration, in Visual Studio.

Metadata:

In addition to execution instructions, CIL code includes metadata about the types and
files included in a program. The metadata includes the following items:


A description of each type within a program or class library

The manifest information containing data about the program itself, along with the
libraries it depends on

P a g e | 138
Visual Programming C#

Custom attributes embedded in the code, providing additional information about the
constructs that the attributes decorate

The metadata is not a cursory, nonessential add-on to the CIL, but rather represents a
core component of the CLI implementation. It provides the representation and the
behavior information about a type and includes location information about which
assembly contains a particular type definition. It plays a key role in saving data from the
compiler and making it accessible at execution time to debuggers and the runtime. This
data not only is available in the CIL code but also is accessible during machine code
execution so that the runtime can continue to make any necessary type checks.

Metadata provides a mechanism for the runtime to handle a mixture of native and
managed code execution. Also, it increases code and execution robustness because it
smooths the migration from one library version to the next, replacing compile-time–
defined binding with a load-time implementation.

All header information about a library and its dependencies is found in a portion of the
metadata known as the manifest. As a result, the manifest portion of the metadata
enables developers to determine a module’s dependencies, including information about
particular versions of the dependencies and signatures indicating who created the
module. At execution time, the runtime uses the manifest to determine which
dependent libraries to load, whether the libraries or the main program has been
tampered with, and whether assemblies are missing.

The metadata also contains custom attributes that may decorate the code. Attributes
provide additional metadata about CIL instructions that are accessible via the program
at execution time.

Reflection and Late Binding:

Metadata is available at execution time by a mechanism known as reflection. With


reflection, it is possible to look up a type or its member at execution time and then
invoke that member or determine whether a construct is decorated with a particular
attribute. This provides for late binding, in which the system determines which code to
execute at execution time rather than at compile time. Reflection can even be used for
generating documentation by iterating through metadata and copying it into a help
document of some kind.
P a g e | 139
Visual Programming C#

.NET Native and Ahead of Time Compilation

The .NET Native feature creates a platform-specific executable. This is referred to as


ahead of time (AOT) compilation.

.NET Native allows programmers to continue to code in C# while achieving native code
performance and faster startup times by eliminating the need to JIT compile code.
When .NET Native compiles an application, the .NET FCL is statically linked to the
application; .NET Framework runtime components optimized for static pre-compilation
are included as well. These specially built components are optimized for .NET Native
and provide improved performance over the standard .NET runtime. The compilation
step does not change your application in any way. You are free to use all the constructs
and APIs of .NET, as well as depend on managed memory and memory cleanup, since
.NET Native will include all components of the .NET Framework in your executable.

C# Reflection:
Reflection objects are used for obtaining type information at
runtime. The classes that give access to the metadata of a running
program are in the System.Reflection namespace.

The System.Reflection namespace contains classes that allow you to


obtain information about the application and to dynamically add
types, values, and objects to the application.

Applications of Reflection

Reflection has the following applications −

• It allows view attribute information at runtime.


• It allows examining various types in an assembly and
instantiate these types.
• It allows late binding to methods and properties
• It allows creating new types at runtime and then performs
some tasks using those types.
P a g e | 140
Visual Programming C#

Viewing Metadata

We have mentioned in the preceding chapter that using reflection


you can view the attribute information.

The MemberInfo object of the System.Reflection class needs to be


initialized for discovering the attributes associated with a class. To
do this, you define an object of the target class, as −

System.Reflection.MemberInfo info = typeof(MyClass);

The following program demonstrates this −

using System;

[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute {
public readonly string Url;

public string Topic // Topic is a named parameter {


get {
return topic;
}
set {
topic = value;
}
}
public HelpAttribute(string url) // url is a
positional parameter {
this.Url = url;
}
private string topic;
}

[HelpAttribute("Information on the class MyClass")]


class MyClass {

namespace AttributeAppl {
class Program {
P a g e | 141
Visual Programming C#

static void Main(string[] args) {


System.Reflection.MemberInfo info =
typeof(MyClass);
object[] attributes =
info.GetCustomAttributes(true);

for (int i = 0; i < attributes.Length; i++) {


System.Console.WriteLine(attributes[i]);
}
Console.ReadKey();
}
}
}

When it is compiled and run, it displays the name of the custom


attributes attached to the class MyClass −

HelpAttribute
Example

In this example, we use the DeBugInfo attribute created in the


previous chapter and use reflection to read metadata in
the Rectangle class.

Live Demo
using System;
using System.Reflection;

namespace BugFixApplication {
//a custom attribute BugFix to be assigned to a class
and its members
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]

public class DeBugInfo : System.Attribute {


P a g e | 142
Visual Programming C#

private int bugNo;


private string developer;
private string lastReview;
public string message;

public DeBugInfo(int bg, string dev, string d) {


this.bugNo = bg;
this.developer = dev;
this.lastReview = d;
}
public int BugNo {
get {
return bugNo;
}
}
public string Developer {
get {
return developer;
}
}
public string LastReview {
get {
return lastReview;
}
}
public string Message {
get {
return message;
}
set {
message = value;
}
}
}
[DeBugInfo(45, "Zara Ali", "12/8/2012", Message =
"Return type mismatch")]
[DeBugInfo(49, "Nuha Ali", "10/10/2012", Message =
"Unused variable")]

class Rectangle {
//member variables
protected double length;
P a g e | 143
Visual Programming C#

protected double width;

public Rectangle(double l, double w) {


length = l;
width = w;
}
[DeBugInfo(55, "Zara Ali", "19/10/2012", Message =
"Return type mismatch")]
public double GetArea() {
return length * width;
}
[DeBugInfo(56, "Zara Ali", "19/10/2012")]
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle

class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle(4.5, 7.5);
r.Display();
Type type = typeof(Rectangle);

//iterating through the attribtues of the


Rectangle class
foreach (Object attributes in
type.GetCustomAttributes(false)) {
DeBugInfo dbi = (DeBugInfo)attributes;

if (null != dbi) {
Console.WriteLine("Bug no: {0}",
dbi.BugNo);
Console.WriteLine("Developer: {0}",
dbi.Developer);
Console.WriteLine("Last Reviewed: {0}",
dbi.LastReview);
Console.WriteLine("Remarks: {0}",
dbi.Message);
}
}
P a g e | 144
Visual Programming C#

//iterating through the method attribtues


foreach (MethodInfo m in type.GetMethods()) {

foreach (Attribute a in
m.GetCustomAttributes(true)) {
DeBugInfo dbi = (DeBugInfo)a;

if (null != dbi) {
Console.WriteLine("Bug no: {0}, for
Method: {1}", dbi.BugNo, m.Name);
Console.WriteLine("Developer: {0}",
dbi.Developer);
Console.WriteLine("Last Reviewed: {0}",
dbi.LastReview);
Console.WriteLine("Remarks: {0}",
dbi.Message);
}
}
}
Console.ReadLine();
}
}
}

When the above code is compiled and executed, it produces the


following result −

Length: 4.5
Width: 7.5
Area: 33.75
Bug No: 49
Developer: Nuha Ali
Last Reviewed: 10/10/2012
Remarks: Unused variable
Bug No: 45
Developer: Zara Ali
Last Reviewed: 12/8/2012
Remarks: Return type mismatch
Bug No: 55, for Method: GetArea
P a g e | 145
Visual Programming C#

Developer: Zara Ali


Last Reviewed: 19/10/2012
Remarks: Return type mismatch
Bug No: 56, for Method: Display
Developer: Zara Ali
Last Reviewed: 19/10/2012
Remarks:

C# - Attributes:
An attribute is a declarative tag that is used to convey information
to runtime about the behaviors of various elements like classes,
methods, structures, enumerators, assemblies etc. in your program.
You can add declarative information to a program by using an
attribute. A declarative tag is depicted by square ([ ]) brackets
placed above the element it is used for.

Attributes are used for adding metadata, such as compiler


instruction and other information such as comments, description,
methods and classes to a program. The .Net Framework provides
two types of attributes: the pre-defined attributes and custom
built attributes.

Specifying an Attribute

Syntax for specifying an attribute is as follows −

[attribute(positional_parameters, name_parameter = value, ...)]


element

Name of the attribute and its values are specified within the square
brackets, before the element to which the attribute is applied.
Positional parameters specify the essential information and the
name parameters specify the optional information.

Predefined Attributes

The .Net Framework provides three pre-defined attributes −


P a g e | 146
Visual Programming C#

• AttributeUsage
• Conditional
• Obsolete
AttributeUsage

The pre-defined attribute AttributeUsage describes how a custom


attribute class can be used. It specifies the types of items to which
the attribute can be applied.

Syntax for specifying this attribute is as follows −

[AttributeUsage (
validon,
AllowMultiple = allowmultiple,
Inherited = inherited
)]

Where,

• The parameter validon specifies the language elements on


which the attribute can be placed. It is a combination of the
value of an enumerator AttributeTargets. The default value
is AttributeTargets.All.
• The parameter allowmultiple (optional) provides value for
the AllowMultiple property of this attribute, a Boolean value. If
this is true, the attribute is multiuse. The default is false
(single-use).
• The parameter inherited (optional) provides value for
the Inherited property of this attribute, a Boolean value. If it is
true, the attribute is inherited by derived classes. The default
value is false (not inherited).

For example,

[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
P a g e | 147
Visual Programming C#

AttributeTargets.Property,
AllowMultiple = true)]
Conditional

This predefined attribute marks a conditional method whose


execution depends on a specified preprocessing identifier.

It causes conditional compilation of method calls, depending on the


specified value such as Debug or Trace. For example, it displays the
values of the variables while debugging a code.

Syntax for specifying this attribute is as follows −

[Conditional(
conditionalSymbol
)]

For example,

[Conditional("DEBUG")]

The following example demonstrates the attribute −

#define DEBUG
using System;
using System.Diagnostics;

public class Myclass {


[Conditional("DEBUG")]

public static void Message(string msg) {


Console.WriteLine(msg);
}
}
class Test {
static void function1() {
Myclass.Message("In Function 1.");
function2();
}
static void function2() {
P a g e | 148
Visual Programming C#

Myclass.Message("In Function 2.");


}
public static void Main() {
Myclass.Message("In Main function.");
function1();
Console.ReadKey();
}
}

When the above code is compiled and executed, it produces the


following result −

In Main function
In Function 1
In Function 2
Obsolete:

This predefined attribute marks a program entity that should not be


used. It enables you to inform the compiler to discard a particular
target element. For example, when a new method is being used in a
class and if you still want to retain the old method in the class, you
may mark it as obsolete by displaying a message the new method
should be used, instead of the old method.

Syntax for specifying this attribute is as follows −

[Obsolete (
message
)]

[Obsolete (
message,
iserror
)]

Where,

• The parameter message, is a string describing the reason why


the item is obsolete and what to use instead.
P a g e | 149
Visual Programming C#

• The parameter iserror, is a Boolean value. If its value is true,


the compiler should treat the use of the item as an error.
Default value is false (compiler generates a warning).

The following program demonstrates this −

using System;

public class MyClass {


[Obsolete("Don't use OldMethod, use NewMethod
instead", true)]

static void OldMethod() {


Console.WriteLine("It is the old method");
}
static void NewMethod() {
Console.WriteLine("It is the new method");
}
public static void Main() {
OldMethod();
}
}

When you try to compile the program, the compiler gives an error
message stating −

Don't use OldMethod, use NewMethod instead


Creating Custom Attributes

The .Net Framework allows creation of custom attributes that can


be used to store declarative information and can be retrieved at
run-time. This information can be related to any target element
depending upon the design criteria and application need.

Creating and using custom attributes involve four steps −

• Declaring a custom attribute


• Constructing the custom attribute
• Apply the custom attribute on a target program element
• Accessing Attributes Through Reflection
P a g e | 150
Visual Programming C#

The Last step involves writing a simple program to read through the
metadata to find various notations. Metadata is data about data or
information used for describing other data. This program should use
reflections for accessing attributes at runtime. This we will discuss
in the next chapter.

Declaring a Custom Attribute

A new custom attribute should is derived from


the System.Attribute class. For example,

//a custom attribute BugFix to be assigned to a class and


its members
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]

public class DeBugInfo : System.Attribute

In the preceding code, we have declared a custom attribute


named DeBugInfo.

Constructing the Custom Attribute

Let us construct a custom attribute named DeBugInfo, which stores


the information obtained by debugging any program. Let it store the
following information −

• The code number for the bug


• Name of the developer who identified the bug
• Date of last review of the code
• A string message for storing the developer's remarks

The DeBugInfo class has three private properties for storing the first
three information and a public property for storing the message.
Hence the bug number, developer's name, and date of review are
P a g e | 151
Visual Programming C#

the positional parameters of the DeBugInfo class and the message


is an optional or named parameter.

Each attribute must have at least one constructor. The positional


parameters should be passed through the constructor. The following
code shows the DeBugInfo class −

//a custom attribute BugFix to be assigned to a class and


its members
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]

public class DeBugInfo : System.Attribute {


private int bugNo;
private string developer;
private string lastReview;
public string message;

public DeBugInfo(int bg, string dev, string d) {


this.bugNo = bg;
this.developer = dev;
this.lastReview = d;
}
public int BugNo {
get {
return bugNo;
}
}
public string Developer {
get {
return developer;
}
}
public string LastReview {
get {
return lastReview;
P a g e | 152
Visual Programming C#

}
}
public string Message {
get {
return message;
}
set {
message = value;
}
}
}
Applying the Custom Attribute

The attribute is applied by placing it immediately before its target −

[DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return


type mismatch")]
[DeBugInfo(49, "Nuha Ali", "10/10/2012", Message =
"Unused variable")]
class Rectangle {
//member variables
protected double length;
protected double width;
public Rectangle(double l, double w) {
length = l;
width = w;
}
[DeBugInfo(55, "Zara Ali", "19/10/2012", Message =
"Return type mismatch")]

public double GetArea() {


return length * width;
}
[DeBugInfo(56, "Zara Ali", "19/10/2012")]

public void Display() {


Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
P a g e | 153
Visual Programming C#

C# Serialization:
In C#, serialization is the process of converting object into byte stream so that it can be
saved to memory, file or database. The reverse process of serialization is called
deserialization.

Serialization is internally used in remote applications.

C# SerializableAttribute
To serialize the object, you need to apply SerializableAttribute attribute to the type. If you
don't apply SerializableAttribute attribute to the type, SerializationException exception is
thrown at runtime.

C# Serialization example
Let's see the simple example of serialization in C# where we are serializing the object of
Student class. Here, we are going to use BinaryFormatter.Serialize(stream,
reference) method to serialize the object.

1. using System;
2. using System.IO;
3. using System.Runtime.Serialization.Formatters.Binary;
4. [Serializable]
5. class Student
6. {
7. int rollno;
8. string name;
9. public Student(int rollno, string name)
P a g e | 154
Visual Programming C#

10. {
11. this.rollno = rollno;
12. this.name = name;
13. }
14. }
15. public class SerializeExample
16. {
17. public static void Main(string[] args)
18. {
19. FileStream stream = new FileStream("e:\\sss.txt", FileMode.OpenOrCreate);
20. BinaryFormatter formatter=new BinaryFormatter();
21.
22. Student s = new Student(101, "Ahmad");
23. formatter.Serialize(stream, s);
24.
25. stream.Close();
26. }
27. }

sss.txt:

JConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null


Student rollnoname e Ahmad

As you can see, the serialized data is stored in the file. To get the data, you need to
perform deserialization.

C# Deserialization
In C# programming, deserialization is the reverse process of serialization. It means you
can read the object from byte stream. Here, we are going to
use BinaryFormatter.Deserialize(stream) method to deserialize the stream.
P a g e | 155
Visual Programming C#

C# Deserialization Example
Let's see the simple example of deserialization in C#.

1. using System;
2. using System.IO;
3. using System.Runtime.Serialization.Formatters.Binary;
4. [Serializable]
5. class Student
6. {
7. public int rollno;
8. public string name;
9. public Student(int rollno, string name)
10. {
11. this.rollno = rollno;
12. this.name = name;
13. }
14. }
15. public class DeserializeExample
16. {
17. public static void Main(string[] args)
18. {
19. FileStream stream = new FileStream("e:\\sss.txt", FileMode.OpenOrCreate);
20. BinaryFormatter formatter=new BinaryFormatter();
21.
22. Student s=(Student)formatter.Deserialize(stream);
23. Console.WriteLine("Rollno: " + s.rollno);
P a g e | 156
Visual Programming C#

24. Console.WriteLine("Name: " + s.name);


25.
26. stream.Close();
27. }
28. }

Output:

Rollno: 101
Name: Ahmad

Working with Files & Directories in C#


C# provides the following classes to work with the File system. They
can be used to access directories, access files, open files for reading
or writing, create a new file or move existing files from one location to
another, etc.

Usage Class Name

File is a static class that provides different functionalities like copy, create, move, delete, open for reading or File
/writing, encrypt or decrypt, check if a file exists, append lines or text to a file's content, get last access time, etc.

The FileInfo class provides the same functionality as a static File class. You have more control on how you do FileInfo
read/write operations on a file by writing code manually for reading or writing bytes from a file.

Directory is a static class that provides functionality for creating, moving, deleting and accessing subdirectories. Directory
DirectoryInfo provides instance methods for creating, moving, deleting and accessing subdirectories. DirectoryInfo
Path is a static class that provides functionality such as retrieving the extension of a file, changing the extension Path
of a file, retrieving the absolute physical path, and other path related functionalities.

File
C# includes static File class to perform I/O operation on physical file
system. The static File class includes various utility method to interact
with physical file of any type e.g. binary, text etc.
P a g e | 157
Visual Programming C#

Use this static File class to perform some quick operation on physical
file. It is not recommended to use File class for multiple operations on
multiple files at the same time due to performance reasons. Use
FileInfo class in that scenario.

Important Methods of Static File Class


Usage Method

Appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, AppendAllLines
writes the specified lines to the file, and then closes the file.

Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this AppendAllText
method creates a file, writes the specified string to the file, then closes the file.

Creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file AppendText
does not exist.

Copies an existing file to a new file. Overwriting a file of the same name is not allowed. Copy

Creates or overwrites a file in the specified path. Create

Creates or opens a file for writing UTF-8 encoded text. CreateText

Decrypts a file that was encrypted by the current account using the Encrypt method. Decrypt

Deletes the specified file. Delete

Encrypts a file so that only the account used to encrypt the file can decrypt it. Encrypt

Determines whether the specified file exists. Exists

Gets a FileSecurity object that encapsulates the access control list (ACL) entries for a specified file. GetAccessControl

Moves a specified file to a new location, providing the option to specify a new file name. Move

Opens a FileStream on the specified path with read/write access. Open

Opens a binary file, reads the contents of the file into a byte array, and then closes the file. ReadAllBytes

Opens a text file, reads all lines of the file, and then closes the file. ReadAllLines

Opens a text file, reads all lines of the file, and then closes the file. ReadAllText

Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating Replace
a backup of the replaced file.

Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already WriteAllBytes
exists, it is overwritten.
P a g e | 158
Visual Programming C#

Usage Method

Creates a new file, writes a collection of strings to the file, and then closes the file. WriteAllLines

Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, WriteAllText
it is overwritten.

C# Program to Create a Directory


A directory is a file system that stores file. Now our task is to create a directory
in C#. We can create a directory by using the CreateDirectory() method of the
Directory class. This method is used to create directories and subdirectories in a
specified path. If the specified directory exists or the given path is invalid then
this method will not create a directory. To use CreateDirectory() method we
have to import the system.IO namespace in the program.
Syntax:
public static System.IO.DirectoryInfo CreateDirectory (string path);
Parameter: path is the directory path.
Return: This will return the object of the specified created directory.
Exception: It will throw the following exception:
• IOException: This exception occurs when the directory specified by
path is a file.
• UnauthorizedAccessException: This exception occurs when the caller
does not have the required permission.
• ArgumentException: This exception occurs when the path is prefixed
with, or contains, only a colon character (:).
• ArgumentNullException: This exception occurs when the path is null.
• PathTooLongException: This exception occurs when the specified path,
file name, or both exceed the system-defined maximum length.
• DirectoryNotFoundException: This exception occurs when the
specified path is invalid
• NotSupportedException: This exception occurs when the path contains
a colon character(:) that is not part of a drive label (“D:\”).
P a g e | 159
Visual Programming C#

Example:

• C#

// C# program to illustrate how


// to create directory
using System;
using System.IO;

class GFG{

public static void Main()


{

// Create directory named Sravan in C drive


// Using CreateDirectory() method
Directory.CreateDirectory("C:\\sravan");

Console.WriteLine("Created");
}
}

Output:
Created
P a g e | 160
Visual Programming C#

Garbage Collection in C#
Garbage collection is a memory management technique used in the .NET
Framework and many other programming languages. In C#, the garbage
collector is responsible for managing memory and automatically freeing up
memory that is no longer being used by the application.
The garbage collector works by periodically scanning the application’s memory
to determine which objects are still being used and which are no longer
needed. Objects that are no longer being used are marked for garbage
collection, and their memory is freed up automatically by the garbage collector.

Some of the key features of the garbage collector in C# include:

1. Automatic memory management: With the garbage collector,


developers don’t need to worry about manually allocating or freeing
up memory. The garbage collector takes care of memory
management automatically, which can help reduce the risk of memory
leaks and other issues.
2. Low impact on application performance: The garbage collector runs in
the background and typically has a low impact on application
performance. However, in some cases, garbage collection can cause
brief pauses or slowdowns in the application, particularly when large
amounts of memory need to be freed up at once.
3. Generation-based collection: The garbage collector in C# uses a
generation-based approach to memory management. Objects are
initially allocated in a “young” generation and are moved to an “old”
generation if they survive multiple garbage collection cycles. This
approach helps reduce the amount of time required for garbage
collection, as most objects are collected in the young generation.
4. Finalization: The garbage collector also provides support for
finalization, which is a process that allows objects to perform cleanup
tasks before they are destroyed. Objects with finalizers are moved to
a separate finalization queue, which is processed by the garbage
collector after all other objects have been collected.
Overall, the garbage collector is a powerful and convenient feature of the .NET
Framework that can help simplify memory management in C# applications.
P a g e | 161
Visual Programming C#

While it may cause occasional performance issues, these can generally be


managed with careful design and optimization of the application’s memory
usage.
Automatic memory management is made possible by Garbage Collection in
.NET Framework. When a class object is created at runtime, a certain memory
space is allocated to it in the heap memory. However, after all the actions related
to the object are completed in the program, the memory space allocated to it is
a waste as it cannot be used. In this case, garbage collection is very useful as it
automatically releases the memory space after it is no longer required.
Garbage collection will always work on Managed Heap and internally it has an
Engine which is known as the Optimization Engine. Garbage Collection occurs
if at least one of multiple conditions is satisfied. These conditions are given as
follows:

• If the system has low physical memory, then garbage collection is


necessary.
• If the memory allocated to various objects in the heap memory exceeds
a pre-set threshold, then garbage collection occurs.
• If the GC.Collect method is called, then garbage collection occurs.
However, this method is only called under unusual situations as
normally garbage collector runs automatically.
Phases in Garbage Collection

There are mainly 3 phases in garbage collection. Details about these are given
as follows:
P a g e | 162
Visual Programming C#

1. Marking Phase: A list of all the live objects is created during the
marking phase. This is done by following the references from all the
root objects. All of the objects that are not on the list of live objects
are potentially deleted from the heap memory.
2. Relocating Phase: The references of all the objects that were on the
list of all the live objects are updated in the relocating phase so that
they point to the new location where the objects will be relocated to
in the compacting phase.
3. Compacting Phase: The heap gets compacted in the compacting
phase as the space occupied by the dead objects is released and the
live objects remaining are moved. All the live objects that remain after
the garbage collection are moved towards the older end of the heap
memory in their original order.
Heap Generations in Garbage Collection
The heap memory is organized into 3 generations so that various objects with
different lifetimes can be handled appropriately during garbage collection. The
memory to each Generation will be given by the Common Language
Runtime(CLR) depending on the project size. Internally, Optimization Engine will
P a g e | 163
Visual Programming C#

call the Collection Means Method to select which objects will go into Generation
1 or Generation 2.

• Generation 0 : All the short-lived objects such as temporary variables


are contained in the generation 0 of the heap memory. All the newly
allocated objects are also generation 0 objects implicitly unless they
are large objects. In general, the frequency of garbage collection is
the highest in generation 0.
P a g e | 164
Visual Programming C#

• Generation 1 : If space occupied by some generation 0 objects that are


not released in a garbage collection run, then these objects get
moved to generation 1. The objects in this generation are a sort of
buffer between the short-lived objects in generation 0 and the long-
lived objects in generation 2.
• Generation 2 : If space occupied by some generation 1 objects that are
not released in the next garbage collection run, then these objects get
moved to generation 2. The objects in generation 2 are long lived
such as static objects as they remain in the heap memory for the
whole process duration.
Note: Garbage collection of a generation implies the garbage collection of all
its younger generations. This means that all the objects in that particular
generation and its younger generations are released. Because of this reason,
the garbage collection of generation 2 is called a full garbage collection as all
the objects in the heap memory are.released. Also, the memory allocated to
the Generation 2 will be greater than Generation 1’s memory and similarly the
memory of Generation 1 will be greater than Generation 0’s
memory(Generation 2 > Generation 1 > Generation 0).

Application domains in C#:


C# (C sharp) is a versatile programming language that can be used in various application
domains.

Here are some common application domains where C# is widely used:

Desktop Applications: C# is commonly used for developing Windows desktop applications


using the .NET Framework or .NET Core. It provides a rich set of libraries and frameworks like
Windows Forms (WinForms) and Windows Presentation Foundation (WPF) for creating user-
friendly graphical interfaces.

Web Applications: C# is widely used for building web applications using ASP.NET and
ASP.NET Core frame work. These frameworks allow developers to create dynamic, scalable,
and secure web applications that run Windows servers. C# can be used for server-side
programming, handling HTTP requests and responses, and interacting with databases.

Mobile Applications: With the introduction of Xamarin, a cross-platform mobile


development framework, C# can be used to build native mobile applications for iOS and
Android platforms.
P a g e | 165
Visual Programming C#

Xamarin allows developers to write code in C# and share a significant portion of it across
multiple platforms, reducing development time and effort.

Game Development: C# is a popular language for game development, particularly when


using the Unity game engine. Unity supports C# as its primary scripting language, making it
easier to develop games for various platforms, including PC, consoles, and mobile devices.
C# enables game logic implementations, asset management, and interaction with various
game engine features.

Internet of Things (IoT): C# can be used for developing applications for IoT devices.
Microsoft's Azure IoT platform provides SDKs and tools that allow developers to build IoT
solutions using C#.

With C#, you can connect, control, and monitor IoT devices, as well as process and analyze
data collected from these devices.

Data Analysis and Machine Learning: C# can be utilized for data analysis and machine

learning tasks.Libraries like ML.NET and Accord.NET provide machine learning capabilities in
C#.

ML.NET is a cross-platform, open-source ramework developed by Microsoft for building


custom machine learning models. Accord.NET is a popular third-party library that offers a
wide range of statistical and machineearning algorithms.

Financial Applications: C# is commonly used in the development of financial applications,

including trading platforms, banking software, and accounting systems. C# provides


extensive support for data manipulation, calculations, andintegration with databases,
making it suitable for complex financial operations.

Scientific and Engineering Applications: C# can be applied in scientific and engineering

domains for tasks such as data analysis, simulation, and modeling. Libraries like Math.NET

Numerics provide mathematicalfunctions and linear algebra capabilities, making it easier to

perform complex scientific computations.

Marshal by value and marshal by reference in C#


P a g e | 166
Visual Programming C#

In C#, when working with interop between managed and unmanaged code, the concepts of

"marshal by value" and "marshal by reference" come into play. These concepts determine
how data is passed between managed and unmanaged memory spaces. Let's understand
each of them:

Marshal by Value:
In marshal by value, the actual data is copied from the managed memory to the unmanaged
memory or vice versa. This means that a separate copy of the data is created in each
memory space.

When passing a value type (such as an integer or a struct) by value, it is automatically


marshaled by values. The value is copied from the managed stack to the unmanaged stack
or vice versa.

When passing a reference type (such as a string or an object) by value, a copy of the
reference is passed to the unmanaged code, but the actual object resides in managed
memory. Any modifications made to the object in the unmanaged code will not affect the
original object in the managed code.
In C#, when working with interop between managed and unmanaged code, the concepts of

"marshal by value" and " marshal by reference" come into play. These concepts determine
how data is passed between managed and unmanaged memory spaces. Let's understand
each of them:

Marshal by Value:
In marshal by value, the actual data is copied from the managed memory to the unmanaged
memory or vice versa. This means that a separate copy of the data is created in each
memory space.

When passing a value type (such as an integer or a struct) by value, it is automatically


marshaled by value.The value is copied from the managed stack to the unmanaged stack or
vice versa.

When passing a reference type (such as a string or an object) by value, a copy of the
reference is passed to the unmanaged code, but the actual object resides in managed
memory. Any modifications made to the object in the unmanaged code will not affect the
original object in the managed code.
P a g e | 167
Visual Programming C#

Marshal by Reference:
In marshal by reference, instead of copying the actual data, a reference or pointer to the
data is passed between managed and unmanaged memory. This means that both managed
and unmanaged code work with the same data, and modifications made in one memory
space are visible in the other.

When passing a reference type by reference explicitly, you can use the ref or out keywords
in C#. The reference to the object is passed to the unmanaged code, and any modifications
made to the object in the unmanaged code will be reflected in the managed code as well.

It's important to note that marshal by reference is generally used for specific scenarios
where sharing data across managed and unmanaged code is required, such as using COM
interop or accessing native libraries that expectreferences to data structures.

The choice between marshal by value and marshal by reference depends on the specific
requirements of your code and the interop scenario you are working with. It's important to
consider factors like performance, data consistency, and the need for bi-directional data
updates when deciding which approach to use.

using System;

using System.Runtime.InteropServices;

namespace MarshalExample

// Example struct for marshal by value

[StructLayout(LayoutKind.Sequential)]

public struct Point

public int X;

public int Y;

class Program
P a g e | 168
Visual Programming C#

// Example method for marshal by reference

[DllImport("user32.dll")]

public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);

static void Main(string[] args)

// Marshal by value: Passing a struct by value

Point point = new Point { X = 10, Y = 20 };

Console.WriteLine("Before: X = {0}, Y = {1}", point.X, point.Y);

ModifyPointByValue(point);

Console.WriteLine("After (marshal by value): X = {0}, Y = {1}", point.X, point.Y);

// Marshal by reference: Passing a reference type by reference

string message = "Hello, World!";

Console.WriteLine("Before: Message = {0}", message);

ShowMessageBoxByReference(ref message);

Console.WriteLine("After (marshal by reference): Message = {0}", message);

Console.ReadLine();

static void ModifyPointByValue(Point p)

// Modifying the struct (marshal by value)

p.X = 100;
P a g e | 169
Visual Programming C#

p.Y = 200;

static void ShowMessageBoxByReference(ref string message)

// Calling the MessageBox function from user32.dll (marshal by reference)

MessageBox(IntPtr.Zero, message, "Message", 0);

message = "Modified Message!";

In the above example, we have a struct called Point representing a 2D point. The
ModifyPointByValue method demonstrates marshal by value by accepting a Point struct
parameter and modifying its values. However, the modifications made inside the
method do not affect the original point variable in the Main method.

On the other hand, the ShowMessageBoxByReference method demonstrates marshal by


reference. It uses the MessageBox function from user32.dll via platform invoke (P/Invoke)
to display a message box. The message parameter is passed by reference using the ref
keyword. Any modifications made to the message variable inside the method are
reflected in the original message variable in the Main method.

When you run the code, you'll see that the modifications made in ModifyPointByValue do
not affect the original point struct, while the modifications made in
ShowMessageBoxByReference are visible in the original message string.

Authentication and authorization


Authentication and authorization are two critical concepts in computer security

that play a crucial role in controlling access to resources and ensuring the integrity
P a g e | 170
Visual Programming C#

of a system. Let's understand each concept:

1. Authentication:
Authentication is the process of verifying the identity of a user or entity.

It ensures that the user or entity claiming to be a particular identity is indeed

who they claim to be. Authentication typically involves presenting credentials

such as a username/password combination, digital certificates, biometric data

(fingerprint or facial recognition), or other authentication factors.

Common authentication mechanisms include:

- Username and password: Users provide a username and password

combination to prove their identity.

- Multi-factor authentication (MFA): Users provide multiple authentication

factors, such as a password and a one-time code sent to their mobile device,

to enhance security.

Single Sign-On (SSO): Users authenticate once with a central identity provider

and obtain access to multiple applications without needing to provide credentials

again.

2. Authorization:
Authorization is the process of granting or denying access to specific resources or

functionalities based on the authenticated user's privileges and permissions. Once a

user's identity is authenticated, authorization determines what actions they are allowed

to perform and what data they can access.


P a g e | 171
Visual Programming C#

Authorization mechanisms include:

- Role-based access control (RBAC): Users are assigned roles, and each role is
associated with a set of permissions. Access to resources is granted based on the user's
assigned role.

- Attribute-based access control (ABAC): Access decisions are based on attributes


assigned to users, resources, and environmental conditions.

- Claims-based authorization: Access decisions are based on claims, which are


statements about the authenticated user's identity or attributes.

Authentication and authorization often work together in a layered approach to ensure


secure access to resources. After authentication, the user's identity is established, and
then authorization determines the user's privileges and grants or denies access
accordingly.

It's important to implement robust authentication and authorization mechanisms to


protects sensitive data, prevent unauthorized access, and enforce security policies within
an application or system.
using System;

namespace AuthenticationExample

class Program

static void Main(string[] args)

Console.WriteLine("Enter your username:");

string username = Console.ReadLine();

Console.WriteLine("Enter your password:");

string password = Console.ReadLine();

if (IsValidUser(username, password))
P a g e | 172
Visual Programming C#
{

Console.WriteLine("Authentication successful. Welcome, " + username + "!");

else

Console.WriteLine("Invalid username or password. Authentication failed.");

Console.ReadLine();

static bool IsValidUser(string username, string password)

// Validate the user credentials

// This is a simple hardcoded validation for demonstration purposes.

// In a real-world scenario, you would typically check against a database or user store.

// Check if the username and password match

return (username == "admin" && password == "password");

Certainly! Here's a simple short code example in C# that demonstrates user authorization
based on roles:

using System;

namespace AuthorizationExample

{
P a g e | 173
Visual Programming C#
class Program

static void Main(string[] args)

string username = "admin";

string role = "admin";

if (IsUserInRole(username, role))

Console.WriteLine("Access granted. User has the required role: " + role);

else

Console.WriteLine("Access denied. User does not have the required role: " + role);

Console.ReadLine();

static bool IsUserInRole(string username, string role)

// Check if the user has the required role

// This is a simple hardcoded authorization check for demonstration purposes.

// In a real-world scenario, you would typically check against a user's role or permissions
store.

// In this example, we only allow the user with the username "admin" to have the "admin"
role.

return (username == "admin" && role == "admin");

}
P a g e | 174
Visual Programming C#
}

Configure security in a C#:


To configure security in a C# application, you'll typically need to consider various aspects, such as

authentication, authorization, secure communication, and data protection. The specific configuration
steps will depend on the framework or platform you are using. Here are some general guidelines:

1. Authentication and Authorization:

- Choose an appropriate authentication mechanism based on your application's requirements,

such as username/password, token-based authentication (JWT), or federated authentication (OAuth).

- Configure authentication middleware to handle authentication requests and set authentication


schemes, such as cookie authentication or bearer token authentication.

- Implement user authentication and authorization logic, which may involve integrating with an identity

provider or user store, managing roles and permissions, and enforcing access control policies.

2. Secure Communication:

- Use secure protocols, such as HTTPS, for communication between client and server to ensure data

confidentiality and integrity.

- Obtain and configure an SSL/TLS certificate to enable HTTPS.

- Configure your web server or application hosting environment to enforce HTTPS connections.

3. Data Protection:

- Implement appropriate mechanisms to protect sensitive data, such as personally identifiable

information (PII) or passwords, at rest and in transit.

- Hash and salt passwords before storing them in a database using secure hashing algorithms,

such as bcrypt or Argon2.

- Encrypt sensitive data when storing it or transmitting it over the network, using algorithms like

AES or RSA.
P a g e | 175
Visual Programming C#

- Protect sensitive configuration settings, connection strings, or API keys by using secure storage

mechanisms, such as environment variables or secure configuration files.

4. Input Validation and Sanitization:

- Implement proper input validation and sanitization techniques to prevent common security

vulnerabilities, such as cross-site scripting (XSS) or SQL injection attacks.

- Use parameterized queries or ORMs (Object-Relational Mappers) to mitigate SQL injection


vulnerabilities.

- Apply input validation techniques to sanitize user-provided data and prevent malicious input from
affecting the application's functionality or security.

5. Logging and Monitoring:

- Implement logging mechanisms to record important security events, errors, and suspicious activities.

- Monitor logs and set up security event alerts to detect and respond to potential security incidents.

- Regularly review and analyze logs to identify any security weaknesses or unusual activities.

6. Regular Updates and Patching:

- Stay updated with the latest security patches and updates for your application's dependencies ,
frameworks, libraries, and operating system.

- Regularly review and apply security updates to address any known vulnerabilities or security issues.

Remember that security is a continuous process, and it's essential to conduct regular security
assessments, vulnerability scans, and penetration testing to identify and mitigate potential risks and
threats. Additionally, following security best practices and guidelines specific to your development
framework or platform is crucial to ensure the overall security of your application.

Code access security:


Certainly! Here's a short and simple explanation:

1. Authentication: Authentication is the process of verifying the identity of a user. It ensures


that the user is who they claim to be. For example, when you enter your username and
P a g e | 176
Visual Programming C#

password to log into a website, the website authenticates your credentials to determine
if they are correct.

2. Authorization: Authorization determines what actions or resources a user is allowed to access


once they have been authenticated. It involves checking the permissions and roles assigned to
a user to decide if they have the necessary privileges to perform a specific action or access
certain resources.

3. Secure Communication: Secure communication ensures that data transmitted between a


client and a server is protected from unauthorized access. It typically involves using encryption
and secure protocols, such as HTTPS, to prevent eavesdropping, tampering, or data interception
during transmission.

4. Data Protection: Data protection involves safeguarding sensitive information from unauthorized
access or modification. This can include encrypting data to make it unreadable without the
proper decryption key, securely storing sensitive data in databases, and applying security
measures to prevent data breaches.

5. Input Validation and Sanitization: Input validation and sanitization are techniques used to ensure
that user inputs are safe and reliable. Input validation involves checking user input to ensure it
meets the required format and constraints, while input sanitization involves removing or
neutralizing potentially harmful or malicious content from user input to prevent security
vulnerabilities like cross-site scripting (XSS) or SQL injection attacks.

6. Logging and Monitoring: Logging involves recording important events, errors, or suspicious
activities in an application. It helps in identifying security issues, troubleshooting, and auditing.
Monitoring refers to actively observing and analyzing application logs and system behavior to
detect and respond to potential security threats or incidents.

7. Regular Updates and Patching: Regular updates and patching involve keeping software, libraries,
and dependencies up to date with the latest security patches and fixes. It helps protect against
known vulnerabilities and security weaknesses.
Code Groups:
By understanding and implementing these security concepts and practices, you can enhance
the security of your applications, protect user data, and mitigate potential risks and threats.
P a g e | 177
Visual Programming C#

In C#, code groups are used in the .NET Framework to organize and manage code access
security policies. Code groups provide a way to group assemblies or application code into
logical units and assign security permissions to those groups. Here's a brief explanation and an
example of using code groups:

Explanation: Code groups are part of the .NET Code Access Security (CAS) system, which allows

administrators to define security policies for .NET applications. Code groups are hierarchical and
represent different levels of trust or permissions.

Each code group has a membership condition that determines which assemblies or code fall
under that group. When an assembly or code is loaded, the .NET runtime checks its membership
condition to determine the code group it belongs to. Based on the code group, the appropriate
security permissions are granted or denied.

Example: Here's an example of creating a custom code group and assigning permissions to it

programmatically using C#:

using System;

using System.Security;

using System.Security.Permissions;

using System.Security.Policy;

namespace CodeGroupExample

class Program

static void Main(string[] args)

// Create a new code group with a membership condition

CodeGroup codeGroup = new UnionCodeGroup(new AllMembershipCondition(),

new PolicyStatement(new
PermissionSet(PermissionState.None)));

// Assign permissions to the code group


P a g e | 178
Visual Programming C#

codeGroup.PolicyStatement.AddPermission(new
FileIOPermission(FileIOPermissionAccess.Read,

"C:\\Temp\\"));

// Check if the current assembly belongs to the code group

if (codeGroup.MembershipCondition.Check(new Evidence()))

// Perform actions that require the specified permissions

try

// Access a file in the specified path, which is allowed by the code group's
permissions

string[] files = System.IO.Directory.GetFiles("C:\\Temp\\");

Console.WriteLine("Number of files in C:\\Temp\\: " + files.Length);

catch (SecurityException ex)

Console.WriteLine("Security Exception: " + ex.Message);

else

Console.WriteLine("Assembly does not belong to the code group.");

Console.ReadLine();

}
P a g e | 179
Visual Programming C#

In this example, a code group is created with an AllMembershipCondition, which includes all

assemblies. The code group is then assigned a PolicyStatement that grants read access to files

in the "C:\Temp" directory using the FileIOPermission.

The example checks if the current assembly belongs to the code group by invoking the Check

method on the membership condition. If the assembly belongs to the code group, it performs

actions that require the specified permissions, such as accessing files in the "C:\Temp" directory.

Note that this is a simplified example for demonstration purposes. In practice, code groups are

typically managed and configured using policy files or security configuration tools based on the

specific requirements and complexity of the application.

Evidence in C#:
In C#, `Evidence` is a class that represents information about the origin and integrity of an

assembly. It contains various types of evidence that can be used to make security decisions in

the .NET Framework.

Evidence can include information such as the assembly's digital signature, the zone from

which the assembly originated, the URL from which it was downloaded, and other evidence
types. The `Evidence` class is part of the `System.Security.Policy` namespace and is commonly
used in the context of code access security (CAS) policies to determine the trustworthiness of an
assembly.

Here's a simple example that demonstrates the usage of `Evidence`:

```csharp

using System;

using System.Security;

using System.Security.Policy;
P a g e | 180
Visual Programming C#

namespace EvidenceExample

class Program

static void Main(string[] args)

// Create a new evidence object

Evidence evidence = new Evidence();

// Add evidence to the object

evidence.AddHostEvidence(new Zone(SecurityZone.Internet));

evidence.AddAssemblyEvidence(new StrongName(new System.Reflection.

StrongNamePublicKeyBlob()));

// Check evidence to make a security decision

if (evidence.GetHostEvidence<Zone>()?.SecurityZone == SecurityZone.Internet)

Console.WriteLine("The assembly is from the Internet zone.");

else

Console.WriteLine("The assembly is not from the Internet zone.");

Console.ReadLine();
P a g e | 181
Visual Programming C#

```

In this example, a new `Evidence` object is created. Host evidence is added to the object using

the `AddHostEvidence` method, which adds information about the zone from which the
assembly originated. Assembly evidence is added using the `AddAssemblyEvidence` method,
which can include information like the assembly's strong name.

The example then checks the evidence using the `GetHostEvidence` method to retrieve the host

evidence of type `Zone`. If the security zone is determined to be the Internet zone, it outputs a

corresponding message.

Please note that in modern versions of .NET, such as .NET Core and .NET 5+, the use of

evidence-based security decisions has been largely deprecated in favor of the more flexible

and granular security model known as Security Transparency.

Permissions:
In the context of security and access control in C#, permissions refer to the rights and

privileges granted to code or users to perform certain actions or access specific resources.
Permissions control what an application or user can do within the system and help enforce
security policies.

There are different types of permissions in C# that can be assigned to code or users:

1. Code Access Permissions:

- Code access permissions grant or deny code the ability to perform specific operations,

such as accessing the file system, making network connections, or interacting with system
resources.

- Examples of code access permissions include FileIOPermission, UIPermission,


SocketPermission,
P a g e | 182
Visual Programming C#

SecurityPermission, and EnvironmentPermission.

- Code access permissions are typically defined in the code access security policy.

2. Role-based Permissions:

- Role-based permissions are used to grant or deny access to certain features or functionality

based on the user's role or group membership.

- Role-based permissions are often used in applications where different users have different

levels of access or privileges.

- Examples include granting an "Admin" role permission to perform administrative tasks or

granting a "User" role permission to perform basic operations.

3. Resource Permissions:

- Resource permissions control access to specific resources or objects within an application or


system.

- Resource permissions can be defined at various levels, such as file system permissions,

database permissions, or permissions for specific application features.

- Examples include read, write, execute, delete, or modify permissions on files, folders, or
database tables.

4. User-based Permissions:

- User-based permissions grant or deny access to specific resources or functionality based

on the user's identity.

- User-based permissions are often used in applications where access control needs to be

fine-grained and specific to individual users.

- Examples include granting a specific user permission to access a restricted area of an

application or allowing a user to perform specific actions.

Permissions are typically enforced by the underlying security infrastructure of the operating

system, framework, or application. They are checked at runtime to determine if a particular


action or access request is allowed or denied based on the permissions granted.
P a g e | 183
Visual Programming C#

To assign and manage permissions, various classes and mechanisms are provided by the .NET

Framework, such as the PermissionSet class, SecurityPermission class, PrincipalPermission class,

and Identity-based security mechanisms.

Please note that the specific permissions available and their implementation may vary
depending on the platform, framework version, and security model being used in your
application.

Role-based security:
Role-based security is a common approach to access control and authorization in software
applications. It involves granting permissions and access rights to users based on their assigned
roles or group memberships. Users are assigned to specific roles, and permissions are associated
with those roles rather than individual users. This simplifies the management of access rights
and allows for easier administration and scalability.

Here's a brief overview of how role-based security works:

1. Roles: Roles represent different categories or groups within an application. Examples of roles
can include "Admin," "Manager," "User," or "Guest." Each role has specific privileges and
permissions associated with it.
2. User-Role Assignment: Users are assigned to one or more roles based on their responsibilities
and access requirements. A user can be a member of multiple roles, allowing them to have
different sets of permissions depending on the context.
3. Permission Assignment: Permissions are associated with roles rather than individual users.
Each role is granted a set of permissions that define what actions or resources they can access.
Permissions can include read, write, update, delete, or execute rights on various application
features or resources.
4. Authorization Check: When a user attempts to perform an action or access a resource,
the application checks if the user's assigned roles have the necessary permissions for
that action or resource. If the user's roles have the required permissions, the action is allowed;
otherwise, it is denied.
5. Role Management: The administration of roles and their associated permissions is typically
6. handled by authorized personnel, such as system administrators or application managers.
They can create, modify, or delete roles and adjust the permissions assigned to each role based
on changing requirements.
Role-based security provides several benefits, including:

- Simplified Administration: Roles allow for centralized management of access rights, making

it easier to handle user permissions on a group level rather than individually.


P a g e | 184
Visual Programming C#

- Scalability: As the application grows and more users are added, managing access control

becomes more manageable since permissions are tied to roles rather than individual users.

- Flexibility: Roles can be dynamically assigned or modified based on changing business


requirements, allowing for flexibility in granting or revoking access to features or resources.

- Separation of Concerns: Role-based security separates the definition of permissions from


individual users allowing for better separation of concerns and improved maintainability.

To implement role-based security in a C# application, you would typically use a combination of

authentication mechanisms to identify users and their assigned roles, store role and permission

information in a database or configuration file, and perform authorization checks based on the

user's roles and requested actions.

Frameworks and libraries like ASP.NET Identity, ASP.NET Core Identity, and custom authorization

attributes in ASP.NET MVC provide built-in support for role-based security and make it easier to

implement and manage role-based access control in your application.

Principals and identities:


In the context of security and authentication in software applications, principals and identities

play important roles. They are fundamental concepts that represent the user or entity interacting

with the system and provide information about their identity, roles, and claims.

1. Principal:

- A principal represents the entity (user, system, or service) that is executing an operation or

requesting access to resources.

- It encapsulates the identity and associated information of the entity, such as the user's name,

roles, and claims.


P a g e | 185
Visual Programming C#

- The `IPrincipal` interface in C# represents a principal and provides methods to check the user's

roles and perform authorization checks.

2. Identity:

- An identity represents the core information about the entity's identity, typically the user,

including their unique identifier, username, and authentication method.

- The `IIdentity` interface in C# represents an identity and provides properties to access

information such as the user's name, authentication type, and whether they are authenticated.

3. Authentication:

- Authentication is the process of verifying the identity of an entity, typically a user, to ensure

they are who they claim to be.

- After successful authentication, an identity is created, which represents the authenticated user.

- The `ClaimsIdentity` class in C# is commonly used to represent an authenticated user's

identity and includes claims (attributes) associated with the user, such as roles, permissions,

or custom claims.

4. Authorization:

- Authorization is the process of determining what operations or resources an authenticated

entity (principal) is allowed to access.

- It involves checking the roles, permissions, or claims associated with the principal's identity to

make access control decisions.

- The `ClaimsPrincipal` class in C# represents a principal with an associated identity and

provides methods to check the user's roles, claims, and perform authorization checks.

Here's a simple example that demonstrates the usage of principals and identities:

```csharp

using System;

using System.Security.Claims;
P a g e | 186
Visual Programming C#

using System.Security.Principal;

namespace PrincipalIdentityExample

class Program

static void Main(string[] args)

// Create an identity

IIdentity identity = new GenericIdentity("john.doe@example.com", "Forms");

// Create claims for the identity

Claim[] claims =

new Claim(ClaimTypes.Name, "John Doe"),

new Claim(ClaimTypes.Role, "Admin"),

new Claim(ClaimTypes.Email, "john.doe@example.com"),

};

// Create a claims identity based on the identity and claims

ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, identity.AuthenticationType);

// Create a principal based on the claims identity

IPrincipal principal = new ClaimsPrincipal(claimsIdentity);

// Check if the principal is in the "Admin" role


P a g e | 187
Visual Programming C#

if (principal.IsInRole("Admin"))

Console.WriteLine("The principal is an admin.");

else

Console.WriteLine("The principal is not an admin.");

Console.ReadLine();

```

In this example, a generic identity is created for the user "john.doe@example.com" with an

authentication type of "Forms." Claims are added to the identity, including the user's name,

role ("Admin"), and email. A claims identity is created based on the identity and claims, and

a principal is created using the claims identity.

The example then checks if the principal is in the "Admin" role using the `IsInRole` method.

Depending on the result, it outputs a corresponding message.

Principals and identities provide a foundation for authentication and authorization in many

frameworks and libraries, such as ASP.NET Identity and Windows Identity Foundation (WIF),

allowing you to perform fine-gr.


P a g e | 188
Visual Programming C#

Data Reader:
In ASP.NET, the `DataReader` class is commonly used to retrieve and read data from a data

source in a forward-only and read-only manner. It provides a lightweight and efficient way

to access and process data without loading the entire result set into memory.

Here's a simplified example of using a `DataReader` in an ASP.NET web application:

```csharp

using System;

using System.Data;

using System.Data.SqlClient;

namespace DataReaderExample

public partial class Default : System.Web.UI.Page

protected void Page_Load(object sender, EventArgs e)

if (!IsPostBack)

// Retrieve data from a database using a DataReader

SqlDataReader dataReader = RetrieveDataFromDatabase();

// Bind the data from the DataReader to a GridView control

GridView1.DataSource = dataReader;

GridView1.DataBind();
P a g e | 189
Visual Programming C#

// Close the DataReader after data retrieval

dataReader.Close();

private SqlDataReader RetrieveDataFromDatabase()

string connectionString = "your_connection_string";

string query = "SELECT Id, Name, Email FROM Customers";

SqlConnection connection = new SqlConnection(connectionString);

SqlCommand command = new SqlCommand(query, connection);

connection.Open();

// Execute the query and retrieve a SqlDataReader

SqlDataReader dataReader =
command.ExecuteReader(CommandBehavior.CloseConnection);

return dataReader;

```
P a g e | 190
Visual Programming C#

In this example, the `Page_Load` event is used to retrieve data from a database using a
`DataReader`.

The `RetrieveDataFromDatabase` method establishes a connection to the database, creates a

`SqlCommand` with the query to execute, and opens the connection.

The `ExecuteReader` method is then called on the `SqlCommand` object to execute the query and
return a `DataReader`. The `DataReader` is then bound directly to the GridView control
(`GridView1`) using the

`DataSource` property.

Once the data is bound, the `DataReader` is closed using the `Close` method to release any
associated resources. Please note that you need to replace `"your_connection_string"` with the
actual connection string to your database.

It's important to remember that the `DataReader` operates in a forward-only manner, meaning it

can only iterate over the data in a sequential order. It's suitable for scenarios where you need to

retrieve large result sets or process data row by row without the need to store the entire dataset
in memory.

Additionally, since the `DataReader` keeps an open connection to the database, it's essential to

close the `DataReader` and associated resources properly to release database connections and

prevent resource leaks. The `CommandBehavior.CloseConnection` flag is used when executing the

`ExecuteReader` method to close the connection automatically when the `DataReader` is closed.

Using a `DataReader` requires careful handling of data access and proper disposal of resources to

ensure efficient and secure data retrieval.

Datasets:
In ASP.NET, datasets can be used as a data container to store and manipulate data retrieved from

various data sources, such as databases, XML files, or web services. Datasets provide a
disconnected model, meaning they can operate independently of the underlying data source
once the data is loaded into the dataset. This makes datasets suitable for web applications where
data needs to be cached and manipulated without a continuous connection to the data source.

Here's a simplified example of using datasets in an ASP.NET web application:


P a g e | 191
Visual Programming C#

```csharp

using System;

using System.Data;

using System.Data.SqlClient;

namespace DataSetExample

public partial class Default : System.Web.UI.Page

protected void Page_Load(object sender, EventArgs e)

if (!IsPostBack)

// Retrieve data from a database and populate a dataset

DataSet dataSet = RetrieveDataFromDatabase();

// Bind the dataset to a GridView control

GridView1.DataSource = dataSet.Tables["Customers"];

GridView1.DataBind();

private DataSet RetrieveDataFromDatabase()

string connectionString = "your_connection_string";


P a g e | 192
Visual Programming C#

string query = "SELECT Id, Name, Email FROM Customers";

using (SqlConnection connection = new SqlConnection(connectionString))

SqlCommand command = new SqlCommand(query, connection);

SqlDataAdapter adapter = new SqlDataAdapter(command);

DataSet dataSet = new DataSet();

adapter.Fill(dataSet, "Customers");

return dataSet;

```

In this example, the `Page_Load` event is used to retrieve data from a database and populate

a dataset. The `RetrieveDataFromDatabase` method establishes a connection to the database,

executes a query, and fills the dataset with the results using a `SqlDataAdapter`. The dataset is

then bound to a GridView control (`GridView1`) on the web page using the `DataSource` property.

By binding the dataset to the GridView control, the data is automatically displayed in tabular

format on the web page. The GridView control handles rendering and paging, making it easy

to display and navigate through the data.

Please note that you need to replace `"your_connection_string"` with the actual connection string

to your database.
P a g e | 193
Visual Programming C#

This is a basic example, and in a real-world scenario, you might have more complex data
operations, such as inserting, updating, or deleting data in the dataset and propagating those
changes back to the database. Datasets provide methods and events to facilitate such data
manipulation operations.

It's worth mentioning that with the introduction of newer technologies in ASP.NET, such as Entity

Framework and LINQ to SQL, working directly with datasets is less common. These technologies

offer more advanced and ORM-based approaches for data access and manipulation.

Interacting with XML:


In ASP.NET, interacting with XML data can be done using various XML-related classes provided

by the .NET Framework, such as `XmlDocument`, `XmlReader`, and `XmlWriter`. These classes

allow you to read, write, manipulate, and query XML data.

Here's a simplified example of interacting with XML data in an ASP.NET web application:

```csharp

using System;

using System.Data;

using System.Xml;

namespace XMLInteractionExample

public partial class Default : System.Web.UI.Page

protected void Page_Load(object sender, EventArgs e)

if (!IsPostBack)

{
P a g e | 194
Visual Programming C#

// Load XML data from a file or a string

XmlDocument xmlDocument = new XmlDocument();

xmlDocument.Load(Server.MapPath("~/Data/Customers.xml")); // Path to your XML file

// Query XML data and retrieve customer names

XmlNodeList customerNodes = xmlDocument.SelectNodes("//Customer");

foreach (XmlNode customerNode in customerNodes)

string customerName = customerNode.SelectSingleNode("Name").InnerText;

Console.WriteLine(customerName);

// Modify XML data

XmlNode firstCustomerNode = customerNodes[0];

XmlNode nameNode = firstCustomerNode.SelectSingleNode("Name");

nameNode.InnerText = "Updated Name";

xmlDocument.Save(Server.MapPath("~/Data/Customers.xml")); // Save the modified


XML data

```

In this example, the `Page_Load` event is used to interact with XML data. First, an `XmlDocument`
P a g e | 195
Visual Programming C#

is created and loaded with XML data from a file using the `Load` method. You'll need to provide
the path to your XML file using the `Server.MapPath` method.

Next, the `SelectNodes` method is used to query the XML data and retrieve a collection of
customer nodes. The example demonstrates how to retrieve the customer names by iterating
over the nodes and accessing the `InnerText` property.

You can also modify the XML data by accessing individual nodes and updating their values. In this

example, the first customer node is retrieved from the collection, and the name node is updated
with a new value using the `InnerText` property. Finally, the modified XML data is saved back to
the XML file using the `Save` method.

Please note that you should adjust the paths and filenames according to your specific XML data
and file locations.

This is a basic example, and depending on your requirements, you can perform more advanced

operations with XML data, such as creating XML documents, adding nodes, deleting nodes, and

using XPath or LINQ to XML for querying and manipulating the XML structure.

It's also worth mentioning that with the introduction of newer technologies, like JSON and
RESTful APIs, XML is less commonly used as a data interchange format. However, the .NET
Framework provides robust support for working with XML data when needed.

Trace events and log information:


In ASP.NET, you can trace events and log information using various techniques and tools.

Tracing helps you monitor and debug your application by providing detailed information

about the execution flow, errors, and performance. Logging allows you to record specific

events or messages for later analysis or troubleshooting.

Here are some common approaches for tracing events and logging in ASP.NET:

1. ASP.NET Tracing:

ASP.NET provides built-in tracing capabilities that allow you to enable tracing for specific

pages or the entire application. Tracing generates detailed information, such as method calls,

variable values, and exception details, which can be viewed in trace output or saved to log files.

To enable tracing, you can add the following section to your web.config file:
P a g e | 196
Visual Programming C#

```xml

<system.web>

<trace enabled="true" requestLimit="40" localOnly="false"/>

</system.web>

```

You can then use the `Trace.Write` or `Trace.Warn` methods within your code to output trace

messages. The trace output can be viewed in the browser by appending "?trace=true" to the

URL or accessed through tools like the ASP.NET Trace Viewer.

2. Logging Frameworks:

Utilizing a logging framework is a more robust and flexible approach for logging events and

messages in ASP.NET applications. Logging frameworks, such as log4net, NLog, or Serilog,


provide advanced logging features, including different log levels, log output destinations (file,
database, etc.), and log filtering. These frameworks allow you to log messages with varying
severity levels, categorize logs,and configure log outputs easily.

Here's an example using log4net:

```csharp

using log4net;

public class MyClass

private static readonly ILog log = LogManager.GetLogger(typeof(MyClass));

public void MyMethod()


P a g e | 197
Visual Programming C#

log.Debug("This is a debug message.");

log.Info("This is an info message.");

log.Warn("This is a warning message.");

log.Error("This is an error message.", new Exception("Exception details."));

```

In this example, log4net is used to log messages with different severity levels. You'll need to

configure log4net in your application's configuration file (e.g., web.config) and specify the
desired

output format and destination.

3. Application Insights:

Application Insights is a cloud-based service provided by Microsoft that offers extensive


monitoring, tracing, and logging capabilities for ASP.NET applications. It allows you to collect
telemetry data, including events, exceptions, performance metrics, and logs, and provides rich
visualization and analysis tools. Application Insights can be easily integrated into your ASP.NET
application by adding the necessary configuration and instrumentation code.

To use Application Insights, you typically need to create an Application Insights resource in Azure

and configure your application to send telemetry data to that resource. The instrumentation code
can be added to your application manually or using application-specific NuGet packages.

These are just a few examples of tracing and logging in ASP.NET. The choice of approach
depends on the specific needs of your application and the level of detail and control you require
for event tracing and logging.

(`BooleanSwitch` and `TraceSwitch` classes):


P a g e | 198
Visual Programming C#

The `BooleanSwitch` and `TraceSwitch` classes are part of the `System.Diagnostics` namespace in
.NET. They are used for controlling the behavior of tracing and logging statements based on a
Boolean or trace level switch.

1. `BooleanSwitch`:

The `BooleanSwitch` class allows you to control the execution of tracing or logging statements

based on a Boolean switch value. It can be used to enable or disable certain types of tracing or

logging statements in your application.

Here's an example of using the `BooleanSwitch`:

```csharp

using System.Diagnostics;

public class MyClass

private static readonly BooleanSwitch mySwitch = new BooleanSwitch("MySwitch", "MySwitch

description");

public void MyMethod()

if (mySwitch.Enabled)

// Perform tracing or logging statements

Trace.WriteLine("This is a trace statement.");

}
P a g e | 199
Visual Programming C#

```

In this example, a `BooleanSwitch` named "MySwitch" is created with a description. By

checking the `Enabled` property of the switch, you can conditionally execute the tracing or

logging statements. You can configure the value of the switch in your application's configuration
file (e.g., web.config)

using the `<system.diagnostics>` section:

```xml

<configuration>

<system.diagnostics>

<switches>

<add name="MySwitch" value="true" />

</switches>

</system.diagnostics>

</configuration>

```

By setting the value of the switch to `true` or `false`, you can control whether the tracing or

logging statements within the `if` block are executed.

2. `TraceSwitch`:

The `TraceSwitch` class allows you to control tracing and logging statements based on different

trace levels. It provides finer-grained control over the verbosity of tracing or logging output.

Here's an example of using the `TraceSwitch`:


P a g e | 200
Visual Programming C#

```csharp

using System.Diagnostics;

public class MyClass

private static readonly TraceSwitch mySwitch = new TraceSwitch("MySwitch", "MySwitch


description");

public void MyMethod()

if (mySwitch.TraceInfo)

// Perform tracing or logging statements

Trace.WriteLine("This is an informational trace statement.");

```

In this example, a `TraceSwitch` named "MySwitch" is created with a description. The switch

has different trace levels, such as `TraceError`, `TraceWarning`, `TraceInfo`, `TraceVerbose`, etc.

By checking the corresponding property (e.g., `TraceInfo`), you can conditionally execute the

tracing or logging statements based on the desired trace level.

Similar to the `BooleanSwitch`, you can configure the value of the `TraceSwitch` in your

application's configuration file using the `<system.diagnostics>` section.


P a g e | 201
Visual Programming C#

Both the `BooleanSwitch` and `TraceSwitch` classes are useful for dynamically controlling the

behavior of tracing and logging statements without modifying the code. They allow you to

enable or disable specific types of tracing or logging statements at runtime, which can be

beneficial for troubleshooting, diagnostics, and performance analysis in your application.--------

Debug` class, part of the `System.Diagnostics:

In .NET, the `Debug` class, part of the `System.Diagnostics` namespace, provides functionality

for printing debugging information during development and debugging sessions. It allows you

to add temporary debug statements to your code that can be easily enabled or disabled without

modifying the code itself.

Here's an example of using the `Debug` class to print debugging information:

```csharp

using System;

using System.Diagnostics;

public class MyClass

public void MyMethod()

// Perform some operations


P a g e | 202
Visual Programming C#

Debug.WriteLine("Debugging information: This is a debug statement.");

Debug.WriteLineIf(DateTime.Now.DayOfWeek == DayOfWeek.Friday, "Today is Friday!");

// Continue with the remaining code

```

In this example, the `Debug.WriteLine` method is used to print a debug statement. The statement

will only be displayed when the application is running in debug mode. When running the
application in release mode, these statements are automatically removed by the compiler,
minimizing any impact on performance.

You can also use the `Debug.WriteLineIf` method to conditionally print debug statements

based on a specified condition. In the example, the debug statement "Today is Friday!" will

only be printed if the current day of the week is Friday.

To view the debug output, you can use a variety of tools:

- **Debug Output Window**: When debugging in Visual Studio, the debug statements are

displayed in the "Output" window. Make sure the "Show output from: Debug" option is selected.

- **Debugger attached console**: If your application runs in a console window and the
debugger is attached, the debug statements will be displayed in the console window.

- **Debug listeners**: You can configure the `Debug` class to send the debug output to different

listeners, such as a text file, the Event Log, or a custom listener. This provides flexibility in how you

capture and view the debug information.

Remember to remove or disable debug statements before deploying your application to a

production environment. Leaving debug statements in production code can impact performance

and may expose sensitive information.


P a g e | 203
Visual Programming C#

Using the `Debug` class allows you to easily add and manage debugging statements during

development, helping you diagnose issues and gather valuable information about the execution

of your code.

In .NET, the `Trace` class, part of the

`System.Diagnostics` namespace, allows you to add instrumentation:


and logging statements to your code. Unlike the `Debug` class, which is only active in debug
builds, the `Trace` class remains active even in release builds, allowing you to capture diagnostic
information in production environments.

Here's an example of using the `Trace` class to instrument a release build:

```csharp

using System;

using System.Diagnostics;

public class MyClass

public void MyMethod()

// Perform some operations

Trace.WriteLine("Instrumentation: This is an instrumentation statement.");

Trace.WriteLineIf(DateTime.Now.DayOfWeek == DayOfWeek.Friday, "Today is Friday!");

// Continue with the remaining code


P a g e | 204
Visual Programming C#

```

In this example, the `Trace.WriteLine` method is used to log an instrumentation statement.

The statement will be logged regardless of whether the application is running in debug or

release mode. This allows you to gather diagnostic information in production environments

without impacting performance.

Similar to the `Debug` class, you can use the `Trace.WriteLineIf` method to conditionally log

statements based on a specified condition. In the example, the statement "Today is Friday!"

will only be logged if the current day of the week is Friday.

To view the trace output, you can configure and utilize different trace listeners:

- **Default Trace Listeners**: The default configuration sends trace output to the system's

default trace listener, which can be the console window or the debug output window in Visual
Studio.

- **Custom Trace Listeners**: You can configure the `Trace` class to send trace output to custom

trace listeners, such as a text file, a database, or a remote logging service. This allows you to

capture and store trace information in various formats and locations.

You can configure trace listeners in your application's configuration file (e.g., web.config or
app.config)

using the `<system.diagnostics>` section. The configuration allows you to specify listeners,

set their output options, and define formatting and filtering rules.

Keep in mind that trace statements remain active in release builds, so it's essential to carefully

manage what information is logged and ensure that sensitive data or excessive logging do not
P a g e | 205
Visual Programming C#

impact performance or breach security.

By instrumenting release builds with the `Trace` class, you can gather valuable diagnostic

information in production environments, aiding in troubleshooting, performance monitoring,

and understanding the behavior of your application during real-world usage.

To implement a custom trace listener in .NET, you need to create a class that derives from the

`TraceListener` abstract base class and override its methods to define the behavior of your
custom listener. Here's an example of implementing a custom trace listener:

```csharp

using System.Diagnostics;

public class MyCustomTraceListener : TraceListener

public override void Write(string message)

// Define the behavior to write the trace message

// to your custom destination (e.g., file, database, etc.)

public override void WriteLine(string message)

// Define the behavior to write the trace message with a new line

// to your custom destination (e.g., file, database, etc.)

}
P a g e | 206
Visual Programming C#

```

In the example, the `MyCustomTraceListener` class is derived from `TraceListener`, and the

`Write` and `WriteLine` methods are overridden. These methods are responsible for defining

how the trace messages should be handled and written to your custom destination.

Inside the overridden methods, you can implement the logic to save the trace messages to a file,

a database, or any other desired storage location. You may use file I/O operations, database

connections, or any other mechanism suitable for your custom listener implementation.

Once you have implemented the custom trace listener, you can configure it in your application's

configuration file (e.g., web.config or app.config) using the `<system.diagnostics>` section. Here's

an example of how to configure the custom listener:

```xml

<configuration>

<system.diagnostics>

<trace>

<listeners>

<add name="MyCustomListener" type="Namespace.MyCustomTraceListener,


AssemblyName" />

</listeners>

</trace>

</system.diagnostics>

</configuration>

```

Make sure to replace "Namespace" with the actual namespace of your `MyCustomTraceListener`
P a g e | 207
Visual Programming C#

class, and "AssemblyName" with the name of the assembly where your custom trace listener is
defined.

With the custom listener configured, the trace output generated by your application will be sent

to your custom listener, allowing you to process and store the trace information as desired.

Implementing a custom trace listener gives you the flexibility to route trace output to various

destinations and perform custom operations on the trace messages. This enables you to integrate

with external logging systems, store trace data in databases, or implement custom formatting
and filtering rules based on your specific requirements.

You might also like