Visual Programming C Sharp Notes
Visual Programming C Sharp Notes
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#
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.
• 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.
• 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#
C# Features:
C# is object oriented programming language. It provides a lot of features that are
given below.
• Simple
• Object oriented
• Type safe
• Interoperability
• Component oriented
• 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#
• Using System
• Using namespace
C# Simple Example:
• class Program
• {
• {
• 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#
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#
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#
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#
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#
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 Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Creating and setting the properties of label
this.Controls.Add(l);
// Creating and setting the properties of Button
Mybutton.AutoSize = true;
Mybutton.BackColor = Color.LightBlue;
Mybutton.Padding = new Padding(6);
Mybutton.Font = new Font("French Script MT", 18);
this.Controls.Add(Mybutton);
this.Controls.Add(Mybutton1);
}
}
}
P a g e | 18
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. }
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:
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#
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#
{
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#
void draw();
Console.WriteLine("drawing rectangle...");
Console.WriteLine("drawing circle...");
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...
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#
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#
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.
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).
• Improved colors.
• Improved scalability.
C# code:
mygraphics.Drawline(mypen,4,2,12,6);
mygraphics.DrawRectangle(mypen,100,50,80,40);
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:
Ok
Ok only
Ok Cancel Ok Cancel
Cancel
No
Yes YesNoCancel
Exclaimation.
Critical.
Question.
C# code to use these styles:
{
P a g e | 37
Visual Programming C#
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.
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.
A programmable network has APIs in its infrastructure that developers can use to
program applications and other components to interact directly with the network.
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.
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.
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#
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
rotocolType.Tcp);
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:
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:
6. socket.Send(data);
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:
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
eam, ProtocolType.Tcp);
4. serverSocket.Listen(10);
11. clientSocket.Close();
12. serverSocket.Close();
13.
eam, ProtocolType.Tcp);
22. clientSocket.Close();
Terminologies
Class Library: It is a package or file that contains different namespaces and class definitions that are
used by other programs.
Step 2
Step 3
Step 4
Step 5
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
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.
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. {
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.
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.
• Text Box
• Label
• Button
• ListBox
• Combo Box
• Radio Button
• Checkbox
• Checklistbox
• PictureBox
• ScrollBar
• Date Time Picker
• Progress Bar
• TreeView
• ListView
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.
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.
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.
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.
CursorChanged It is found in TextBox, when the textbox control is removed from the
Control.ControlCollection.
MouseClick A MouseClick event occurs when the mouse clicks the control.
Furthermore, we can also refer to the VB.NET Microsoft documentation to get a complete
list of TextBox properties and events.
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.
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 alignment of text such as centre, bottom, top, left, or right. TextAlign
It is used to get or sets the shortcut menu associated with the Label control. ContextMenu
It is used to set the index value to a label control displayed on the Windows form. ImageIndex
An AutoSizeChanged event occurs in the Label control when the value of AutoSize AutoSizeChanged
property is changed.
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.
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.
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.
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 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
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.
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 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
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
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()
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:
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
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
When the data is bound with a combo box control, a format event is called. Format
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
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 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()
Example:
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 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 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 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 validate whether the specified object is equal to the current object Equals(Object)
in the CheckedListBox or not.
It is used to get the text of the specified item in the CheckedListBox. GetItemText(Object)
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#
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.
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#
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.
Description Events
It occurs when the property of the backcolor is changed in the PictureBox BackColorChanged
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#
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.
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.
It is used to update the ScrollBar control using the Minimum, maximum, and UpdateScrollInfo
the value of LargeChange properties.
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.
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.
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
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.
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#
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.
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#
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.
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#
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.
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.
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#
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 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.
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.
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.
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#
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:
Output:
Now, click on the Click Me button of the Windows Form, it displays the dialog box, as
shown below.
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.
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.
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
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#
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.
Let's create a simple program to display the Color dialog box in the VB.NET Windows
Forms.
ColorDialog.vb
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#
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.
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.
The Equals() method is used to check whether the current or defined object is the same. Equals()
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.
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.
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
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#
Output:
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.
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.
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.
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
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#
Let's create a PrintDialog control in the VB.NET Windows form using the following steps.
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.
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.
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.
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
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 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.
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#
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.
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#
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.
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.
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,
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.
<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”.
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>
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#
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
<httpRuntime>
This section can be used to configure the general runtime settings of the application.
The main two are:
XML
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
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
<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#
<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#
C#
ConfigurationSettings.AppSettings("Emailto");
This can be read very easily accessed from the code-behind as:
C#
There are more ways for using custom configuration sections. Check this
article: CustomConfigurationSection.
• 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.
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();
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:
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.
.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.
Applications of Reflection
Viewing Metadata
using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute {
public readonly string Url;
namespace AttributeAppl {
class Program {
P a g e | 141
Visual Programming C#
HelpAttribute
Example
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)]
class Rectangle {
//member variables
protected double length;
P a g e | 143
Visual Programming C#
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle(4.5, 7.5);
r.Display();
Type type = typeof(Rectangle);
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#
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();
}
}
}
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#
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.
Specifying an Attribute
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
• AttributeUsage
• Conditional
• Obsolete
AttributeUsage
[AttributeUsage (
validon,
AllowMultiple = allowmultiple,
Inherited = inherited
)]
Where,
For example,
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
P a g e | 147
Visual Programming C#
AttributeTargets.Property,
AllowMultiple = true)]
Conditional
[Conditional(
conditionalSymbol
)]
For example,
[Conditional("DEBUG")]
#define DEBUG
using System;
using System.Diagnostics;
In Main function
In Function 1
In Function 2
Obsolete:
[Obsolete (
message
)]
[Obsolete (
message,
iserror
)]
Where,
using System;
When you try to compile the program, the compiler gives an error
message stating −
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.
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#
}
}
public string Message {
get {
return message;
}
set {
message = value;
}
}
}
Applying the Custom Attribute
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.
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:
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#
Output:
Rollno: 101
Name: Ahmad
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.
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
Decrypts a file that was encrypted by the current account using the Encrypt method. Decrypt
Encrypts a file so that only the account used to encrypt the file can decrypt it. Encrypt
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 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.
Example:
• C#
class GFG{
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.
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.
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.
Xamarin allows developers to write code in C# and share a significant portion of it across
multiple platforms, reducing development time and effort.
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#.
domains for tasks such as data analysis, simulation, and modeling. Libraries like Math.NET
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 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 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
[StructLayout(LayoutKind.Sequential)]
public int X;
public int Y;
class Program
P a g e | 168
Visual Programming C#
[DllImport("user32.dll")]
public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);
ModifyPointByValue(point);
ShowMessageBoxByReference(ref message);
Console.ReadLine();
p.X = 100;
P a g e | 169
Visual Programming C#
p.Y = 200;
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.
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.
that play a crucial role in controlling access to resources and ensuring the integrity
P a g e | 170
Visual Programming C#
1. Authentication:
Authentication is the process of verifying the identity of a user or entity.
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
again.
2. Authorization:
Authorization is the process of granting or denying access to specific resources or
user's identity is authenticated, authorization determines what actions they are allowed
- 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.
namespace AuthenticationExample
class Program
if (IsValidUser(username, password))
P a g e | 172
Visual Programming C#
{
else
Console.ReadLine();
// In a real-world scenario, you would typically check against a database or user store.
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
if (IsUserInRole(username, role))
else
Console.WriteLine("Access denied. User does not have the required role: " + role);
Console.ReadLine();
// 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.
}
P a g e | 174
Visual Programming C#
}
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:
- 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
- Configure your web server or application hosting environment to enforce HTTPS connections.
3. Data Protection:
- Hash and salt passwords before storing them in a database using secure hashing algorithms,
- 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
- Implement proper input validation and sanitization techniques to prevent common security
- Apply input validation techniques to sanitize user-provided data and prevent malicious input from
affecting the application's functionality or security.
- 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.
- 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.
password to log into a website, the website authenticates your credentials to determine
if they are correct.
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
using System;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
namespace CodeGroupExample
class Program
new PolicyStatement(new
PermissionSet(PermissionState.None)));
codeGroup.PolicyStatement.AddPermission(new
FileIOPermission(FileIOPermissionAccess.Read,
"C:\\Temp\\"));
if (codeGroup.MembershipCondition.Check(new Evidence()))
try
// Access a file in the specified path, which is allowed by the code group's
permissions
else
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
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
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
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.
```csharp
using System;
using System.Security;
using System.Security.Policy;
P a g e | 180
Visual Programming C#
namespace EvidenceExample
class Program
evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
StrongNamePublicKeyBlob()));
if (evidence.GetHostEvidence<Zone>()?.SecurityZone == SecurityZone.Internet)
else
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
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:
- 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.
- 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
- Role-based permissions are often used in applications where different users have different
3. Resource Permissions:
- Resource permissions can be defined at various levels, such as file system permissions,
- Examples include read, write, execute, delete, or modify permissions on files, folders, or
database tables.
4. User-based Permissions:
- User-based permissions are often used in applications where access control needs to be
Permissions are typically enforced by the underlying security infrastructure of the operating
To assign and manage permissions, various classes and mechanisms are provided by the .NET
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.
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
- 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.
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
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
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
- It encapsulates the identity and associated information of the entity, such as the user's name,
- The `IPrincipal` interface in C# represents a principal and provides methods to check the user's
2. Identity:
- An identity represents the core information about the entity's identity, typically the user,
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
- After successful authentication, an identity is created, which represents the authenticated user.
identity and includes claims (attributes) associated with the user, such as roles, permissions,
or custom claims.
4. Authorization:
- It involves checking the roles, permissions, or claims associated with the principal's identity to
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
// Create an identity
Claim[] claims =
};
if (principal.IsInRole("Admin"))
else
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
The example then checks if the principal is in the "Admin" role using the `IsInRole` method.
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),
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.
```csharp
using System;
using System.Data;
using System.Data.SqlClient;
namespace DataReaderExample
if (!IsPostBack)
GridView1.DataSource = dataReader;
GridView1.DataBind();
P a g e | 189
Visual Programming C#
dataReader.Close();
connection.Open();
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 `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
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.
```csharp
using System;
using System.Data;
using System.Data.SqlClient;
namespace DataSetExample
if (!IsPostBack)
GridView1.DataSource = dataSet.Tables["Customers"];
GridView1.DataBind();
adapter.Fill(dataSet, "Customers");
return dataSet;
```
In this example, the `Page_Load` event is used to retrieve data from a database and populate
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
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.
by the .NET Framework, such as `XmlDocument`, `XmlReader`, and `XmlWriter`. These classes
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
if (!IsPostBack)
{
P a g e | 194
Visual Programming C#
Console.WriteLine(customerName);
```
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.
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
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>
</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
2. Logging Frameworks:
Utilizing a logging framework is a more robust and flexible approach for logging events and
```csharp
using log4net;
```
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
3. Application Insights:
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.
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
```csharp
using System.Diagnostics;
description");
if (mySwitch.Enabled)
}
P a g e | 199
Visual Programming C#
```
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)
```xml
<configuration>
<system.diagnostics>
<switches>
</switches>
</system.diagnostics>
</configuration>
```
By setting the value of the switch to `true` or `false`, you can control whether the tracing or
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.
```csharp
using System.Diagnostics;
if (mySwitch.TraceInfo)
```
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
Similar to the `BooleanSwitch`, you can configure the value of the `TraceSwitch` in your
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
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
```csharp
using System;
using System.Diagnostics;
```
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
- **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
production environment. Leaving debug statements in production code can impact performance
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.
```csharp
using System;
using System.Diagnostics;
```
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
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!"
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
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#
By instrumenting release builds with the `Trace` class, you can gather valuable diagnostic
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;
// Define the behavior to write the trace message with a new line
}
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
```xml
<configuration>
<system.diagnostics>
<trace>
<listeners>
</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.