Vous êtes sur la page 1sur 548

.NET 4.

0 and Visual Studio 2010 Page 1 of 548


D. HARSHA VARDHAN








M Mi ic cr ro os so of ft t

. .N NE ET T F Fr ra am me ew wo or rk k 4 4. .0 0

A
A
n
n
d
d


C
C
#
#
.
.
N
N
E
E
T
T





A
A
u
u
t
t
h
h
o
o
r
r
:
:
M
M
r
r
.
.
H
H
a
a
r
r
s
s
h
h
a
a
V
V
a
a
r
r
d
d
h
h
a
a
n
n






.NET 4.0 and Visual Studio 2010 Page 2 of 548
D. HARSHA VARDHAN

.NET Framework 4.0 and Visual Studio 2010
C#.NET Training Program Schedule
Trainer: D. Harsha Vardhan Duration: 50 Hours

Chapter I: .NET Framework Basics
Hour 1 Introduction to .NET Framework
Page 5
Hour 2 Applications of .NET, Versions of .NET, Advantages of .NET
Page 11
Hour 3 .NET Framework Architecture, FCL, CTS, MSIL, Assemblies, CTS
Page 21
Hour 4 Execution Environment of .NET Apps, CLR
Page 27
Hour 5 Introduction to Visual Studio, Getting Started with Visual Studio 2010
Page 30

Chapter II: C# Language Basics
Hour 6 C# Introduction, Basics of Language, Application Definition Syntax
Page 45
Hour 7 Keywords, System.Console Class, Data Types, Variables, Constants
Page 51
Hour 8 Type Casting, Boxing and Unboxing, Scope of Variables, Operators, Control
Statements, Enumerations
Page 60
Hour 9 Arrays, Command Line Arguments
Page 74

Chapter III: Object Oriented Programming
Hour 10 Introduction to OOP, Access Modifiers, Principles of OOP, Classes, Objects,
Fields, Methods
Page 86
Hour 11 Read-only Fields, Ref parameters, Out parameters, this keyword, Named
Parameters
Page 96
Hour 12 Static Members, Static Classes, Constructors, Destructors, Object Initializer
Page 102
Hour 13 Static Constructors, Method Overloading, Operator Overloading
Page 111
Hour 14 Generics, Properties, Partial Classes
Page 116
Hour 15 Indexer, Inheritance, Sealed Classes, Hiding the Methods, Method
Overriding
Page 130
Hour 16 Abstract Classes and Methods, Interfaces, Structures
Page 146
Hour 17 Extension Methods, Delegates
Page 154





.NET 4.0 and Visual Studio 2010 Page 3 of 548
D. HARSHA VARDHAN


Chapter IV: Utility Programming
Hour 18 Array Class, Math Class, String Class
Page 159
Hour 19 DateTime Structure, Random Class, Collections, Collection Initializer,
PrintDocument Class
Page 171
Hour 20 DriveInfo Class, DirectoryInfo Class
Page 184
Hour 21 FileInfo class, StreamWriter Class, StreamReader class
Page 191
Hour 22 Multi Threading, Anonymous Methods
Page 197
Hour 23 Speech Translation, Memory Management
Page 205
Hour 24 LINQ
Page 211
Hour 25 Exception Handling, EventLog, Break points, Immediate window
Page 220
Hour 26 Assemblies
Page 236


Chapter V: Windows Forms Applications Development using C#
Hour 27 Getting started with Windows Apps
Page 243
Hour 28 Button, Event Handling, The Form class
Page 256
Hour 29 Label, Textbox, Checkbox, Radiobutton, LinkLabel, Picturebox
Page 276
Hour 30 Panel, GroupBox, Listbox, Combobox, TreeView, NumericUpdown,
DomainUpdown, DateTimePicker, MonthCalendar
Page 290
Hour 31 TrackBar, Timer, ProgressBar, MenuStrip, ContextMenuStrip
Page 307
Hour 32 ColorDialog, FontDialog, OpenFileDialog, SaveFileDialog, PrintDialog,
RichTextBox, NotifyIcon
Page 319
Hour 33 TabControl, TreeView, MDI Applications, ToolStrip, StatusStrip,
MessageBox, Adding Controls Programmatically
Page 336
Hour 34 User Controls and Windows Forms Control Library
Page 350
Hour 35 Creating Graphics with GDI+
Page 359






.NET 4.0 and Visual Studio 2010 Page 4 of 548
D. HARSHA VARDHAN


Chapter VI: Data Access using C# with ADO.NET support
Hour 36 SQL Server Basics
Page 367
Hour 37 ADO.NET Basics, ADO.NET Library and ADO.NET Database Connection
Page 378
Hour 38 Sending Commands to the Database using Command Class
Page 388
Hour 39 Retrieving Data using Command and DataReader
Page 400
Hour 40 ADO.NET Disconnected Model using DataAdapter, DataSet, DataTable,
DataRow and DataColumn
Page 416
Hour 41 Working with Stored Procedures and Functions
Page 432
Hour 42 Storing the Connection String in App.config
Page 444

Chapter VII: Database Reports Development using C#
Hour 43 Crystal Reports
Page 447

Chapter VIII: Network Programming using C#
Hour 44 Introduction to Distributed Application Development
Page 454
Hour 45 .NET Remoting
Page 465
Hour 46 .NET Remoting
Page 469
Hour 47 Network communication with Sockets
Page 477

Chapter IX: Windows Services Development using C#
Hour 48 Windows Services Basics, ServiceProcessInstaller, ServiceInstaller,
installutil.exe
Page 483
Hour 49 Development of Windows Services, ChatService Development
Page 485

Chapter X: Package and Deployment
Hour 50 Setup Project Development, Installing and Un-installing the projects
Page 496

Chapter XI: Mini Project

Chapter XII: FAQs





.NET 4.0 and Visual Studio 2010 Page 5 of 548
D. HARSHA VARDHAN



A An n I In nt tr ro od du uc ct ti io on n t to o . .N NE ET T F Fr ra am me ew wo or rk k

The .NET framework is a collection of many small technologies integrated together, to
develop most powerful applications which can be executed anywhere and anytime.
In other words, .NET Framework is a Microsoft's development platform, which is used
for development of software applications.
Its a Network enabled technologies collection. Thats why it was named as .NET.
There is no any abbreviation for .NET.
It can also be considered as Frontend Tool as it is used to develop the frontend
applications.
For the any live project development, we require two tools to be used:
Frontend tool: It is used to develop UI (User Interface), which is actually
visible by the user. The UI can be termed as Application. The limitation of
application is: any frontend application cant store the data. Thats why you
require backend tool to store the necessary data.

Backend tool: It acts as storage mechanism. The data related to the project
will be stored in this backend tool. It allows us to create and store the databases.
Ex: Oracle, SQL Server, My SQL, Sybase, DB2 etc.

It was released by Microsoft Corporation in 2002. At this year, in the programming world,
we have so many languages like Basic, COBOL, Pascal, Fortran, C, C++, VB, VC++ etc.
But if you observe these languages, each and every language is having its own





.NET 4.0 and Visual Studio 2010 Page 6 of 548
D. HARSHA VARDHAN

limitations and boundaries only. To overcome all of the limitations, Microsoft announces
and releases .NET Framework in 2002.
Later, several improvements take place in .NET Framework, which makes it as much
strong, advanced and more efficient platform for building different kinds of software
applications.
It offers visually stunning user experiences, which is mostly required todays competitive
programming world.
It offers much advanced security features never before.
Its not a single language; its a collection of multiple languages and multiple
technologies. Thats why it can be called as platform (by containing multiple languages
and technologies).
.NET Framework:
Languages:
1. VC#.NET Visual C Sharp.NET
2. VB.NET Visual Basic.NET
3. VC++.NET Visual C++.NET
4. VJ#.NET Visual Java Sharp.NET
etc.
Technologies:
1. ASP.NET Active Server Pages.NET
2. ADO.NET ActiveX Data Objects.NET
3. WCF Windows Communication Foundation
4. WPF Windows Presentation Foundation
5. WWF Windows Workflow Foundation
6. AJAX Asynchronous JavaScript And Xml
7. LINQ Language Integrated Query

Language: It acts as interface (mediator) between the programmer and the system. It
offers some rules and regulations for writing the programs. It also offers some library,
which is required for writing the programs. Obviously, the collection of programs is called
as Software.

Technology: It is designed for a particular purpose. For example, for development of
web related applications, you have a technology called ASP.NET. For development of
Introduced in .NET 3.0
Introduced in .NET 3.5





.NET 4.0 and Visual Studio 2010 Page 7 of 548
D. HARSHA VARDHAN

database related applications, you have another technology called ADO.NET. Bu the
technology doesnt offer any specific rules for writing the programs. But it offers some
library. Thats why; a technology cant be implemented individually. It requires a
language for the rules to write the programs.

Features of .NET Framework

Next Generation User Experiences:
.NET offers a Framework for building applications and high-fidelity
experiences in Windows that blend together application UI, documents, and media
content, while exploiting the full power of the computer. WPF (Windows Presentation
Foundation) offers developers support for 2D and 3D graphics, hardware accelerated
effects, scalability to different form factors, interactive data visualization, and
superior content readability.


Seamless and Secured Environment:
Application security is a big deal these days; perhaps the most closely
examined feature of any new application. .NET offers its best secured environment at
run time. So that it is highly impossible to access the .NET application and its related
data by the un-authorized users / hackers.

The assembly (the compiled code of .NET framework) contains the
security information like which categories of users or who can access the class or
method. So that we can say that .NET Framework applications are much secured.

The security can be improved in the ASP.NET Web Sites by Security
models like Integrated Windows Authentication, Microsoft Passport Authentication,
Forms Authentication, and Client Certificate authentication.








.NET 4.0 and Visual Studio 2010 Page 8 of 548
D. HARSHA VARDHAN

Multi Language Support:
.NET provides a multi-language development platform, so you can work
in the programming language you prefer. The Common Language Runtime (A part of
.NET Framework) provides support for 3 Microsoft developed languages and several
other languages from other vendors.

Languages Supported by .NET Framework
Languages from
Microsoft
Visual C#.NET
Visual Basic.NET
Visual C++.NET
Languages from other
vendors
VJ#.NET,
Python.NET,
IronPython.NET,
APL.NET,
Cobol.NET,
Perl.NET,
Pascal.NET,
Component Pascal.NET,
Curriculum.NET,
Eiffel.NET,
Forth.NET,
Fortran.NET,
Haskell.NET,
Mercury.NET,
Mondrian.NET,
Oberon.NET,
RPG.NET,
Scheme.NET,
Small Talk.NET,
Standard ML.NET


Flexible Data Access:
.NET Framework supports flexible accessibility of database data with
ADO.NET (ActiveX Data Objects .NET). ADO.NET is a set of classes that expose data
access services to the .NET programmer. ADO.NET provides a rich set of components
for creating distributed, data-sharing applications. It is an integral part of the .NET
Framework, providing access to relational, XML, and application data.








.NET 4.0 and Visual Studio 2010 Page 9 of 548
D. HARSHA VARDHAN

Superior of all previous languages and technologies:
Microsofts target is to be at the top of all the development technologies
/ languages. Thats why Microsoft designed .NET Framework with more advanced
and superior programming features and standards, such as
Platform independency
Hardware independency
Language independency
Automatic generation of designer code
Multi-threaded programming
Rich OOP features like delegates, interfaces, extension methods,
anonymous types, anonymous methods etc.
Support for mobile application development
etc.



Modules of .NET

1. VC#.NET (Visual C Sharp.NET) (Language)
It is highly used .NET programming
language, used by most of the .NET
programmers.
It borrows some programming features from C and some other
programming features from C++. In addition to these, it borrows few of
the good features of java language.
It is the object oriented programming language.



2. VB.NET (Visual Basic.NET) (Language)
It is the Microsofts recommended
language for beginners of windows
programming.





.NET 4.0 and Visual Studio 2010 Page 10 of 548
D. HARSHA VARDHAN

But in fact, it is used in very few of the projects in the real-time development
world, because most of the programmers usually comes with C and C++
background; hence they feel comfortable with C#.
It borrows some programming features from VB (Visual Basic) language.
It is the object oriented programming language.


3. ASP.NET (Active Server Pages.NET) (Web Technology)
It is the Microsofts web technology.
It is used for web sites development.
It offers much attractive and user friendly
user interfaces in the server side
applications.
It is the new version to another Microsofts technology called ASP (Active
Server Pages), which is a famous web technology before introducing
ASP.NET.
It requires HTML for web page designing.
It requires a .NET language (like C#, VB.NET, VC++.NET etc.) for server
side logic implementation.

4. ADO.NET (ActiveX Data Objects.NET) (Database Technology)
It is the Microsofts database technology.
It offers necessary programming libraries to access
the local / server databases.
It is the new version to another Microsofts
technology called ADO (ActiveX Data Objects),
which is a famous database technology, used with
VB, VC++ and ASP languages.
It requires a .NET language (like C#, VB.NET, VC++.NET etc.) for logic
implementation.





.NET 4.0 and Visual Studio 2010 Page 11 of 548
D. HARSHA VARDHAN

A Ap pp pl li ic ca at ti io on ns s o of f . .N NE ET T
Using .NET Framework, we offered to develop the following types of applications.
1. Console Applications

These applications contains similar user interface to the operating systems like MS-
DOS and UNIX.
Known as C.U.I (Character User Interface) applications.
These are similar to C/C++ applications.
These are smaller in size.
Doesnt contain any graphical features like mouse pointer, colors, fonts, buttons etc.


2. Windows Forms Applications
These applications are designed similar to the Windows operating system.
Known as G.U.I (Graphical User Interface) applications.
Offers graphical features like mouse pointer, colors, fonts, buttons, text boxes etc.





.NET 4.0 and Visual Studio 2010 Page 12 of 548
D. HARSHA VARDHAN



3. Windows Services
A Windows service is a long-running executable application.
These can run only on windows platforms.
These perform specific functions as background process.
Doesnt contain user interface or doesnt require any user interaction.
Windows services can be configured to start when the operating system
is booted and run in the background as long as Windows is running, or they can be
started manually when required.
Examples:
i. Windows Time.
ii. Windows Audio.
iii. Anti-Virus Security.
iv. Database services like SQL Server, My SQL and Oracle etc.
v. Plug and Play.
vi. Battery Power Supply Status on Laptops.
etc.
To see the all the installed windows services on the system, click on Start
Control Panel Administrative Tools Services.





.NET 4.0 and Visual Studio 2010 Page 13 of 548
D. HARSHA VARDHAN



4. Windows Mobile Applications
The Mobile applications can run on the
small devices like Pocket PCs, Smart
phones and mobile devices.
Ex: Mobile based calculators, schedulers,
database manipulation applications etc.














.NET 4.0 and Visual Studio 2010 Page 14 of 548
D. HARSHA VARDHAN

5. Web Sites / Web Applications
These are most frequently used applications by every internet literature.
In modern life every business (commercial) / educational / service oriented
organizations are having their own web sites.
Some other web sites are offering general purpose services that can be used by
anybody like E-Mail, Search Engines, and Blogs etc.
So, there is much demand for these applications in modern software development
industry.
In .NET Framework, the web sites can be developed using the technology called
ASP.NET.
Ex:
i. http://www.yahoo.com/
ii. http://www.google.co.in/
iii. http://www.orkut.com/
iv. http://www.hotmail.com/







.NET 4.0 and Visual Studio 2010 Page 15 of 548
D. HARSHA VARDHAN

6. Web Services
Web Services are simple and easy to understand.
These can be developed using again ASP.NET.
The web services are used to implement SOA (Service Oriented Architecture) in
web applications.
The main purpose of SOA is to implement some interaction between two
applications.
Examples:
i. Online shopping requires credit card authentication, from back web site.
ii. www.way2sms.com accesses the mail services of Yahoo and Gmail.

7. WPF Applications
WPF stands for Windows Presentation Foundation.
WPF Applications are GUI applications similar to Windows Applications.
These Applications support more advanced graphical features like shapes, object
transformation, brushes etc.








.NET 4.0 and Visual Studio 2010 Page 16 of 548
D. HARSHA VARDHAN

W Wh ha at t y yo ou u n ne ee ed d t to o l le ea ar rn n . .N NE ET T
To get started with .NET Programming, the programmer must have
previous knowledge in the following languages.

C
(For General Programming Experience)
C++ (or) OOP Theory
(For Object Oriented Programming Experience)
SQL
(For writing the database queries in ADO.NET)
HTML
(For web page designing in ASP.NET)


P Pr ro om mi is se es s b by y M Mi ic cr ro os so of ft t: :

While introducing .NET Framework, Microsoft Corporation has given a promise to
the software industry to deliver a standard Framework which overcomes the old problems and
along with following:

Multiple platforms: The system runs on a broad range of computers, from servers and
desktop machines, smart phones and cell phones.
Industry standards: The system uses industry standard communication protocols,
such as XML, HTTP, SOAP, and WSDL.
Security: The system can provide a much safer execution environment, which cant be
hacked or robbed by others.






.NET 4.0 and Visual Studio 2010 Page 17 of 548
D. HARSHA VARDHAN

V Ve er rs si io on ns s o of f . .N NE ET T
.NET Framework
Version
Exact Version
Number
Date of Release Visual Studio
.NET Framework 1.0 1.0.3705.0 Feb 13, 2002 Visual Studio.NET 2002
.NET Framework 1.1 1.1.4322.573 April 24, 2003 Visual Studio.NET 2003
.NET Framework 2.0 2.0.50727.42 November 17, 2005 Visual Studio 2005
.NET Framework 3.0 3.0.4506.30 November 06, 2006 [No Visual Studio]
.NET Framework 3.5 3.5.21022.8 November 19, 2007 Visual Studio 2008
.NET Framework 4.0 4.0.30319.0 April 12, 2010 Visual Studio 2010

A Ad dv va an nt ta ag ge es s o of f . .N NE ET T

Supports multiple languages like VC#, VB.NET, VC++.NET, VJ#.NET etc., so that the
programmer can write the code in his/her interested language.
Offers more secured environment never before.
Offers flexible data access with ADO.NET.
Supports to develop windows services and web services, which are necessary to
handle in the live projects in the modern programming world.
Supports to develop applications for small devices like PDAs, smart phones, mobile
phones etc.
Offers Partial platform independency, because it supports to run the .NET
applications on Windows and LINUX platforms with Mono Tool.
Offers easier and faster UI design (with drag and drop technique), when compared with
the languages like Java.





.NET 4.0 and Visual Studio 2010 Page 18 of 548
D. HARSHA VARDHAN

Offers the best debugging tools in the industry, which makes the programmer to easily
fix the bugs.
Offers improved object oriented programming features like properties, sealed
classes, inner classes, delegates, enumerations, collections, interfaces, generics,
extension methods, anonymous types, anonymous methods, lambda expressions, named
parameters etc.
Offers to share and reuse the code among multiple applications very easily, with the
concept of Assemblies.
Offers to write db queries in the programming code itself, using the newly added
querying technology called LINQ (Language Integrated Query), which is introduced in
.NET 3.5.
Offers faster and easier Deployment features, to generate Installer packages for
installing the .NET application on the client systems.
Offers to create multiple threads and also to manage them for creating Multi-Threaded
Applications.
Offers XML support and interaction, which is mostly required in the modern application
development environment.
Supports to create user defined graphics like lines, rectangles, bars, circles etc., very
easily using GDI+ (Graphics Device Interface) concepts.
Offers a new and attractive feature called WPF (Windows Presentation
Foundation), which is built on Vector based graphics and which enables the
programmer to create 2-D and 3-D graphics, animations, games, audio and view players
etc. This is newly added feature in .NET 3.0.
Offers another prestigious feature called WCF (Windows Communication Foundation),
which integrates the several distributed technologies like .NET Remoting, SOAP enabled
web services, named pipes and message queues etc., which helps the programmer to
develop service and network oriented applications using .NET. This is newly added
feature in .NET 3.0.
Support for the most recent web technology called AJAX (Asynchronous JavaScript and
XML) along with ASP.NET. As a result of AJAX, the developer can produce newer
generation user experiences on the web. Ex: www.orkut.com.







.NET 4.0 and Visual Studio 2010 Page 19 of 548
D. HARSHA VARDHAN


. .N NE ET T ( (v vs s) ) J Ja av va a
Microsofts .NET and SUNs Java are strong competitors.
Similarities
Sl.
No
.NET and Java
1
Both of these support to develop console applications, windows applications, web
sites, web services etc.
2
Both use their own intermediate language. Java calls it as byte code and .NET
calls it as MSIL.
3 Both are Object oriented programming languages.
4 Both support Remoting.
5 Both support multi-threading.
6 Both support web related languages like Java Script, XML, CSS etc.
7 Both support the recent web development technology like AJAX.
8
Both support Garbage collection, which automatically clears the un-used
memory.
9
Both support to develop the applications for small devices like PDAs, mobile
phones, smart phones etc.
10 Both offer better security features in their own style.

Differences
Sl.
No
.NET Java
1
It is cost effective. Costs more than
$700 (nearly Rs. 35,000)
It is open source product, which can be
freely downloaded on the Internet.
2 Its a collection of multiple languages Its itself is a language.
3
Its partially platform independent (as
.NET applications can run on
Windows and LINUX operating
systems)
Its fully platform independent.
4
Offers IDE as Visual Studio by
Microsoft.
Doesnt offer any IDE. But other IDEs by
other vendors such as Eclipse etc.
5
Offers easiest and fastest application
development, which indirectly reduces
the cost of the software.
Requires much time for the application
development, which indirectly increases
the cost of the software.
6
Designing the UI is very much easy
with Drag and Drop technique.
UI Design requires much programmers
effort and stress.
7 AJAX is implementation is much easy.
AJAX is implementation is much time
taking process, requires much code to
write.






.NET 4.0 and Visual Studio 2010 Page 20 of 548
D. HARSHA VARDHAN



. .N NE ET T F Fr ra am me ew wo or rk k T Ty yp pe es s: :

The .NET Framework is available in 3 different types:

.NET Framework: This is the general version, required to run .NET applications on
Windows operating system.
.NET Mono Framework: This is required to run .NET applications on other operating
systems like UNIX, LINUX and Solaris etc.
.NET Compact Framework: This is required to run .NET applications on other devices
like PDA (Personal Digital Assistants), Mobile phones and Smart phones.





.NET 4.0 and Visual Studio 2010 Page 21 of 548
D. HARSHA VARDHAN

C Co om mp po on ne en nt ts s o of f . .N NE ET T F Fr ra am me ew wo or rk k

The .NET Framework is simply a collection of two components.

1. FCL (.NET Framework Class Library)
2. CLR (Common Language Runtime)

You can see the .NET Framework Architecture in the following diagram.

1 1. . . .N NE ET T F Fr ra am me ew wo or rk k C Cl la as ss s L Li ib br ra ar ry y ( (F FC CL L) )
The .NET Framework class library contains the necessary library classes that are
needed for development of different types of .NET applications like Console
applications, Windows applications, Windows services, ASP.NET Web sites, ASP.NET
Web Services, Windows Communication Foundation (WCF) applications and Windows
Presentation Foundation (WPF) applications.
The librarys classes are organized using a hierarchy of namespaces.
A namespace is nothing but a collection of classes.





.NET 4.0 and Visual Studio 2010 Page 22 of 548
D. HARSHA VARDHAN

For example, all the classes for performing I/O operations are located in the
System.IO namespace.
All the types (structures and classes) are commonly available for all the .NET
languages. This concept can be called as CTS (Common Type System).



N Na am mi in ng g C Co on nv ve en nt ti io on n

We have to follow these naming conventions for good practice of programming:
1 1. . F Fo or r N Na am me es sp pa ac ce e, , C Cl la as ss se es s, , S St tr ru uc ct tu ur re es s a an nd d M Me et th ho od ds s: :
Each world in the name space should be started with upper case character.
Ex: WebControls, Threading, OleDbClient, InitializeComponent() etc.

2 2. . F Fo or r V Va ar ri ia ab bl le es s a an nd d o ob bj je ec ct ts s: :
This is programmers choice. You can maintain all the characters in lower case (or)
you can also maintain the naming convention recommended for namespaces.
Ex: i, abc, Abc, AbcXyz etc.






.NET 4.0 and Visual Studio 2010 Page 23 of 548
D. HARSHA VARDHAN

T Th he e . .N NE ET T F Fr ra am me ew wo or rk k C Cl la as ss s L Li ib br ra ar ry y ( (F FC CL L) ) A Ar rc ch hi it te ec ct tu ur re e
The .NET Framework Class Library contains the following namespaces.
Note: A namespace is a collection of few classes or namespaces. The inner namespaces, contained by another namespace is
called as sub namespace. The most frequently used namespaces of FCL are listed here.










System
Windows Web Drawing Data Xml Linq Threading IO
Configuration
Printing Forms UI
HtmlControls WebControls
OleDb SqlClient
Text Speech Runtime
Remoting





.NET 4.0 and Visual Studio 2010 Page 24 of 548
D. HARSHA VARDHAN


2 2. . C Co om mm mo on n L La an ng gu ua ag ge e R Ru un n T Ti im me e ( (C CL LR R) )

The Common Language Runtime (CLR) is the agent that manages your .NET
applications at execution time. In other words, CLR is the completely responsible
component of .NET Framework that is responsible to manage the .NET applications at
run time.
In other words, The Common Language Runtime (CLR) is the virtual machine in the
.NET Framework.
It provides core services such as memory management, thread management,
exception handling, security and resource management.
A .NET application is compiled into a bytecode format known as MSIL (Microsoft
Intermediate Language). The MSIL bytecode allows .NET applications to be portable
(at least theoretically) to other platforms because the application is compiled to native
code only during runtime.
During execution, the CLRs JIT (just - in - time) compiles the bytecode into the
processors native code and executes the application.


A As ss se em mb bl li ie es s a an nd d M Mi ic cr ro os so of ft t I In nt te er rm me ed di ia at te e L La an ng gu ua ag ge e ( (M MS SI IL L) )

In .NET, when an application is compiled, into a bytecode called MSIL. That MSIL code
is stored in an assembly. The assembly is contained in one or more PE (portable
executable) files and may end with an EXE or DLL extension.
The assembly contents are:
Byte code The code in MSIL language.
Security Information Information about the users / user types, who can
access the assembly.
Manifest Information about the assembly, such as identification, name,
version, and so on.
Versioning The version number of an assembly.
Metadata Information that describes the types and methods of the assembly.







.NET 4.0 and Visual Studio 2010 Page 25 of 548
D. HARSHA VARDHAN

T Ty yp pe es s o of f A As ss se em mb bl li ie es s

Private Assemblies: The private assemblies are simple types. An assembly that can
be used only within a software application is called as Private assembly. This type of
assemblies contains .exe file extension.
Shared Assemblies: An assembly that can be used by one or more software
applications is called as Shared Assemblies. This type of assemblies contains .dll
(dynamic linking library) file extension.


Example:
To get a better idea of a MSIL file and its content, take a look at the following
example, which has two console applications. One is written in C# and the other is written in
VB.NET.
The following C# code displays the Hello, World message in the
console window:

















The following VB.NET code displays the Hello, World message in the
console window:






using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloWorldCS
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Hello, World!);
Console.ReadLine();
}
}
}

Module Module1
Sub Main()
Console.WriteLine(Hello, World!)
Console.ReadLine()
End Sub
End Module






.NET 4.0 and Visual Studio 2010 Page 26 of 548
D. HARSHA VARDHAN

The Main method of the C# MSIL looks like this:











The Main method of the VB.NET MSIL looks like this:













Conclusion: The Main method of the VB.NET MSIL looks very similar to that of the C#.NETs
MSIL program.

The important thing to note here is that regardless of the language you use to develop your .NET
applications, all .NET applications are compiled to the MSIL bytecode as this example shows.

Note: MSIL can also be called as IL (Intermediate Language) and CIL (Common Intermediate
Language).
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 19 (0x13)
.maxstack 8
IL_0000: nop
IL_0001: ldstr Hello, World!
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: call string [mscorlib]System.Console::ReadLine()
IL_0011: pop
IL_0012: ret
} // end of method Program::Main

.method public static void Main() cil managed
{
.entrypoint
.custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00
00 00 )
// Code size 20 (0x14)
.maxstack 8
IL_0000: nop
IL_0001: ldstr Hello, World!
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: call string [mscorlib]System.Console::ReadLine()
IL_0011: pop
IL_0012: nop
IL_0013: ret
} // end of method Module1::Main






.NET 4.0 and Visual Studio 2010 Page 27 of 548
D. HARSHA VARDHAN

T Th he e R RT TE E ( (R Ru un n T Ti im me e E En nv vi ir ro on nm me en nt t) ) o of f a a . .N NE ET T A Ap pp pl li ic ca at ti io on n



















Code in C#.NET

Code in VB.NET
Code in another .NET
Language
Just-in Time
Compiler
VB.NET Compiler
(vbc)

Another Compiler
MSIL Code

Common Language Run Time

C#.NET Compiler
(csc)
Native Machine Code
01010101010111010
01010101010111010
01010101010111010
01010101010111010



Operating System

Assembly (.exe)





.NET 4.0 and Visual Studio 2010 Page 28 of 548
D. HARSHA VARDHAN

C
C
o
o
m
m
p
p
o
o
n
n
e
e
n
n
t
t
s
s
o
o
f
f
C
C
L
L
R
R

The CLR contains the following components.
Security Manager / Code safety verifier
JIT Compiler
Memory Manager
Garbage Collector
Exception Manager

1 1. . S Se ec cu ur ri it ty y M Ma an na ag ge er r / / C Co od de e S Sa af fe et ty y V Ve er ri if fi ie er r

This is the initial and most component of CLR.
Application security is much more important issues today.
If you analyze this in-depth, we have 3 types of security support by .NET Framework.
A. Evidence Based Security (EBS):
This security feature is meant for protecting entire assembly not to
be accessed by un-authorized users.
The Security Manager component first checks privileges of the
current user that the user is allowed to access the assembly or
not, based on the evidence.
The evidence is nothing but the information about the security
permissions related to the assembly, that resides with in the
assembly.

B. Code Access Security (CAS):
This verifies whether the current user is allowed to perform the
actions written in the MSIL code.
For example, accessing the file system, event log, printing, remote
or network access etc.







.NET 4.0 and Visual Studio 2010 Page 29 of 548
D. HARSHA VARDHAN

2 2. . J JI IT T C Co om mp pi il le er r
As you seen in the diagram of RTE previously, the JIT compiler is responsible for
compiling the MSIL code into the Native code.
The native code is directly understandable by the system hardware.

3 3. . M Me em mo or ry y M Ma an na ag ge er r
The Memory Manager component of CLR, allocates necessary memory for the
variables and objects that are to be used by the application.

4 4. . G Ga ar rb ba ag ge e C Co ol ll le ec ct to or r
This component of CLR de-allocates or cleans-up the un-necessary memory of the
application, after usage automatically.
Instead, in older languages such as C/C++ this kind of component is not available so
that the programmer should free-up the memory explicitly using some code.

5 5. . E Ex xc ce ep pt ti io on n M Ma an na ag ge er r
An exception means Run time error.
This component redirect the processor to execute the catch block or finally block,
whenever an exception is occurred at run time.
We can learn how to write these catch and finally blocks in C#.NET and VB.NET
languages later.






.NET 4.0 and Visual Studio 2010 Page 30 of 548
D. HARSHA VARDHAN

I
I
n
n
t
t
r
r
o
o
d
d
u
u
c
c
i
i
n
n
g
g
V
V
i
i
s
s
u
u
a
a
l
l
S
S
t
t
u
u
d
d
i
i
o
o


About Visual Studio:

Visual Studio is nothing but the Visual IDE (Integrated Development
Environment), which is needed to development applications with .NET Framework.
The IDE integrates three features:
Editor
Compiler (For compilation)
Interpreter (For running the application)
In simple, we can say like .NET Framework is something that is required to run the
.NET applications and which also offers the necessary library and Visual Studio is
something that is required to develop the .NET applications.

Visual Studio Versions:
There are several versions in Visual Studio like Visual Studio 2002, Visual Studio
2003, Visual Studio 2005, Visual Studio 2008, and Visual Studio 2010 (as shown in
the previous table).

Getting started with Visual Studio:
To start with Visual Studio 2010, click Start Programs Microsoft Visual
Studio 2010 Microsoft Visual Studio 2010.





.NET 4.0 and Visual Studio 2010 Page 31 of 548
D. HARSHA VARDHAN















.NET 4.0 and Visual Studio 2010 Page 32 of 548
D. HARSHA VARDHAN

Then the screen appears like this:





















.NET 4.0 and Visual Studio 2010 Page 33 of 548
D. HARSHA VARDHAN

Finally, Visual Studio 2010 will be opened. The initial screens looks like this:






S Sy ys st te em m R Re eq qu ui ir re em me en nt ts s o of f V Vi is su ua al l S St tu ud di io o 2 20 00 08 8

Processor:
Minimum: P-IV
Recommended: Higher than P-IV
RAM:
Minimum: 512 MB
Recommended: 1 GB (or above)
OS:
MS Windows
(XP / 2003 / Vista / 2008 / Windows 7)





.NET 4.0 and Visual Studio 2010 Page 34 of 548
D. HARSHA VARDHAN

Hard disk free space:
4.2 GB (on system drive ( C: ))
Internet Connection (optional)
(To get latest news and updates from Microsofts web site)


S Sy ys st te em m R Re eq qu ui ir re em me en nt ts s o of f V Vi is su ua al l S St tu ud di io o 2 20 01 10 0

Processor:
Minimum: P-IV
Recommended: Higher than P-IV
RAM:
Minimum: 512 MB
Recommended: 1 GB (or above)
OS:
MS Windows
(XP Service Pack 3 / 2003 / Vista / 2008 / Windows 7)
Hard disk free space:
6.3 GB (on system drive ( C: ))
Internet Connection (optional)
(To get latest news and updates from Microsofts web site)





.NET 4.0 and Visual Studio 2010 Page 35 of 548
D. HARSHA VARDHAN

G Ge et tt ti in ng g S St ta ar rt te ed d w wi it th h V Vi is su ua al l S St tu ud di io o 2 20 01 10 0

I I) ) O Op pe en ni in ng g V Vi is su ua al l S St tu ud di io o 2 20 01 10 0
Click on Start Programs Microsoft Visual Studio 2010 Microsoft Visual Studio
2010.
The following screen will be opened.

Initially, the Visual Studio 2010 will be opened along with Start Page.
The start page is nothing but the welcome page, which contains
Logo: A logo of Microsoft Visual Studio 2010 on the top of the start page.
Recent Projects: List of most recently opened projects. If you click on any one,
the project will be opened immediately.
Get started / Guidance and Resources / Latest News: Headlines of visual
studio help for .NET programmers. If you click on any one head line, online help
will be opened (if Internet connection is available).






.NET 4.0 and Visual Studio 2010 Page 36 of 548
D. HARSHA VARDHAN

I II I) ) T Th he e V Vi is su ua al l S St tu ud di io o 2 20 01 10 0 B Ba as si ic cs s
To start programming with Visual Studio, you should know some common terminology
that is used most frequently in Visual Studio.

Project: An application developed in Visual Studio. That may be of different
types such as Console application, Windows application, Windows Service, Web
site etc.

Solution: Collection of one or more projects. Initially, in a solution, one project
will be placed. Later, you can add other projects to it.

Build: Compilation of entire .NET Project (all the files will be compiled at-a-
time).
Class: A collection of data members and methods (member functions).
Ex:









Namespace: Its nothing but a collection of classes. It may also contain sub
namespaces. A project may require implementing at least one or more classes.
Any class cant be defined individually, without a namespace. In .NET, all of the
classes related one application should be defined with a user defined namespace.





class class1
{
int mydatamember;
void mymethod()
{
}
}





.NET 4.0 and Visual Studio 2010 Page 37 of 548
D. HARSHA VARDHAN

Ex:









I II II I) ) C Cr re ea at ti in ng g a a n ne ew w p pr ro oj je ec ct t
To create a new project in Visual Studio, follow the steps given below.

Open Microsoft Visual Studio 2010.
Click on File New Project.

namespace MyApplication
{
class class1
{
}
class class2
{
}
}





.NET 4.0 and Visual Studio 2010 Page 38 of 548
D. HARSHA VARDHAN


In the New Project dialog box, the left side panel displays the list of .NET
languages like
* Visual C#
* Visual Basic
* Visual C++
etc.
The right side panel displays the list of project templates like
* Windows Forms Application
* Class Library
* ASP.NET Web Application
* ASP.NET Web Service Application
* WPF Application
* WPF Browser Application
* Console Application
* WCF Service Application
* Windows Forms Control Library






.NET 4.0 and Visual Studio 2010 Page 39 of 548
D. HARSHA VARDHAN

Select the appropriate language and required project template. For example
select Visual C# and Windows Forms Application.
Provide the following details:
Name: Specifies the name of the project.
Ex: WindowsFormsApplication1.
Location: Specifies the path, in which the project is to be stored.
Solution Name: The actual name of the solution. (By default the
solution will be created with one project, later you can add other
projects to this solution if needed).
Click on OK to confirm. Then the new project will be created.


In the above screen, you can see an empty form created automatically, named as Form1.


I IV V) ) P Pr ro oj je ec ct t D Di ir re ec ct to or ry y S St tr ru uc ct tu ur re e
When we create a new project, some directory structure will be created automatically by
following the below specified rules.





.NET 4.0 and Visual Studio 2010 Page 40 of 548
D. HARSHA VARDHAN

Each solution will be created as a folder.
Each project will be created as a folder, and placed in the solution folder.
All the files related to the project, will be placed in the project folder.
The information about the solution members will be saved in a file called
Solution file and it will be placed in the solution folder. When we double click
on it, that solution will be opened in Visual Studio. The file extension of the
solution file is .sln.
In the same way, the information about the project members will be saved in the
Project file and it will be placed in the project folder. When we double click on
it, that project will be opened in Visual Studio.

You can observe the project directory structure according to our previous example.
Note: First, recollect the project name, project location and solution name from previous
example.

Solution Folder:


Project Folder Solution File





.NET 4.0 and Visual Studio 2010 Page 41 of 548
D. HARSHA VARDHAN

Project Folder:

* bin: This folder contains the EXE file after compiling the project.
* obj: This folder contains the temporary files of the project, while compilation.
* Properties: This folder contains necessary files that contain information about the
settings and resources related to the project.
* WindowsFormsApplication1.csproj (Project File): This file contains the information
about all the files related to the project; When you double click on it, the project will be
opened in Visual Studio.
* Form1.cs: This file contains the executable code of Form1.
* Form1.Designer.cs: This file contains the code related to the design of Form1.
* Program.cs: This file contains the code of Program class with Main() method.






.NET 4.0 and Visual Studio 2010 Page 42 of 548
D. HARSHA VARDHAN

C Co om mp po on ne en nt ts s o of f V Vi is su ua al l S St tu ud di io o I ID DE E
In this section, we make a closer look to the IDE offered by Visual Studio.






1) Menu Bar: This bar contains the available menus in Visual Studio like File, Edit,
View and Project etc.
2) Tool Bars: There are several toolbars in Visual Studio, which contain frequently used
options in Visual Studio.
3) Tabs: Displays tabs; just click to open required tab.
4) Form designer: Used to view and edit the visual design of the form.
5) Code Window: This is where you write actual programming of your application. You
can switch to this view, by right click on the form designer and choosing View Code
(or) by pressing F7 key on the keyboard.
Menu Bar Tool Bars Form Designer Solution Explorer
Toolbox Properties window
Tabs





.NET 4.0 and Visual Studio 2010 Page 43 of 548
D. HARSHA VARDHAN


6) Solution Explorer: Explores the information about the solution and its members.
7) Properties: Displays the available properties and values for the selected solution,
project, form or control; and also allows changing the property values.
8) Other: In addition to the above specified IDE components, some other components are
also available docked at the bottom area of Visual Studio window like Output, Error
List, Command window, Immediate window, Breakpoints. We discuss about these
components whenever required, in upcoming chapters later.

V V) ) C Cr re ea at ti in ng g C Co on ns so ol le e A Ap pp pl li ic ca at ti io on ns s
The console applications are the project types, recommended for the .NET programming
beginners, where you can learn the language features better.

In Microsoft Visual Studio 2010, click on File New Project.
Select the language as Visual C# and select the project template as Console
Application.





.NET 4.0 and Visual Studio 2010 Page 44 of 548
D. HARSHA VARDHAN


Then enter the project name and location (with your choice) and click on OK.







.NET 4.0 and Visual Studio 2010 Page 45 of 548
D. HARSHA VARDHAN

O Ov ve er rv vi ie ew w
Its a programming language, offered by .NET Framework.
It is recommended for both .NET programming beginners and .NET professionals.
This is the mostly used language used by most of the IT companies today.
It derives some programming features from C and C++ also.
It is the object oriented programming language.
It is the case sensitive language.
The programmer, having knowledge in C and C++ can easily understand the
programming in C#.

F Fi il le e E Ex xt te en ns si io on ns s i in n C C# #
Project File Extension: .csproj (means C Sharp Project)
Code File Extension: .cs (means C Sharp)

B Ba as si ic c T Te er rm mi in no ol lo og gy y i in n C C# #
Statement: Its a line in the program.
--------------;
Keyword: Its a reserved word, which has some pre-defined meaning. Ex: void, class,
struct, using, while, do, for, if, else etc.
Data type: Its a keyword, which specifies the type of the data that you are going to
store in a variable or constant. Ex: int, float, char, string etc.
Variable: Its a named memory location, which contains a particular type value and
which value can be changed during the program execution.


Constant: Its a fixed value, which value cant be changed during the program
execution. Ex: 1, 10, a, abcd.
Operator: Its a symbol, which performs some operation. Ex: +, -, *, /, ++ etc.
Condition: Its an expression, which can have a result (True / False).
data_type variable_name;





.NET 4.0 and Visual Studio 2010 Page 46 of 548
D. HARSHA VARDHAN



Array: Its a collection of multiple values, of same data type.
Enumeration: Its a collection of multiple constants. For each constant, one integer
value will be associated automatically, starting from 0.
Class: Its a collection of fields, properties and methods (member functions).







Object: Its an instance to the class. The memory will be allocated for the object only,
not for the class. It is able to access the members of the class. An object can be created
as follows:



Field / Data Member: Its a variable, declared inside of the class.
Property: Its almost all similar to the filed. The additional feature of property is, it
executes some code automatically, whenever the value is changed.
Method / Member Function: A function, defined inside of a class. Its a collection of
few statements. It can receive one or more arguments and can return a value.
Argument / Parameter: A value that can be sent as an input value for the method.
Return value: A value that is given back to the calling portion of the function, as a
result.
Namespace: Its a collection of few classes. A namespace can also contain sub
namespaces.

S Sa am mp pl le e A Ap pp pl li ic ca at ti io on n D De ev ve el lo op pm me en nt t i in n C C# #
Launch Visual Studio 2010.
Create a new Console Application with Visual C# language.
It generates an empty Program class, with Main() method.
Type a simple program as follows:
class <classname>
{
//fields
//properties
//methods
}
classname objname = new classname();
(x == y)





.NET 4.0 and Visual Studio 2010 Page 47 of 548
D. HARSHA VARDHAN





To run the application, simply press F5 key on the keyboard. Then the application will
be executed and output will be as follows.



Application 1: A simple C# program





.NET 4.0 and Visual Studio 2010 Page 48 of 548
D. HARSHA VARDHAN

A A c cl lo os se er r l lo oo ok k a at t t th he e s sy yn nt ta ax x




1 1. . I Im mp po or rt ti in ng g s se ec ct ti io on n: :
This section contains importing statements that are used to import (include or link) the
.NET Framework Class Library (FCL).
This is most similar to the include statements in C language.
Syn:
using namespace;
Note: If the required namespace is a member of another namespace, we have specify
the parent and child namespaces separated with . (dot).
Ex:
using System;
Importing section Namespace Declaration Class Declaration
Main() method





.NET 4.0 and Visual Studio 2010 Page 49 of 548
D. HARSHA VARDHAN

using System.IO;
using System.Data;
etc.

2 2. . N Na am me es sp pa ac ce e d de ec cl la ar ra at ti io on n: :
Here, a user define namespace is to be declared.
Rule: In .NET applications, all the classes related to the project should be declared in
one namespace.
Syn:
namespace namespacename
{

}
Generally, the namespace name will be same as Project name.

2 2. . C Cl la as ss s d de ec cl la ar ra at ti io on n: :
This is to declare the startup class of the project.
In every .NET application (like Console and Windows Application), there should a startup
class. In these applications, the startup class name should be Program. You cant
change it.
A startup class nothing but a class, which contains Main() method.
Syn:
class classname
{

}

3 3. . M Ma ai in n( () ) m me et th ho od d: :
As you know already in C/C++ languages, the Main() method is the Starting Execution
Point of the application.
When the application is executed, the Main() method will be executed first.
This method contains the main logic of the application.





.NET 4.0 and Visual Studio 2010 Page 50 of 548
D. HARSHA VARDHAN

Syn:






Features of Main() Method:
void: It cant return any value unlike other methods. So that, it should be defined with
void keyword.
static: In fact to access any class member, an object should be created. Object can be
created after starting the application only. But to start the application execution, Main()
method is to be called. So that, it should be accessed without creating any object for the
Program class. Thats why you need to declare it as a static method.
string[] args: To receive the command like arguments. A command line argument is
nothing but an argument, which can be passed from the command window, before the
application execution is started.

C Co om mp pi il li in ng g a an nd d R Ru un nn ni in ng g t th he e a ap pp pl li ic ca at ti io on n
Compile:
Click on Build menu Build Solution. (or) Press Ctrl+Shift+B.
Run:
Click on Debug menu Start Debugging. (or) Press F5.


Specifies that Main() is a static method; which
allows to directly call Main() method, without
creating an instance of Program class.
Means no return value
Receives arguments sent
to the Main() method in a
string array format.





.NET 4.0 and Visual Studio 2010 Page 51 of 548
D. HARSHA VARDHAN

I I) ) B Ba as si ic c P Pr ro og gr ra am mm mi in ng g T Te ec ch hn ni iq qu ue es s i in n C C# #

1 1) ) K Ke ey yw wo or rd ds s
You can observe the available keywords in C#.


2 2) ) T Th he e C Co on ns so ol le e c cl la as ss s: :
To implement the UI in the console applications, Microsoft has provided a class called
Console.
Library: System.Console
With the support of properties and
methods of Console class, you can
implement the UI in console
applications.
All the properties and methods of
Console class are static members.
So that you can access them,
without creating any object for that
class.







.NET 4.0 and Visual Studio 2010 Page 52 of 548
D. HARSHA VARDHAN



Properties of Console class
Property Description
Title Specifies the title of the console window.
BackgroundColor Specifies background color of the text.
ForegroundColor Specifies foreground color of the text.
CursorSize Specifies the height of the cursor in the console window. (1-100)

Methods of Console class
Method Description
Clear() Clears the screen.
Beep() Plays a beep sound using PC speaker at run time.
ResetColor() Resets the background and foreground colors to its default state.
Write(string) Displays the specified message on the console window.
WriteLine(string) Same as Write() method, but automatically moves the cursor to the next
line after printing the message.
Write(variable) Displays the value of the given variable.
WriteLine(variable) Displays the value of the given variable along with moving the cursor to
the next line.
Read() Reads a single character on the keyboard and returns its ASCII value.
ReadLine() Reads a string value from the keyboard and returns the entered value (in
string mode only).










.NET 4.0 and Visual Studio 2010 Page 53 of 548
D. HARSHA VARDHAN

3 3) ) C Co om mm me en nt ts s
Single Line Comment:
//comment
Multi Line Comment:
/* comment line 1
comment line 2
comment line 3
*/


























Application 2: Demo on Console class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleClassDemo
{
/*Demo on Console Class*/
class Program
{
static void Main(string[] args)
{
//Output demo
System.Console.WriteLine(".NET Framework is:");
System.Console.Write("C#.NET+");
System.Console.Write("VB.NET+");
System.Console.WriteLine("ASP.NET");

//Input demo
string name;
System.Console.Write("\nEnter your name: ");
name = System.Console.ReadLine();

//clear the screen
System.Console.Clear();

//change the window title
System.Console.Title = "A System.Console class demo";

//play beep sound
System.Console.Beep();





.NET 4.0 and Visual Studio 2010 Page 54 of 548
D. HARSHA VARDHAN













O Ou ut tp pu ut t: :

A Af ft te er r p pr re es ss si in ng g E En nt te er r


4 4) ) S Sk ki ip p w wr ri it ti in ng g t th he e i im mp po or rt te ed d n na am me es sp pa ac ce es s
When you import any namespace, all of the classes of that namespace are implicitly
accessible in the code.
For example, when we import System namespace, all of the classes under System
namespace can be accessed without specifying System..
Ex:
When you import like:
using System;
To access Console class:
System.Console is not required. Console is enough.
//change the cursor size
System.Console.CursorSize = 60;

//background and foreground colors demo
System.Console.BackgroundColor = ConsoleColor.DarkRed;
System.Console.ForegroundColor = ConsoleColor.Yellow;
System.Console.WriteLine("Hello, " + name);

//reset the background and foreground colors
System.Console.ResetColor();
System.Console.WriteLine("Thank you, visit again!");

System.Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 55 of 548
D. HARSHA VARDHAN

5 5) ) D Da at ta a T Ty yp pe es s
C# supports several types of predefined data types. You can observe them in the
following diagram.

You can observe the data types, memory size and ranges in the following table.
Data Type Description Range Bytes
sbyte 8-bit signed integer -128 to 127 1
byte 8-bit unsigned integer 0 to 255 1
short 16-bit signed integer -32,768 to 32,767 2
ushort 16-bit unsigned integer 0 to 65,535 2
int 32-bit signed integer -2,147,483,648 to 2,147,483,647 4
uint 32-bit unsigned integer 0 to 4,294,967,295 4
long 64-bit signed integer
-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
8
ulong 64-bit unsigned integer 0 to 18,446,744,073,709,551,615 8
float Single-precision float 1.510
-45
to 3.410
38
4
double Double-precision float 510
-324
to 1.710
308
8
decimal
Decimal value with
28-significant-digit
precision
1.010
28 to
7.910
28
16
bool Boolean true, false 1
char Unicode character Any one character 2
string Group of characters 2 billion characters
No. of chars X 2
(Initially 0)
object Any type of value ----
Based on the
value








.NET 4.0 and Visual Studio 2010 Page 56 of 548
D. HARSHA VARDHAN

6 6) ) V Va ar ri ia ab bl le es s
Variable declaration:
Syn: datatype variable;
Ex: int x;
Variable declaration along with initialization:
Syn: datatype variable=value;
Ex: int x=10;
Multiple Variable declaration:
Syn: datatype variable1, variable2, variable3,;
Ex: int x,y,z;

Note: When we declare any variable, it should be assigned to a value before its usage.
Otherwise, it causes a compile time error.
Note: + is known as concatenation operator, which can concatenate two similar or
different types of values as a string.
Application 3: Demo on Variables
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Variables
{
class Program
{
static void Main(string[] args)
{
int n = 4561;
Console.WriteLine(n);
decimal a, b, c;
double d1, d2=45.123, d3;
Console.WriteLine("d2 value is " + d2);
string s1;
bool b1 = true;
Console.WriteLine(b1);
string Country = "India";
int States = 28;
Console.WriteLine("Our country is " + Country + ". It has " + States + " states.");





.NET 4.0 and Visual Studio 2010 Page 57 of 548
D. HARSHA VARDHAN




Output:


7 7) ) E Es sc ca ap pe e S Se eq qu ue en nc ce e C Ch ha ar ra ac ct te er rs s
Escape Sequence Description Actual Character
\ Single quotation mark
\ Double quotation mark
\\ Backslash \
\0 Null Null
\b Backspace Backspace
\n New line New line
\t Tab Tab space (8 spaces)







Application 4: Demo on Escape Sequence Characters
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EscapeSequenceCharacters
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This is first line\nThis is second line\nThis is third line.");
Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 58 of 548
D. HARSHA VARDHAN





O Ou ut tp pu ut t: :


8 8) ) C Co on ns st ta an nt ts s
Constants look just like variables, but concept wise, they differ from variables.
The main differences between constants and variables are:
The value of constants cant be changed during the program execution time.
The constants should be initialized at the time of its declaration.
To declare constants,
Syn: const datatype constantname = value;
Ex: const int x=100;








Application 5: Demo on Constants
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Constants
{
//An application, that calculates area of circle
class Program
{
Console.WriteLine("\'C#\' has derived from \"C\" and \"C++\".");
Console.WriteLine("The escape sequence character \\n is used to insert new line.");
Console.WriteLine("One\tTwo\tThree");
Console.WriteLine("An\bt");
Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 59 of 548
D. HARSHA VARDHAN









O Ou ut tp pu ut t: :


static void Main(string[] args)
{
const double PI = 3.14;
Console.WriteLine("Enter r value:");
int r = Convert.ToInt32(Console.ReadLine());
double area = PI * r * r;
Console.WriteLine("Area of circle is " + area);
Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 60 of 548
D. HARSHA VARDHAN

9 9) ) T Ty yp pe e c ca as st ti in ng g
Def: The process of converting the value from one data type to another data type is
called as Casting.
This is of two types.
1. Implicit Casting:
The value can be converted by the compiler automatically, without using any
extra statement.
2. Explicit Casting:
The value can be converted by the programmer using a conversion method.

I Im mp pl li ic ci it t C Ca as st ti in ng g
Implicit casting is possible in the following cases.
Any numerical value from lower to higher type.
Ex: byte to short
short to int
float to double
etc.
Any numerical value from non-decimal type to decimal type.
Ex: int to float
long to double
etc.
The following table shows the all possible implicit conversions supported by C#.









.NET 4.0 and Visual Studio 2010 Page 61 of 548
D. HARSHA VARDHAN

Implicit Casting in C#:


E Ex xp pl li ic ci it t C Ca as st ti in ng g
Explicit casting should be performed in the following cases:
Any numerical value from higher type to lower type.
Any numerical value from decimal type to non-decimal type.
Any value from numerical type to non-numerical type.
Any value from non-numerical type to numerical type.
Syn: (target data type)variable
(target data type)value





Application 6: Demo on Casting
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Casting
{
class Program
{
static void Main(string[] args)
{





.NET 4.0 and Visual Studio 2010 Page 62 of 548
D. HARSHA VARDHAN







O Ou ut tp pu ut t: :


E Ex xp pl li ic ci it t C Ca as st ti in ng g u us si in ng g C Co on nv ve er rs si io on n M Me et th ho od ds s
Explicit casting can also be performed by using the Conversion methods. The System.Convert
class provides several methods to perform explicit casting.
System.Convert.ToSByte(value);
Converts the value into sbyte type.
System.Convert.ToByte(value);
Converts the value into byte type.
System.Convert.ToInt16(value);
Converts the value into short type.
System.Convert.ToUInt16(value);
Converts the value into ushort type.
System.Convert.ToInt32(value);
Converts the value into int type.
int x = 10;
long y = x; //implicit
byte z = (byte)x; //explicit
double p = x; //implicit
int q = (int)p; //explicit
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
Console.WriteLine(p);
Console.WriteLine(q);
Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 63 of 548
D. HARSHA VARDHAN

System.Convert.ToUInt32(value);
Converts the value into uint type.
System.Convert.ToInt64(value);
Converts the value into long type.
System.Convert.ToUInt64(value);
Converts the value into ulong type.
System.Convert.ToSingle(value);
Converts the value into float type.
System.Convert.ToDouble(value);
Converts the value into double type.
System.Convert.ToDecimal(value);
Converts the value into decimal type.
System.Convert.ToChar(value);
Converts the value into char type.
System.Convert.ToString(value);
Converts the value into string type.
System.Convert.ToBoolean(value);
Converts the value into bool type.








Application 7: Demo on Casting with Conversion Methods
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConversionMethods
{
class Program
{
static void Main(string[] args)
{





.NET 4.0 and Visual Studio 2010 Page 64 of 548
D. HARSHA VARDHAN











O Ou ut tp pu ut t: :


I IM MP P N No ot te e: :
By default, C# recognizes all the integer constants as the type of int.
In the same way, C# recognizes all the floating point constants as the type of
double.
There is no ToObject() method to convert a value into object data type.










1 10 0) ) B Bo ox xi in ng g a an nd d U Un nb bo ox xi in ng g

Boxing: Converting a variable value into Object type value implicitly.
Unboxing: Converting the Object type value into variable explicitly (using
conversion methods).



Application 8: Demo on Boxing and Unboxing
int x = 10;
long y = x; //implicit
byte z = Convert.ToByte(x); //explicit
double p = x; //implicit
int q = Convert.ToInt32(p); //explicit
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
Console.WriteLine(p);
Console.WriteLine(q);
char c = 'A';
string s = Convert.ToString(c); //explicit
Console.WriteLine(s);
Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 65 of 548
D. HARSHA VARDHAN






















































































O Ou ut tp pu ut t: :











1 11 1) ) V Va ar ri ia ab bl le e S Sc co op pe es s
A variable scope simply is something, which decides the lifetime of the variable.
The variable scope depends on the place, where the variable is declared in the program.
For example, a variable is declared in if block, is available only within the if block
itself.
To have a better idea on this, we discuss about all available scopes in C#.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BoxingAndUnboxingDemo
{
class Program
{
static void Main(string[] args)
{
int x = 10;

//boxing
Object obj;
obj = x;
Console.WriteLine(obj);

//un-boxing
x = Convert.ToInt32(obj);
Console.WriteLine(x);

Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 66 of 548
D. HARSHA VARDHAN

Scope Description Accessibility Example
1) Class level
scope
A variable declared
within the class.
This is known as data
member, which accessibility is
based on the access modifier
you use. (like private, public
etc.)
class sample
{
private int x;
}
2) Method
level scope
A variable declared
within the method
Accessible only within the
method only.
void sample()
{
int x;
//some code
}
3) Block
level scope
A variable declared
within a block. Ex: if
block, else block, for
block, try block, catch
block etc.
Note: A block can be
specified when you use
curly braces. { }
Accessible only within the
block only.
if (x==y)
{
int x;
//some code
}

Strong Rule to follow: Multiple variables with same name within the same scope
cant be declared anywhere.




1 12 2) ) O Op pe er ra at to or rs s
C# supports different kinds of operators.

Assignment operator
=
Arithmetical / Mathematical operators
+, -, *, /, %
Self Assignment operators
+=, -=, *=, /=
Prefix and Postfix operators
++, --
Relational operators
==, !=, <, >, <=, >=





.NET 4.0 and Visual Studio 2010 Page 67 of 548
D. HARSHA VARDHAN

Logical operators
&&, ||, !
Comment operators
//xxxxxxxxxxxxxx
(or)
/* xxxxxxxxxxx
xxxxxxxxxxx
xxxxxxxxxxx*/

Concatenation Operator
+
Block specification operators
{ }
Method specification operators
( )
Conditional operator
? :
Dynamic memory allocation operator
new





.NET 4.0 and Visual Studio 2010 Page 68 of 548
D. HARSHA VARDHAN

Operator Precedence:

1 13 3) ) F Fl lo ow w C Co on nt tr ro ol l w wi it th h C Co on nt tr ro ol l S St ta at te em me en nt ts s
C# supports several types control statements.
These are almost all similar to C.

T Ty yp pe es s o of f C Co on nt tr ro ol l S St ta at te em me en nt ts s
Branching Control Statements
if
switch-case
break
continue
goto
Looping Control Statements
while
do-while
for





.NET 4.0 and Visual Studio 2010 Page 69 of 548
D. HARSHA VARDHAN


Note: All the syntaxes are same as C/C++. Just for idea, we recollect the syntaxes now.
Implementation Syntax of Control Statements
Branching Control Statements
if
+ Simple if
if (condition)
{
----;
----;
}

+ if-else
if (condition)
{
----;
----;
}
else
{
----;
----;
}

+ else-if
if (condition)
{
----;
----;
}
else if (condition)
{
----;
----;
}
else if (condition)
{
----;
----;
}
else
{
----;
----;
}





.NET 4.0 and Visual Studio 2010 Page 70 of 548
D. HARSHA VARDHAN


+ Nested-if
if (condition)
{
if (condition)
{
----;
----;
}
else
{
----;
----;
}
}
else
{
if (condition)
{
----;
----;
}
else
{
----;
----;
}
}

switch-case
switch (variable)
{
case value1: ---------; break;
case value2: ---------; break;
case value3: ---------; break;
case value4: ---------; break;
default: ---------; break;
}

break
for loop / while loop / do-while loop
{
----------;
----------;
break;
----------;
}






.NET 4.0 and Visual Studio 2010 Page 71 of 548
D. HARSHA VARDHAN

continue
for loop / while loop / do-while loop
{
----------;
----------;
continue;
----------;
}

goto
----------;
----------;
----------;
goto labelname;
----------;
----------;
labelname:
----------;
----------;
----------;


Looping Control Statements
while
initialization;
while (condition)
{
----------;
----------;
----------;
Increment / decrement;
}

do-while
initialization;
do
{
----------;
----------;
----------;
Increment / decrement;
} while(condition);





.NET 4.0 and Visual Studio 2010 Page 72 of 548
D. HARSHA VARDHAN

for
for (initialization; condition; increment/decrement)
{
----------;
----------;
----------;
}

Note: You can also implement nested loops as you implemented in C/C++.

1 14 4) ) E En nu um me er ra at ti io on ns s
An enumeration is a collection of constants. That means you can create your own set of
named constants by using enumerations.
Each constant will have a name with an integer value.
Syntax for Enumeration Declaration:
public enum enumname
{
Constant1 = value1, Constant2 = value2, Constant3 = value3
}
Syntax for usage
enumname.constantname










Application 9: Enumeration Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EnumerationDemo
{
public enum Months
{
January = 1, February = 2, March = 3, April = 4, May = 5, June = 6, July = 7,
August = 8, September = 9, October = 10, November = 11, December = 12
}
class Program
{





.NET 4.0 and Visual Studio 2010 Page 73 of 548
D. HARSHA VARDHAN






O Ou ut tp pu ut t: :


static void Main(string[] args)
{
Console.WriteLine(Months.March);
Console.WriteLine((int)Months.March);
Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 74 of 548
D. HARSHA VARDHAN

1 15 5) ) A Ar rr ra ay ys s
An array is the collection of similar type of values.
Each value in the array is to be called as an element.
The total no. of array elements is called as Array size.

Implementation of Arrays:
+ Single Dimensional Arrays:
Array declaration:
Without initialization:
datatype[] arrayname = new datatype[size];
With initialization:
datatype[] arrayname = {val1,val2,val3,..};
Accessing the elements:
arrayname[index]

+ Double Dimensional Arrays:
Array declaration:
Without initialization:
datatype[,] arrayname = new datatype[rows size,columns size];
With initialization:
datatype[,] arrayname = {{val1,val2,}, {val1,val2,},};
Accessing the elements:
arrayname[row index,column index]



Single-dim
array
Double-dim
array





.NET 4.0 and Visual Studio 2010 Page 75 of 548
D. HARSHA VARDHAN

+ Multi Dimensional Arrays:
Same as Double dimensional arrays, but increase the no. of
dimensions.
Application 10: Demo on Single Dim Arrays
namespace ArrayDemo
{
//Demo on Single-Dim Array.
class Program
{
static void Main(string[] args)
{
//read the no. of students
int n;
Console.Write("Enter no. of students: ");
n = Convert.ToInt32(Console.ReadLine());

//check n value whether it is greater than 0 or not.
if (n > 0)
{
//declare the arrays
string[] Names = new string[n];
int[] Marks = new int[n];
string[] Result = new string[n];

//read student names
Console.WriteLine("\nEnter " + n + " students names:");
for (int i = 0; i < n; i++)
{
Console.Write((i + 1) + ": ");
Names[i] = Console.ReadLine();
}

//read student marks
Console.WriteLine("\nEnter " + n + " students marks:");
for (int i = 0; i < n; i++)
{
Console.Write((i + 1) + ": ");
Marks[i] = Convert.ToInt32(Console.ReadLine());
}

//calculate results
for (int i = 0; i < n; i++)
{





.NET 4.0 and Visual Studio 2010 Page 76 of 548
D. HARSHA VARDHAN

















O Ou ut tp pu ut t: :



if (Marks[i] >= 0 && Marks[i] <= 100)
{
if (Marks[i] >= 80)
Result[i] = "Distinction";
else if (Marks[i] >= 60)
Result[i] = "First Class";
else if (Marks[i] >= 50)
Result[i] = "Second Class";
else if (Marks[i] >= 35)
Result[i] = "Third Class";
else
Result[i] = "Fail";
}
else
Result[i] = "Invalid";
}

//display the student names and marks
Console.WriteLine("\n\nStudent Details:");
for (int i = 0; i < n; i++)
Console.WriteLine((i + 1) + ". " + Names[i] + " - " + Marks[i] + " - " + Result[i]);
}
else
Console.WriteLine("N value can't be zero.");
Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 77 of 548
D. HARSHA VARDHAN



Application 11: Demo on Multi Dim Arrays
namespace MultiDimArrays
{
//Demo on Multi-Dimensional Arrays
class Program
{
static void Main(string[] args)
{
//Single dimensional arrays
int[] x = { 10, 20, 30, 40};
Console.WriteLine("Single dimensional array:");
for (int i = 0; i < x.Length; i++)
Console.Write(x[i] + ", ");
//Double dimensional arrays
int[,] y = { {10, 20}, {30, 40}, {50, 60} };
Console.WriteLine("\n\nDouble dimensional array:");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
Console.Write(y[i, j] + " ");
Console.WriteLine();
}
//Multi dimensional arrays
int[, ,] z = { { { 5, 10 }, { 15, 20 } }, { { 25, 30 }, { 35, 40 } }, { { 45, 50 }, { 55, 60 } } };
Console.WriteLine("\nMulti dimensional array:");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 2; k++)
Console.Write(z[i, j, k] + " ");
Console.WriteLine();
}
Console.WriteLine();
}
Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 78 of 548
D. HARSHA VARDHAN


O Ou ut tp pu ut t: :

f fo or re ea ac ch h L Lo oo op p
One of the most common usages of the for loop is to iterate through a collection of
values (array).
C# offers a simplified and easier syntax of for loop called foreach loop, designed only
for such kind of array iterations.
Syntax:
foreach (datatype variable in arrayname)
{
-----------;
-----------;
}
In the above syntax, the loop will be executed once for each value in the array. For
every iteration, the values of the array will be assigned to the variable.
For example, you take the following for loop.
int[] nums = { 10, 20, 30};
for (int i = 0;i < nums.Length; i++)
{
Console.WriteLine(nums[i]));
}
You can re-write the above example with foreach syntax as follows:
int[] nums = { 10, 20, 30};
foreach (int n in nums)
{
Console.WriteLine(n);
}






.NET 4.0 and Visual Studio 2010 Page 79 of 548
D. HARSHA VARDHAN

Note: The arrayname.Length property gets the size of the array. We discuss about the Array
class in future.


J Ja ag gg ge ed d A Ar rr ra ay ys s

A two-dimensional array is of rectangular size always.
But the jagged arrays are more flexible in sizing them.
They may not be rectangular size.
To declare them, declare the array size in one brackets [size] and then give empty
brackets, because different no. of elements can be stored in each row.












Application 12: Demo on Jagged Arrays
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JaggedArraysDemo
{
class Program
{
static void Main(string[] args)
{
int[][] a = new int[3][];
a[0] = new int[] { 1, 2 };
a[1] = new int[] { 3, 4, 5, 6, 7, 8 };
a[2] = new int[] { 9, 10, 11 };





.NET 4.0 and Visual Studio 2010 Page 80 of 548
D. HARSHA VARDHAN









O Ou ut tp pu ut t: :


1 16 6) ) E Ex xe ec cu ut ti in ng g . .N NE ET T A Ap pp pl li ic ca at ti io on ns s f fr ro om m C Co om mm ma an nd d W Wi in nd do ow w: :
Sometimes, you may require running the .NET applications from Command window
(MS-DOS window).
At that time, follow the below steps:
Click on Start Run.
Type cmd.
Press Enter.
A MS-DOS prompt window will be opened.

for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < a[i].Length; j++)
{
Console.Write(a[i][j] + " ");
}
Console.WriteLine();
}

Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 81 of 548
D. HARSHA VARDHAN

Now, locate the bin folder of the required application, by using the following
commands. For example, let us imagine that there is a project named
ConsoleApplication1 in D: drive.

Now, you got the output as
Welcome to C# Console Programming


1 17 7) ) P Pa as ss si in ng g A Ar rg gu um me en nt ts s t to o M Ma ai in n( () ) M Me et th ho od d
All of the previous examples in the material have been given without any arguments
to the Main() method.
However, when the program is invoked, you can pass some arguments to the Main()
method, if required.
C#s Main() method receives those arguments in string array format, traditionally
called as args (of course, C# allows you change the name also).

Syn: Main(string[] args)

Those arguments could be called as Command line arguments.
You can use these command line arguments for the internal logic in the application.



For example, Let us create this application on D:
Application 13: Demo on Main() method arguments





.NET 4.0 and Visual Studio 2010 Page 82 of 548
D. HARSHA VARDHAN













O Ou ut tp pu ut t: :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArgsDemo
{
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
Console.WriteLine(args.Length + " arguments found. Those are:");
for (int i = 0; i < args.Length; i++)
Console.WriteLine(args[i]);
}
else
Console.WriteLine("No arguments found...");
Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 83 of 548
D. HARSHA VARDHAN

1 18 8) ) M Mu ul lt ti ip pl le e M Ma ai in n( () ) M Me et th ho od ds s
As you know already, Main() method is nothing but the entry point of the application.
Most commonly, a .NET application contains only one Main() method.
If needed, you are supposed to define multiple Main() methods also.
But, at run time, only one Main() method can be specified as Entry Point. This
specification can be changed using the project properties.
To understand better, we start with an example on this.



























Application 14: Demo on Multiple Main() Methods
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MultipleMainMethods
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This is the Main() method in Program class.");
Console.Read();
}
}
class MySample
{
static void Main(string[] args)
{
Console.WriteLine("This is the Main() method in MySample class.");
Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 84 of 548
D. HARSHA VARDHAN

When this program is compiled, the compiler shows 2 compile time errors.

Its because, two Main() methods are found in MySample class and Program class;
So that the compiler cant understand which Main() method is to be used as exact
entry point.
To specify the required entry point, we have to change Startup Object option in the
project properties.
To open the project properties, click on Project menu Properties.
Then the project properties will be opened. Now, observe the Startup Object option.
The Startup Object option contains two options.
(Not Set)
MultipleMainMethods.Program
(MultipleMainMethods is the project name).
Whenever it is set to (Not Set), C# compiler automatically detects the Main()
method, where it is exists. This is the default value in the Startup object option. But
this fails whenever multiple Main() methods are defined.
Now you have to select the required class that contains the desired Main() method as
entry point.





.NET 4.0 and Visual Studio 2010 Page 85 of 548
D. HARSHA VARDHAN


Finally close the properties tab and come to Program.cs tab.
Now run the application.
Then you can get the output from the desired Main() method.






.NET 4.0 and Visual Studio 2010 Page 86 of 548
D. HARSHA VARDHAN

II) Object Oriented Programming Features of C#

I II I. .a a) ) A An n i in nt tr ro od du uc ct ti io on n t to o O Ob bj je ec ct t O Or ri ie en nt te ed d P Pr ro og gr ra am mm mi in ng g: :

Types of Programming Languages:
Structure Oriented Programming Language:
The programming implementation flow depends on structures. That
means you need to create the structures for each data entity. Those
structure members can be created in the individual functions.
Ex: Pascal, C, C++ etc.

Object Oriented Programming Languages:
The programming implementation flow depends on classes. In the
Main() method, you need to create the instances for the classes and
access those methods. These instances are called Objects.
Ex: C++, VC++, Java and all .NET languages.
The OOP is a new type of programming style, introduced in 1980s.

Basic Terminology in OOP Languages:
Class:
A class describes about the logical structure of an object.
That means it describes about the data to be stored in the in an object
and also some operations, that are to be performed on that data.
No memory will be allocated for the class.
In other words, a class is used to classify the objects.
Syn:
class classname
{
//fields
//properties
//methods
}







.NET 4.0 and Visual Studio 2010 Page 87 of 548
D. HARSHA VARDHAN

Field / Data Member:
A variable, declared inside of the class is called as field / data
member.
The fields are used to store the data values.

Property:
Its an extension to the field, which automatically performs the specified
code, whenever its value is changed.

Method / Member function:
Its also called as operation / member function.
A method is nothing but a function, which is defined inside of the class.
It is used to perform some process on the data members.

Object:
Its an instance of the class.
Its required because, no memory will be allocated for the class, so that
you cant store any data and you cant call any operation.
It is similar to structure variables, which is declared for the structure.
The actual memory will be allocated for the object, which includes with
all the data members.
The object can access the members that are defined in the class.












Object1
class employee
employee id
name
phone
address
salary
tax
net_salary

getdetails()
displaydetails()
calculate_net_salary()
Object2
Object3





.NET 4.0 and Visual Studio 2010 Page 88 of 548
D. HARSHA VARDHAN

By default, the objects are isolated. That means there is no any relation
between the data stored in one object and another object.




















C C+ ++ + ( (v vs s) ) C C# #

In C++, the class definition syntax should end with ; whereas in C#, its not required.
In C++, we have private section, public section and protected section separately. But in
C#, there no such kind of sections and the access modifier should be specified for each
member of the class.
In C++, it is not possible to initialize the data members in the class definition. But
whereas in C#, it is possible.
In C++, there is provision to declare the member functions inside the class and then
write the definitions of those member functions outside of the class. But in C#, there is
no such kind of provision. The methods should be defined inside of the class definition
only.
In C++, 3 access modifiers (private, protected and public) only supported. But in C#, 5
access modifiers are supported (private, protected, public, internal, protected internal).
Object1
employee id = 101
name = abc
phone = 9934839328
address = hyd
salary = 9390
tax = 782
net_salary = 8608
Object2
employee id = 102
name = xyz
phone = 9834832821
address = pune
salary = 7800
tax = 450
net_salary = 7350
Object3
employee id = 103
name = pqr
phone = 7839403200
address = chennai
salary = 10380
tax = 1270
net_salary = 9110





.NET 4.0 and Visual Studio 2010 Page 89 of 548
D. HARSHA VARDHAN


I II I. .b b) ) P Pr ri in nc ci ip pl le es s o of f O Ob bj je ec ct t O Or ri ie en nt te ed d P Pr ro og gr ra am mm mi in ng g: :

1) Data Encapsulation / Data Binding
2) Data Abstraction
3) Data Hiding / Security
4) Polymorphism
5) Inheritance

1) Data Encapsulation / Data Binding:
This is the default nature of a class.
A class encapsulates (combines) some data values (fields or properties) and
some operations (methods) related to the data as a pack.
This nature can be called as Data Encapsulation.

2) Data Abstraction:
The nature of instance creation is called as Data Abstraction.
This feature is taken from structures in C languages. (In C language you can
create any no. of structure variables based on one structure. The structure
variables act as instances for the structure).
In the same way, you can create any no. of instances (objects) for a class.

3) Data Hiding / Security:
This feature is not available in C language; introduced in OOP.
By default, all the members of the class will be hidden. So that, those are not
accessible from the object (generally the objects will be created outside of the
class).
Of course, if you want to permit the object to access the class members from
outside of the class, you can give permission.
These permissions can be given using the access modifiers.





.NET 4.0 and Visual Studio 2010 Page 90 of 548
D. HARSHA VARDHAN

Access Modifiers:
1. private: The private members are accessible within the self
class only; not accessible in outside of the class.
2. protected: This is similar to private. The protected members
are accessible within the self class and also in respective derived
classes. This is useful in inheritance.
3. public: The public members are accessible any where. This
offers un-limited accessibility.
4. internal: This is similar to public. The internal members are
accessible any where within the current project.
5. protected internal: This is similar to internal. These
members are accessible in the current project and also in the
classes of other projects, which are derived from the current
working class.
Access Modifier
In the same
class
In derived
classes
In other
classes
In derived
classes
In other
classes
private - X X X X
protected - - X X X
public - - - - -
internal - - - X X
protected internal - - - - X
In the same project In other projects

Note: X = Not Accessible
- = Accessible

Rule to follow: According to the nature of data hiding, it recommends us to define the fields as
private members and methods as public members.
So that finally the object can perform only the allowed operations (defined by the methods);
cant perform other operations.






.NET 4.0 and Visual Studio 2010 Page 91 of 548
D. HARSHA VARDHAN

4) Polymorphism:
The decision making capacity of the compiler is called Polymorphism.
It is of two types:
1) Compile-time Polymorphism:
The decision can be made at the time of compilation.
This can be implemented with two concepts:
i) Method Overloading: You can write multiple
methods with same name within the same class.
ii) Operator Overloading: You can write multiple
definitions for the same operator.

2) Run-time Polymorphism:
The decision can be made at run time.
This can be implemented with two concepts:
i) Templates / Generics: You can pass any type of
value as an argument to a method.
ii) Interfaces: Contains method declarations only,
doesnt contain method definitions.



5) Inheritance:
The process of creating a new class that derives all the features of another
existing class is called as Inheritance.
In other words, we can extend the features of a class.












Super class / Base class
Sub class / Derived class
Inherit





.NET 4.0 and Visual Studio 2010 Page 92 of 548
D. HARSHA VARDHAN

I II I. .c c) ) O OO OP P D De ev ve el lo op pm me en nt t

i) Class Definition Syntax:

class classname
{
//fields
//properties
//methods
}


ii) Fields Declaration Syntax:

accessmodifier functionalModifier datatype variablename;
(or)
accessmodifier functionalModifier datatype variablename = value;


Note 1: We cover about Properties syntax in further hours.
Note 2: The functional modifiers are static, readonly, virtual, override. We cover about these
modifiers also in further hours.


iii) Methods (Member Functions) Declaration Syntax:

accessmodifier functionalModifier returntype/void methodname(args)
{
//method body
}

iv) Object (Instance) Construction Syntax:
//object reference creation
classname objname;

//memory allocation
objname = new classname();


(or)





.NET 4.0 and Visual Studio 2010 Page 93 of 548
D. HARSHA VARDHAN

//object creation along with memory allocation
classname objname = new classname();



v) Accessing Object Members:

obj.field
obj.property
obj.method()

















Application 15: OOP Demo
namespace OOPDemo
{
class test
{
//fields
public string str = "windows";
public int num = 90251;

//methods
public void ReverseString()
{
string r = "";
int i;
int len = str.Length;
for (i = len - 1; i >= 0; i--)
r = r + str[i];
Console.WriteLine("Reversed string is: " + r);
}

public void ReverseNumber()
{
string s = num.ToString();
string r = "";
int i;
int len = s.Length;
for (i = len - 1; i >= 0; i--)
r = r + s[i];
Console.WriteLine("Reversed string is: " + r);
}
}
class Program
{





.NET 4.0 and Visual Studio 2010 Page 94 of 548
D. HARSHA VARDHAN













O Ou ut tp pu ut t: :
















static void Main(string[] args)
{
//construct an object
test t = new test();

//access fields
Console.WriteLine(t.num);
Console.WriteLine(t.str);

//access methods
t.ReverseString();
t.ReverseNumber();

Console.Read();
}
}
}
Application 16: Data Hiding Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataHidingDemo
{
class MyMath
{
//private fields
private int x, y;

//public methods
public void SetValues(int FirstVal, int SecondVal)
{
x = FirstVal;
y = SecondVal;
}





.NET 4.0 and Visual Studio 2010 Page 95 of 548
D. HARSHA VARDHAN





























O Ou ut tp pu ut t: :

public void Addition()
{
int sum = x + y;
Console.WriteLine("Sum is " + sum);
}

public void Subtraction()
{
int diff = x - y;
Console.WriteLine("Difference is " + diff);
}

public void Multiplication()
{
int prod = x * y;
Console.WriteLine("Product is: " + prod);
}
public void Division()
{
int div = x / y;
Console.WriteLine("Division is: " + div);
}
}
class Program
{
static void Main(string[] args)
{
MyMath mm = new MyMath();

mm.SetValues(10, 3);

mm.Addition();
mm.Subtraction();
mm.Multiplication();
mm.Division();

Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 96 of 548
D. HARSHA VARDHAN

ReadOnly Fields
The ReadOnly members are just like constants according to the objects.
The readonly modifier can be used for fields only.
Once you initialize the value of ReadOnly data members, the object cant change that
value, but it can access the value.
Note: The read only fields values can be changed inside of the class only.
To declare the read only fields:
Syntax: access_specifier readonly data_type variable_name = value;




















O Ou ut tp pu ut t: :


Application 17: Demo on ReadOnly fields
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReadOnlyDataMembersDemo
{
class Sample
{
//read only data member
public readonly string CompanyName = "Wipro";
}
class Program
{
static void Main(string[] args)
{
Sample s = new Sample();
Console.WriteLine(s.CompanyName);
//s.CompanyName = "TCS"; // is not allowed bcoz it is the readonly member.
Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 97 of 548
D. HARSHA VARDHAN

R Re ef f P Pa ar ra am me et te er rs s

The reference parameters are similar to the normal parameters.
The only difference between the normal parameters and reference parameters is: When
the value is changed in the reference parameter, would automatically affect
the actual parameter in the calling portion.
Implementation: Use ref keyword in calling portion and also in method definition.
Rule: The actual parameter at the calling portion should be a variable and cant be a
constant.
This is just like Call by reference concept in C/C++.
























Application 18: Ref Parameters Demo
namespace RefParameterDemo
{
class SampleClass
{
public void FirstMethod(int x, int y)
{
x++;
y++;
}
public void SecondMethod(int x, ref int y)
{
x++;
y++;
}
}
class Program
{
static void Main(string[] args)
{
int a = 10, b = 20;
SampleClass sc = new SampleClass();
Console.WriteLine(a + ", " + b);
sc.FirstMethod(a, b);
Console.WriteLine(a + ", " + b);
sc.SecondMethod(a, ref b);
Console.WriteLine(a + ", " + b);
Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 98 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :



O Ou ut t P Pa ar ra am me et te er rs s

This is to return multiple values from a method.
The out parameter is similar to ref parameter; but the difference between these two
parameters is, out parameter does not carries any value from calling portion to the
method definition; but it carries the return value to the calling portion.
Implementation: Use out keyword in calling portion and also in method definition.
So, the out may not be initialized, when you call the method.



















using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OutParametersDemo
{
class Test
{
public string GetBigAndSmall(string s1, string s2, out string small)
{
string big;
if (s1.Length > s2.Length)
big = s1;
else
big = s2;

if (s1.Length < s2.Length)
small = s1;
else
small = s2;

return (big);
}
}
Application 19: Out Parameters Demo





.NET 4.0 and Visual Studio 2010 Page 99 of 548
D. HARSHA VARDHAN












O Ou ut tp pu ut t: :



t th hi is s K Ke ey yw wo or rd d

This is similar to this pointer in C++.
It represents current working object.
It is used to access the members of current working object.
this.field
this.property
this.method()
Current object: The object, with which object, the method is called.
this keyword cant be used in the static methods, because static methods doesnt have
current object.





class Program
{
static void Main(string[] args)
{
Test t = new Test();
string s1 = "dotnet";
string s2 = "framework";
string small; //no need of initialization
string big;
big = t.GetBigAndSmall(s1, s2, out small);
Console.WriteLine("Small string: " + small);
Console.WriteLine("Big string: " + big);
Console.Read();
}
}
}

Application 20: this Keyword Demo





.NET 4.0 and Visual Studio 2010 Page 100 of 548
D. HARSHA VARDHAN




























O Ou ut tp pu ut t: :



N Na am me ed d P Pa ar ra am me et te er rs s

This feature is introduced in C#.NET 4.0.
This is used to pass the arguments to the method, with those names.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ThisKeywordDemo
{
class Sample
{
//fields
public int n = 100;

//methods
public void Increment()
{
int n = 10; //incrementation value
this.n = this.n + n;
}
}
class Program
{
static void Main(string[] args)
{
Sample s = new Sample();
Console.WriteLine(s.n);
s.Increment();
Console.WriteLine(s.n);
Console.Read();
}
}
}
Application 21: Named Parameters Demo





.NET 4.0 and Visual Studio 2010 Page 101 of 548
D. HARSHA VARDHAN


































O Ou ut tp pu ut t: :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NamedParametersDemo
{
class User
{
//fields
public string FirstName;
public string LastName;

//methods
public void SetUserName(string FirstName, string LastName)
{
this.FirstName = FirstName;
this.LastName = LastName;
}

public void ShowUserName()
{
Console.WriteLine(FirstName + " " + LastName);
}
}
class Program
{
static void Main(string[] args)
{
User u = new User();

u.SetUserName(LastName: "Kumar", FirstName: "Raj"); //call a method, with
named parameters
u.ShowUserName();

Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 102 of 548
D. HARSHA VARDHAN

S St ta at ti ic c M Me em mb be er rs s

Types of Class Members:
1. Non-static Members:
This is the default type for all the members.
If you are not using static keyword while the declaration of a field / property or
a method, then it can be called as Non-static member.
The main feature of non-static member is - it will be bounded with the object
only.
+ Non-static Fields / Properties: The memory will be allocated, when
an object is created.
+ Non-static Methods: These methods can implement operations on
non-static fields and properties.

2. Static Members:
If you are using static keyword while the declaration of a field / property or a
method, then it can be called as Static member.
The main feature of non-static member is - it will not be bounded with the any
object. It is individually accessible with the class name. In other words, the static
members are accessible directly, without even creating one object also.

+ Static Fields / Properties: The memory will be allocated individually,
without any relation with the object.
+ Static Methods: These methods can implement operations on static
fields and properties only; and cant access the non-static members.






.NET 4.0 and Visual Studio 2010 Page 103 of 548
D. HARSHA VARDHAN





































class sample
{
int p;
double q;
static int r;
static double s;
}
Object1
p
q
Object2
p
q
Object3
p
q
Sample
r
s
Application 22: Demo on static members
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StaticMembersDemo
{
class Student
{
//non-static data members
public string StudentName;
public string Course;

//non-static methods
public void SetStudentDetails(string StuName, string Cou)
{
StudentName = StuName;
Course = Cou;
}

public void DisplayStudentDetails()
{
Console.WriteLine(StudentName + " - " + Course);
}





.NET 4.0 and Visual Studio 2010 Page 104 of 548
D. HARSHA VARDHAN
























O Ou ut tp pu ut t: :



S St ta at ti ic c C Cl la as ss se es s
A static class can be created using a keyword called static used at the class definition.
A static class can contain only static members (static data members and static methods).
//static data members
public static string CollegeName = "ABC College of Technology";
public static string CollegeAddress = "Hyderabad";

//static methods
public static void DisplayCollegeDetails()
{
Console.WriteLine(CollegeName);
Console.WriteLine(CollegeAddress);
}

}
class Program
{
static void Main(string[] args)
{
//access static members
Student.DisplayCollegeDetails();

//access non-static members
Console.WriteLine();
Student s1 = new Student();
Student s2 = new Student();
s1.SetStudentDetails("Sarath", "MCA");
s2.SetStudentDetails("Syam", "MBA");
s1.DisplayStudentDetails();
s2.DisplayStudentDetails();

Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 105 of 548
D. HARSHA VARDHAN

You cant create an object for the static class.
Advantages:
If you declare any non-static member, it generates a compile time error; so that
it is guaranteed that the class contains only static members; no chance of
declaring non-static member accidentally.
When you try to create an instance to the static class, it again generates a
compile time error, because the all static members can be accessed directly with
its class name.
Syntax:
static class classname
{
//static data members
//static methods
}





















using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StaticClassesDemo
{
static class Sample
{
public static string SampleStaticMember = "This is my static data member";
public static void SampleStaticMethod()
{
Console.WriteLine("This is my static method.");
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Sample.SampleStaticMember);
Sample.SampleStaticMethod();
Console.Read();
}
}
}
Application 23: Static Classes Demo





.NET 4.0 and Visual Studio 2010 Page 106 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :



C Co on ns st tr ru uc ct to or rs s a an nd d D De es st tr ru uc ct to or rs s
Constructor:
The constructor is a special type of method.
It will be called automatically, whenever an object is declared for the class.
This is used to initialize the fields / properties.
Def: A constructor is a method of the class, i.e. meant for initializing the data members.
The constructor gets called automatically, whenever the object is declared.
Note: In C++, it is not possible to initialize the fields directly, thats why you require
Constructor compulsory. But in C#.NET and VB.NET it is possible initialize the data
members directly, along with the declaration. So, to initialize the simple values into the
fields, you dont require the constructor particularly in C#.NET. But if you want to
initialize the fields with some complex code, then you require to write the constructors
compulsory in C#.NET and VB.NET also.

Rules of Constructors:
Its name must be same as "classname".
It must be defined as "public method".
It can be defined with/without arguments.
It can't return any value. So, no return type specification is required.
"Constructor overloading" is possible. Writing multiple constructors in the same class is
called as "Constructor overloading".

Types of Constructors:
i) Implicit constructor:
A constructor, offered by the compiler implicitly is called as "Implicit constructor".





.NET 4.0 and Visual Studio 2010 Page 107 of 548
D. HARSHA VARDHAN

But the compiler automatically offers an implicit constructor, for "constructor-less
class" only.

ii) Explicit constructor:
A constructor, defined by the programmer.
It always overrides the implicit constructor.

Models of Constructors:
i) Default constructor:
It's a constructor, with no arguments.
ii) Parameterized constructor:
It's a constructor, with one or more arguments.

Constructor Implementation:
i) Default constructor:
public classname()
{
---------------;
---------------;
}

ii) Parameterized constructor:
public classname(arguments)
{
---------------;
---------------;
}


D De es st tr ru uc ct to or r

It is also a method of a class, which is having some special features just like constructor.
But it can be called automatically by the compiler, at "object destruction time".
Object destruction time means, the time of clearing of memory i.e. allocated for the
object.





.NET 4.0 and Visual Studio 2010 Page 108 of 548
D. HARSHA VARDHAN

The destructor is used to implement any process that is to be performed at the time of
object closing.

Rules for destructor:
Its name must be defined as class name.
It' name must be started with "~" character.
Access modifier cant be specified for this.
No arguments.
No return value.
Destructor overloading is not possible. That means multiple destructors can't be defined
inside of a class.



Destructor Implementation:
~classname()
{
----------;
----------;
----------;
}















using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConstructorsAndDestructorsDemo
{
class Student
{
//private fields
private int StudentID;
private string StudentName;

//public method
public void Display()
{
Console.WriteLine(StudentID + ", " + StudentName);
}
Application 24: Demo on Constructors and Destructors





.NET 4.0 and Visual Studio 2010 Page 109 of 548
D. HARSHA VARDHAN




































O Ou ut tp pu ut t: : ( (P Pr re es ss s C Ct tr rl l+ +F F5 5) )




//default constructor
public Student()
{
StudentID = 101;
StudentName = "Ram";
}

//parameterized constructor
public Student(int StudentID, string StudentName)
{
this.StudentID = StudentID;
this.StudentName = StudentName;
}

//destructor
~Student()
{
Console.WriteLine("This is destructor...");
}
}
class Program
{
static void Main(string[] args)
{
//invoke default constructor
Student s1 = new Student();
s1.Display();

//invoke parameterized constructor
Student s2 = new Student(102, "Sita");
s2.Display();

Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 110 of 548
D. HARSHA VARDHAN

O Ob bj je ec ct t I In ni it ti ia al li iz ze er r

This concept is introduced in .NET Framework 3.0.
This is used to initialize all the fields of an object, without using a constructor.
Syntax:
Classname ObjectName = new Classname() { field1=value1, field2=value2, };
























O Ou ut tp pu ut t: :

Application 25: Demo on Object Initializer
namespace ObjectInitializerDemo
{
class Department
{
//fields
public int DeptNo;
public string DeptName;
public string Location;

//methods
public void Display()
{
Console.WriteLine("Department No: " + DeptNo);
Console.WriteLine("Department Name: " + DeptName);
Console.WriteLine("Location: " + Location);
}
}
class Program
{
static void Main(string[] args)
{
Department d = new Department() { DeptNo=10, DeptName="Sales",
Location="Hyderabad" };
d.Display();
Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 111 of 548
D. HARSHA VARDHAN

Static Constructors

The static constructor is used to initialize the static data members, whereas the normal
constructor (non-static constructor) is used to initialize the non-static data members.

Syntax:
static classname()
{
//some code
}
Rules:
1. Static constructors cant contain any access modifiers.
2. Static constructors cant be defined with arguments.
3. Static constructors cant access the non-static data members.


























namespace StaticConstructorsDemo
{
class MyCollege
{
//static fields
public static string CollegeName;
public static string Address;

//static constructor
static MyCollege()
{
CollegeName = "ABC College of Technology";
Address = "Hyderabad";
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(MyCollege.CollegeName);
Console.WriteLine(MyCollege.Address);
Console.Read();
}
}
}
Application 26: Demo on Static Constructors





.NET 4.0 and Visual Studio 2010 Page 112 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :



M Me et th ho od d O Ov ve er rl lo oa ad di in ng g

Def: Method overloading is nothing but writing multiple methods with same name and
with different arguments.
To overload methods, you should follow the below rules.
1. All of the overloaded methods name should be same.
2. Any difference between the method arguments should be maintained. The
difference may be in no. of arguments or the data types of arguments.
Finally, when you call the overloaded method, automatically compiler takes the decision
that which method is to be called, based on the arguments that you are passing.


















Application 27: Method Overloading Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MethodOverloadingDemo
{
class OverloadTest
{
public double GetSimpleInterest(double p, double n, double r)
{
double si;
si = (p * n * r) / 100;
return (si);
}
public double GetSimpleInterest(double p, double n)
{
double si;
si = (p * n * 8.45) / 100;
return (si);
}
}





.NET 4.0 and Visual Studio 2010 Page 113 of 548
D. HARSHA VARDHAN










O Ou ut tp pu ut t: :




O Op pe er ra at to or r O Ov ve er rl lo oa ad di in ng g

Def: Re-defining the functionality of an operator is nothing but Operator Overloading.
With the support of operator overloading, you can use any of the existing operators with
the combination of objects.
For example to add two numbers, you write like this (a and b are the variables).
a + b
But suppose you have two objects declared for Student class. Then you cant write like
this:
s1 + s2
Finally, if you want to use the operator with the combination of objects, you require
Operator Overloading.
To implement this feature, write the Operator method as follows:

public static operator symbol(arguments)
{

}
class Program
{
static void Main(string[] args)
{
OverloadTest ot = new OverloadTest();
double result = ot.GetSimpleInterest(9000, 5, 3.5);
Console.WriteLine("Simple Interest is: " + result);
result = ot.GetSimpleInterest(10000, 8);
Console.WriteLine("Simple Interest is: " + result);
Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 114 of 548
D. HARSHA VARDHAN

If you use the specific operator with the objects, then automatically the above method
will be called and the object(s) will be passed as arguments to the above operator
method.
Generally operator method returns a result object.






















Application 28: Operator Overloading Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OperatorOverloadingDemo
{
class PersonHeight
{
//data members
private int Feet, Inches;

//methods
public void SetHeight(int Feet, int Inches)
{
this.Feet = Feet;
this.Inches = Inches;
}

public void DisplayHeight()
{
Console.WriteLine(this.Feet + " feet and " + this.Inches + " inc.");
}

//operator method
public static PersonHeight operator - (PersonHeight p1, PersonHeight p2)
{
PersonHeight ph = new PersonHeight();
if (p1.Inches < p2.Inches)
{
p1.Feet--;
p1.Inches += 12;
}
ph.Inches = p1.Inches - p2.Inches;
ph.Feet = p1.Feet - p2.Feet;
return (ph);
}
}





.NET 4.0 and Visual Studio 2010 Page 115 of 548
D. HARSHA VARDHAN
















O Ou ut tp pu ut t: :


class Program
{
static void Main(string[] args)
{
//create two objects for two persons
PersonHeight p1 = new PersonHeight();
PersonHeight p2 = new PersonHeight();
p1.SetHeight(8, 3);
p2.SetHeight(6, 7);

//display the height of two persons
p1.DisplayHeight();
p2.DisplayHeight();

//create one more object for result
PersonHeight p3 = new PersonHeight();

//use '-' operator
p3 = p1 - p2;

Console.WriteLine("\nThe difference is:");
p3.DisplayHeight();
Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 116 of 548
D. HARSHA VARDHAN

G
G
e
e
n
n
e
e
r
r
i
i
c
c
s
s


Generics are similar to templates in C++.
Def: A generic is an identifier, which automatically identifies the data type of a variable.
This is designed to represent a particular data type, during an object life time or a
method execution.
Here, you can observe two types of generics. One is representing a data type during an
object life time and another one is representing a data type during the method execution
time.

T Ty yp pe es s o of f G Ge en ne er ri ic cs s: :

Generic Classes:
The generic represents a data type, during the objects life time of the class.
Generic Methods:
The generic represents a data type, during the method execution.

D De ef fi in ni it ti io on n o of f G Ge en ne er ri ic c C Cl la as ss se es s: :

A class that contains a data member of the generic type.
This should specify the generic type name after the class name as follows:
class classname<generic type name>
{

}

D De ef fi in ni it ti io on n o of f G Ge en ne er ri ic c M Me et th ho od ds s: :

A method that contains an argument of the generic type.
This should specify the generic type name after the method name as follows:
accessmodifier returntype methodname<generic type name>(arguments)
{

}








.NET 4.0 and Visual Studio 2010 Page 117 of 548
D. HARSHA VARDHAN

A Ad dv va an nt ta ag ge e o of f G Ge en ne er ri ic c C Cl la as ss se es s: :

According to generic classes, when an instance is created, the required type of values
could be stored as the data members.

A Ad dv va an nt ta ag ge e o of f G Ge en ne er ri ic c M Me et th ho od ds s: :

According to generic methods, when you call a method, you can pass different types of
arguments to the same method, without overloading it.


I Im mp pl le em me en nt ta at ti io on n o of f G Ge en ne er ri ic c C Cl la as ss se es s

Class Definition with Generics:
class classname<T>
{
accessmodifier T datamembername;
}

Object Construction:
classname<data type> objname = new classname<data type>;


I Im mp pl le em me en nt ta at ti io on n o of f G Ge en ne er ri ic c M Me et th ho od ds s

Method Definition with Generics:
accessmodifier returntype methodname<T>(T arg)
{

}


Method Calling:
methodname<data type>(value);








Application 29: Demo on Generic Classes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;





.NET 4.0 and Visual Studio 2010 Page 118 of 548
D. HARSHA VARDHAN



























O Ou ut tp pu ut t: :














Application 30: Demo on Generic Methods
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericMethodsDemo
{
class Sample
{
public void ReverseAndPrint<T>(T[] arr)
{
namespace GenericClassesDemo
{
class Sample<T>
{
T n;
public void Set(T n)
{
this.n = n;
}
public void Print()
{
Console.WriteLine(n);
}
}
class Program
{
static void Main(string[] args)
{
Sample<int> s1 = new Sample<int>();
s1.Set(10);
s1.Print();

Sample<string> s2 = new Sample<string>();
s2.Set("hai");
s2.Print();

Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 119 of 548
D. HARSHA VARDHAN
























O Ou ut tp pu ut t: :



P Pr ro op pe er rt ti ie es s

Properties are one of the new features of C#.
Its taken from Visual Basic, not from C/C++.
Generally, Properties concept not used in the classes, in some rare cases and complex /
large scale classes, those are used.
In simple, properties are extensions to data members.
As you know that a data member contains a value, a property implements additional
logic on that data member, especially when its value is changed.
For example, you imaging a windows form.
Array.Reverse(arr);
foreach (T item in arr)
Console.Write(item + ", ");
Console.WriteLine();
}
}

class Program
{
static void Main(string[] args)
{
int[] intArray = { 3, 5, 7, 9, 11 };
string[] stringArray = { "first", "second", "third" };
double[] doubleArray = { 3.567, 7.891, 2.345 };

Sample s = new Sample();
s.ReverseAndPrint<int>(intArray);
s.ReverseAndPrint<string>(stringArray);
s.ReverseAndPrint<double>(doubleArray);

Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 120 of 548
D. HARSHA VARDHAN


Currently, the form window height is 300 pixels.
Suppose you change its height like this:
Form1.Height = 400;
In this case, let us imagine that Height is a normal data member. With the above
statement, the value of the data member will be changed. But its not enough. The
window height should be increased visually. So, whenever you assign the value of the
data member, some necessary code should be executed automatically, that changes the
window height visually. In this kind of situations, Properties are used.
Now, let us imagine that Height is a property. Then whenever you assign a value to it,
its set method will be executed automatically.
In the same way, in the properties, get method is also implemented, which gets
automatically called when the property value is requested in the client code.
We understand better with the following implementation diagram of Properties. It
contains two accessors called set and get.


accessmodifier datatype propertyname
{
set
{
//code to set the property value
}
get
{
//code to get the property value
}
}
No explicit Parameter declaration. The
implicit parameter named value of
the same type as the property type is
available.
Always void return type.
No implicit / explicit parameters.
Always returns a value of the type of
the property.





.NET 4.0 and Visual Studio 2010 Page 121 of 548
D. HARSHA VARDHAN

The Set Accessor:
1. This gets called automatically, whenever a value is assigned to the property in
the client code. Ex: obj.property = value;
2. The value that is assigned in the client code is available as implicit parameter,
named value in this set accessor.
3. This accessor cant return any value.


The Get Accessor:
1. This gets called automatically, whenever the property value is requested in the
client code. Ex: obj.property
2. No implicit parameters are available.
3. This accessor should return the value of the property.

IMP Note: No memory gets allocated for the property. So that it cant store any value. To store
the actual value, we use a private data member.

T Th he e C Co om mp pl le et te e P Pr ro op pe er rt ty y I Im mp pl le em me en nt ta at ti io on n S Sy yn nt ta ax x: :

private datatype variablename;
accessmodifier datatype propertyname
{
set
{
variablename = value;
}
get
{
return (variablename);
}
}

Note: There should be some difference in the variable name and property name.










.NET 4.0 and Visual Studio 2010 Page 122 of 548
D. HARSHA VARDHAN

Ex:
private string name;
public string Name
{
set
{
name = value;
}
get
{
return (name);
}
}

























Application 31: Demo on Properties
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PropertyDemo
{
class Student
{
//private fields
private string studentname_val;
private int age_val;

//public properties
public string StudentName
{
set
{
if (value.Length <= 20)
{
Console.WriteLine("The student name is changed as " + value);
studentname_val = value;
}
else
{
Console.WriteLine("Why you are assigning two large name...?");
}
}
get
{
return studentname_val;
}
}





.NET 4.0 and Visual Studio 2010 Page 123 of 548
D. HARSHA VARDHAN































public int Age
{
set
{
if (value>=18 && value<=60)
{
Console.WriteLine("The student age is changed as " + value);
age_val = value;
}
else
{
Console.WriteLine("Why you are assigning the wrong age...?");
}
}
get
{
return age_val;
}
}
}
class Program
{
static void Main(string[] args)
{
Student stu = new Student();

stu.StudentName = "Syam";
Console.WriteLine(stu.StudentName);

Console.WriteLine();
stu.Age = 25;
Console.WriteLine(stu.Age);

Console.WriteLine();
stu.StudentName = "abcdefghijklmnopqrstuvwxyz";
Console.WriteLine(stu.StudentName);

Console.WriteLine();
stu.Age = 900;
Console.WriteLine(stu.Age);

Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 124 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :






R Re ea ad d o on nl ly y P Pr ro op pe er rt ti ie es s: :

Simply implement get accessor only, dont implement set accessor.
Syn:
private datatype variablename;
accessmodifier datatype propertyname
{
get
{
return (variablename);
}
}

Ex:
private string name;
public string Name
{
get
{
return (name);
}
}












.NET 4.0 and Visual Studio 2010 Page 125 of 548
D. HARSHA VARDHAN

W Wr ri it te e o on nl ly y P Pr ro op pe er rt ti ie es s: :

Simply implement set accessor only, dont implement get accessor.
Syn:
private datatype variablename;
accessmodifier datatype propertyname
{
set
{
variablename = value;
}
}


Ex:
private string name;
public string Name
{
set
{
name = value;
}
}


A Au ut to o I Im mp pl le em me en nt te ed d P Pr ro op pe er rt ti ie es s: :

This is introduced in C#.NET 3.0.
To simplify the syntax of property declaration that contains no extra logic in set
accessor and get accessor, this concept is introduced.
According to this, no code for set and get accessors needed to write.
No extra variable is needed to be declared.
Syn:
accessmodifier datatype propertyname { get; set; }

Ex:
public string Name { get; set; }










.NET 4.0 and Visual Studio 2010 Page 126 of 548
D. HARSHA VARDHAN

D De ef fi in ni in ng g t th he e c cl la as ss s d de ef fi in ni it ti io on ns s i in n i in nd di iv vi id du ua al l f fi il le es s
All of the examples up to now have been implemented with one or more classes within
the same file.
But in the real programming world, each class will be implemented in individual file.
To do so,
o Click on Project menu Add Class.
o Enter the name of the new class.
o Click on Add button to confirm.
o Then a new file will be created in the same project named as:
classname.cs
Note: (cs stands for C Sharp)





















Application 32: Class Definition in individual files
Demo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassDefInSeperateFiles
{
class Demo
{
public void DemoMethod()
{
Console.WriteLine("This is demo method...");
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;





.NET 4.0 and Visual Studio 2010 Page 127 of 548
D. HARSHA VARDHAN









O Ou ut tp pu ut t: :




P Pa ar rt ti ia al l C Cl la as ss se es s
The partial keyword allows you to define a class, struct or interface across multiple
files.
As you learned above, each class will be placed in individual files.
But in some situations in future, you may require to define a class within multiple files. In
other words, the class definition can be split into multiple files.
For example, if multiple programmers need to develop a class simultaneously, this may
be required. In the same way, in windows applications, the automatic code generator
generates some design part code for your own form class. In this case also, partial
classes are required.

Implementation:

MyClassPart1.cs
partial class myclass
{
//some members
}



namespace ClassDefInSeperateFiles
{
class Program
{
static void Main(string[] args)
{
Demo d = new Demo();
d.DemoMethod();
Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 128 of 548
D. HARSHA VARDHAN

MyClassPart2.cs
partial class myclass
{
//some more members
}































SampleClassPart1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PartialClasses
{
partial class SampleClass
{
public void FirstMethod()
{
Console.WriteLine("This is first method.");
}
}
}

SampleClassPart2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PartialClasses
{
partial class SampleClass
{
public void SecondMethod()
{
Console.WriteLine("This is second method.");
}
}
}
Application 33: Demo on Partial Classes





.NET 4.0 and Visual Studio 2010 Page 129 of 548
D. HARSHA VARDHAN































O Ou ut tp pu ut t: :

SampleClassPart3.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PartialClasses
{
partial class SampleClass
{
public void ThirdMethod()
{
Console.WriteLine("This is third method.");
}
}
}


Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PartialClasses
{
class Program
{
static void Main(string[] args)
{
SampleClass sc = new SampleClass();
sc.FirstMethod();
sc.SecondMethod();
sc.ThirdMethod();
Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 130 of 548
D. HARSHA VARDHAN

I In nd de ex xe er r
This is used to access the object like an array.
Syntax: object[index]
When you use the above syntax, a field can be accessed.
Syntax for Indexer:
public datatype this[int index]
{
get
{
return arrayname[index];
}
set
{
arrayname[index] = value;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IndexerDemo
{
class IndexDemo
{
//array field
public string[] countries = new string[10];

//constructor
public IndexDemo()
{
for (int i = 0; i < countries.Length; i++)
countries[i] = "Not set";
}

//method
public void ShowCountries()
{
Application 34: Demo on Indexer





.NET 4.0 and Visual Studio 2010 Page 131 of 548
D. HARSHA VARDHAN


















O Ou ut tp pu ut t: :
foreach (string c in countries)
{
Console.WriteLine(c);
}
}

//indexer
public string this[int ind]
{
get
{
return countries[ind];
}
set
{
countries[ind] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
IndexDemo id = new IndexDemo();

id.countries[3] = "India"; //access value using field
id[5] = "USA"; //access value using indexer

id.ShowCountries();

Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 132 of 548
D. HARSHA VARDHAN

I In nh he er ri it ta an nc ce e
Def: The process of implementing the "Parent-Child" relationship between two or more
classes.
As a part of this "Inheritance" implementation, parent and child classes are to be
implemented.
Advantage: All the data members and methods of the parent
class are accessible by child class. This is called as Re-usability.
That means the parent class members are re-usable in the child
class.
The parent class can also be called as "Base" / "Super" class.
The child class can also be called as "Derived" / Sub class.

Classification of Inheritance supported by C#:
1) Implementation Inheritance:
This is commonly used inheritance.
Whenever a class is derived from another class, it can be called as Implementation
Inheritance.
As said above, all of the members of the super class are adopted by sub class.

2) Interface Inheritance:
This type of inheritance is taken from Java.
Whenever a class is derived from an interface, it can be called as Interface
Inheritance.
The interface is similar to the class, but doesnt contain the method definitions; it
contains the method declarations only. We discuss about the interfaces in-depth later.
BaseClass
DerivedClass





.NET 4.0 and Visual Studio 2010 Page 133 of 548
D. HARSHA VARDHAN

Types of Inheritance:
1) Single Inheritance
This is the simplest type of inheritance.
An inheritance relationship, with only one super class
and one sub class.


2) Hierarchical Inheritance
An inheritance relationship,
with only one super class and
multiple sub classes.




3) Multi-Level Inheritance
An inheritance relationship, with only one super
class and multiple sub classes, and also
extended with another sub class from the first
sub class.
In other words, one class acts as super class
and sub class simultaneously.


4) Multiple Inheritance
An inheritance relationship,
with only multiple super classes
and only one sub class.
Multiple Implementation
Inheritance is not supported
by C#, but Multiple Interface
Inheritance is supported by C#.
BaseClass
DerivedClass
BaseClass
DerivedClass 1 DerivedClass 2
BaseClass
Intermediate Class
DerivedClass
BaseClass 1
DerivedClass
BaseClass 2





.NET 4.0 and Visual Studio 2010 Page 134 of 548
D. HARSHA VARDHAN


5) Hybrid Inheritance
An inheritance relationship
that contains a
combination of any other
two types of inheritances.

Ex:
+ Multiple +
Hierarchical Inheritance
+ Multiple + Multi Level Inheritance etc.

Note: Other OOP languages like C++ support multiple inheritance. But C# and VB.NET doesnt
support multiple inheritance to avoid some practical problems while developing future GUI
applications like windows forms applications, web sites etc.
But instead, C# and VB.NET supports multiple interface inheritance, because it doesnt
cause any practical problems.

Implementation steps for Inheritance
Define the super class
class superclassname
{
//data members of super class
//methods of super class
}

Define the sub class
class subclassname : superclassname
{
//data members of sub class
//methods of sub class
}

Intermediate Class 1
DerivedClass
Intermediate Class 2

BaseClass





.NET 4.0 and Visual Studio 2010 Page 135 of 548
D. HARSHA VARDHAN

Construct the object for sub class
SubClass obj = new SubClass();
Invoke members
obj.SuperClassMember
obj.SubClassMember

E Ex xa am mp pl le e

We start with an example:
class A
{
void Hello()
{
Console.WriteLine(Hello, World!);
}
}
class B:A
{
void Hai()
{
Console.WriteLine(Hai to all!);
}
}

In the above example, we have two classes called A and B. The inheritance
relationship has been established between these classes. Now, the A class is called as
Super class and B class is called as Sub class. All the members of A class are
exactly copied into B class. Finally, whenever you construct an object for the B class,
you can access both Hello() method and Hai() method also from that object. This is
what we learned up-to-now.
But sometimes, some of the super class members may not be accessible directly from
the sub classs object. This kind of nature depends on the access modifiers, we use in
the super class, while we declare the super class members.










.NET 4.0 and Visual Studio 2010 Page 136 of 548
D. HARSHA VARDHAN
























O Ou ut tp pu ut t: :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleInheritanceDemo
{
//super class
class Country
{
public void ShowCountry()
{
Console.WriteLine("This is India..");
}
}

//sub class
class State : Country
{
public void ShowState()
{
Console.WriteLine("This is Andhra Pradesh..");
}
}

class Program
{
static void Main(string[] args)
{
//create instance for sub class
State st = new State();

//access the members
st.ShowCountry();
st.ShowState();

Console.Read();
}
}
}
Application 35: A simple demo on inheritance





.NET 4.0 and Visual Studio 2010 Page 137 of 548
D. HARSHA VARDHAN






















O Ou ut tp pu ut t: :



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ProtectedModifierDemo
{
//super class
class Country
{
protected void ShowCountry()
{
Console.WriteLine("This is India..");
}
}
//sub class
class State : Country
{
public void ShowState()
{
ShowCountry();
Console.WriteLine("This is Andhra Pradesh..");
}
}
class Program
{
static void Main(string[] args)
{
//create instance for sub class
State st = new State();
//access the members
st.ShowState();
Console.Read();
}
}
}
Application 36: Demo on protected modifier





.NET 4.0 and Visual Studio 2010 Page 138 of 548
D. HARSHA VARDHAN

T Tr ry y t to o i im mp pl le em me en nt t t th he e f fo ol ll lo ow wi in ng g a ap pp pl li ic ca at ti io on ns s

1) An application with Single Inheritance.


2) An application with Hierarchical Inheritance.






.NET 4.0 and Visual Studio 2010 Page 139 of 548
D. HARSHA VARDHAN




3) An application with Multi Level Inheritance.












.NET 4.0 and Visual Studio 2010 Page 140 of 548
D. HARSHA VARDHAN




4) An application with Hybrid Inheritance.







.NET 4.0 and Visual Studio 2010 Page 141 of 548
D. HARSHA VARDHAN

S Se ea al le ed d C Cl la as ss se es s


The sealed classes can be declared using sealed keyword as follows:
sealed class classname
{
//some members
}
The sealed classes are just like normal classes, but you cant inherit the sealed class. In
other words, you cant create a sub class for the sealed class.
Trying to inherit the sealed class would cause a compilation error.
This is just like Final classes in java.
Demo:
sealed class one
{

}
class two : one //cant inherit this. Will give a compilation error.
{

}


H Hi id di in ng g t th he e S Su up pe er r C Cl la as ss s M Me et th ho od ds s

Let us imagine a super class and a sub class having two methods with same name and
same arguments.
If you call the method from the client code, which method would be called? (either super
class method or sub class method?) Ans: Sub Class Method only.
This is called as Hiding Methods. Here, the super class method is hidden by sub class
method.
But, a compile time warning will be displayed in the sub class method definition to use a
keyword called new.
The new keyword hides the super class method, that contains same name and same
arguments set.





.NET 4.0 and Visual Studio 2010 Page 142 of 548
D. HARSHA VARDHAN

Of course, this is done by default, but to implement a strong programming, new
keyword is recommended to be used when you want to hide the super class method with
intention.


























O Ou ut tp pu ut t: :



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NewKeywordDemo
{
class US
{
public void ShowCountry()
{
Console.WriteLine("This is United States.");
}
}
class India : US
{
public new void ShowCountry()
{
Console.WriteLine("This is India.");
}
}
class Program
{
static void Main(string[] args)
{
India i = new India();
i.ShowCountry();
Console.Read();
}
}
}
Application 37: Hiding Methods with new keyword





.NET 4.0 and Visual Studio 2010 Page 143 of 548
D. HARSHA VARDHAN

V Vi ir rt tu ua al l M Me et th ho od ds s a an nd d M Me et th ho od d O Ov ve er rr ri id di in ng g

The similar operation as above can be implemented with two keywords called virtual
and override.
The virtual keyword should be used in the super class method definition and the
override keyword should be used in the sub class method definition.
This concept can be called as Method Overriding.
In fact, there is no much difference between Hiding methods and Method Overriding.
This is similar to virtual functions in C++; but override keyword is not required in
C++.
The access modifiers used in the base and derived classes for the virtual methods should
be same.






















namespace VirtualDemo
{
class US
{
public virtual void ShowCountry()
{
Console.WriteLine("This is United States.");
}
}
class India : US
{
public override void ShowCountry()
{
Console.WriteLine("This is India.");
}
}
class Program
{
static void Main(string[] args)
{
India i = new India();
i.ShowCountry();
Console.Read();
}
}
}
Application 38: Virtual Methods and Method Overriding





.NET 4.0 and Visual Studio 2010 Page 144 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :



C Ca al ll li in ng g b ba as se e c cl la as ss s v ve er rs si io on ns s o of f m me et th ho od ds s

In the above two applications, the base class method named ShowCountry() is not
executed.
If you want to call the base class version, simply use base keyword in the sub class
method.
The base keyword simply represents the respective super class.
Syn:
base.superclassmethod();




















using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BaseKeywordDemo
{
class US
{
public virtual void ShowCountry()
{
Console.WriteLine("This is United States.");
}
}
class India : US
{
public override void ShowCountry()
{
base.ShowCountry(); //call the base class method
Console.WriteLine("This is India.");
}
}
class Program
{
Application 39: Demo on base keyword





.NET 4.0 and Visual Studio 2010 Page 145 of 548
D. HARSHA VARDHAN








O Ou ut tp pu ut t: :


static void Main(string[] args)
{
India i = new India();
i.ShowCountry();
Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 146 of 548
D. HARSHA VARDHAN

A Ab bs st tr ra ac ct t C Cl la as ss se es s a an nd d M Me et th ho od ds s


Abstract Methods
The abstract method is same as pure virtual functions in C++.
The abstract method can be declared with abstract keyword like this:
public abstract void samplemethod();
The abstract method doesnt contain method definition; it contains only method
declaration as above.
The abstract methods can be declared only within abstract classes.


Abstract Classes
A class that is declared with abstract keyword is called as abstract class.
abstract class classname
{

}

Rule: If a class contains at least one abstract method, that class should be declared as
abstract class.
The abstract class can contain abstract methods, non-abstract class and normal data
members also.
Note: You cant create an object for the abstract class. It can be inherited from another
non-abstract class.
The non-abstract class, that inherits the abstract class, should implement the
definition(s) (with override keyword) for all of the abstract methods declared in the
abstract class.
Note: The access modifiers used in the base and derived classes for the abstract
methods should be same.









.NET 4.0 and Visual Studio 2010 Page 147 of 548
D. HARSHA VARDHAN

Implementation Syntax:
abstract class abstractclassname
{
//data members if any
//non-abstract methods if any
accessmodifier abstract returntype methodname(arguments);
}

class derivedclassname : abstractclassname
{
accessmodifier override returntype methodname(arguments)
{
//method body
}
}

















using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AbstractDemo
{
//abstract class
abstract class MyBaseClass
{
public abstract void FirstMethod();
public void SecondMethod()
{
Console.WriteLine("This is Non-Abstract Method");
}
}
//non-abstract class
class MyDerivedClass : MyBaseClass
{
Application 40: Abstract Classes and Methods





.NET 4.0 and Visual Studio 2010 Page 148 of 548
D. HARSHA VARDHAN














O Ou ut tp pu ut t: :



S Su um mm ma ar ry y o of f M Mo od di if fi ie er rs s
Up to now, you learned several modifiers like static, new, virtual, abstract, override,
sealed.
You get a summary of all of these modifiers with following table:
Sl.
No
Modifier Applies to Description
1 new Methods only
The method hides a base class method with same
signature.
2 static All members
The member does not depends / instantiates with any of
with its classs objects. It can be accessed with its class
name.
3 virtual Methods only The member can be overridden by a derived class.
4 abstract
Classes and
Methods only
The abstract class cant be instantiated.
The abstract method is nothing but a virtual method that
contains only declaration with no definition. It should be
implemented with override keyword in the derived
class.
5 override Methods only
The member overrides an inherited virtual or abstract
member of the base class.
6 sealed Classes only The class cant be inherited.
public override void FirstMethod()
{
Console.WriteLine("This is Abstract Method");
}
}
class Program
{
static void Main(string[] args)
{
MyDerivedClass s = new MyDerivedClass();
s.FirstMethod();
s.SecondMethod();
Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 149 of 548
D. HARSHA VARDHAN

I In nt te er rf fa ac ce es s

This is the one of the most important features of C#.
The .NET beginners may not understand the importance of the interfaces exactly, but in the
real-time development of .NET applications, the interfaces are used by the Sr. Developers
and the Jr. Developers.
The Interfaces are similar to abstract classes, but having its own features along with having
some differences with the abstract classes.

Features of Interfaces:
o The interface can be declared with interface keyword, as follows:
interface interfacename
{

}
o The interface contains only method declarations and cant contain method
definitions (similar to the abstract methods).
o The interface cant contain any data members but can contain automatic
properties (Already you know that the automatic property doesnt contain
definitions for get and set accessors).
o Interface methods are by default public. You cant use another access modifier
like private and public etc.
o The interface cant be instantiated. That means you cant create an object for the
interface.
o The interface cant contain constructors.
o The class that inherits the interface is called as Implementation Class.
o The implementation class should implement the definitions for all the interface
methods. If not, it would generate compile time errors.
o One interface can be inherited by any no. of classes (Hierarchical inheritance).
o One class can inherit any no. of interfaces (Multiple inheritance).
o The interface methods cant be declared as virtual or static in the interface
definition.









.NET 4.0 and Visual Studio 2010 Page 150 of 548
D. HARSHA VARDHAN

Implementation Syntax of Interfaces:
//interface definition
interface interfacename
{
returntype methodname(arguments);
}


//implementation class definition
class classname : interfacename
{
public returntype methodname(arguments)
{
//some code
}
}

































namespace InterfaceDemo
{
interface SimpleInterest
{
double GetSimpleInterest(double P, int N, double R);
}
class SimpleInterestImpl : SimpleInterest
{
public double GetSimpleInterest(double P, int N, double R)
{
return ((P * N * R) / 100);
}
}
class Program
{
static void Main(string[] args)
{
SimpleInterestImpl sii = new SimpleInterestImpl();
Console.WriteLine("Simple Interest: " + sii.GetSimpleInterest(5000, 3, 4.5));
Console.Read();
}
}
}
Application 41: Demo on Interfaces





.NET 4.0 and Visual Studio 2010 Page 151 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :



S St tr ru uc ct tu ur re es s

This concept is not new in C#; it is taken from C language.
In C languages structures, you can write only some member variables, called as data
members / fields. But in C#s structures, you can write fields along with some
methods also.
So, In C#, structures are almost all similar to the classes, but having some differences
with the classes.

C Cl la as ss se es s ( (v vs s) ) S St tr ru uc ct tu ur re es s

Sl. No Classes Structures
1 Declared with class keyword. Declared with struct keyword.
2
Can contain fields, methods, constructors,
destructors, properties etc.
Can contain fields, methods,
constructors, destructors, properties
etc.
3 Supports inheritance. Doesnt support inheritance.
4
User-defined default constructor can be
implemented.
User-defined default constructor cant
be implemented.
5
Data Members can be initialized in the
class definition.
Data members cant be initialized in the
structure definition.

I Im mp pl le em me en nt ta at ti io on n: :

Define structure
struct structurename
{
//fields
//methods
}

Create instance for structure
structurename instancename = new structurename();





.NET 4.0 and Visual Studio 2010 Page 152 of 548
D. HARSHA VARDHAN










































Application 42: Demo on Structures
namespace StructuresDemo
{
struct Employee
{
//fields
private int EmployeeID;
private string EmployeeName;
private double Salary, Tax, NetSalary;

//methods
public void ReadData()
{
Console.Write("Enter Employee ID: ");
EmployeeID = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Employee Name: ");
EmployeeName = Console.ReadLine();
Console.Write("Enter Salary: ");
Salary = Convert.ToDouble(Console.ReadLine());
}
public void Calculate()
{
Tax = Salary * 10 / 100;
NetSalary = Salary - Tax;
}
public void DisplayData()
{
Console.WriteLine("\n\nEmployee ID: " + EmployeeID);
Console.WriteLine("Employee Name: " + EmployeeName);
Console.WriteLine("Salary: " + Salary);
Console.WriteLine("Tax: " + Tax);
Console.WriteLine("Net Salary: " + NetSalary);
}
}
class Program
{
static void Main(string[] args)
{
//create structure instance
Employee e = new Employee();
//call the methods
e.ReadData();
e.Calculate();
e.DisplayData();
Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 153 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :






.NET 4.0 and Visual Studio 2010 Page 154 of 548
D. HARSHA VARDHAN

E Ex xt te en ns si io on n M Me et th ho od ds s


This is concept is meant for extending the methods of a class.
There are two ways to extend a class:
o Inheritance
o Extension Methods
As you know already in inheritance, you can extend the features of a class by defining
derived class.
But in this inheritance feature, you are creating two classes (base class and derived
class).
But, if you want to add a method to an existing class, that is accessible with the
objects of the same class, it is not possible in inheritance. But it is possible using
Extension Methods.
Conclusion: This feature allows you to add one or more new methods to the same
class, without changing the definition of that particular class.
This is more useful, when you want to add more methods to a pre-defined class.

Implementation:
When you want to implement this concept practically, simply take a new static class first.
In this static class, write a static method, with the required name.
In that method, the first argument should be like this:
this classname argumentname
Here, in place of classname, specify the class name, for which you want to write the
extension method.
Then the argument name acts as this pointer in the code.
Note: Even though it is defined as a static method it is accessible as a non-static
method from the object of the source class.
Syntax:
public static return_type method_name(this class_name arg, <other args if any>)
{
//some code
}
Limitation: You cant add a static method for an existing class.





.NET 4.0 and Visual Studio 2010 Page 155 of 548
D. HARSHA VARDHAN



























O Ou ut tp pu ut t: :

StringExtension.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExtensionMethodsDemo
{
static class StringExtension
{
public static string Reverse(this String str)
{
char[] ch = str.ToCharArray();
Array.Reverse(ch);
string mystr = new String(ch);
return (mystr);
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExtensionMethodsDemo
{
class Program
{
static void Main(string[] args)
{
string s = "abcdefghijklmnopqrstuvwxyz";
Console.WriteLine(s.Reverse());
Console.Read();
}
}
}
Application 43: Extension Methods Demo





.NET 4.0 and Visual Studio 2010 Page 156 of 548
D. HARSHA VARDHAN

D De el le eg ga at te es s

This is the new concept introduced in C#.
Def: A delegate is the reference to the method.
Using the delegate, you can call the method.
This is used in GUI Events and Multi-Threading concept in future.

Implementation Syntax:

1. Define the Method:
accessmodifier returntype methodname(arguments)
{
//some code
}
2. Declare the delegate (as a data member):
delegate returntype delegatename(arguments);
3. Create instance of the delegate:
delegatename delegateinstancename = new delegatename(methodname);
4. Access the properties of the delegate:
+ delegateinstancename.Target
//gets the class name that contains the target method
+ delegateinstancename.Method
//gets the signature of the target method
5. Invoke / call the target method:
delegateinstancename.Invoke();
(or)
delegateinstancename.Invoke(arguments);






using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
Application 44: Demo on Delegates





.NET 4.0 and Visual Studio 2010 Page 157 of 548
D. HARSHA VARDHAN





























O Ou ut tp pu ut t: :



namespace DelegatesDemo
{
class Sample
{
public int GetSum(int a, int b, int c)
{
return (a + b + c);
}
}
class Program
{
//create the delegate
delegate int SampleDelegate(int a, int b, int c);

static void Main(string[] args)
{
//create the object
Sample s = new Sample();

//create the delegate instance
SampleDelegate sd = new SampleDelegate(s.GetSum);

//access properties of delegate
Console.WriteLine("Target Method: " + sd.Target);
Console.WriteLine("Target Method Signature: " + sd.Method);

//call the method
int SumValue = sd.Invoke(10, 20, 30);
Console.WriteLine("\nSum is: " + SumValue);

Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 158 of 548
D. HARSHA VARDHAN

M Mu ul lt ti i C Ca as st t D De el le eg ga at te es s

It contains the address of multiple methods.
You can add the reference of the methods, one by one using += operator.
When you call the methods using Invoke() method, all the methods will be called at-a-
time.
Rule: All of the methods should have same return type and same arguments set.
Limitation: If there is any return value, you can get only the last returned value.























O Ou ut tp pu ut t: :

namespace MultiCastDelegatesDemo
{
class Test
{
public void ShowSquare(int n)
{
int x = n * n;
Console.WriteLine("Square: " + x);
}
public void ShowCube(int n)
{
int x = n * n * n;
Console.WriteLine("Cube: " + x);
}
}
class Program
{
delegate void MyDelegate(int n);
static void Main(string[] args)
{
Test t = new Test();
MyDelegate md = new MyDelegate(t.ShowSquare);
md += new MyDelegate(t.ShowCube);
md.Invoke(10);
Console.Read();
}
}
}
Application 45: Multi-Cast Delegates Demo





.NET 4.0 and Visual Studio 2010 Page 159 of 548
D. HARSHA VARDHAN

T Th he e A Ar rr ra ay y c cl la as ss s

There is a pre-defined class called Array.
C# recognizes every array as an object for the System.Array class.
As an advantage of this, every array can access the members for that Array class.
For common programming needs, the Array class offers few properties and few
methods, which are useful for general manipulations of arrays.
Here, you can see the available properties of array class in this table:
Properties of Array Class
Property Description
Length Gets the array size (total no. of elements in the array)
Rank Gets the no. of dimensions of the array

Syntax to access the property: arrayname.Property



M Ma an ni ip pu ul la at ti io on ns s o on n A Ar rr ra ay ys s

Copying arrays:
Syn: arrayname.CopyTo(DestinationArray, StartIndex);
Ex: a.CopyTo(b, 0);
Note: The size and dimensions of both a and b arrays, should be same. It copies
all the elements into the destination array.

Sorting arrays:
Syn: Array.Sort(arrayname);
Ex: Array.Sort(a);
Note: Sort is a static method of Array class. It sorts all the array elements in
ascending order.

Reversing arrays:
Syn: Array.Reverse(arrayname);
Ex: Array.Reverse(a);





.NET 4.0 and Visual Studio 2010 Page 160 of 548
D. HARSHA VARDHAN

Note: Reverse is a static method of Array class. It exactly reverses the all
the array elements.

Searching arrays for an element:
Syn: Array.IndexOf(arrayname, value);
Ex: Array.IndexOf(a, 50);
Note: IndexOf is a static method of Array class. It searches the array for the
given value, and returns its index if it is found; otherwise it returns -1;


























using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArrayClassDemo
{
class Program
{
static void Main(string[] args)
{
//single dimensional array
Console.WriteLine("Single dimensional array:");
int[] a = { 643, 32948, 39, 23094, 112};
foreach (int i in a)
Console.Write(i + " ");
Console.WriteLine("\nLength: " + a.Length);
Console.WriteLine("Rank: " + a.Rank);

//double dimensional array
Console.WriteLine("\nDouble dimensional array:");
int[,] b = { {56, 1238, 8812}, {99, 2784, 2892} };
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
Console.Write(b[i,j] + " ");
Console.WriteLine();
}
Console.WriteLine("Length: " + b.Length);
Console.WriteLine("Rank: " + b.Rank);

//string array
Console.WriteLine("\nString array:");
Application 46: Array Class Demo





.NET 4.0 and Visual Studio 2010 Page 161 of 548
D. HARSHA VARDHAN




























string[] s = { "Java", "Corba", "C++", "Perl", "AJAX", "JavaScript" };
foreach (string i in s)
Console.Write(i + " ");

//copying arrays
Console.WriteLine("\n\nSingle dim array after copy:");
int[] c = new int[5];
a.CopyTo(c, 0);
foreach (int i in c)
Console.Write(i + " ");
//sorting arrays
Array.Sort(c);
Array.Sort(s);
Console.WriteLine("\n\nSingle dim array after sorting:");
foreach (int i in c)
Console.Write(i + " ");
Console.WriteLine("\n\nString array after sorting:");
foreach (string i in s)
Console.Write(i + " ");

//reversing arrays
Array.Reverse(c);
Array.Reverse(s);
Console.WriteLine("\n\nSingle dim array after reversing:");
foreach (int i in c)
Console.Write(i + " ");
Console.WriteLine("\n\nString array after reversing:");
foreach (string i in s)
Console.Write(i + " ");
Console.WriteLine("\n");

//searching an element
Console.WriteLine("Index of 'Java' in the string array is : " + Array.IndexOf(s,
"Java"));

Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 162 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :



T Th he e M Ma at th h c cl la as ss s

The System.Math class offers some pre-defined methods related to mathematical
operations.
Math is a static class. So, all of the methods of Math class are static methods, so that
you can access them without creating any object.
Here, you can see the available methods of Math class in this table:

Methods of Math Class
Method Description
Abs(value) Returns absolute (positive) value.
Pow(n, m) Returns n power m (n
m
) value
Min(n1, n2) Returns the minimum value among given two values.
Max(n1, n2) Returns the maximum value among given two values.
Sqrt(n) Returns the square root value of n.





.NET 4.0 and Visual Studio 2010 Page 163 of 548
D. HARSHA VARDHAN

Floor(n) Returns the previous integer value of n.
Ceiling(n) Returns the next integer value of n.
Round(n)
Returns rounded integer value of n. If the decimal part starts with a digit,
i.e. lesser than 5, it returns previous integer value; otherwise it returns next
integer value.
Round(n, dec) Returns rounded decimal value of n, based on the given no. of decimals.
Sign(n)
Returns 1, if the n value is positive.
Returns 0, if the n value is 0.
Returns -1, if the n value is negative.





















Fields of Math Class
Data Member Description
PI Its a constant. It contains the value of PI. (3.14)
namespace MathClassDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Math.Abs(-84));
Console.WriteLine(Math.Pow(10, 3));
Console.WriteLine(Math.Min(5, 100));
Console.WriteLine(Math.Max(5, 100));
Console.WriteLine(Math.Min(25, Math.Min(78, 87)));
Console.WriteLine(Math.Max(25, Math.Max(78, 87)));
Console.WriteLine(Math.Sqrt(9));
Console.WriteLine(Math.Floor(10.56));
Console.WriteLine(Math.Ceiling(10.56));
Console.WriteLine(Math.Round(10.56));
Console.WriteLine(Math.Round(10.23));
Console.WriteLine(Math.Round(10.2342, 2));
Console.WriteLine(Math.Round(10.2392, 2));
Console.WriteLine(Math.Sign(10));
Console.WriteLine(Math.Sign(-10));
Console.WriteLine(Math.PI);
Console.Read();
}
}
}
Application 47: Math Class Demo





.NET 4.0 and Visual Studio 2010 Page 164 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :



T Th he e S St tr ri in ng g c cl la as ss s

In C#, every string variable will be recognized as an object for System.String class.
The String class provides necessary properties and methods for performing all the
common and advanced manipulations on strings.
Here are the properties of String class.

Properties of String Class
Property Description Syntax
Length Gets the total no. of characters in the string object. stringobj.Length

Methods of String Class
Method Description Syntax
ToLower()
Converts the string into lower case and
returns it.
stringobj.ToLower()
ToUpper()
Converts the string into upper case and
returns it.
stringobj.ToUpper()
Trim()
Removes the blank spaces at left and
right side of the string and returns it.
stringobj.Trim()
TrimStart()
Removes the blank spaces at left of the
string and returns it.
stringobj.TrimStart()





.NET 4.0 and Visual Studio 2010 Page 165 of 548
D. HARSHA VARDHAN

TrimEnd()
Removes the blank spaces at right side
of the string and returns it.
stringobj.TrimEnd()
Equals()
Checks the string with the given string
for equality. If both are equal, returns
true, otherwise returns false.
stringobj.Equals(str)
StartsWith()
Checks whether the string contains the
given string at the left most side. If it
contains, returns true, otherwise
returns false.
stringobj.StartsWith(str)
EndsWith()
Checks whether the string contains the
given string at the right most side. If it
contains, returns true, otherwise
returns false.
stringobj.EndsWith(str)
Insert()
Inserts the given string value into the
string object at the specific index and
returns it.
stringobj.Insert(index,
stringvalue)
Remove()
Removes all the characters from the
string, starting from given index and
returns it.
stringobj.Remove(index)
Remove()
Removes specific no. of characters
(based on the given count) from the
string, starting from given index and
returns it.
stringobj.Remove(index, count)
Substring()
Gets the part of the string starting from
given index up to end of the string and
returns it.
stringobj.Substring(index)
Substring()
Gets the part of the string starting from
given index based on the expected
length and returns it.
stringobj.Substring(index, length)
Replace()
Replaces the each occurrence of given
character(s) with another character(s)
and returns it.
stringobj.Replace(old char, new
char)
PadLeft()
Pads out the string by adding the given
repeated character at the left side of
stringobj.PadLeft(total width,
padding char)





.NET 4.0 and Visual Studio 2010 Page 166 of 548
D. HARSHA VARDHAN

the string and returns it.
PadRight()
Pads out the string by adding the given
repeated character at the right side of
the string and returns it.
stringobj.PadRight(total width,
padding char)
ToCharArray()
Converts the string into a character
array, by treating each character in the
string as an element of the character
array, and returns it.
stringobj.ToCharArray()
Split()
Splits the string based on the given
separator character and finally returns a
string array.
stringobj.Split(separator char)
IndexOf()
Searches for existence of given
character(s) in the string. If it is found
(for the first occurrence), returns the
index of the first character. If it is not
found, then returns -1.
stringobj.IndexOf(str/char)
IndexOf()
Searches for existence of given
character(s) in the string starting from
specified index. If it is found (for the
first occurrence), returns the index of
the first character. If it is not found,
then returns -1.
stringobj.IndexOf(str/char, start
index)
LastIndexOf()
Searches for existence of given
character(s) in the string in reverse. If it
is found (for the first occurrence),
returns the index of the first character.
If it is not found, then returns -1.
stringobj.LastIndexOf(str/char)
LastIndexOf()
Searches for existence of given
character(s) in the string starting from
specified index in reverse. If it is found
(for the first occurrence), returns the
index of the first character. If it is not
found, then returns -1.
stringobj.LastIndexOf(str/char,
start index)






.NET 4.0 and Visual Studio 2010 Page 167 of 548
D. HARSHA VARDHAN



































using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringDemo
{
class Program
{
static void Main(string[] args)
{
//create string object
string s = "I am a .NET Developer";
Console.WriteLine("The original string is: " + s);
Console.WriteLine("The original string's length is: " + s.Length);

//copy strings
string s1;
s1 = s;
Console.WriteLine("\nThe copied string is: " + s1);

//concatenate strings
string s2 = "I am working in Wipro.";
string s3;
s3 = s1 +". " + s2;
Console.WriteLine("\nThe concatenated string is: " + s3);

//compare strings
if (s1 == s2)
Console.WriteLine("\ns1 and s2 are equal");
else
Console.WriteLine("\ns1 and s2 are not equal");
string s4 = s1;
if (s1 == s4)
Console.WriteLine("\ns1 and s4 are equal");
else
Console.WriteLine("\ns1 and s4 are not equal");

//convert the string into lower case
string s6 = s.ToLower();
Console.WriteLine("\nLower case is: " + s6);

//convert the string into upper case
string s7 = s.ToUpper();
Console.WriteLine("\nUpper case is: " + s7);
Application 48: Demo on String Class





.NET 4.0 and Visual Studio 2010 Page 168 of 548
D. HARSHA VARDHAN



































//string trimming
string s8 = " Hello, World ";
Console.WriteLine("\nString before trimming: " + s8);
string s9 = s8.Trim();
Console.WriteLine("\nString after trimming: " + s9);
string s10 = s8.TrimStart();
Console.WriteLine("\nString after left trimming: " + s10);
string s11 = s8.TrimEnd();
Console.WriteLine("\nString after right trimming: " + s11);

//check for the start
if (s.StartsWith("I"))
Console.WriteLine("\nString starts with 'I'");
else
Console.WriteLine("\nString doesn't starts with 'I'");
if (s.StartsWith("i"))
Console.WriteLine("\nString starts with 'i'");
else
Console.WriteLine("\nString doesn't starts with 'i'");

//check for the end
if (s.EndsWith("Developer"))
Console.WriteLine("\nString ends with 'Developer'");
else
Console.WriteLine("\nString doesn't ends with 'Developer'");
if (s.EndsWith("am"))
Console.WriteLine("\nString ends with 'am'");
else
Console.WriteLine("\nString doesn't ends with 'am'");

//insert character(s) into the string
string s12 = s.Insert(7, "ASP");
Console.WriteLine("\nString after insetion: " + s12);

//remove character(s) from the string
string s13 = s.Remove(7);
Console.WriteLine("\nString after removal: " + s13);
string s14 = s.Remove(7, 5);
Console.WriteLine("\nString after 5 characters removal: " + s14);

//get the sub string
string s15 = s.Substring(7);
Console.WriteLine("\nSub String is: " + s15);

string s16 = s.Substring(7, 4);
Console.WriteLine("\nAnother Sub String is: " + s16);

//replace the character(s)
string s17 = s.Replace("a", "x");
Console.WriteLine("\nString after replace: " + s17);





.NET 4.0 and Visual Studio 2010 Page 169 of 548
D. HARSHA VARDHAN




























//left padding
string s18 = s.PadLeft(26, '*');
Console.WriteLine("\nString after left padding: " + s18);

//right padding
string s19 = s.PadRight(26, '*');
Console.WriteLine("\nString after right padding: " + s19);

//split the string
string s20 = "This is first line.This is second line.This is third line.";
Console.WriteLine("\nA string for splitting:\n" + s20);
string[] s21 = s20.Split('.');
Console.WriteLine("\nThe string array after splitting:");
foreach (string temp in s21)
Console.WriteLine(temp);

//search the string for character(s)
Console.WriteLine("Index of 'D' is: " + s.IndexOf('D'));
Console.WriteLine("Index of 'x' is: " + s.IndexOf('x'));
Console.WriteLine("Index of 'am' is: " + s.IndexOf("am"));
Console.WriteLine("Index of 'a' is: " + s.IndexOf('a'));
Console.WriteLine("Index of 'a' after 3rd character is: " + s.IndexOf('a', 3));

Console.WriteLine("LastIndex of 'D' is: " + s.LastIndexOf('D'));
Console.WriteLine("LastIndex of 'x' is: " + s.LastIndexOf('x'));
Console.WriteLine("LastIndex of 'am' is: " + s.LastIndexOf("am"));
Console.WriteLine("LastIndex of 'a' is: " + s.LastIndexOf('a'));
Console.WriteLine("LastIndex of 'a' after 3rd character is: " + s.LastIndexOf('a', 3));

Console.Read();
}
}
}







.NET 4.0 and Visual Studio 2010 Page 170 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :







.NET 4.0 and Visual Studio 2010 Page 171 of 548
D. HARSHA VARDHAN

T Th he e D Da at te eT Ti im me e S St tr ru uc ct tu ur re e

Library: System.DateTime
To store date and time values, you require creating an instance for DateTime
structure.
The instance for System.DateTime class, can hold date and time value in US format:
Date and time Format: mm/dd/yyyy hh:mi:ss AM/PM

O Ob bj je ec ct t I Im mp pl le em me en nt ta at ti io on n: :

Create an instance for System.DateTime structure:
DateTime dtobj;
Assign any date&time value:
dtobj = Convert.ToDateTime(mm/dd/yyyy hh:mi:ss AM/PM);
Assign System date&tme:
dtobj = DateTime.Now;

Properties of DateTime Structure
Property Description Syntax
Day Gets the day (dd) dtobj.Day
Month Gets the month (mm) dtobj.Month
Year Gets the year (yy) dtobj.Year
Hour Gets the hour (hh) (in 24-hours format) dtobj.Hour
Minute Gets the minute (mi) dtobj.Minute
Second Gets the second (ss) dtobj.Second
MilliSecond Gets the milli second dtobj.MilliSecond
DayOfYear Gets the index of the current day, in the year (0 to 366) dtobj.DayOfYear
DayOfWeek Gets the current week name (Sunday, Monday,,Saturday) dtobj.DayOfWeek


Methods of DateTime Structure
Method Description Syntax
ToString()
Returns the date and time value as string
in following format.
mm/dd/yyy hh:mi:ss AM/PM
dtobj.ToString()





.NET 4.0 and Visual Studio 2010 Page 172 of 548
D. HARSHA VARDHAN

ToShortDateString()
Returns the date value as string in the
following format.
mm/dd/yyyy
dtobj.ToShortDateString()
ToLongDateString()
Returns the date value as string in the
following format.
Day, Month dd, yyyy
dtobj.ToLongDateString()
ToShortTimeString()
Returns the time value as string in the
following format.
hh:mi AM/PM
dtobj.ToShortTimeString()
ToLongDateString()
Returns the date value as string in the
following format.
hh:mi:ss AM/PM
dtobj.ToLongTimeString()
AddDays()
Adds the given no. of days to the date
object and returns it.
dtobj.AddDays(n)
AddMonths()
Adds the given no. of months to the date
object and returns it.
dtobj.AddMonths(n)
AddYears()
Adds the given no. of years to the date
object and returns it.
dtobj.AddYears(n)
AddHours()
Adds the given no. of hours to the date
object and returns it.
dtobj.AddHours(n)
AddMinutes()
Adds the given no. of minutes to the date
object and returns it.
dtobj.AddMinutes(n)
AddSeconds()
Adds the given no. of seconds to the date
object and returns it.
dtobj.AddSeconds(n)
AddMilliSeconds()
Adds the given no. of milli seconds to the
date object and returns it.
dtobj.AddMilliSeconds(n)

Static Properties of DateTime Structure
Property Description Syntax
Now Gets the current system date and time DateTime.Now

Static Methods of DateTime Structure
Method Description Syntax
IsLeapYear()
Returns a bool value, that indicates whether
the given year is a leap year or not.
DateTime.IsLeapYear(year)





.NET 4.0 and Visual Studio 2010 Page 173 of 548
D. HARSHA VARDHAN

DaysInMonth()
Returns the no. of days in the given month,
based on the given year.
DateTime.DaysInMonth(year,
month)

D Da at te e C Co om mp pa ar ri is so on ns s

Date comparisons are very simple in C#, because DateTime structure overloads the
necessary relational operators such as ==, !=, <, >, <=, >=.
You can directly use these operators between two dates and get the appropriate result.


D Da at te e D Di if ff fe er re en nc ce e

To find out the difference between two dates, simply use - operator, which is already
overloaded.
When you use this, you can get the result as an System.TimeSpan object.





















using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DateTimeDemo
{
class Program
{
static void Main(string[] args)
{
//create DateTime obj
DateTime dt1;
dt1 = Convert.ToDateTime("7/16/2009 6:23 PM");
DateTime dt2 = DateTime.Now;
//display dates
Console.WriteLine("dt1 is: " + dt1.ToString());
Console.WriteLine("dt2 is: " + dt2.ToString());

//display individual values
Console.WriteLine("\nIndividual values of dt2:");
Console.WriteLine("dd: " + dt2.Day);
Console.WriteLine("mm: " + dt2.Month);
Console.WriteLine("yyyy: " + dt2.Year);
Console.WriteLine("hh: " + dt2.Hour);
Console.WriteLine("mi: " + dt2.Minute);
Application 49: DateTime Structure Demo





.NET 4.0 and Visual Studio 2010 Page 174 of 548
D. HARSHA VARDHAN



































Console.WriteLine("ss: " + dt2.Second);
Console.WriteLine("ms: " + dt2.Millisecond);

//implement user-defined date formats
string IndianFormattedDate = dt2.Day + "-" + dt2.Month + "-" + dt2.Year;
Console.WriteLine("\nDate in indian format: " + IndianFormattedDate);

//display the day index
Console.WriteLine("\nDay of year: " + dt2.DayOfYear);
Console.WriteLine("\nDay of week: " + dt2.DayOfWeek);

//long and short formatted date and time
Console.WriteLine("\nShort date format: " + dt2.ToShortDateString());
Console.WriteLine("\nLong date format: " + dt2.ToLongDateString());
Console.WriteLine("\nShort time format: " + dt2.ToShortTimeString());
Console.WriteLine("\nLong time format: " + dt2.ToLongTimeString());

//adding values
DateTime dt3 = dt2.AddDays(5);
Console.WriteLine("\ndt2 after adding 5 days: " + dt3.ToShortDateString());
DateTime dt4 = dt2.AddMonths(5);
Console.WriteLine("\ndt2 after adding 5 months: " + dt4.ToShortDateString());
DateTime dt5 = dt2.AddYears(5);
Console.WriteLine("\ndt2 after adding 5 years: " + dt5.ToShortDateString());
DateTime dt6 = dt2.AddHours(5);
Console.WriteLine("\ndt2 after adding 5 hours: " + dt6.ToLongTimeString());
DateTime dt7 = dt2.AddMinutes(5);
Console.WriteLine("\ndt2 after adding 5 minutes: " + dt7.ToLongTimeString());
DateTime dt8 = dt2.AddSeconds(5);
Console.WriteLine("\ndt2 after adding 5 seconds: " + dt8.ToLongTimeString());

//check whether this is leap year or no
if (DateTime.IsLeapYear(dt2.Year))
Console.WriteLine("\nThis is a leap year.");
else
Console.WriteLine("\nThis is not a leap year.");

//get the total no. of days in this month
Console.WriteLine("\nNo. of days in this month: " + DateTime.DaysInMonth(dt2.Year,
dt2.Month));

//date comparision
if (dt1 == dt2)
Console.WriteLine("\ndt1 and dt2 are equal.");
else if (dt1 > dt2)
Console.WriteLine("\ndt1 is greater than dt2.");
else if (dt1 < dt2)
Console.WriteLine("\ndt1 is less than dt2.");

//date difference
TimeSpan ts = dt2 - dt1;






.NET 4.0 and Visual Studio 2010 Page 175 of 548
D. HARSHA VARDHAN






O Ou ut tp pu ut t: :



Console.WriteLine("\nThe difference between dt2 and dt1 is: " + ts.Days + " days.");
Console.Read();
}
}
}







.NET 4.0 and Visual Studio 2010 Page 176 of 548
D. HARSHA VARDHAN

T Th he e R Ra an nd do om m c cl la as ss s

Library: System.Random
This class is used to generate a random number, at any time.
In future, while performing different programming logics, this random number generation
concept may be required.

Implementation:
Create an instance:
Random r = new Random();
Generate the random number based on the given boundary values:
r.Next(min value, max value);




















using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RandomDemo
{
class Program
{
static void Main(string[] args)
{
Random r = new Random();
for (int i = 0; i < 300; i++)
{
Console.Write(r.Next(1, 300) + ", ");
}
Console.Read();
}
}
}
Application 50: Demo on Random Class





.NET 4.0 and Visual Studio 2010 Page 177 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :



C Co ol ll le ec ct ti io on ns s

The concept of collections is basically developed from Arrays.
Already you know that, arrays are multiple value containers of fixed type.
In order to hold different types of values on the same array, you require collections.
Another advantage of collections is those are dynamic sizable. In other words, the array
is of fixed size and the collection is of dynamic size.
Finally, if you dont know how many values are to be stored in the array at the time of its
declaration, you require to use collections; (or) if you want to store different type of
values in the same array, at that case also, you require to use collections.
.NET offers some pre-defined classes for maintenance of collections.

C Co ol ll le ec ct ti io on n C Cl la as ss se es s: :

List:
1) Contains n no. of values of same type. Its a generic class.
2) This is member of System.Collections.Generic namespace.
ArrayList:
1) Contains n no. of values of different types.
2) This is member of System.Collections namespace.






.NET 4.0 and Visual Studio 2010 Page 178 of 548
D. HARSHA VARDHAN

I Im mp pl le em me en nt ta at ti io on n o of f L Li is st t c cl la as ss s: :

Import namespace:
using System.Collections.Generic;
Create instance:
List<data type> obj = new List<data type>();
Add values:
obj.Add(value);
Get the currently existing no. of values in the collection:
obj.Count
Get the individual element in the collection:
obj[index];



I Im mp pl le em me en nt ta at ti io on n o of f A Ar rr ra ay yL Li is st t c cl la as ss s: :

Import namespace:
using System.Collections;
Create instance:
ArrayList obj = new ArrayList();
Add values:
obj.Add(value);
Get the currently existing no. of values in the collection:
obj.Count
Get the individual element in the collection:
obj[index];










using System.Collections.Generic;

namespace ListClass
{
class Program
{
static void Main(string[] args)
Application 51: Demo on List Class





.NET 4.0 and Visual Studio 2010 Page 179 of 548
D. HARSHA VARDHAN



















O Ou ut tp pu ut t: :



















using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ArrayListClass
{
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();

al.Add("Hai");
Application 52: Demo on ArrayList Class
{
List<string> MyMessages = new List<string>();

MyMessages.Add("Good Morning");
MyMessages.Add("Good Afternoon");
MyMessages.Add("Good Evening");
MyMessages.Add("Good Night");

//MyMessages.Add(10); //error

Console.WriteLine(MyMessages.Count + " messages found.\n");
foreach (string s in MyMessages)
{
Console.WriteLine(s);
}

Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 180 of 548
D. HARSHA VARDHAN













O Ou ut tp pu ut t: :



C Co ol ll le ec ct ti io on n I In ni it ti ia al li iz ze er r

As per the previous examples with collections, we require to add the values to the
collections using Add() method.
Suppose you want to add so many elements to the collection. Then if you are using it
takes Add() method (as above), it takes no. of lines of code.
To solve this problem, Collection Initializer can be used.
Purpose: To initialize the elements of a collection, at the time declaration.
Syntax:
1) List collection class:
List<data type> obj = new List<data type>() { val1, val2, . };
2) ArrayList collection class:
ArrayList obj = new ArayList() { val1, val2, . };



al.Add("How r u");
al.Add(1000);
al.Add(true);
al.Add(DateTime.Now);

Console.WriteLine(al.Count + " values found.\n");
for (int i = 0; i < al.Count; i++)
Console.WriteLine(al[i]);

Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 181 of 548
D. HARSHA VARDHAN




















O Ou ut tp pu ut t: :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace CollectionInitializerDemo
{
class Program
{
static void Main(string[] args)
{
//Collection Initializer with List class
Console.WriteLine("List:");
List<string> lst = new List<string>() { "one", "two", "three", "four" }; //collection
initializer
lst.Add("five"); //add additional elements if required

foreach (string s in lst)
Console.WriteLine(s);

Console.WriteLine("\n\nArray List:");
ArrayList arrlst = new ArrayList() { "emp_001", "Srinivas", 8900, "Washington" };
//collection initializer
arrlst.Add(DateTime.Now); //add additional elements if required
foreach (object s in arrlst)
Console.WriteLine(s);

Console.Read();
}
}
}
Application 53: Demo on Collection Initializer





.NET 4.0 and Visual Studio 2010 Page 182 of 548
D. HARSHA VARDHAN

T Th he e P Pr ri in nt tD Do oc cu um me en nt t c cl la as ss s

.NET supports to print any type of documents through the printer.
Library: System.Drawing.Printing.PrintDocument
This class object represents a document (any type of file), that is ready to print.

Note: By default, System.Drawing assembly will not be linked with the Console applications.
Thats why you need to add a reference to that as follows:
Click on Project menu Add Reference.
Select System.Drawing assembly.
Click on OK. Then the System.Drawing assembly will be linked with the current
project and it will be displayed in References folder in the Solution Explorer.


Implementation:
Import the namespace:
using System.Drawing.Printing;
Construct the object:
PrintDocument obj = new PrintDocument();
Assign the document name, that is to be printed:
obj.DocumentName = file path to be printed;
Start Printing:
obj.Print();











Application 54: Demo on Printing
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Printing;

namespace PrintingDemo
{
class Program
{





.NET 4.0 and Visual Studio 2010 Page 183 of 548
D. HARSHA VARDHAN










O Ou ut tp pu ut t: :


static void Main(string[] args)
{
PrintDocument doc = new PrintDocument();
doc.DocumentName = "c:\\SampleDocument.doc";
doc.Print();
Console.WriteLine("Printing started...");
Console.Read();
}
}
}







.NET 4.0 and Visual Studio 2010 Page 184 of 548
D. HARSHA VARDHAN

The DriveInfo class

.NET support to access the available drives information on the computer such as C: drive,
D: drive etc.
This drives may include with hard disks, CD-ROM drives, DVD-ROM drives, pen drives etc.
It offers to get the volume labels, total space and current free space of the drives etc.

Library: System.IO.DriveInfo

The DriveInfo class object can represent a drive on the computer. It offers several properties
and methods to access the related information of the drive.

Object Construction:
Syn: DriveInfo obj = new DriveInfo(drive letter);
Ex: DriveInfo obj = new DriveInfo(c);

You can observe the list of all available properties, methods of this class.

Properties of DriveInfo class
Property Description
IsReady Indicates whether the drive is ready or not (true / false)
Name Represents the name of the drive with drive letter. (Ex: c:\)
DriveType Represents the type of the drive. (like Fixed, CD Rom, Removable)
VolumeLabel Represents the volume label.
DriveFormat Represents the file system of the drive like FAT32, NTFS, CDFS etc.
TotalSize Represents the total memory capacity of the drive in bytes.
TotalFreeSpace Represents the total free space in the drive in bytes.

Static Methods of DriveInfo class
Method Description
GetDrives() Returns all the currently available drive objects in the form of an array.







Application 55: Demo on DriveInfo class For a Single Drive
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;





.NET 4.0 and Visual Studio 2010 Page 185 of 548
D. HARSHA VARDHAN























O Ou ut tp pu ut t: :









namespace DriveInfoDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the drive letter (a to z):");
string driveletter = Console.ReadLine();

DriveInfo d = new DriveInfo(driveletter);

if (d.IsReady)
{
Console.WriteLine(d.Name);
Console.WriteLine(d.DriveType);
Console.WriteLine(d.VolumeLabel);
Console.WriteLine(d.DriveFormat);
Console.WriteLine(d.TotalSize + " bytes.");
Console.WriteLine(d.TotalFreeSpace + " bytes.");
}
else
Console.WriteLine(d.Name + " - " + " Not Ready.");

Console.Read();
}
}
}

Application 56: Demo on DriveInfo class For Multiple Drives
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace GetDrivesDemo
{





.NET 4.0 and Visual Studio 2010 Page 186 of 548
D. HARSHA VARDHAN





















O Ou ut tp pu ut t: :

class Program
{
static void Main(string[] args)
{
DriveInfo[] dinfo = DriveInfo.GetDrives();
Console.WriteLine(dinfo.Length + " drives found on this computer.");
foreach (DriveInfo d in dinfo)
{
Console.WriteLine();
if (d.IsReady)
{
Console.WriteLine(d.Name);
Console.WriteLine(d.DriveType);
Console.WriteLine(d.VolumeLabel);
Console.WriteLine(d.DriveFormat);
Console.WriteLine(d.TotalSize + " bytes.");
Console.WriteLine(d.TotalFreeSpace + " bytes.");
}
else
Console.WriteLine(d.Name + " - " + d.DriveType + " - Not Ready.");
}
Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 187 of 548
D. HARSHA VARDHAN

The DirectoryInfo class

The System.IO namespace necessary API to access the folders (directories) information
also.
According to this, a folder is to be represented as an object.
The folder object is able to get the details of the folder like folder full path, sub
directories and files etc.

Library: System.IO.DirectoryInfo

This class object represents a folder on the file system. This able to get the information
of the folder and also to perform certain operations on that folder.

Object Construction:
Syn: DirectoryInfo obj = new DirectoryInfo(path of the directory);
Ex: DirectoryInfo obj = new DirectoryInfo(c:\\windows);

You can observe the list of all available properties, methods of this class.

Properties of DirectoryInfo class
Property Description
Exists
Checks the existence of the directory. If it exists, it indicates
true. Otherwise, it indicates false.
Name Gets only the name of the directory (without path)
FullName Gets the name along with full path.
CreationTime Gets the date & time, when the directory is created.
LastAccessTime Gets the date & time, when the directory is accessed last time.
LastWriteTime Gets the date & time, when the directory is modified last time.
Parent
Gets the directory object, which represents the respective parent
folder.
Root Gets the name of the drive, in which the directory exists.

Methods of DirectoryInfo class
Method Description
Create() Creates a new directory.
CreateSubdirectory(name) Creates a sub directory.
Delete() Deletes the directory, if it is empty.
Delete(true)
Deletes the entire directory, along with its sub directories and
files.





.NET 4.0 and Visual Studio 2010 Page 188 of 548
D. HARSHA VARDHAN

GetFiles() Gets all the files in the directory as FileInfo class object array.
GetFiles(search pattern)
Gets the files in the directory as FileInfo class object array,
based on the given search pattern.
GetDirectories()
Gets all the directories in the directory as DirectoryInfo class
object array.
GetDirectories(search
pattern)
Gets the directories in the directory as DirectoryInfo class object
array, based on the given search pattern.





























Application 57: Demo on DirectoryInfo class
using System.IO;

namespace DirectoryInfoDemo1
{
class Program
{
static void Main(string[] args)
{
string directorypath = "c:\\windows\\help";
DirectoryInfo dinfo = new DirectoryInfo(directorypath);

if (dinfo.Exists)
{
Console.WriteLine("Directory Name: " + dinfo.Name);
Console.WriteLine("Directory Full Path: " + dinfo.FullName);
Console.WriteLine("\nCreated on: " + dinfo.CreationTime);
Console.WriteLine("Last accessed on: " + dinfo.LastAccessTime);
Console.WriteLine("Last modified on: " + dinfo.LastWriteTime);
Console.WriteLine("\nParent: " + dinfo.Parent.FullName);
Console.WriteLine("Root: " + dinfo.Root);

Console.WriteLine("\nFiles:");
FileInfo[] fobjs = dinfo.GetFiles();
foreach (FileInfo f in fobjs)
Console.WriteLine(f.FullName);

Console.WriteLine("\nSub Directories:");
DirectoryInfo[] dobjs = dinfo.GetDirectories();
foreach (DirectoryInfo d in dobjs)
Console.WriteLine(d.FullName);
}
else
Console.WriteLine(directorypath + " is not available on the system.");

Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 189 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :
























Application 58: Creating a Directory
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DirectoryInfoDemo2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the directory path:");
string directorypath = Console.ReadLine();
DirectoryInfo dinfo = new DirectoryInfo(directorypath);

if (!dinfo.Exists)
{
dinfo.Create();
Console.WriteLine("Directory created.");
}
else
Console.WriteLine(directorypath + " is already exists.");

Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 190 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :
























O Ou ut tp pu ut t: :

Application 59: Deleting a Directory
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DirectoryInfoDemo3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the directory path:");
string directorypath = Console.ReadLine();
DirectoryInfo dinfo = new DirectoryInfo(directorypath);

if (dinfo.Exists)
{
dinfo.Delete(true);
Console.WriteLine("Directory deleted.");
}
else
Console.WriteLine(directorypath + " doesn't exists.");

Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 191 of 548
D. HARSHA VARDHAN

The FileInfo class

Similar to the drives and folders, the System.IO namespace is used to manipulate the
files also.
The file manipulations include with checking for the file existence, get the file details like
file size, file attributes, created date, last accessed date etc., and write new content to
the files and also read content from existing files.
Every file is to be represented as an object, created for System.IO.FileInfo class.

Library: System.IO.FileInfo

This class object represents a file on the file system. This able to get the information of
the file and also to perform certain operations on that folder.

Object Construction:
Syn: FileInfo obj = new FileInfo(path of the file);
Ex: FileInfo obj = new FileInfo(c:\\tc\list.h);

You can observe the list of all available properties, methods of this class.

Properties of FileInfo class
Property Description
Exists
Checks the existence of the directory. If it exists, it indicates
true. Otherwise, it indicates false.
Name Gets only the name of the file (without path)
FullName Gets the name along with full path.
Extension Gets the extension of the file.
DirectoryName Gets the name of the file, in which the file exists.
Length Gets the size of the file (in bytes).
CreationTime Gets the date & time, when the file is created.
LastAccessTime Gets the date & time, when the file is accessed last time.
LastWriteTime Gets the date & time, when the file is modified last time.

Methods of FileInfo class
Method Description
Delete() Deletes the file permanently.
CopyTo(destination file name)
Copies the file into the destination location with the specified
file name.
MoveTo(destination file name)
Moves the file into the destination location with the specified
file name.





.NET 4.0 and Visual Studio 2010 Page 192 of 548
D. HARSHA VARDHAN






























Application 60: Demo on FileInfo class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace FileInfoDemo
{
class Program
{
static void Main(string[] args)
{
string filepath;
Console.WriteLine("Enter the file path:");
filepath = Console.ReadLine();

FileInfo fobj = new FileInfo(filepath);

if (fobj.Exists)
{
Console.WriteLine("\nName: " + fobj.Name);
Console.WriteLine("Full Name: " + fobj.FullName);
Console.WriteLine("Extension: " + fobj.Extension);
Console.WriteLine("Directory: " + fobj.DirectoryName);
Console.WriteLine("File Size: " + fobj.Length + " bytes");
Console.WriteLine("Created on: " + fobj.CreationTime);
Console.WriteLine("Last Accessed on: " + fobj.LastAccessTime);
Console.WriteLine("Last Modified on: " + fobj.LastWriteTime);
}
else
Console.WriteLine("File not found.");

Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 193 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :



File Streams
To write / read the content to / write the file, you require file streams.
A file stream acts as a pointer for the file, which contains the memory address of the file
on the disc.
There are two types of file streams.
1) Reading Streams
2) Writing Streams

API: System.IO.StreamReader (to read the content of the file)
System.IO.StreamWriter (to write the content into the file)


Writing content to the file
Import the API
using System.IO;
Create the stream writer object
StreamWriter sw = new StreamWriter(file name);
Write the content
sw.Write(content here);
Close the Writer
sw.Close();







.NET 4.0 and Visual Studio 2010 Page 194 of 548
D. HARSHA VARDHAN

Reading content from the file
Import the API
using System.IO;
Create the stream reader object
StreamReader sr = new StreamReader(file name);
Reade the content
sr.ReadToEnd();
Close the Reader
sr.Close();
Application 61: File Writing Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace FileWriteDemo
{
class Program
{
static void Main(string[] args)
{
string filepath;
Console.WriteLine("Enter the file path:");
filepath = Console.ReadLine();
FileInfo fobj = new FileInfo(filepath);

if (!fobj.Exists)
{
string content;
Console.WriteLine("\nEnter content to write:");
content = Console.ReadLine();

StreamWriter sw = new StreamWriter(filepath);
sw.Write(content);
sw.Close();

Console.WriteLine("\nWritten successfully!");
}
else
Console.WriteLine("File already exists.");





.NET 4.0 and Visual Studio 2010 Page 195 of 548
D. HARSHA VARDHAN





O Ou ut tp pu ut t: :

























Application 62: File Reading Demo
using System;
using System.IO;

namespace FileReadDemo
{
class Program
{
static void Main(string[] args)
{
string filepath;
Console.WriteLine("Enter the file path:");
filepath = Console.ReadLine();
FileInfo fobj = new FileInfo(filepath);

if (fobj.Exists)
{
StreamReader sr = new StreamReader(filepath);
string content = sr.ReadToEnd();
Console.WriteLine(content);

sr.Close();
}
else
Console.WriteLine("File not found.");

Console.Read();
}
}
}

Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 196 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :







.NET 4.0 and Visual Studio 2010 Page 197 of 548
D. HARSHA VARDHAN

M Mu ul lt ti i T Th hr re ea ad di in ng g

Multi Threading is one of the rich features of .NET applications.
Using this feature, the user is able to create multi-threaded applications.
This concept is introduced in VC++. This is also supported by Java.
Definition of Multi Threading: The ability of an application that maintains multiple
threads at run time.
Definition of Thread: The thread is a sub process (part of the process). That means it
has some code to execute.
Advantage of Multi-Threading: Using multi threading, you can break a complex
task in a single application into multiple threads that execute independently and
simultaneously.
In other words, multi threading is the sub form of multi tasking.
Before starting with the implementation of Multi Threading, you should recollect the
concept of Multi-Tasking.

Multi Tasking:
Def: Ability of the OS, that is able to perform more than one task, at-a-time
(simultaneously) is called as Multi-Tasking.
As a part of this, OS allocates the CPU clock (CPU capacity) for each task.
Note: Just like multi-tasking, OS allocates the CPU clock for each thread.

Threading Architecture:










.NET Application

Thread 1

Thread 2

Thread 3
CLR

OS
Processor





.NET 4.0 and Visual Studio 2010 Page 198 of 548
D. HARSHA VARDHAN

Implementation of Multi Threading:
.NET Framework offers a namespace called System.Threading for implementation of
multi threading.
Library: System.Threading.Thread
This class object represents a thread.

Import the API:
using System.Threading;
Create the Thread Object:
Thread th = new Thread(method_name);
Start the Thread:
th.Start();






















Application 63: Simple Demo on Multi Threading
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SimpleThreadingDemo
{
class ThreadingDemo
{
private void FirstMethod()
{
for (int i = 1; i <= 300; i++)
Console.Write("i=" + i + " ");
}
private void SecondMethod()
{
for (int j = 1; j <= 300; j++)
Console.Write("j=" + j + " ");
}
public void Display()
{
Thread th1 = new Thread(FirstMethod);
Thread th2 = new Thread(SecondMethod);

th1.Start();
th2.Start();





.NET 4.0 and Visual Studio 2010 Page 199 of 548
D. HARSHA VARDHAN










O Ou ut tp pu ut t: :




}
}
class Program
{
static void Main(string[] args)
{
ThreadingDemo td = new ThreadingDemo();
td.Display();
Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 200 of 548
D. HARSHA VARDHAN

Thread States

The thread state specifies the current status of the thread. Sometimes, the thread
automatically switches from one state to another state automatically; at some other times, you
can switch its state by using the methods offered by Thread class.

The following diagram called Thread Life Cycle describes the different states of a
thread.

Thread Life Cycle


















1. Ready: This is the initial state. The thread object is created.
2. Running: The thread is currently being executed.
3. Sleeping: The thread is temporarily paused. .NET framework offers automatic switching
between Running and Sleeping states, when other threads are executed.
Ready
Running
Sleeping
Dead
Start()
Automatic / Sleep()
Automatic
Automatic / Abort()
Suspended
Suspend()
Resume()





.NET 4.0 and Visual Studio 2010 Page 201 of 548
D. HARSHA VARDHAN

4. Suspended: The thread is temporarily suspended (paused). It will be continued, when
you call Resume() method.
5. Dead: The thread was closed; it cant be restarted or continued.

Thread class methods:

o thobj.Start()
This method starts-up the thread execution.

o Thread.Sleep(mille_sec)
This method puts the thread under Sleeping state, up to a certain no. of mille
seconds. When the given no. of mille seconds are completed, automatically the
thread execution will be continued.

o thobj.Suspend()
This is similar to Sleep() method, but here, no time limit will be given. That
means whenever the Suspend() method is called, the thread will be put under
Suspended state, until the Resume() method is called.

o thobj.Resume()
This is to continue the thread execution that is under Suspended state. This
method wont work if the thread is not under Suspended state.

o thobj.Abort()
This is close the thread execution completely, at any time. Once, if the Abort()
method is called, the thread cant be started or resumed. This is the end of every
thread life cycle.







Application 64: Demo on Thread States





.NET 4.0 and Visual Studio 2010 Page 202 of 548
D. HARSHA VARDHAN
































using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadLifeCycleDemo
{
class ThreadingDemo
{
private void FirstMethod()
{
for (int i = 1; i <= 50; i++)
{
Console.Write("i=" + i + " ");
Thread.Sleep(1000);
}
}
private void SecondMethod()
{
for (int j = 1; j <= 50; j++)
{
Console.Write("j=" + j + " ");
Thread.Sleep(1000);
if (j == 20)
th1.Suspend();
else if (j == 30)
th1.Resume();
}
}

Thread th1, th2;

public void Display()
{
th1 = new Thread(FirstMethod);
th2 = new Thread(SecondMethod);
th1.Start();
th2.Start();
}
}
class Program
{
static void Main(string[] args)
{
ThreadingDemo td = new ThreadingDemo();
td.Display();
Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 203 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :


A An no on ny ym mo ou us s M Me et th ho od ds s

This is used to create a method, without any name.
Syntax:
delegate()
{
//some code
}

Application 65: Demo on Anonymous Methods
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace AnonymousMethodsDemo
{
class ThreadingDemo
{
public void Display(string name)
{
Thread th1 = new Thread(delegate()
{
while (true)
{
Console.WriteLine("Welcome to " + name);
Thread.Sleep(500);
}
});
th1.Start();
}
}






.NET 4.0 and Visual Studio 2010 Page 204 of 548
D. HARSHA VARDHAN









O Ou ut tp pu ut t: :



class Program
{
static void Main(string[] args)
{
string name;
Console.WriteLine("Enter your name:");
name = Console.ReadLine();

ThreadingDemo td = new ThreadingDemo();
td.Display(name);

Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 205 of 548
D. HARSHA VARDHAN

S Sp pe ee ec ch h T Tr ra an ns sl la at ti io on n

This is to translate the text as speech.
This makes us to listen a voice from the speakers that reads some specified text.
Library: System.Speech.Synthesis.SpeechSynthesizer
This class used to speak the required text through the speakers.

Implementation:
Create the object of SpeechSynthesizer class:
SpeechSynthesizer ss = new SpeechSynthesizer();
Set the volume (1 to 100):
ss.Volume = n;
Set the speed of speaking (-10 to +10):
ss.Rate = n;
Change the voice gender and age:
ss.SelectVoiceByHints(VoiceGender.xxxx, VoiceAge.xxxx);
Speak the text:
ss.SpeakAsync(message);















Application 66: Demo on Speech Translation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Speech.Synthesis;

namespace SpeechTranslationDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter text to speak:");
string TextToSpeak = Console.ReadLine();

SpeechSynthesizer ss = new SpeechSynthesizer();

ss.Volume = 100; //1 to 100





.NET 4.0 and Visual Studio 2010 Page 206 of 548
D. HARSHA VARDHAN









O Ou ut tp pu ut t: :




M Me em mo or ry y M Ma an na ag ge em me en nt t

Every application requires some amount of memory to run.
That memory will be allocated in the primary memory (RAM).
For every variable, individual memory will be allocated.
The RAM contains two memory locations.
o Stack
o Heap
Now, we need to understand, where the
application memory is getting allocated in the
RAM.
The storage area in the RAM depends on the
data type that you are using for declaring the
variable in the program.
The data types are two types in C#
o Value Types
o Reference Types

ss.Rate = -3; // -10 to +10

ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Child);

ss.SpeakAsync(TextToSpeak);

Console.Read();
}
}
}


Stack

Heap
RAM





.NET 4.0 and Visual Studio 2010 Page 207 of 548
D. HARSHA VARDHAN

1) Value Types:
Def: Whenever a data type is designed based on a structure, it can be called as
Value Type.
All the standard data types built based on structures.
You can see the list of data types and respective structures here:
Data Type Structure Name
sbyte System.SByte
byte System.Byte
short System.Int16
ushort System.UInt16
int System.Int32
uint System.UInt32
long System.Int64
ulong System.UInt64
float System.Single
double System.Double
decimal System.Decimal
bool System.Boolean
char System.Char

So finally, the following are value types in C#:
1) Structures
2) Enumerations
3) sbyte, byte, short, ushort, int, uint, long, ulong, float, double, decimal, bool,
char, decimal, DateTime

Note 1: The value types cant be inherited.
Note 2: All the value types (structures and enumerations), are derived from a
common base class called System.ValueType.

2) Reference Types:
Def: Whenever a data type is designed based on a class, it can be called as
Reference Type.
The following are the reference types in C#:
1) Classes
2) Interfaces
3) String, Object
Reference types support inheritance.





.NET 4.0 and Visual Studio 2010 Page 208 of 548
D. HARSHA VARDHAN

The Value Type variables will be allocated in the Stack.
The Reference Type variables (objects) will be allocated in the Heap.

The System.Object class:
This class acts as super class for all other classes (pre-defined / user-defined
classes).
So, it can be called as Ultimate base class.












The Object class offers the following methods.
Method Description
Equals(value) Checks the equality of the value of the object with the given
argument value. If both are equal, then returns true, otherwise
returns false.
Ex:
MyObj.Equals(AnotherObject);
In this example, MyObj will be compared with AnotherObject.
GetType() Gets the name of the class, for which, it is declared.
Ex:
MyObj.GetType();
ToString() Converts the value of the object and returns it.
Ex:
MyObj.ToString();
In this example, the value of MyObj will be converted as string
type, and that string value will be returned.


Object
ValueType
Classes Structures Enumerations





.NET 4.0 and Visual Studio 2010 Page 209 of 548
D. HARSHA VARDHAN



























O Ou ut tp pu ut t: :
Application 67: Demo on System.Object class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ObjectClassMethods
{
class Program
{
static void Main(string[] args)
{
int x = 100;
int y = 100;

Console.WriteLine("x is " + x);
Console.WriteLine("y is " + y);

Console.WriteLine();

if (x.Equals(y))
Console.WriteLine("x is equal to y");
else
Console.WriteLine("x is not equal to y");

Console.WriteLine("\nx is the type of " + x.GetType());

string s = x.ToString();
Console.WriteLine("\nThe integer value after converting into string is: " + s);

Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 210 of 548
D. HARSHA VARDHAN


Garbage Collector:
This is one of the components of CLR (Common Language Runtime).
This component is dedicated for de-allocating the un-used memory of the
application, automatically.
This uses Mark and Compact algorithm for clearing the un-used memory.
Mark: Markup the un-used objects and push those objects towards up.
Compact: Clear the marked objects memory.











Note: The above functionality is in-built in Garbage collector component. Anyhow, there is a
provision for the programmer to command the garbage collector to perform garbage collection
at run time, programmatically. Then use the following method from System.GC class.
Syn: System.GC.Collect();

Object 1
Object 2
Object 3
Object 4
The Memory Heap





.NET 4.0 and Visual Studio 2010 Page 211 of 548
D. HARSHA VARDHAN

L LI IN NQ Q

LINQ (pronounced link) stands for Language Integrated Query.
This concept is introduced in .NET Framework 3.5.
This is a query writing technology.
This is most useful while working large amount of data in the live projects.

I In nt tr ro od du uc ct ti io on n: :

In relational database system, data is organized in the form of tables, on which you can
write SQL queries to retrieve the required data according to the requirement in the
application.
But you cant write a query on the non-database data, which in the form of objects in the
application. There, you can write the queries using the new concept called LINQ.
You can write queries on arrays, objects, databases and XML using LINQ.
Note: Before writing the LINQ queries, you should import the System.Linq
namespace..

The following example shows a small demo on LINQ:
















using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQtoArrayDemo
{
class Program
{
static void Main(string[] args)
{
//data source
int[] numbers = { 2, 12, 10, 5, 15, 4, 62 };

//ling query
IEnumerable<int> result = from n in numbers where n <= 10 select n;
Application 68: LINQ to Arrays





.NET 4.0 and Visual Studio 2010 Page 212 of 548
D. HARSHA VARDHAN











O Ou ut tp pu ut t: :

In the above application, the array contains few numbers. After executing the query, you
got only the numbers, which are less than 10. In this manner, you can execute the queries on
data sets (after learning ADO.NET) also.

L LI IN NQ Q S Sy yn nt ta ax x: :




The above syntax consists of 7 clauses.
from clause
in clause
let clause
where clause
orderby clause
select clause
group by clause

Mandatory clauses:
from clause
in clause
select clause

Def of Clause: A part of the query.

from in let where orderby select group by
//output
foreach (var x in result)
Console.WriteLine(x);

Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 213 of 548
D. HARSHA VARDHAN

U Un nd de er rs st ta an nd di in ng g C Cl la au us se es s: :

1. from clause: This is used to specify the iteration variable name. This acts as alias name
for the data source.
2. in clause: This is used to specify the main data source for the query.
3. let clause (optional): This is used to declare a new identifier with a value, that is to be
used during the query execution.
4. where clause (optional): This is most frequently used optional clause, using which
you can specify the condition in the query.
5. orderby clause (optional): This is used to specify the sorting expression if required.
6. select clause: This is used to specify the object, which is required in the query results.
7. group by (optional): This is similar to group by clause in SQL. This retrieves grouped
data, based on a column.

Note: The result of a LINQ query should be assigned into a IEnumerable<data type> type
variable. IEnumerable is an interface.

Library: System.Collections.Generic.IEnumerable
















Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQtoObjectsDemo
{
class Student
{
//fields
public int StudentID;
public string Name;
public string Course;
public int Marks;
Application 69: LINQ to Objects





.NET 4.0 and Visual Studio 2010 Page 214 of 548
D. HARSHA VARDHAN





































//constructor
public Student(int StudentID, string Name, string Course, int Marks)
{
this.StudentID = StudentID;
this.Name = Name;
this.Course = Course;
this.Marks = Marks;
}
}
}

Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQtoObjectsDemo
{
class Program
{
static void Main(string[] args)
{
//data source
Student[] stu = { new Student(101, "Prakash", "MBA", 765),
new Student(102, "Pradeep", "MBA", 471),
new Student(103, "Pushpa", "Msc", 590),
new Student(104, "Purna", "MCA", 223),
new Student(105, "Purnima", "MCA", 450)};

//linq query with where clause
IEnumerable<Student> result1 = from s in stu where s.Course == "MCA" select s;
Console.WriteLine("MCA Students:");
foreach (Student r in result1)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " +
r.Marks);

//linq query with compound where clause
IEnumerable<Student> result2 = from s in stu where s.Name.EndsWith("a") &&
s.Marks>=400 && s.Marks<=600 select s;
Console.WriteLine("\nStudents whose name ends with 'a', and marks is >=400 and
<=600:");
foreach (Student r in result2)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " +
r.Marks);





.NET 4.0 and Visual Studio 2010 Page 215 of 548
D. HARSHA VARDHAN





































//linq query with let and where clauses
IEnumerable<Student> result3 = from s in stu let avg = s.Marks / 10 where avg < 35
select s;
Console.WriteLine("\nFailed Students:");
foreach (Student r in result3)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with orderby clause
IEnumerable<Student> result4 = from s in stu orderby s.Marks select s;
Console.WriteLine("\nStudents (sort on marks):");
foreach (Student r in result4)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with orderby clause (descending)
IEnumerable<Student> result5 = from s in stu orderby s.Marks descending select s;
Console.WriteLine("\nStudents (sort on marks - descending):");
foreach (Student r in result5)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with group clause
IEnumerable<IGrouping<string,Student>> result6 = from s in stu group s by s.Course;
Console.WriteLine("\nStudents with grouping:");
foreach (IGrouping<string, Student> StuGrp in result6)
{
Console.WriteLine(StuGrp.Key + ":");
foreach (Student r in StuGrp)
Console.WriteLine(" " + r.StudentID + ", " + r.Name + ", " + r.Course + ", " +
r.Marks);
}

Console.Read();
}
}
}







.NET 4.0 and Visual Studio 2010 Page 216 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :



L LI IN NQ Q w wi it th h L La am mb bd da a E Ex xp pr re es ss si io on ns s

LINQ queries can be written in two syntaxes:
1) General Query Syntax
2) Lambda Expression Syntax
The previously written applications are written with General Query Syntax.
Syntax for Lambda Expression:
DataSource.Clause(DataAliasName => Expression)
Ex:
stu.Where(s => s.Marks < 300)



goes to





.NET 4.0 and Visual Studio 2010 Page 217 of 548
D. HARSHA VARDHAN



































Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQtoObjectsDemo
{
class Student
{
//fields
public int StudentID;
public string Name;
public string Course;
public int Marks;
//constructor
public Student(int StudentID, string Name, string Course, int Marks)
{
this.StudentID = StudentID;
this.Name = Name;
this.Course = Course;
this.Marks = Marks;
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQwithLambaExpressions
{
class Program
{
static void Main(string[] args)
{
//data source
Student[] stu = { new Student(101, "Prakash", "MBA", 765),
new Student(102, "Pradeep", "MBA", 471),
new Student(103, "Pushpa", "Msc", 590),
new Student(104, "Purna", "MCA", 223),
new Student(105, "Purnima", "MCA", 450)};
Application 70: LINQ with Lambda Expressions





.NET 4.0 and Visual Studio 2010 Page 218 of 548
D. HARSHA VARDHAN














































//linq query with where clause
IEnumerable<Student> result1 = stu.Where(s => s.Course == "MCA");
Console.WriteLine("MCA Students:");
foreach (Student r in result1)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with compound where clause
IEnumerable<Student> result2 = stu.Where(s => s.Name.EndsWith("a") && s.Marks
>= 400 && s.Marks <= 600);
Console.WriteLine("\nStudents whose name ends with 'a', and marks is >=400 and
<=600:");
foreach (Student r in result2)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with orderby clause
IEnumerable<Student> result4 = stu.OrderBy(s => s.Marks);
Console.WriteLine("\nStudents (sort on marks):");
foreach (Student r in result4)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with orderby clause (descending)
IEnumerable<Student> result5 = stu.OrderByDescending(s => s.Marks);
Console.WriteLine("\nStudents (sort on marks - descending):");
foreach (Student r in result5)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with group clause
IEnumerable<IGrouping<string, Student>> result6 = stu.GroupBy(s => s.Course);
Console.WriteLine("\nStudents with grouping:");
foreach (IGrouping<string, Student> StuGrp in result6)
{
Console.WriteLine(StuGrp.Key + ":");
foreach (Student r in StuGrp)
Console.WriteLine(" " + r.StudentID + ", " + r.Name + ", " + r.Course + ", " +
r.Marks);
}

Console.Read();
}
}
}





.NET 4.0 and Visual Studio 2010 Page 219 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :







.NET 4.0 and Visual Studio 2010 Page 220 of 548
D. HARSHA VARDHAN

E Ex xc ce ep pt ti io on n H Ha an nd dl li in ng g

This is one of the major features of OOP languages like C++, VC++, VB.NET, C#.NET,
Java etc.
Def: "The process of handling the run time exceptions" is called as "Exception
handling".
Note: Exception = Run time error

Types of Errors:
1) Compile Time Errors: The errors occurred after compiling the program, are called as
compile time errors.
2) Run Time Errors: The errors occurred during the execution of the program, are called
as run time errors.

Overview of Exception Handling:
The exception may occur at run time, based on the mistake of the user / programmer /
system problem also.
When exception is raised, automatically it leads to "abnormal application termination".
The cause of the exception may be anything; the project developer should take care
about the exceptions.
As a part of this exception handling, the programmer has to display "particular error
message" to the user.
Purpose of Exception Handling: To avoid "abnormal application termination", even
though exception occurs.

Types of Application Termination:

Normal Application Termination: Whenever the program execution controls executes
all the statements in the program and reaches to end of the code, the application will be
terminated automatically. It can be called as Normal Application Termination.

Abnormal Application Termination: Whenever an exception occurred at run time,
the application will be terminated automatically. It can be called as Abnormal Application
Termination.





.NET 4.0 and Visual Studio 2010 Page 221 of 548
D. HARSHA VARDHAN

If the application was terminated abnormally, if will be most inconvenience for the user. So being
a programmer, you are responsible to avoid that kind of abnormal application termination, even
though exception is occurred at run time.

A small demo on exceptions:




















In the above code, the highlighted line contains an error, because it is trying to access an
array element which is in out of range of the array. So, it leads to abnormal application
termination at run time.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo1
{
class Program
{
static void Main(string[] args)
{
string[] Cities = { "Vijayawada", "New Delhi", "Banglore", "Hyderabad" };
Console.WriteLine(Cities[3]);
Console.WriteLine(Cities[4]);
Console.Read();
}
}
}
Application 71: Simple Demo on Exceptions





.NET 4.0 and Visual Studio 2010 Page 222 of 548
D. HARSHA VARDHAN

Then screen looks like this:


To avoid this, we have to implement exception handling for this code.

Syntax of Exception Handling:












try
{
---------------------;
---------------------;
---------------------;
---------------------;
}
catch (Exception ex)
{
--------------------;
--------------------;
}
finally
{
--------------------;
--------------------;
}





.NET 4.0 and Visual Studio 2010 Page 223 of 548
D. HARSHA VARDHAN

In the above syntax, we can observe to blocks.
1) try block
2) catch block
3) finally block

1) try block:
The try block contains the actual code, which
is to be executed.
After every try block, there should catch
block without fail.
The system tries to execute the code in the
try block.
During the execution, if any exception
occurs, then the execution control automatically goes to catch block.
At the same time, the try block throws the exception to the catch block in the
form of an object. That object is called as exception object.

2) catch block:
This is also known as error handler.
This is followed by the try block.
The catch block will be executed if any
exception is occurred during the execution
of try block.
The catch block contains necessary code
which displays an error message to the
user.
This receives the exception, thrown by the try block, in the form of an object. In
the following syntax, ex is the Exception object. The Exception is the class
for the exception object.
Library: System.Exception




catch (Exception ex)
{
--------------------;
--------------------;
}
try
{
---------------------;
---------------------;
---------------------;
---------------------;
}






.NET 4.0 and Visual Studio 2010 Page 224 of 548
D. HARSHA VARDHAN

3) finally block:
This block will be executed automatically and
compulsorily, after executing try block / catch
block.
That means even though exception is raised or
not raised, the finally block will be executed without fail.
This is optional block. You can write the exception handling syntax only with
try and catch blocks, without finally block.




























using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo2
{
class Program
{
static void Main(string[] args)
{
try
{
string[] Cities = { "Vijayawada", "New Delhi", "Banglore", "Hyderabad" };
Console.WriteLine(Cities[3]);
Console.WriteLine(Cities[4]);
}
catch (Exception ex)
{
Console.WriteLine("Error occurred.");
}
finally
{
Console.WriteLine("This is 'finally' block.");
Console.Read();
}
}
}
}
Application 72: Demo Exception Handling
finally
{
--------------------;
--------------------;
}





.NET 4.0 and Visual Studio 2010 Page 225 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :



Types of Catch Block Messages:

Already we have discussed that the catch block generates an error message, when an exception
occurs. That error message can be of two types.
1. User Defined Message
2. System Defined Message

1. User Defined Message: Your own message can be written.
Ex: Error Occurred.
Operation is not successful.
etc.
2. System Defined Message: The system provides the description of the error, so that
you can print that on the output directly. To access the system defined message, you can
use the exception object as follows:
Syn: ex.Message
Example:












catch (Exception ex)
{
Console.WriteLine(ex.Message);
}





.NET 4.0 and Visual Studio 2010 Page 226 of 548
D. HARSHA VARDHAN

Exceptional Classes

+ Already you know that C# recognizes the exception as an object.
+ To declare the exception object, we have used a class called System.Exception, in
the previous examples.
+ The Exception class recognizes any type of exceptions. In order to catch the particular
type of error, C# provides other exceptional classes. Some of them are given here.

Sl. No Exceptional Class Description
1 System.OverflowException
Occurs when a large value is
assigned to a variable, which is not
fit in that variable.
2
System.FormatException /
System.InvalidCastException
Occurs when the casting is failed
from one data type of another data
type.
3 System.DivideByZeroException
Occurs when any number is divided
by 0.
4 System.IndexOutOfRangeException
Occurs when an index is accessed in
out of range.
5 System.InsufficientMemoryException
Occurs when there is no sufficient
memory in RAM for the execution of
the application.
6 System.IO.FileNotFoundException
Occurs when a non-existing file is
accessed.
7 System.IO.DirectoryNotFoundException
Occurs when a non-existing directory
is accessed.
8 System.IO.FileLoadException
Occurs when any error occurred
during the opening of any file.
9 System.IO.IOException
Occurs when any error occurred
during file read or writing.
10 System.Threading.ThreadInterruptedException
Occurs when any error occurred
during the execution of the thread.





.NET 4.0 and Visual Studio 2010 Page 227 of 548
D. HARSHA VARDHAN

11 System.Threading.ThreadStartException
Occurs when any error occurred
while starting the thread.
12 System.InvalidOperationException
Occurs when any error occurred
while opening the database
connection.
13 System.Data.OleDb.OleDbException
Occurs when any error occurred
while performing query or non-query
transactions on OleDb databases.
14 System.Data.SqlClient.SqlException
Occurs when any error occurred
while performing query or non-query
transactions on SqlServer database.
15 System.EntryPointNotFoundException
Occurs when you try to run the
application, without defining any
entry point (main() method).
16 System.InvalidTimeZoneException
Occurs when the system has an
invalid time zone setting the date &
time settings.

Note: Based on the situation, the above specified exception classes could be used.















using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo3
{
class Program
{
static void Main(string[] args)
{
try
{
int n1, n2, n3;

Console.WriteLine("Enter first value:");
n1 = Convert.ToInt32(Console.ReadLine());
Application 73: Demo on Exceptional Classes





.NET 4.0 and Visual Studio 2010 Page 228 of 548
D. HARSHA VARDHAN












O Ou ut tp pu ut t: :


Note: If you want to handle more than one type of exception for the same try block, then you
need to write multiple catch blocks.















using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo4
{
class Program
{
static void Main(string[] args)
{
try
{
int n1, n2, n3;

Console.WriteLine("Enter first value:");
n1 = Convert.ToInt32(Console.ReadLine());

Application 74: Demo on Multiple Catch Blocks
Console.WriteLine("Enter second value:");
n2 = Convert.ToInt32(Console.ReadLine());

n3 = n1 / n2;

Console.WriteLine("Result is: " + n3);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Can't divide the number with zero.");
}
Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 229 of 548
D. HARSHA VARDHAN

















O Ou ut tp pu ut t: :






Console.WriteLine("Enter second value:");
n2 = Convert.ToInt32(Console.ReadLine());

n3 = n1 / n2;
Console.WriteLine("Result is: " + n3);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("This is divide by zero exception.");
}
catch (OverflowException ex)
{
Console.WriteLine("This is overflow excpetion.");
}
catch (FormatException ex)
{
Console.WriteLine("This is invalid cast exception.");
}
Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 230 of 548
D. HARSHA VARDHAN

The EventLog

+ EventLog is a service, offered by Microsoft Windows.
+ It is used to store the exceptions / warnings / any messages permanently, even though
the application is closed.
+ Let us imagine you have done a live project and issue it to the client.
+ At run time there may be so many exceptions. But after few days, you went to the client
location, and want to know what kind of run time errors were coming in your application.
+ Then no information is available with you.
+ So, in this case, you require some thing, that stores the exceptions information
automatically, for further information, which helps you while you want to debug your
application and develop a next version.
+ That kind of service is EventLog.
+ To open EventLog and view the current events:
Start Control Panel Administrative Tools Event Viewer.







.NET 4.0 and Visual Studio 2010 Page 231 of 548
D. HARSHA VARDHAN

Writing a new entry programmatically:
System.Diagnostics.EventLog.WriteEntry("project name", message, EventLogEntryType.Error);

























using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace EventLogDemo
{
class Program
{
static void Main(string[] args)
{
try
{
string filename = "c:\\sample.txt";
StreamReader sr = new StreamReader(filename);

string content = sr.ReadToEnd();
Console.WriteLine("The file content is:\n");
Console.WriteLine(content);
}
catch (Exception ex)
{
string EventMsg = ex.Message + "\n\n" + ex.StackTrace;
EventLog.WriteEntry("My Sample Project 1.0", EventMsg,
EventLogEntryType.Error);
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Press any key to exit..");
Console.Read();
}
}
}
}
Application 75: Demo on Event Log





.NET 4.0 and Visual Studio 2010 Page 232 of 548
D. HARSHA VARDHAN

O Ou ut tp pu ut t: :





D De eb bu ug gg gi in ng g

Bug: An error.
Debugging: Removing the bugs.

.NET offers more features for debugging. To start with the .NET application debugging, you
should create the break points.

Break Points

i) Definition: A break point is a point in the program, where the application execution
control pauses until you press F10 key. In the code, that line is highlighted with red
color.

ii) Creating a break point: Just click on the left side margin of the required line.





.NET 4.0 and Visual Studio 2010 Page 233 of 548
D. HARSHA VARDHAN



iii) Running the Application with Break Points: Just press F5 key. The
application will be executed normally. But whenever the execution control reaches to
the break point line, automatically the execution will be paused and the break point
line will be highlighted with yellow color. To continue with the execution to the next
statement, press F10 key.

iv) Observing the values of variables or objects: While you are executing the
application with break points, to know the current value of any variable or object,
just place the mouse pointer over it.



Application 76: Demo on Break Points





.NET 4.0 and Visual Studio 2010 Page 234 of 548
D. HARSHA VARDHAN





Immediate window

The Immediate window resides at bottom side of Visual Studio IDE. It will automatically
appear at run time. If not, press Ctrl + Alt + I.
This window is used to know the current values of the required variables, objects or data
members, which is not possible to find the value by just placing the mouse pointer over
it.










.NET 4.0 and Visual Studio 2010 Page 235 of 548
D. HARSHA VARDHAN







Locals window

It automatically displays all the current local variables along with their values.
To open this window, while running the application, get into the Visual Studio and press
Ctrl+D and the L.

Application 77: Demo on Immediate window





.NET 4.0 and Visual Studio 2010 Page 236 of 548
D. HARSHA VARDHAN

Assemblies

+ Def: An assembly is the container of compiled code of .NET applications.
+ It contains the code in MSIL (Microsoft Intermediate Language) language.
+ At run time, it will be compiled by CLRs JIT compiler into machine language.
+ The assembly file (with .exe or .dll extension) will be generated in the project folder \
bin folder, after compilation.

Types of Assemblies (based on extension):

1. Executable Assemblies / Process Assemblies / Private Assemblies (with .EXE
extension)
This is generated with
A. Console Applications
B. Smart Device Applications
C. Windows Applications
These files are ready for execution. You can execute those by simply double clicking.
Limitation: The code in this assembly is not accessible from other projects.

2. Library Assemblies / Re-usable Assemblies / Shared Assemblies (with .DLL
extension)
This is generated with
A. Class Library
B. Windows Forms Control Library
These are non-executable files.
Advantage: The code is this assembly is accessible from other projects.


Overview of Class Library Project

+ A class library project is meant for the development of Shared Assemblies.
+ The shared assemblies are re-usable in other applications also.





.NET 4.0 and Visual Studio 2010 Page 237 of 548
D. HARSHA VARDHAN

+ That means the class librarys code is re-usable in other applications, whenever required.
+ Class library project contains only user-defined classes.
+ Whenever the class library project is compiled, a library assembly file (with .DLL
extension) will be generated in the bin\Debug folder.
+ The class library project cant be executed directly unlike console applications, windows
applications etc.




Global Assembly Cache (GAC): All the shared assemblies should be saved in the GAC. GAC
offers the following advantages.
+ Unique identification of the shared assemblies.
+ Avoids the DLL hell (replacement of an assembly related to one application, by another
application).
+ Faster accessibility.






.NET 4.0 and Visual Studio 2010 Page 238 of 548
D. HARSHA VARDHAN

To view the currently installed assemblies in the GAC, open the following folder.
C:\windows\assembly
The above folder is able to contain multiple dll files with same name, with different
versions.


Strong Name Keys (SNK): The strong name key is a file, which acts as a unique
identifier, for the shared assemblies, stored in the GAC. In other words, GAC recognizes the
assembly with this strong name only.


Implementation Steps of Shared Assemblies

1. Create a Class Library Project.
Create a new Class Library project.
Write the required code in the project.

2. Create a strong name key.
Right click on the project in the Solution Explorer and choose Properties.
In the project properties, select the check box Sign the assembly.
In the Choose a strong name key file drop down, select <New> option.
In the Create strong name key dialog box, enter the name of the strong name key
file.
If password security is not required, uncheck the Protect my key file with a
password checkbox.
Click on OK.

3. Customize the Assembly Information (AssemblyInfo.cs).
This is optional step.
To change the additional details of the assembly like displayed name, version,
company, copy right, description etc., open AssemblyInfo.cs file from the
Properties folder in the Solution Explorer.






.NET 4.0 and Visual Studio 2010 Page 239 of 548
D. HARSHA VARDHAN

4. Generate the DLL File.
Build the class library project.
Then the .dll file will be generated in the bin\debug folder of your class library
project.

5. Write the assembly into GAC (Global Assembly Cache).
Open the following folder.
C:\Windows\Assembly
Drag and drop the .DLL file from bin\Debug folder into the
c:\windows\assembly folder.
After dragging, the name of your shared assembly will appear in the existing list.
Now, the shared assembly is ready. The rest of your work involved with the usage of
the shared assembly.

6. Invoke the Shared Assembly.
Create the executable project (Console application / windows application).
Click on Project Add Reference.
Click on Browse tab.
Open the class library projects bin\Debug folder.
Select the dll file and click on OK.
Then the reference of the selected shared assembly will be added to the current
project.
Then you can construct objects for the required class in the class library and perform
required activities on that.


Demo on Shared Assemblies







Application 78: Demo on Shared Assemblies
In this example,
Class Library Project: SharedAssemblyLibrary
Console Application Project: SharedAssemblyDemo





.NET 4.0 and Visual Studio 2010 Page 240 of 548
D. HARSHA VARDHAN

1. Create a Class Library Project.
Open Visual Studio 2008.
Click on File New Project.
Select the language as Visual C# and project template as Class Library.
Enter the name as SharedAssemblyLibrary.
Click on OK. It creates a new class library project. Initially it contains a new class
called class1.
In the solution explorer, rename the class1.cs as MyLibraryClass.cs.
Then type the following code.















2. Create a strong name key.
Right click on the
project in the
Solution Explorer
and choose
Properties.
In the project
properties, select
the check box Sign
the assembly.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharedAssemblyLibrary
{
public class MyLibraryClass
{
public bool IsValidLogin(string Username, string Password)
{
if (Username == "system" && Password == "manager")
return true;
else
return false;
}
}
}





.NET 4.0 and Visual Studio 2010 Page 241 of 548
D. HARSHA VARDHAN

In the Choose a strong name key file drop down, select <New> option.
In the Create strong name key dialog box, enter the name of the strong name key
file as MyKeyFile.
Uncheck the Protect my key file with a password checkbox.
Click on OK.

3. Customize the Assembly Information (AssemblyInfo.cs).
Change the assembly version as 1.5.0.0.

4. Generate the DLL File.
Build the class library project by clicking on Build menu Build Solution.

5. Write the assembly into GAC (Global Assembly Cache).
Open the following folder.
C:\Windows\Assembly
Drag and drop the SharedAssemblyLibrary.DLL file from bin\Debug folder
into the c:\windows\assembly folder.

6. Invoke the Shared Assembly.
Create a new Console Application. Name: SharedAssemblyDemo
Click on Project Add Reference.
Click on Browse tab.
From the class library projects
bin\Debug folder, select the
SharedAssemblyLibrary.dll
file and click on OK. Then the
.dll file reference will be added.










.NET 4.0 and Visual Studio 2010 Page 242 of 548
D. HARSHA VARDHAN

Enter the code as follows:























O Ou ut tp pu ut t: :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharedAssemblyLibrary;

namespace SharedAssemblyDemo
{
class Program
{
static void Main(string[] args)
{
MyLibraryClass mlc = new MyLibraryClass();

string Username, Password;
Console.Write("Enter Username: ");
Username = Console.ReadLine();
Console.Write("Enter Password: ");
Password = Console.ReadLine();

bool result = mlc.IsValidLogin(Username, Password);
if (result == true)
Console.WriteLine("\nLogin successful!");
else
Console.WriteLine("\nInvalid Username / Password!");

Console.Read();
}
}
}






.NET 4.0 and Visual Studio 2010 Page 243 of 548
D. HARSHA VARDHAN

Windows Forms Applications

C# supports two kinds of User Interfaces.
o C.U.I (Character User Interface)
This user interface supports a blank screen, with some characters
only.
It is not attractive for the user. Thats why it is not suitable for the
live projects.

o G.U.I (Graphical User Interface)
It supports graphical components like windows, icons, mouse
pointer, toolbars, status bars, buttons etc.
It is attractive for the user. Thats why it is suitable for the live
projects.





.NET 4.0 and Visual Studio 2010 Page 244 of 548
D. HARSHA VARDHAN


Almost all the softwares you are using today like Notepad, WordPad,
Paint, MS Word, My computer and My documents etc., are the GUI
applications.

Windows Forms Application:
It can also be called as Windows Application.
Its a collection of windows forms.















Login Form Registration Form
Data Entry Form
A Windows Application
Report Form





.NET 4.0 and Visual Studio 2010 Page 245 of 548
D. HARSHA VARDHAN


Form:
The graphical container, which
can contain the graphical
controls like labels, textboxes,
buttons, list boxes etc., is called
as Form. It acts as container
for the controls.
It is also called as a window.
It has the visual appearance
with a title bar, icon, control box
(with minimize button, maximize button and close button).


C Cr re ea at ti in ng g a a W Wi in nd do ow ws s F Fo or rm ms s A Ap pp pl li ic ca at ti io on n p pr ro oj je ec ct t: :
* Open Microsoft Visual Studio 2010.
* Click on File New Project.
* Select the language as Visual C#.
* Select the project type as Windows Forms Application.
* Enter the name and location of the project.
* Click on OK.






.NET 4.0 and Visual Studio 2010 Page 246 of 548
D. HARSHA VARDHAN



* Then it will create a windows forms application, along with a form, named Form1.
* Then the screen looks like this:





.NET 4.0 and Visual Studio 2010 Page 247 of 548
D. HARSHA VARDHAN



Development of a Form
It includes with two stages:
o Designing
o Coding

1) Designing the Form:
Drag and Drop the controls from the ToolBox.
Application 79: A Sample Windows Application Project (with Login Form)





.NET 4.0 and Visual Studio 2010 Page 248 of 548
D. HARSHA VARDHAN


Select the control and set the properties as your wish.
For example, set the following properties as per given below:
o Form1
Text: Login
o Label1
Text: User Name
o Label2
Text: Password
o TextBox1
(No properties are required in this example)
o TextBox2
PasswordChar: *
o Button1
Text: OK
o Button2
Text: Cancel






.NET 4.0 and Visual Studio 2010 Page 249 of 548
D. HARSHA VARDHAN

Then the screen looks like this:

The above process is called as Form designing.

2) Coding the Form:
Double click on the controls and write the code in the Code window.
For example, double click on OK button and write the following code:







And then, double click on Cancel button and write the following code:

private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "system" && textBox2.Text == "manager")
MessageBox.Show("Login is successful.");
else
MessageBox.Show("Invalid Login.");
}






.NET 4.0 and Visual Studio 2010 Page 250 of 548
D. HARSHA VARDHAN





The above process is called as Form coding.

= Every Form is a Class:
C#.NET recognizes every form as a class.
In VB 6.0, every form is known as an object for the Form class. But in C#, every form
is a class; so that at run time, you can create any no. of objects as your wish. For
example, if you want to display Login form twice at run time, you can simply create
two objects and can show it.

= The Automatic Generated Code:
While you design the controls, the Visual Studio generates some automatic code in the
Form1.Designer.cs file.
To open this file, Open Solution Explorer, Expand Form1, then double click on
Form1.Designer.cs.
For example, you can see the automatic generated code for the previous Login
example:










private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
Form1.Designer.cs:

namespace WindowsFormsApplication1
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;

/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed;
otherwise, false.</param>





.NET 4.0 and Visual Studio 2010 Page 251 of 548
D. HARSHA VARDHAN





























protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(186, 44);
this.textBox1.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(232, 27);
this.textBox1.TabIndex = 0;
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(186, 102);
this.textBox2.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.textBox2.Name = "textBox2";
this.textBox2.PasswordChar = '*';
this.textBox2.Size = new System.Drawing.Size(232, 27);
this.textBox2.TabIndex = 1;
//
// button1
//
this.button1.Location = new System.Drawing.Point(186, 167);
this.button1.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(107, 37);
this.button1.TabIndex = 2;
this.button1.Text = "OK";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);





.NET 4.0 and Visual Studio 2010 Page 252 of 548
D. HARSHA VARDHAN






























//
// button2
//
this.button2.Location = new System.Drawing.Point(314, 167);
this.button2.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(107, 37);

this.button2.TabIndex = 3;
this.button2.Text = "Cancel";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);

//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(64, 48);
this.label1.Margin = new System.Windows.Forms.Padding(5, 0, 5, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(104, 19);
this.label1.TabIndex = 4;
this.label1.Text = "User Name:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(64, 107);
this.label2.Margin = new System.Windows.Forms.Padding(5, 0, 5, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(93, 19);
this.label2.TabIndex = 5;
this.label2.Text = "Password:";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 19F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(492, 244);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
this.Font = new System.Drawing.Font("Tahoma", 12F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.Name = "Form1";
this.Text = "Login";
this.ResumeLayout(false);
this.PerformLayout();






.NET 4.0 and Visual Studio 2010 Page 253 of 548
D. HARSHA VARDHAN











= Dont worry about the above automatic generated code; it will be generated automatically,
while you design the form in the Design window.
= The entire code is generated in a method called InitializeComponent().
= Finally, coming to a conclusion; every form contains two files:
o Form1.Designer.cs
Contains the code for designing (Automatically generated code by Visual Studio).
o Form1.cs
Contains the actual functionality code (Written by the Programmer).


Class Definition Syntax of a Windows Form:







Form1.cs

importing section;
namespace ProjectName
{
public partial class FormName : Form
{
public FormName()
{
InitializeComponent();
}
}
}


}

#endregion

private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
}
}








.NET 4.0 and Visual Studio 2010 Page 254 of 548
D. HARSHA VARDHAN

Rules for the Form class definition:
In the importing section, you can import the necessary namespaces that you want.
The namespace name should be same as project name.
A user-defined class with the form name is to be defined.
It should be the sub class of "System.Windows.Forms.Form" class; as it offers some
visual design, properties, methods and events for the user-defined form class.
It will be defined as a public class (this is optional). Whenever it is a public class, in
future, it can be accessed from other projects also.
It should be defined as "partial" class, as its definition is written in the following two files.
o Form1.cs
o Form1.Designer.cs
It should contain a constructor, with a statement called InitializeComponent();,
which calls the designer code that is generated in Form1.Designer.cs file.


= Program.cs file in Windows Forms Applications:
Generally, when you Start the windows application project, automatically the Form1
will be appeared on the screen.
Then dont think like directly Form1 will be opened.
In fact, when you click on Start option, the Main() method will be invoked first.
Like Console Applications, Main() method is located in Program.cs file.





.NET 4.0 and Visual Studio 2010 Page 255 of 548
D. HARSHA VARDHAN


For reference you open Solution Explorer Program.cs file.
In the Main() method, you can see two important statements.
+ Application.EnableVisualStyles();
This statement enables the better styles (for sleek appearance) for the
entire application, based on the current working theme offered by the
O/S.

+ Application.Run(new Form1());
This statement creates a new Form1 class object and that object will be
shown on the screen.






.NET 4.0 and Visual Studio 2010 Page 256 of 548
D. HARSHA VARDHAN

Controls Handling Windows Applications
Common Properties for all the controls:
The following properties commonly available for all the controls:
Common Properties
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
BackColor Specifies the background color of the control.
ForeColor Specifies the foreground color of the control.
Font Specifies the font style of the controls text.
Enabled Enables / Disables the control.
Visible Displays / Hides the control.
Cursor
Specifies the mouse pointer style, when the mouse is over on the control at
run time.
Size Specifies the Width and Height of the control.
Location Specifies the X and Y co-ordinations of the controls position on the form.
TextAlign Specifies the position of the text in the control.
Image
Specifies the image that is to be displayed in the control along with the
text.
ImageAlign Specifies the position of the image in the control
TabIndex Specifies the index of the control in the tab order.
ContextMenuStrip Contains the reference of the respective context menu control.


Common Events for all the controls:
The following events commonly available for all the controls:

Common Events
Event Description
Click Executes when the user clicks the control run time.
DoubleClick Executes when the user double-clicks the control at run time.
MouseMove Executes when the mouse pointer is moves across the control.
MouseEnter Executes when the mouse pointer is focused on to the control.
MouseLeave Executes when the mouse pointer is out of the control.
KeyPress
Executes when any key is pressed on the keyboard, while the focus is on
the control.
Enter Executes when the focus is entered into the control.
Leave Executes when the focus got out of the control.

Event: An event is a run time action that can be performed by the user.
Let us practice the above properties and events on the button control.





.NET 4.0 and Visual Studio 2010 Page 257 of 548
D. HARSHA VARDHAN





Take a new Windows Forms Application project.
Design the form as follows:


To design the form as above set the following properties.













Application 80: Demo on Buttons
Design
button1:
Text: Whats the time now?

button2:
Text: Show Me a Random Number
ForeColor: Green

button3:
Text: Exit
BackColor: Purple
ForeColor: Yellow
Image: c:\close.jpg
ImageAlign: MiddleLeft
FlatStyle: Popup
Font: Lucida Sans, Bold, 11






.NET 4.0 and Visual Studio 2010 Page 258 of 548
D. HARSHA VARDHAN

Double click on Button1 and Write the following code:








Double click on Button2 and Write the following code:









Double click on Button3 and Write the following code:








Then finally run the application.



Changing Property Values at run time

You can change the property values at run time (programmatically).
For example, you have designed a button with blue background. Later, after the user
clicks it, you want to display that button with green background.
Then you require to change the BackColor property value at run time.
Syntax:
controlname.property = value;
Ex:
button1.Text = Button is clicked;

private void button1_Click(object sender, EventArgs e)
{
DateTime dt = DateTime.Now;
MessageBox.Show(dt.ToString());
}
private void button2_Click(object sender, EventArgs e)
{
Random r = new Random();
int n = r.Next(1, 500);
MessageBox.Show(n.ToString());
}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("Bye....");
Application.Exit();
}





.NET 4.0 and Visual Studio 2010 Page 259 of 548
D. HARSHA VARDHAN

But sometimes, when you are trying to change some property values, you may face
some problems.
For example, the following statements are not valid statements:
button1.BackColor = green;
button1.Cursor = hand;
button1.TextAlign = TopLeft;
So, while you are changing the property values, you remember and follow the following
syntaxes:

Assign Property Values at Run Time
Property Statement to assign the value at run time
Name
Not possible to change at run time.
Text
controlname.Text = xxxxx;
Enabled
controlname.Enabled = true / false;
Visible
controlname.Visible = true / false;
Location
controlname.Location = new System.Drawing.Point(x, y);
Size
controlname.Size = new System.Drawing.Size(width, height);
Font
controlname.Font = new System.Drawing.Font(font name,
fontsize);
BackColor
controlname.BackColor = System.Drawing.Color.xxxxx;
ForeColor
controlname.ForeColor = System.Drawing.Color.xxxxx;
Cursor
controlname.Cursor = System.Windows.Forms.Cursors.xxxxx;
Image
controlname.Image = System.Drawing.Image.FromFile(image file
path);
TextAlign
controlname.TextAlign =
System.Drawing.ContentAlignment.MiddleRight;
ImageAlign
controlname.TextAlign =
System.Drawing.ContentAlignment.MiddleRight;
TabIndex
controlname.TabIndex = n;
ContextMenuStrip
controlname.ContextMenuStrip = xxxxx;










.NET 4.0 and Visual Studio 2010 Page 260 of 548
D. HARSHA VARDHAN

IMP Notes to remember:
In the above syntaxes, we are using few pre-defined classes, pre-defined structures and pre-
defined enumerations also.
Classes
1) System.Drawing.Point
2) System.Drawing.Size
3) System.Drawing.Font
4) System.Drawing.Image
5) System.Windows.Forms.Cursors
Structures 1) System.Drawing.Color
Enumerations 1) System.Drawing.ContentAlignment












Application 81: Demo on Changing Property Values at Run Time





.NET 4.0 and Visual Studio 2010 Page 261 of 548
D. HARSHA VARDHAN



private void button2_Click(object sender, EventArgs e)
{
button1.Text = "My Test Button";
}

private void button3_Click(object sender, EventArgs e)
{
button1.Enabled = false;
}

private void button4_Click(object sender, EventArgs e)
{
button1.Enabled = true;
}

private void button5_Click(object sender, EventArgs e)
{
button1.Visible = false;
}

private void button6_Click(object sender, EventArgs e)
{
button1.Visible = true;
}

private void button7_Click(object sender, EventArgs e)
{
button1.Location = new Point(150, 400);
}

private void button8_Click(object sender, EventArgs e)
{
button1.Size = new Size(250, 100);
}

private void button9_Click(object sender, EventArgs e)
{
button1.Font = new Font("Showcard Gothic", 17);
}

private void button10_Click(object sender, EventArgs e)
{
button1.BackColor = Color.LightCoral;
}

private void button11_Click(object sender, EventArgs e)
{
button1.ForeColor = Color.Green;
}

private void button12_Click(object sender, EventArgs e)
{





.NET 4.0 and Visual Studio 2010 Page 262 of 548
D. HARSHA VARDHAN




Event Handling

Def: The event handling includes with executing some code, whenever the user
performs an action.
The necessary code is to be written in a special method. That method is called as Event
Handler.

Event Handler:
An event handler is a method, which will be called automatically, whenever the user
performs certain event at run time.
The event handler should be defined in the form class.
Syntax:





In the above syntax, there are two arguments:
o sender: Represents the control, based on which the event is raised. For
example, in the button1_click event handler, the sender argument
represents button1 control.
o e: Contains some additional information about the event. For example, in the
MouseClick event, the position of the mouse will be represented, where it
is clicked.
Event through you know the syntax of event handler properly, dont try to type it
manually in the code. The event handler method should be generated through the proper
way.
private void controlname_eventname(object sender, EventArgs e)
{
//some code
}
button1.Image = Image.FromFile("c:\\flagindia.gif");
button1.ImageAlign = ContentAlignment.MiddleLeft;
button1.TextAlign = ContentAlignment.MiddleRight;
button1.Size = new Size(200, 60);
}





.NET 4.0 and Visual Studio 2010 Page 263 of 548
D. HARSHA VARDHAN

In the previous examples, you have generated the event handlers by double clicking on
the controls.
But already you know that, for all the controls, there are multiple events. But when you
double click the control, it will generate the event handler for only one event. That
particular event can be called as Default event.
For example, the default event for the button is Click event.
If you want to implement the event handlers for other controls, you require to follow the
steps given below.

Implementation of Event Handler:
First, in the design window, select the form or control, for which you want to create the
event handler.
Open Properties window, and click on Events
option.
Select the required event, for which you want to create
the event handler.
Press Enter.
Then the event handler will be created in the code
window.



















.NET 4.0 and Visual Studio 2010 Page 264 of 548
D. HARSHA VARDHAN






Application 82: Demo on Event Handling
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("You have clicked the button");
}

private void button1_MouseEnter(object sender, EventArgs e)
{
button1.BackColor = Color.Yellow;
button1.ForeColor = Color.DarkRed;
}

private void button1_MouseLeave(object sender, EventArgs e)
{
button1.BackColor = Color.DarkRed;
button1.ForeColor = Color.Yellow;
}
Design
button1:
Text: Click Me
BackColor: DarkRed
ForeColor: Yellow






.NET 4.0 and Visual Studio 2010 Page 265 of 548
D. HARSHA VARDHAN

Working with Multiple Forms

Adding a new Form to the Project:
In the Solution Explorer, right click on the project and choose Add - Windows Form.
In the dialog box, enter the name of the new form.
Then the new form will be created.

Deleting a Form from the Project:
In the Solution Explorer, right click on the required form, which you want to delete and
click on Delete option.
Click on OK for confirmation.

Changing Startup Form:
Even, if you add multiple forms to the project, when the project is started, the Form1
will be opened by default. This is called as Startup form.
To change the startup form, change the following statement with the required class
name in the Program classs Main() method.
Syn: Application.Run(new <form name>());
Ex: Application.Run(new Form2());


Invoke Forms at Run Time (Programmatically):
To open any form at run time programmatically, you require to create an object for the
form class.
FormName obj = new FormName();
obj.Show();







Application 83: Multiple Forms Handling





.NET 4.0 and Visual Studio 2010 Page 266 of 548
D. HARSHA VARDHAN








Controls in Windows Applications
I. Common Controls
1) Button
2) Label
3) TextBox
4) PictureBox
5) LinkLabel
6) CheckBox
7) RadioButton
8) ListBox
9) ComboBox
10) DomainUpDown
11) NumericUpDown
12) DateTimePicker
13) MonthCalendar
Form1.cs

private void Form1_DoubleClick(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
}





.NET 4.0 and Visual Studio 2010 Page 267 of 548
D. HARSHA VARDHAN

II. Container Controls
14) Panel
15) GroupBox
16) TabControl
17) FlowLayoutPanel
18) SplitContainer
19) TableLayoutPanel
III. Background Process Controls
20) Timer
21) ProgressBar
IV. Menu & ToolBar Controls
22) MenuStrip
23) ContextMenuStrip
24) ToolStrip
25) StatusStrip
V. Dialog Box Controls
26) ColorDialog
27) FontDialog
28) FolderBrowserDialog
29) OpenFileDialog
30) SaveFileDialog
31) PrintDialog
VI. Data Controls
32) DataGridView
33) BindingSource
34) DataSet
35) Chart
VII. Component Controls
36) Tooltip
37) NotifyIcon
38) EventLog
39) ImageList
40) ErrorProvider






.NET 4.0 and Visual Studio 2010 Page 268 of 548
D. HARSHA VARDHAN

VIII. Reporting Controls
41) CrystalReportViewer
42) ReportViewer
IX. Other User Friendly Controls
43) LineShape
44) OvalShape
45) RectangleShape
46) PrintForm
X. Other User Friendly Controls
47) RichTextBox
48) TrackBar
49) TreeView
50) WebBrowser






.NET 4.0 and Visual Studio 2010 Page 269 of 548
D. HARSHA VARDHAN

T Th he e S Sy ys st te em m. .W Wi in nd do ow ws s. .F Fo or rm ms s. .F Fo or rm m C Cl la as ss s

The System.Windows.Forms.Form class offers few properties, methods and events for each
user-defined form class.
Properties of System.Windows.Forms.Form Class
Property Description
Name Specifies the name of the form class.
Text Specifies the title bar text of the form.
ShowIcon Specifies whether the form icon is to be displayed or not.
ShowInTaskBar Specifies whether the task bar icon is to be displayed or not.
MinimizeBox Specifies whether the minimize button is to be displayed or not.
MaximizeBox Specifies whether the maximize button is to be displayed or not.
HelpButton Displays / hides the ? button in the form title bar.
ControlBox
Specifies whether the control box is to be displayed or not. Here
the control box means minimize, maximize and close buttons.
Enabled Activates / Deactivates the functionality of the entire form.
AutoScroll Enables / Disables automatic activation of scrollbars in the form.
TopMost Activates / de-activates the nature of Always on top
IsMDIContainer When it is true, the form acts as Parent form.
BackColor Specifies the background color of the form.
ForeColor Specifies default foreground color for all the controls of this form.
Font Specifies default font for all the controls of this form.
BackgroundImage
Specifies the background image of the form. It requires an image
file of any image format.
BackgroundImageLayout
Specifies mode of the background image. (None / Tile / Center /
Stretch / Zoom)
Icon
Specifies the icon of the form, displayed at left most side of the
form title bar. It requires icon file with .ico file.
WindowState
Specifies the status of the form window. (Normal / Minimized /
Maximized)
Cursor Specifies the mouse cursor style. (Arrow, Hand etc.)
FormBorderStyle
None / FixedSingle / Fixed3D / FixedDialog / Sizable /
FixedToolWindow / SizableToolWindow
Size (Width and Heght) Specifies the size of the form (pixels format).
Location (X and Y) Specifies the position of the form (pixels format).
Opacity Specifies form graphics depth percentage. (1% to 100%)

Syntax to access the Properties at run time: this.Property = value;










.NET 4.0 and Visual Studio 2010 Page 270 of 548
D. HARSHA VARDHAN

While you are changing the property values, you remember and follow the following syntaxes:
Assign Form Property Values at Run Time
Property Statement to assign the value at run time
Name
Not possible to change at run time.
Text
this.Text = xxxxxxxxxx;
ShowIcon
this.ShowIcon = true / false;
ShowInTaskbar
this.ShowInTaskbar = true / false;
MinimizeBox
this.MinimizeBox = true / false;
MaximizeBox
this.MaximizeBox = true / false;
HelpButton
this.HelpButton = true / false;
ControlBox
this.ControlBox = true / false;
Enabled
this.Enabled = true / false;
AutoScroll
this.AutoScroll = true / false;
TopMost
this.TopMost = true / false;
IsMdiContainer
this.IsMdiContainer = true / false;
BackColor
this.BackColor = System.Drawing.Color.xxxxxxx;
ForeColor
this.ForeColor = System.Drawing.Color.xxxxxxx;
Font
this.Font = new System.Drawing.Font(font name, size);
BackgroundImage
this.BackgroundImage = System.Drawing.Image.FromFile(image file
path);
BackgroundImageLayout
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.xxxxx
Icon
this.Icon = new System.Drawing.Icon(icon file path);
WindowState
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
(or)
this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
(or)
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
Cursor
this.Cursor = System.Windows.Forms.Cursors.xxxxx;
FormBorderStyle
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.xxxxx;
Size
this.Size = new System.Drawing.Size(width, height);
Location
this.Location = new System.Drawing.Point(x, y);
Opacity
this.Opacity = n;







.NET 4.0 and Visual Studio 2010 Page 271 of 548
D. HARSHA VARDHAN

IMP Notes to remember:
In the above syntaxes, we are using few pre-defined classes, pre-defined structures and pre-
defined enumerations also.
Classes
1) System.Drawing.Point
2) System.Drawing.Size
3) System.Drawing.Font
4) System.Drawing.Image
5) System.Drawing.Icon
6) System.Windows.Forms.Cursors
Structures 7) System.Drawing.Color
Enumerations
8) System.Drawing.ContentAlignment
9) System.Windows.Forms.ImageLayout
10) System.Windows.Forms.FormWindowState
11) System.Windows.Forms.FormBorderStyle

Methods of System.Windows.Forms.Form Class
Method Description
Hide() Makes the form invisible at run time.
Show() Makes the form visible at run time.
Close() Closes the form.
Syntax to access the Methods in the code: this.Method();

Events of System.Windows.Forms.Form Class
Event Description
Load
Executes whenever the form is loaded in the memory at run time, before the
form is displayed on the screen.
Shown Executes after the form is displayed on the screen.
FormClosing Executes when the form is about to be closed.
FormClosed Executes after the form is closed.
Click Executes when the user clicks on the form at run time.
DoubleClick Executes when the user double-clicks on the form at run time.
MouseMove Executes when the mouse pointer is moves across the form.
MouseEnter Executes when the mouse pointer is focused on to the form.
MouseLeave Executes when the mouse pointer is out of the form.
Move Executes when the form is moved at run time, using keyboard or mouse.
Resize Executes when the form is resized at run time.
KeyPress Executes when any key is pressed on the keyboard, while running on the form.
Enter Executes when the focus is got into the form.
Leave Executes when the focus is out of the form.





.NET 4.0 and Visual Studio 2010 Page 272 of 548
D. HARSHA VARDHAN



































Application 84: Demo on Form Events
private void Form1_Load(object sender, EventArgs e)
{
this.Text = "This is load event.";
}

private void Form1_Move(object sender, EventArgs e)
{
this.Text = "This is move event.";
}

private void Form1_Click(object sender, EventArgs e)
{
this.Text = "This is click event.";
}

private void Form1_DoubleClick(object sender, EventArgs e)
{
this.Text = "This is double click event.";
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
MessageBox.Show("Bye. Thank you.");
}

private void Form1_Resize(object sender, EventArgs e)
{
this.Text = "This is resize event.";
}

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
this.Text = "This is key press event.";
}





.NET 4.0 and Visual Studio 2010 Page 273 of 548
D. HARSHA VARDHAN






























Application 85: A Simple Demo on Form Properties
private void Form1_Click(object sender, EventArgs e)
{
this.Text = "Thanks for clicking";
this.BackColor = Color.Green;
this.WindowState = FormWindowState.Maximized;
}
Application 86: Demo on Form Properties
Design
button1:
Text: Red
Name: btnRed

button2:
Text: Green
Name: btnGreen

button3:
Text: Blue
Name: btnBlue

Design
Form1:
Text: Click the form






.NET 4.0 and Visual Studio 2010 Page 274 of 548
D. HARSHA VARDHAN



































private void btnRed_Click(object sender, EventArgs e)
{
this.BackColor = Color.Red;
}

private void btnGreen_Click(object sender, EventArgs e)
{
this.BackColor = Color.Green;
}

private void btnBlue_Click(object sender, EventArgs e)
{
this.BackColor = Color.Blue;
}
Application 87: Demo on Form Properties
private void btnNormal_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
}

private void btnMinimize_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}

private void btnMaximize_Click(object sender, EventArgs e)
{
Design
button1:
Text: Normal
Name: btnNormal

button2:
Text: Minimize
Name: btnMinimize

button3:
Text: Maximize
Name: btnMaximize

button3:
Text: Exit
Name: btnExit






.NET 4.0 and Visual Studio 2010 Page 275 of 548
D. HARSHA VARDHAN




























Application 88: Demo on Form Properties
private void btnShowBackgroundImage_Click(object sender, EventArgs e)
{
this.BackgroundImage = Image.FromFile("c:\\globe.jpg");
this.BackgroundImageLayout = ImageLayout.Zoom;
}

private void btnClearBackgroundImage_Click(object sender, EventArgs e)
{
this.BackgroundImage = null;
}
this.WindowState = FormWindowState.Maximized;
}

private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
Design
button1:
Text: Show Background Image
Name: btnShowBackgroundImage

button2:
Text: Clear Background Image
Name: btnClearBackgroundImage







.NET 4.0 and Visual Studio 2010 Page 276 of 548
D. HARSHA VARDHAN

1 1) ) B Bu ut tt to on n

It is known as action based control. Executes an operation, when it is clicked.
API: System.Windows.Forms.Button
Naming Convension: btnxxxxxx
Properties of Button
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
BackColor Specifies the background color of the control.
ForeColor Specifies the foreground color of the control.
Font Specifies the font style of the controls text.
Enabled Enables / Disables the control.
Visible Displays / Hides the control.
Cursor Specifies the mouse pointer style, when it is over on the control.
Size Specifies the Width and Height of the control.
Location Specifies the X and Y co-ordinations of the controls position on the form.
TextAlign Specifies the position of the text in the control.
Image
Specifies the image that is to be displayed in the control along with the
text.
ImageAlign Specifies the position of the image in the control
TabIndex Specifies the index of the control in the tab order.
ContextMenuStrip Contains the reference of the respective context menu control.
FlatStyle Specifies style of the button. (Flat / Popup / Standard / System)

Events of Button
Event Description
Click Executes when the user clicks the control run time.
DoubleClick Executes when the user double-clicks the control at run time.
MouseMove Executes when the mouse pointer is moves across the control.
MouseEnter Executes when the mouse pointer is focused on to the control.
MouseLeave Executes when the mouse pointer is out of the control.
KeyPress
Executes when any key is pressed on the keyboard, while the focus is on
the control.
Enter Executes when the focus is get into the control.
Leave Executes when the focus is out of the control.









.NET 4.0 and Visual Studio 2010 Page 277 of 548
D. HARSHA VARDHAN

2 2) ) L La ab be el l

Mainly used for presentation purpose, to display a message or description to the
user.

API: System.Windows.Forms.Label
Naming Convension: lblxxxxxx
Properties of Label
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
BackColor Specifies the background color of the control.
ForeColor Specifies the foreground color of the control.
Font Specifies the font style of the controls text.
Enabled Enables / Disables the control.
Visible Displays / Hides the control.
Cursor Specifies the mouse pointer style, when it is over on the control.
Size Specifies the Width and Height of the control.
Location
Specifies the X and Y co-ordinations of the controls position on the
form.
TextAlign Specifies the position of the text in the control.
Image
Specifies the image that is to be displayed in the control along with
the text.
ImageAlign Specifies the position of the image in the control
TabIndex Specifies the index of the control in the tab order.
ContextMenuStrip Contains the reference of the respective context menu control.
AutoSize
Enables / disables automatic sizing of the control, based on the
text.

Events of Label
Event Description
Click Executes when the user clicks the control run time.
DoubleClick Executes when the user double-clicks the control at run time.
MouseMove Executes when the mouse pointer is moves across the control.
MouseEnter Executes when the mouse pointer is focused on to the control.
MouseLeave Executes when the mouse pointer is out of the control.
KeyPress
Executes when any key is pressed on the keyboard, while the focus
is on the control.
Enter Executes when the focus is entered into the control.
Leave Executes when the focus is out of the control.









.NET 4.0 and Visual Studio 2010 Page 278 of 548
D. HARSHA VARDHAN

3 3) ) T Te ex xt tB Bo ox x

Used to take any user input in the application.

API: System.Windows.Forms.TextBox
Naming Convension: txtxxxxxx
Properties of TextBox
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
BackColor Specifies the background color of the control.
ForeColor Specifies the foreground color of the control.
Font Specifies the font style of the controls text.
Enabled Enables / Disables the control.
Visible Displays / Hides the control.
Cursor Specifies the mouse pointer style, when it is over on the control.
Size Specifies the Width and Height of the control.
Location
Specifies the X and Y co-ordinations of the controls position on the
form.
TextAlign
Specifies the position of the text in the control (Left / Center /
Right)
Image
Specifies the image that is to be displayed in the control along with
the text.
ImageAlign Specifies the position of the image in the control
TabIndex Specifies the index of the control in the tab order.
ContextMenuStrip Contains the reference of the respective context menu control.
ReadOnly
Enables / disables read-only nature of the textbox. In the read only
textbox, the user can not enter any text.
MultiLine
Enables / disables multiple lines in the text box. By default, the text
box will be single-line textbox.
WordWrap
This is used in multi line textboxes, which automatically moves the
cursor to the next line, when the current line exceeds.
Scrollbars Enables / disables scroll bars in the textbox.
PasswordChar Used to specify the password display character. Ex: *
MaxLength
Specifies the maximum no. of characters that can be entered in the
textbox.

Events of TextBox
Event Description
TextChanged Executes when any character is typed / removed in the textbox.
Click Executes when the user clicks the control run time.
DoubleClick Executes when the user double-clicks the control at run time.
MouseMove Executes when the mouse pointer is moves across the control.
MouseEnter Executes when the mouse pointer is focused on to the control.
MouseLeave Executes when the mouse pointer is out of the button.
KeyPress
Executes when any key is pressed on the keyboard, while the focus
is on the control.





.NET 4.0 and Visual Studio 2010 Page 279 of 548
D. HARSHA VARDHAN

Enter Executes when the focus is entered into the control.
Leave Executes when the focus is out of the control.

Methods of TextBox
Method Description
Clear() Clears all the contents of the textbox and makes it empty.
Focus() Moves the focus to the control.





























Application 89: Demo on TextBox
private void btnOK_Click(object sender, EventArgs e)
{
string name = txtName.Text;
string message = "Welcome to " + name;
lblMessage.Text = message;
lblMessage.Visible = true;
}
Design
label1:
Text: Enter your Name:
Name: lblName

textBox1:
Name: txtName

label2:
Text: Message
Name: lblMessage
Visible: False

button1:
Text: OK
Name: btnOK
ForeColor: Red






.NET 4.0 and Visual Studio 2010 Page 280 of 548
D. HARSHA VARDHAN



































Application 90: Demo on TextBox
Design
label1:
Text: Enter First Value:
Name: lblFirstValue

textBox1:
Name: txtFirstValue

label2:
Text: Enter Second Value:
Name: lblSecondValue

button1:
Name: btnAdd
Text: +

button2:
Name: btnSubtract
Text: -


(Continued)
button3:
Name: btnMultiply
Text: *

button4:
Name: btnDivide
Text: /

label3:
Name: lblResult
Text: Result:

textBox3:
Name: txtResult
ReadOnly: True






.NET 4.0 and Visual Studio 2010 Page 281 of 548
D. HARSHA VARDHAN



































private void btnAdd_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtFirstValue.Text);
int b = Convert.ToInt32(txtSecondValue.Text);
int c = a + b;
txtResult.Text = Convert.ToString(c);
}

private void btnSubtract_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtFirstValue.Text);
int b = Convert.ToInt32(txtSecondValue.Text);
int c = a - b;
txtResult.Text = Convert.ToString(c);
}

private void btnMultiply_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtFirstValue.Text);
int b = Convert.ToInt32(txtSecondValue.Text);
int c = a * b;
txtResult.Text = Convert.ToString(c);
}

private void btnDivide_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtFirstValue.Text);
int b = Convert.ToInt32(txtSecondValue.Text);
int c = a / b;
txtResult.Text = Convert.ToString(c);
}
Application 91: Demo on TextBox


label1:
Text: Enter your text here:
Name: lblSourceText

textBox1:
Name: txtSourceText

label2:
Text: Copied Text:
Name: lblDestinationText

textBox2:
Name: txtDestinationText
Design
Design
label1:
Text: Enter your text here:
Name: lblSourceText

textBox1:
Name: txtSourceText

label2:
Text: Copied Text:
Name: lblDestinationText

button1:
Name: txtDestinationText
ReadOnly: True






.NET 4.0 and Visual Studio 2010 Page 282 of 548
D. HARSHA VARDHAN



































private void txtSourceText_TextChanged(object sender, EventArgs e)
{
txtDestinationText.Text = txtSourceText.Text;
}
Application 92: Demo on TextBox


label1:
Text: Generate Numbers
Name: lblGenerateNumbers

label2:
Text: From:
Name: lblFrom

textBox1:
Name: txtFrom

label3:
Text: To:
Name: lblTo

textBox2:
Name: txtTo

button1:
Text: GO:
Name: btnGO

textBox3:
Name: txtNumbers
Design
private void btnGO_Click(object sender, EventArgs e)
{
int n1 = Convert.ToInt32(txtFrom.Text);
int n2 = Convert.ToInt32(txtTo.Text);
txtNumbers.Clear();
for (int i = n1; i <= n2; i++)
{
txtNumbers.Text = txtNumbers.Text + i + ", ";
}
txtFrom.Focus();
}
Design
label1:
Text: Generate Numbers
Name: lblGenerateNumbers

label2:
Text: From:
Name: lblFrom

textBox1:
Name: txtFrom


label3:
Text: To:
Name: lblTo

textBox2:
Name: txtTo


button1:
Name: btnGo
Text: GO

textBox3:
Name: txtNumbers
ReadOnly: True
MultiLine: True
ScollBars: Vertical






.NET 4.0 and Visual Studio 2010 Page 283 of 548
D. HARSHA VARDHAN

4 4) ) C Ch he ec ck kB Bo ox x

Used to take the choice from the user. The check box can be checked or
un-checked by the user.

API: System.Windows.Forms.CheckBox
Naming Convension: chkxxxxxx

Properties of CheckBox
Property Description
Name Specifies the name of the control.
Checked
Represents the current status of the check box, whether it is
checked or un-checked.
Text Specifies the displayable text of the control.
BackColor, ForeColor, Font, Enabled, Visible, Cursor, Size, Location, TextAlign, Image, ImageAlign,
TabIndex, ContextMenuStrip

Events of CheckBox
Event Description
CheckedChanged Executes when the user checks / un-checks the checkbox.
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Methods of CheckBox
Method Description
Focus() Moves the focus to the control.














Application 93: Demo on CheckBox





.NET 4.0 and Visual Studio 2010 Page 284 of 548
D. HARSHA VARDHAN








5 5) ) R Ra ad di io oB Bu ut tt to on n

Used to take the choice from the user. We have to implement two or
more radio buttons. At run time, any one of the radio buttons can be
selected.

API: System.Windows.Forms.RadioButton
Naming Convension: rbxxxxxx

Properties of RadioButton
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
Checked
Represents the current status of the check box, whether it is
checked or un-checked.
BackColor, ForeColor, Font, Enabled, Visible, Cursor, Size, Location, TextAlign, Image, ImageAlign,
TabIndex, ContextMenuStrip

Events of RadioButton
Event Description
CheckedChanged Executes when the user checks / un-checks the radio button.
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Methods of RadioButton
Method Description
Focus() Moves the focus to the control.






private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
label1.Text = "The check box is checked.";
else
label1.Text = "The check box is un-checked.";
}





.NET 4.0 and Visual Studio 2010 Page 285 of 548
D. HARSHA VARDHAN



































Application 94: Demo on RadioButton
private void rbBeige_CheckedChanged(object sender, EventArgs e)
{
this.BackColor = Color.Beige;
}

private void rbLightGreen_CheckedChanged(object sender, EventArgs e)
{
this.BackColor = Color.LightGreen;
}

private void rbLightYellow_CheckedChanged(object sender, EventArgs e)
{
this.BackColor = Color.LightYellow;
}

private void rbBisque_CheckedChanged(object sender, EventArgs e)
{
this.BackColor = Color.Bisque;
}
Design
label1:
Text: Select Background Color:
Name: lblBackgroundColor

radioButton1:
Text: Beige
Name: rbBeige

radioButton2:
Text: Light Green
Name: rbLightGreen


radioButton3:
Text: Light Yellow
Name: rbLightYellow

radioButton4:
Text: Bisque
Name: rbBisque






.NET 4.0 and Visual Studio 2010 Page 286 of 548
D. HARSHA VARDHAN

6 6) ) L Li in nk kL La ab be el l

Used to create hyperlinks.

API: System.Windows.Forms.LinkLabel
Naming Convension: lnkxxxxxx

Properties of LinkLabel
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
LinkColor Specifies the default link color
VisitedLinkColor Specifies the visited link color
ActiveLinkColor Specifies the active link color
BackColor, ForeColor, Font, Enabled, Visible, Cursor, Size, Location, TextAlign, Image, ImageAlign,
TabIndex, ContextMenuStrip

Events of LinkLabel
Event Description
LinkClicked Executes when the user clicks on the link.
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Methods of LinkLabel
Method Description
Focus() Moves the focus to the control.







Application 95: Demo on LinkLabel
Design
linkLabel1:
Text: My Link Label:
Name: linkLabel1






.NET 4.0 and Visual Studio 2010 Page 287 of 548
D. HARSHA VARDHAN






7 7) ) P Pi ic ct tu ur re eB Bo ox x

Used to display an image on the form, at desired place.

API: System.Windows.Forms.PictureBox
Naming Convension: picxxxxxx

Properties of PictureBox
Property Description
Name Specifies the name of the control.
Image Specifies the image, which is to be displayed in the control.
SizeMode
Specifies mode of the image sizing in the control.
(Normal, Stretch, Auto Size, Center, Zoom)
BackColor, Enabled, Visible, Cursor, Size, Location, ContextMenuStrip

Events of PictureBox
Event Description
Click Executes when the user clicks on the picture box.
DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave





private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
MessageBox.Show("The link label is clicked.");
}
Application 96: Demo on PictureBox
Design
label1:
Text: Enter image path:
Name: lblEnterImagePath

textBox1:
Name: txtImagePath

button1:
Text: Show
Name: btnShow


pictureBox1:
BorderStyle: Fixed3D
Name: picBoxImage


button2:
Text: Clear Image
Name: btnClearImage

label2:
Text: Size Mode:
ForeColor: Red

radioButton1:
Text: Normal
Name: rbNormal

radioButton2:
Text: Stretch
Name: rbStretch

radioButton3:
Text: Auto Size
Name: rbAutoSize

radioButton4:
Text: Center
Name: rbCenter

radioButton5:
Text: Zoom
Name: rbZoom






.NET 4.0 and Visual Studio 2010 Page 288 of 548
D. HARSHA VARDHAN




















using System.IO;
private void btnShow_Click(object sender, EventArgs e)
{
string imagepath = txtImagePath.Text;
FileInfo fobj = new FileInfo(imagepath);
if (fobj.Exists)
{
picBoxImage.Image = Image.FromFile(imagepath);
}
else
{
MessageBox.Show("Image file not found.");
}
}

private void btnClearImage_Click(object sender, EventArgs e)
{
picBoxImage.Image = null;
}

private void rbNormal_CheckedChanged(object sender, EventArgs e)
{
picBoxImage.SizeMode = PictureBoxSizeMode.Normal;
}





.NET 4.0 and Visual Studio 2010 Page 289 of 548
D. HARSHA VARDHAN












private void rbStretch_CheckedChanged(object sender, EventArgs e)
{
picBoxImage.SizeMode = PictureBoxSizeMode.StretchImage;
}

private void rbAutoSize_CheckedChanged(object sender, EventArgs e)
{
picBoxImage.SizeMode = PictureBoxSizeMode.AutoSize;
}

private void rbCenter_CheckedChanged(object sender, EventArgs e)
{
picBoxImage.SizeMode = PictureBoxSizeMode.CenterImage;
}

private void rbZoom_CheckedChanged(object sender, EventArgs e)
{
picBoxImage.SizeMode = PictureBoxSizeMode.Zoom;
}





.NET 4.0 and Visual Studio 2010 Page 290 of 548
D. HARSHA VARDHAN

8 8) ) P Pa an ne el l

This acts as container, which can contain other type
of controls like labels, textboxes, buttons,
checkboxes etc.

API: System.Windows.Forms.Panel
Naming Convension: pnlxxxxxx

Properties of Panel
Property Description
Name, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, BackgroundImage,
BackgroundImageLayout, ContextMenuStrip, BorderStyle

Events of Panel
Event Description
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave
















Note: When you want to create multiple groups of radio buttons, then use the panel or group
box control to group-up those radio buttons.


Application 97: Demo on Panel





.NET 4.0 and Visual Studio 2010 Page 291 of 548
D. HARSHA VARDHAN

9 9) ) G Gr ro ou up pB Bo ox x

This is also acts as container, similar to panel, but it
contains text also.

API: System.Windows.Forms.GroupBox
Naming Convension: grpxxxxxx


Properties of GroupBox
Property Description
Name, Text, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, BackgroundImage,
BackgroundImageLayout, ContextMenuStrip

Events of GroupBox
Event Description
Enter, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Leave








Application 98: Demo on GroupBox





.NET 4.0 and Visual Studio 2010 Page 292 of 548
D. HARSHA VARDHAN



































private void rbWhite_CheckedChanged(object sender, EventArgs e)
{
txtMyTextBox.BackColor = Color.White;
}

private void rbRed_CheckedChanged(object sender, EventArgs e)
{
txtMyTextBox.BackColor = Color.Red;
}

private void rbYellow_CheckedChanged(object sender, EventArgs e)
{
txtMyTextBox.BackColor = Color.Yellow;
}

private void rbBlue_CheckedChanged(object sender, EventArgs e)
{
txtMyTextBox.ForeColor = Color.Blue;
}

private void rbGreen_CheckedChanged(object sender, EventArgs e)
{
txtMyTextBox.ForeColor = Color.Green;
}

private void rbOrange_CheckedChanged(object sender, EventArgs e)
{
txtMyTextBox.ForeColor = Color.Orange;
}
Design
textBox1:
Name: txtMyTextBox

groupBox1:
Name: grpBackgroundColor
Text: TextBox Background Color:

groupBox2:
Name: grpForegroundColor
Text: TextBox Foreground Color:

radioButton1:
Text: White
Name: rbWhite

radioButton2:
Text: Red
Name: rbRed


















radioButton3:
Text: Yellow
Name: rbYellow


radioButton4:
Text: Blue
Name: rbBlue

radioButton5:
Text: Green
Name: rbGreen

radioButton6:
Text: Orange
Name: rbOrange






.NET 4.0 and Visual Studio 2010 Page 293 of 548
D. HARSHA VARDHAN

1 10 0) ) L Li is st tB Bo ox x

This contains multiple options (items). Among those items, the user can
select any one option. In some list boxes, multiple items also can be
selected. Those list boxes are called as Mutiple item selection list
boxes.

API: System.Windows.Forms.ListBox
Naming Convension: lstxxxxxx

Properties of ListBox
Property Description
Items Contains the list of items, that can be displayed in the list box.
SelectionMode
Specifies mode of the item selection.
None No item can be selected.
One - Single item can only be selected
MultiSimple Multiple items can be selected, directly by clicking on the items.
MultiExtended Multiple items can be selected, with Shift+Click or Ctrl+Click.
Sorted Enables / disables automatic sorting of items
Name, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, ContextMenuStrip

Events of ListBox
Event Description
SelectedIndexChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Leave

Run Time Properties of ListBox
Property Description
ListboxName.SelectedItem Represents the currently selected item in the list box.
ListboxName.SelectedIndex Represents the index of the currently selected item in the list box.
ListboxName.Items.Count Represents the total no. of items in the list box.
ListboxName.Items[index] Gets the specified item, based on the given index.
ListboxName.SelectedItems.Count
Represents the total no. of items, currently being selected. (For
multiple selection list boxes)
ListboxName.SelectedItems[index]
Gets the particular item in the currently selected items. (For
multiple selection list boxes)

Methods of ListBox
Property Description
ListboxName.Items.Add(xxxxx) Adds a new item at the end of the list box items.
ListboxName.Items.Insert(index,
xxxx)
Inserts a new item at the specified position.
ListboxName.Items.RemoveAt(index) Removes an item, based on its index.
ListboxName.Items.Clear() Removes all the items in the list box.
ListboxName.Items.IndexOf(xxxx)
Searches the given string the items collection, and returns the
index, if it is found; otherwise, it returns -1.






.NET 4.0 and Visual Studio 2010 Page 294 of 548
D. HARSHA VARDHAN





















Application 99: Demo on Single item Selection ListBox
private void lstCourses_SelectedIndexChanged(object sender, EventArgs e)
{
lblSelectedCourse.Text = Convert.ToString(lstCourses.SelectedItem);
lblSelectedCourseIndex.Text = Convert.ToString(lstCourses.SelectedIndex);
}
Design
label1:
Name: lblSelectCourse
Text: Select your Course:

listBox1:
Name: lstCourses
Items: .NET 4.0
Java
Share Point
Oracle DBA
Sql Server
QTP
MS BI

label2:
Name: lblSelectedCoursePrompt
Text: Selected Course:

label3:
Name: lblSelectedCourse
Text: Selected Course Here

label4:
Name: lblSelectedCourseIndexPrompt
Text: Selected Course Index:

label5:
Name: lblSelectedCourseIndex
Text: Selected Course Index Here






.NET 4.0 and Visual Studio 2010 Page 295 of 548
D. HARSHA VARDHAN




















Application 100: Demo on Single item Selection ListBox
Design
groupBox1:
Name: grpCities
Text: Cities:

listBox1:
Name: lstCities
Items: Hyderabad
Pune
New Delhi
Banglore
Dehradun

groupBox2:
Name: grpOptions
Text: Options:

label1:

Name: lblNewCity
Text: New City Name:

textBox1:

Name: txtNewCity

button1:
Name: btnAdd
Text: Add

button2:
Name: btnRemoveCity
Items: Remove Selected City

button3:
Name: btnClearAll
Text: Clear All

button4:

Name: btnShowCount
Text: Show Count






.NET 4.0 and Visual Studio 2010 Page 296 of 548
D. HARSHA VARDHAN



































private void btnAdd_Click(object sender, EventArgs e)
{
if (txtNewCity.Text != "")
{
lstCities.Items.Add(txtNewCity.Text);
txtNewCity.Clear();
}
else
MessageBox.Show("Enter new city name.");
txtNewCity.Focus();
}

private void btnRemoveCity_Click(object sender, EventArgs e)
{
if (lstCities.SelectedIndex >= 0)
lstCities.Items.RemoveAt(lstCities.SelectedIndex);
else
MessageBox.Show("Select any city.");
}

private void btnClearAll_Click(object sender, EventArgs e)
{
lstCities.Items.Clear();
MessageBox.Show("All cities cleared.");
}

private void btnShowCount_Click(object sender, EventArgs e)
{
int count = lstCities.Items.Count;
MessageBox.Show(count + " cities found.");
}





.NET 4.0 and Visual Studio 2010 Page 297 of 548
D. HARSHA VARDHAN




















Application 101: Demo on Multiple item Selection ListBox
Design
label1:
Name: lblAvailableBooks
Text: Available Books:

listBox1:
Name: lstAvailableBooks
Sorted: True
SelectionMode: MultiSimple
Items: ASP.NET for Professionals
C# 4.0 for Beginners
HTML 4.0
Java Complete Reference
JavaScript Bible
Let Us C
Let Us C++


label2:
Name: lblSelectedBooks
Text: Selected Books:

listBox2:

Name: lstSelectedBooks
Sorted: True

button1:

Name: btnSend






.NET 4.0 and Visual Studio 2010 Page 298 of 548
D. HARSHA VARDHAN









1 11 1) ) C Co om mb bo oB Bo ox x

This also contains multiple options (items), similar to list box.
But, unlike list box, in the combo box, the user cant select
multiple items. One more advantage of combo box is, it offers
some text entry similar to text box. Finally the combo box is a combination of list box and text
box.

API: System.Windows.Forms.ComboBox
Naming Convension: cmbxxxxxx
Properties of ComboBox
Property Description
Items Contains the list of items that can be displayed in the list box.
DropDownStyle
Simple: It looks like a text box, but the items can be accessed by pressing up / down
arrow keys.
DropDown: It is the default value. The user can type new text (or) can select the
items from the list.
DropDownList: The user can type new text. Only selection is possible.
Sorted Enables / disables automatic sorting of items
Name, Text, TextAlign, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, ContextMenuStrip

Events of ComboBox
Event Description
SelectedIndexChanged, TextChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave,
KeyPress, Leave

Run Time Properties of ComboBox
Property Description
cmbObj.SelectedItem Represents the currently selected item in the combo box.
cmbObj.SelectedIndex
Represents the index of the currently selected item in the combo
box.
cmbObj.Items.Count Represents the total no. of items in the combo box.
cmbObj.Items[index] Gets the specified item, based on the given index.
cmbObj.Text Gets the text, entered in the combo box.
private void btnSend_Click(object sender, EventArgs e)
{
int i;
lstSelectedBooks.Items.Clear();
for (i = 0; i < lstAvailableBooks.SelectedItems.Count; i++)
lstSelectedBooks.Items.Add(lstAvailableBooks.SelectedItems[i]);
}





.NET 4.0 and Visual Studio 2010 Page 299 of 548
D. HARSHA VARDHAN

Methods of ComboBox
Method Description
cmbObj.Items.Add(xxxxx) Adds a new item at the end of the combo box items.
cmbObj.Items.Insert(index, xxxx) Inserts a new item at the specified position.
cmbObj.Items.RemoveAt(index) Removes an item, based on its index.
cmbObj.Items.Clear() Removes all the items in the combo box.
cmbObj.Items.IndexOf(xxxx)
Searches the given string the items collection, and returns the
index, if it is found; otherwise, it returns -1.
cmbObj.Clear() Clears the text entered in the combo box.




























Application 102: Demo on ComboBox
Design
label1:
Name: lblSeleCourse
Text: Select Course:

comboBox1:
Name: cmbCourse
DropDownStyle: DropDownList
Items: .NET
Java
C
C++
Oracle

label2:

Name: lblFee
Text: Fee:

textBox1:

Name: txtFee
ReadOnly: True






.NET 4.0 and Visual Studio 2010 Page 300 of 548
D. HARSHA VARDHAN












1 12 2) ) N Nu um me er ri ic cU Up pD Do ow wn n

This offers to enter a numerical value, within a given range. The user can enter a
value, out of the range.

API: System.Windows.Forms.NumericUpDown
Naming Convension: numxxxxxx
Properties of NumericUpDown
Property Description
Value Gets or sets the current value in the NumericUpDown control.
DecimalPlaces Specifies the no. of decimal places in the value
Minimum Specifies the minimum value in the range.
Maximum Specifies the maximum value in the range.
TextAlign Left / Center / Right
UpDownAlign Left / Right
Name, ReadOnly, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, BackgroundImage,
BackgroundImageLayout, ContextMenuStrip, BorderStyle

Events of NumericUpDown
Event Description
ValueChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave





private void cmbCourse_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbCourse.SelectedIndex == 0)
txtFee.Text = "Rs. 4,900/-";
else if (cmbCourse.SelectedIndex == 1)
txtFee.Text = "Rs. 6,200/-";
else if (cmbCourse.SelectedIndex == 2)
txtFee.Text = "Rs. 1,000/-";
else if (cmbCourse.SelectedIndex == 3)
txtFee.Text = "Rs. 1,200/-";
else if (cmbCourse.SelectedIndex == 4)
txtFee.Text = "Rs. 1,500/-";
}





.NET 4.0 and Visual Studio 2010 Page 301 of 548
D. HARSHA VARDHAN

1 13 3) ) D Do om ma ai in nU Up pD Do ow wn n

It is similar to combo box, but it looks like NumericUpDown.

API: System.Windows.Forms.DomainUpDown
Naming Convension: domxxxxxx

Properties of DomainUpDown
Property
Items, Sorted, Name, Text, TextAlign, BackColor, ForeColor, Font, Enabled, Visible, Size, Location,
ContextMenuStrip

Events of DomainUpDown
Event
SelectedItemChanged, TextChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave,
KeyPress, Leave

Run Time Properties of DomainUpDown
Property
domObj.SelectedItem, domObj.SelectedIndex, domObj.Items.Count, domObj.Items[index], domObj.Text

Methods of DomainUpDown
Method
domObj.Items.Add(xxxxx) Adds a new item at the end of the domainupdown items.
domObj.Items.Insert(index, xxxx) Inserts a new item at the specified position.
domObj.Items.RemoveAt(index) Removes an item, based on its index.
domObj.Items.Clear() Removes all the items in the domainupdown.
domObj.Items.IndexOf(xxxx)
Searches the given string the items collection, and returns the
index, if it is found; otherwise, it returns -1.
domObj.Clear() Clears the text entered in the domainupdown.










Application 103: Demo on NumericUpDown and DomainUpDown





.NET 4.0 and Visual Studio 2010 Page 302 of 548
D. HARSHA VARDHAN



































private void ChangeFont()
{
string font = Convert.ToString(domFont.SelectedItem);
int size = Convert.ToInt32(numSize.Value);
txtMyText.Font = new Font(font, size);
}

private void domFont_SelectedItemChanged(object sender, EventArgs e)
{
ChangeFont();
}
Design
textBox1:
Name: txtMyText

label1:
Name: lblFont
Text: Font:

domainUpDown1:

Name: domFont
Text: Tahoma
Items: Times New Roman
Tahoma
Arial
Arial Black
Century Gothic
Trebuchet MS
Palatino Linotype


label2:

Name: lblSize
Text: Size:

label3:

Name: numSize
Value: 10
Minimum: 1
Maximum: 100






.NET 4.0 and Visual Studio 2010 Page 303 of 548
D. HARSHA VARDHAN







1 14 4) ) D Da at te eT Ti im me eP Pi ic ck ke er r

This control enables the user, to select a date
or time value at run time. When the drop down
button is clicked, it displays a calendar for date selection. When you change the Format
property, it offers to select the time also.

API: System.Windows.Forms.DateTimePicker
Naming Convension: dtPickerxxxxxx
Properties of DateTimePicker
Property Description
Value Gets or sets the current value in the control.
Format Specifies the format of the date selection. (Short / Long / Time / Custom)
CustomFormat
Used to specify the customer date formats. (with words and symbols like dd,
mm, yyyy, -, / etc.)
ShowUpDown Enables / Disables the up/down buttons in the control.
MinDate Specifies the minimum date, which can be selected at run time.
MaxDate Specifies the maximum date, which can be selected at run time.
Name, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, ContextMenuStrip

Events of DateTimePicker
Event
ValueChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave









Application 104: Demo on DateTimePicker
private void numSize_ValueChanged(object sender, EventArgs e)
{
ChangeFont();
}





.NET 4.0 and Visual Studio 2010 Page 304 of 548
D. HARSHA VARDHAN


























1 15 5) ) M Mo on nt th hC Ca al le en nd da ar r

Similar to DateTimePicker. It offers for a date selection. But this
control, displays the calendar directly. In the calendar, the user can
select any date.

API: System.Windows.Forms.MonthCalendar
Naming Convension: monCalxxxxxx
private void Form1_Load(object sender, EventArgs e)
{
dtPickerDOB.Value = DateTime.Now.AddYears(-20);
}

private void dtPickerDOB_ValueChanged(object sender, EventArgs e)
{
DateTime dob = dtPickerDOB.Value;
DateTime now = DateTime.Now;
if (now > dob)
{
TimeSpan ts = now - dob;
int Age = ts.Days / 365;
lblAge.Text = Age + " years.";
}
else
lblAge.Text = "Invalid DOB.";
}
Design
label1:
Name: lblSelectDOB
Text: Select Date of Birth:

dateTimePicker1:
Name: dtPickerDOB
Format: Short

label2:
Name: lblAgePrompt
Text: Age:

label3:

Name: lblAge
Text: Age here






.NET 4.0 and Visual Studio 2010 Page 305 of 548
D. HARSHA VARDHAN

Properties of MonthCalendar
Property Description
ShowToday Displays / hides todays date at the bottom of the control.
ShowWeekNumbers Displays / hides the week nos at left side.
MinDate Specifies the minimum date, which can be selected at run time.
MaxDate Specifies the maximum date, which can be selected at run time.
Name, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, ContextMenuStrip

Events of MonthCalendar
Event Description
DateChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Note: There is not any property, which gets the currently selected date in the calendar; so that,
we have to use DateRangeEventArgs class object to access currently selected date value in the
DateChanged event.


















Application 105: Demo on MonthCalendar
lblSelectAnyDate
monCalMyDate
ShowWeekNumbers: true
lblSelectDate





.NET 4.0 and Visual Studio 2010 Page 306 of 548
D. HARSHA VARDHAN











private void monCalMyDate_DateChanged(object sender, DateRangeEventArgs e)
{
DateTime dt = e.Start;
lblSelectedDate.Text = "You have selected: " + dt.ToShortDateString();
}
Design
label1:
Name: lblSelectAnyDate
Text: Select any Date:

monthCalendar1:
Name: monCalMyDate

label2:
Name: lblSelectedDate
Text: Select Date Here






.NET 4.0 and Visual Studio 2010 Page 307 of 548
D. HARSHA VARDHAN

1 16 6) ) T Tr ra ac ck kB Ba ar r

Similar to numericupdown, but it offers
visualization for the value selection.

API: System.Windows.Forms.TrackBar
Naming Convension: trkxxxxxx
Properties of TrackBar
Property Description
Value Gets or sets the current value in the control.
Minimum Specifies the minimum value in the range.
Maximum Specifies the maximum value in the range.
TickFrequency Specifies the difference between each tick.
Orientation Horizontal / Vertical
TickStyle None, TopLeft, BottomRight, Both
Name, BackColor, ForeColor, Enabled, Visible, Size, Location, ContextMenuStrip, BorderStyle

Events of TrackBar
Event Description
Scroll, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave


















Application 106: Demo on TrackBar





.NET 4.0 and Visual Studio 2010 Page 308 of 548
D. HARSHA VARDHAN



















1 17 7) ) T Ti im me er r

It is known as Invisible Control. That means it cant be displayed on the form
UI. But it works during the execution time. It performs background processing.
It executes a certain logic, whenever a certain interval time is completed.

API: System.Windows.Forms.Timer
Naming Convension: tmrxxxxxx

Properties of Timer
Property Description
Interval Specifies the interval time of the timer, in the form of mille seconds.
Name, Enabled
Events of Timer
Event
Tick Executes on every completion of interval time.



private void trkFontSize_Scroll(object sender, EventArgs e)
{
int n = trkFontSize.Value;
lblMyText.Font = new Font("Tahoma", n);
}
Application 107: Demo on Timer
Design
label1:
Name: lblFontSize
Text: Font Size:

trackBar1:
Name: trkFontSize
Minimum: 1
Maximum: 200
TickFrequency: 5

label2:
Name: lblMyText
Text: .NET Framework 4






.NET 4.0 and Visual Studio 2010 Page 309 of 548
D. HARSHA VARDHAN



































private void Form1_Load(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToLongTimeString();
}

private void tmrTime_Tick(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToLongTimeString();
}
Application 108: Demo on Timer
Design
label1:
Name: lblTime
Text: Time here

timer1:
Name: tmrTime
Interval: 1000
Enabled: True

Design
timer1:
Name: tmrBackColor
Interval: 500
Enabled: True






.NET 4.0 and Visual Studio 2010 Page 310 of 548
D. HARSHA VARDHAN

















1 18 8) ) P Pr ro og gr re es ss sB Ba ar r

It shows the progress of a certain process. Its value is
limited to the range of 0 to 100. Whenever its value is
reached to 100, that means the process is completed. It can be implemented with the
combination of timer control.

API: System.Windows.Forms.ProgressBar
Naming Convension: prgxxxxxx

Properties of ProgressBar
Property Description
Value Gets or sets the current value in the control.
Minimum Specifies the minimum value in the range.
Maximum Specifies the maximum value in the range.
Name, BackColor, ForeColor, Enabled, Visible, Size, Location, ContextMenuStrip, BackgroundImage,
BackgroundImageLayout

Events of ProgressBar
Event Description
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave


int n = 0;

private void tmrBackColor_Tick(object sender, EventArgs e)
{
n++;
switch (n)
{
case 1: this.BackColor = Color.Black; break;
case 2: this.BackColor = Color.Blue; break;
case 3: this.BackColor = Color.LightCoral; break;
case 4: this.BackColor = Color.LightCyan; break;
case 5: this.BackColor = Color.Green; break;
case 6: this.BackColor = Color.Red; break;
case 7: this.BackColor = Color.Chocolate; break;
case 8: this.BackColor = Color.DarkKhaki; break;
case 9: this.BackColor = Color.Firebrick; break;
case 10: this.BackColor = Color.Gold; break;
default: n = 0; break;
}
}





.NET 4.0 and Visual Studio 2010 Page 311 of 548
D. HARSHA VARDHAN



































Application 109: Demo on Progress Bar
Design
label1:
Name: lblFileName
Text: Enter File Name:

textBox1:
Name: txtFileName

button1:
Name: btnOpen
Text: Open

label2:
Name: lblLoading
Text: Loading
ForeColor: Red
Visible: False

progressBar1:
Name: prgFile
Visible: False


textBox2:
Name: txtContent
ReadOnly: True
WordWrap: False
Multiline: True
Scrollbars: Both

timer1:
Name: tmrFileOpen
Enabled: False
Interval: 100






.NET 4.0 and Visual Studio 2010 Page 312 of 548
D. HARSHA VARDHAN



























1 19 9) ) M Me en nu uS St tr ri ip p

Used to create a menu bar in the form. A menu bar
is a collection of multiple menu items. It is known
as invisible control. The menu items are of two types.
1) Parent Menu Items
2) Child Menu Items

using System.IO;
private void OpenFile()
{
string filename = txtFileName.Text;
FileInfo fobj = new FileInfo(filename);
if (fobj.Exists)
{
StreamReader sr = new StreamReader(filename);
string content = sr.ReadToEnd();
txtContent.Text = content;
sr.Close();
}
else
MessageBox.Show("File not found.");
}

private void btnOpen_Click(object sender, EventArgs e)
{
prgFile.Value = 0;
tmrFileOpen.Enabled = true;
lblLoading.Visible = true;
prgFile.Visible = true;
}

private void tmrFileOpen_Tick(object sender, EventArgs e)
{
prgFile.Value++;
if (prgFile.Value == 100)
{
tmrFileOpen.Enabled = false;
lblLoading.Visible = false;
prgFile.Visible = false;
OpenFile();
}
}





.NET 4.0 and Visual Studio 2010 Page 313 of 548
D. HARSHA VARDHAN

API: System.Windows.Forms.MenuStrip
Naming Convension: mnuxxxxxx

Each menu item will be created as a control for
System.Windows.Forms.ToolStripMenuItem class. The default naming convention for the
menu item is: xxxxxToolStripMenuItem.

Properties of MenuStrip
Property Description
Dock Top, Bottom, Left, Right, Fill
TextDirection Horizontal, Vertial90, Vertical270.
Name, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, BackgroundImage,
BackgroundImageLayout, ContextMenuStrip
Events of MenuStrip
Event Description
ItemClicked, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Properties of Menu Item
Property Description
Name, Text, TextAlign, BackColor, ForeColor, Font, Image, ImageAlign, Checked, Enabled, Visible,
ShortcutKeys, ShowShortcutKeys, Size, Location, BackgroundImage, BackgroundImageLayout,
ContextMenuStrip, BorderStyle
Events of Menu Item
Event Description
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave











Application 110: Demo on MenuStrip





.NET 4.0 and Visual Studio 2010 Page 314 of 548
D. HARSHA VARDHAN




























private void showToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = Image.FromFile("c:\\globe.jpg");
}

private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = null;
}

private void normalToolStripMenuItem_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
}

private void minimizedToolStripMenuItem_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}

private void maximizedToolStripMenuItem_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
}





.NET 4.0 and Visual Studio 2010 Page 315 of 548
D. HARSHA VARDHAN











2 20 0) ) C Co on nt te ex xt tM Me en nu uS St tr ri ip p

It is also a menu related control, similar to MenuStrip. But the context
menu would be displayed, when the user right
clicks on a control or a form, at run time. This is
also a collection of menu items. The context
menu is also called as Shortcut menu. The ContextMenuStrip is an
invisible control.
API: System.Windows.Forms.ContextMenuStrip
Naming Convension: conMnuxxxxxx

Properties of ContextMenuStrip
Property Description
Name, BackColor, Font, Enabled, Size, Location, BackgroundImage, BackgroundImageLayout,
ContextMenuStrip

Events of ContextMenuStrip
Event Description
ItemClicked, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave





Design the following two context menus in Form1.

Application 111: Demo on ContextMenuStrip
private void form2ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
}

private void form3ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form3 f = new Form3();
f.Show();
}





.NET 4.0 and Visual Studio 2010 Page 316 of 548
D. HARSHA VARDHAN
























.NET 4.0 and Visual Studio 2010 Page 317 of 548
D. HARSHA VARDHAN






























private void displayIconToolStripMenuItem_Click(object sender, EventArgs e)
{
if (displayIconToolStripMenuItem.Checked == true)
{
displayIconToolStripMenuItem.Checked = false;
this.ShowIcon = false;
}
else
{
displayIconToolStripMenuItem.Checked = true;
this.ShowIcon = true;
}
}

private void redToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackColor = Color.Red;
redToolStripMenuItem.Checked = true;
greenToolStripMenuItem.Checked = false;
blueToolStripMenuItem.Checked = false;
}

private void greenToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackColor = Color.Green;
redToolStripMenuItem.Checked = false;
greenToolStripMenuItem.Checked = true;
blueToolStripMenuItem.Checked = false;
}
Design
contextMenuStrip1:
Name: conMnuForm

displayIconToolStripMenuItem:
Checked: True

showInTaskBarToolStripMenuItem:
Checked: True

contextMenuStrip2:
Name: conMnuTextBox

Form1:
ContextMenuStrip: contextMenuStrip
Text: conMnuForm

textBox1:
Name: txtMyText
ContextMenuStrip: conMnuTextBox






.NET 4.0 and Visual Studio 2010 Page 318 of 548
D. HARSHA VARDHAN

























private void blueToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackColor = Color.Blue;
redToolStripMenuItem.Checked = false;
greenToolStripMenuItem.Checked = false;
blueToolStripMenuItem.Checked = true;
}

private void showInTaskBarToolStripMenuItem_Click(object sender, EventArgs e)
{
if (showInTaskBarToolStripMenuItem.Checked == true)
{
showInTaskBarToolStripMenuItem.Checked = false;
this.ShowInTaskbar = false;
}
else
{
showInTaskBarToolStripMenuItem.Checked = true;
this.ShowInTaskbar = true;
}
}

private void upperCaseToolStripMenuItem_Click(object sender, EventArgs e)
{
txtMyText.Text = txtMyText.Text.ToUpper();
}

private void lowerCaseToolStripMenuItem_Click(object sender, EventArgs e)
{
txtMyText.Text = txtMyText.Text.ToLower();
}

private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
txtMyText.Clear();
}





.NET 4.0 and Visual Studio 2010 Page 319 of 548
D. HARSHA VARDHAN

D Di ia al lo og g C Co on nt tr ro ol ls s

These are meant for creating dialog boxes at run time.
A dialog box can be defined as a Force responsive window, which requires the users
attention at run time. That means, without answering the dialog box, the user cant work
with the form.
In order to display different types of dialog boxes, .NET offers several dialog box
controls.
1) ColorDialog
2) FontDialog
3) FolderBrowserDialog
4) OpenFileDialog
5) SaveFileDialog
6) PrintDialog

Note: All the dialog box controls are known as invisible controls.


2 21 1) ) C Co ol lo or rD Di ia al lo og g

Displays a dialog box, for a color selection.

API: System.Windows.Forms.ColorDialog
Naming Convension: colorDlgxxxxxx

To invoke the dialog box at run time:
colorDialog1.ShowDialog();
Get the currently selected color in the dialog box:
colorDialog1.Color;











.NET 4.0 and Visual Studio 2010 Page 320 of 548
D. HARSHA VARDHAN























2 22 2) ) F Fo on nt tD Di ia al lo og g

Displays a dialog box, for a font selection (with font name, bold, italic, regular, underline, font
size options).

API: System.Windows.Forms.FontDialog
Naming Convension: fontDlgxxxxxx

To invoke the dialog box at run time:
fontDialog1.ShowDialog();
Get the currently selected color in the
dialog box:
fontDialog1.Font;

Application 112: Demo on ColorDialog
private void btnBackColor_Click(object sender, EventArgs e)
{
colorDlgBackColor.ShowDialog();
this.BackColor = colorDlgBackColor.Color;
}
Design
button1:
Name: btnBackColor
Text: Back Color

colorDialog1:
Name: colorDlgBackColor






.NET 4.0 and Visual Studio 2010 Page 321 of 548
D. HARSHA VARDHAN
























2 23 3) ) F Fo ol ld de er rB Br ro ow ws se er rD Di ia al lo og g

Displays a dialog box, for a folder selection.

API: System.Windows.Forms.FolderBrowserDialog
Naming Convension: folderBrowserDlgxxxxxx

To invoke the dialog box at run time:
folderBrowserDialog1.ShowDialog();
Get the currently selected folders full path
in the dialog box:
folderBrowserDialog1.SelectedPath;
Application 113: Demo on FontDialog
private void btnFont_Click(object sender, EventArgs e)
{
fontDialogMyText.ShowDialog();
txtMyText.Font = fontDialogMyText.Font;
}
Design
textBox1:
Name: txtMyText

button1:
Name: btnFont
Text: Font

fontDialog1:
Name: fontDialogMyText






.NET 4.0 and Visual Studio 2010 Page 322 of 548
D. HARSHA VARDHAN
















Application 114: Demo on FolderBrowserDialog
Design
button1:
Name: btnBrowseFolder
Text: Browse Folder

label1:
Name: lblSelectedFolder
Text: Selected Folder:

label2:
Name: lblFiles
Text: Files:

label3:
Name: lblSubFolders
Text: Sub Folders:

listBox1:
Name: lstFiles

listBox2:
Name: lstSubFolders






.NET 4.0 and Visual Studio 2010 Page 323 of 548
D. HARSHA VARDHAN



















2 24 4) ) O Op pe en nF Fi il le eD Di ia al lo og g

Displays a dialog box, for a file selection for
opening of a file.

API: System.Windows.Forms.OpenFileDialog
Naming Convension: openFileDlgxxxxxx

To invoke the dialog box at run time:
openFileDialog1.ShowDialog();
Get the currently selected file path
and name:
openFileDialog1.FileName;





using System.IO;
private void btnBrowseFolder_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
string selectedfolder = folderBrowserDialog1.SelectedPath;
lblSelectedFolder.Text = "Selected Folder: " + selectedfolder;
DirectoryInfo d = new DirectoryInfo(selectedfolder);
if (d.Exists)
{
DirectoryInfo[] subdirs = d.GetDirectories();
FileInfo[] files = d.GetFiles();
lstSubFolders.Items.Clear();
lstFiles.Items.Clear();
foreach (DirectoryInfo dobj in subdirs)
lstSubFolders.Items.Add(dobj.Name);
foreach (FileInfo fobj in files)
lstFiles.Items.Add(fobj.Name);
}
else
MessageBox.Show("The seleced folder not found.");
}
Application 115: Demo on OpenFileDialog





.NET 4.0 and Visual Studio 2010 Page 324 of 548
D. HARSHA VARDHAN


Design
label1:
Name: lblFileName
Text: Enter File Name:

textBox1:
Name: txtFileName

button1:
Name: btnBrowse
Text: Browse...

button2:
Name: btnOpen
Text: Open

textBox2:
Name: txtContent
ReadOnly: True
MultiLine: True
WordWrap: False
ScrollBars: Both






.NET 4.0 and Visual Studio 2010 Page 325 of 548
D. HARSHA VARDHAN



















2 25 5) ) S Sa av ve eF Fi il le eD Di ia al lo og g

Displays a dialog box, for a file selection for
saving a file.

API: System.Windows.Forms.SaveFileDialog
Naming Convension: saveFileDlgxxxxxx

To invoke the dialog box at run
time:
saveFileDialog1.ShowDialog();
Get the currently selected file path
and name:
saveFileDialog1.FileName;



using System.IO;
private void btnOpen_Click(object sender, EventArgs e)
{
string filename = txtFileName.Text;
FileInfo fobj = new FileInfo(filename);
if (fobj.Exists)
{
StreamReader sr = new StreamReader(filename);
string content = sr.ReadToEnd();
txtContent.Text = content;
sr.Close();
}
else
MessageBox.Show("File not found.");
}

private void btnBrowse_Click(object sender, EventArgs e)
{
openFileDialog1.Reset();
openFileDialog1.ShowDialog();
txtFileName.Text = openFileDialog1.FileName;
}
Application 116: Demo on SaveFileDialog





.NET 4.0 and Visual Studio 2010 Page 326 of 548
D. HARSHA VARDHAN



































Design
label1:
Name: lblFileName
Text: Enter File Name:

textBox1:
Name: txtFileName

button1:
Name: btnBrowse
Text: Browse...

button2:
Name: btnSave
Text: Save

textBox2:
Name: txtContent
MultiLine: True
WordWrap: False
ScrollBars: Both






.NET 4.0 and Visual Studio 2010 Page 327 of 548
D. HARSHA VARDHAN
























2 26 6) ) P Pr ri in nt tD Di ia al lo og g

Displays a dialog box, for printing preferences selection like no. of copies, name of the printer,
paper range and paper orientation etc.

API: System.Windows.Forms.PrintDialog
Naming Convension: printDlgxxxxxx

To invoke the dialog box at run time:
printDialog1.ShowDialog();
Get the selected printer settings:
printDialog1.PrinterSettings;

using System.IO;
private void btnBrowse_Click(object sender, EventArgs e)
{
saveFileDialog1.Reset();
saveFileDialog1.ShowDialog();
txtFileName.Text = saveFileDialog1.FileName;
}

private void btnSave_Click(object sender, EventArgs e)
{
string filename = txtFileName.Text;
if (filename != "")
{
FileInfo fobj = new FileInfo(filename);
if (!fobj.Exists)
{
StreamWriter sw = new StreamWriter(filename);
string content = txtContent.Text;
sw.Write(content);
sw.Close();
MessageBox.Show("Successfully Saved.");
}
else
MessageBox.Show("File already exists!");
}
else
MessageBox.Show("Select any file name first.");
}






.NET 4.0 and Visual Studio 2010 Page 328 of 548
D. HARSHA VARDHAN



































Application 117: Demo on PrintDialog
using System.Drawing.Printing;
using System.IO;
private void btnBrowse_Click(object sender, EventArgs e)
{
openFileDialog1.Reset();
openFileDialog1.ShowDialog();
txtFileName.Text = openFileDialog1.FileName;
}

private void btnPrint_Click(object sender, EventArgs e)
{
string filename = txtFileName.Text;
if (filename != "")
{
Design
label1:
Name: lblFileName
Text: Enter File Name:

textBox1:
Name: txtFileName

button1:
Name: btnBrowse
Text: Browse...

button2:
Name: btnPrint
Text: Print






.NET 4.0 and Visual Studio 2010 Page 329 of 548
D. HARSHA VARDHAN














2 27 7) ) R Ri ic ch hT Te ex xt tB Bo ox x

A rich textbox is used for development of text editor applications like word pad, edit plus
etc.
It offers better features, when compared with the standard textbox.
It supports built-in file interaction with .rtf files. (rtf stands for Rich Text Format).
One of the highlights of rich textbox is, to support different fonts and colors for part of
the text.

API: System.Windows.Forms.RichTextBox
Naming Convension: rtbxxxxxx

Run Time Properties of RichTextBox
Property Description
Text Gets or sets the text of the entire rich textbox.
SelectedText Gets or sets the currently selected text.
SelectionBackColor Represents the background color for the selected text.
SelectionColor Represents the foreground color for the selected text.
SelectionAlignment Left / Right / Center / Justify
SelectionFont Represents the font settings for the seleted text.
Name, BackColor, ForeColor, Enabled, Visible, Size, Location, ContextMenuStrip, Scrollbars, BorderStyle

FileInfo fobj = new FileInfo(filename);
if (fobj.Exists)
{
printDialog1.Reset();
printDialog1.ShowDialog();
PrintDocument doc = new PrintDocument();
doc.PrinterSettings = printDialog1.PrinterSettings;
doc.DocumentName = filename;
doc.Print();
MessageBox.Show("Printing Started...");
}
else
MessageBox.Show("File not found.");
}
else
MessageBox.Show("Enter file name");
}





.NET 4.0 and Visual Studio 2010 Page 330 of 548
D. HARSHA VARDHAN

Events of RichTextBox
Event Description
TextChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Methods of RichTextBox
Property Description
Clear() Clears entire text of the control.
Cut() Cuts the selected text.
Copy() Copies the selected text.
Paste() Pastes the text from the clipboard.
SelectAll() Selects the entire text in the control.
LoadFile(rtf file path) Loads the text from the specified .rtf file.
SaveFile(rtf file path) Saves the text of the control, into .rtf file.
Undo() Undos the previous action.
Redo() Redos the previous action.










Application 118: Demo on RichTextBox





.NET 4.0 and Visual Studio 2010 Page 331 of 548
D. HARSHA VARDHAN




















































bool IsFileSaved = true;

private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
if (IsFileSaved == false)
{
DialogResult dr = MessageBox.Show("Do you want to save the file", "Text
Editor 1.0", MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
if (this.Text == "Untitled")
{
saveFileDialog1.Reset();
saveFileDialog1.Filter = "Rich Text Files|*.rtf";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
rtbMyText.SaveFile(saveFileDialog1.FileName);
this.Text = saveFileDialog1.FileName;
IsFileSaved = true;
}
}
else
{
rtbMyText.SaveFile(this.Text);
IsFileSaved = true;
}
rtbMyText.Clear();
this.Text = "Untitled";
IsFileSaved = true;
}
else if (dr == DialogResult.No)
{
rtbMyText.Clear();
this.Text = "Untitled";
IsFileSaved = true;
}
}
else
{
rtbMyText.Clear();
this.Text = "Untitled";
IsFileSaved = true;
}
}

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.Reset();
openFileDialog1.Filter = "Rich Text Files|*.rtf";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{





.NET 4.0 and Visual Studio 2010 Page 332 of 548
D. HARSHA VARDHAN
































rtbMyText.LoadFile(openFileDialog1.FileName);
this.Text = openFileDialog1.FileName;
IsFileSaved = true;
}
}

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.Text == "Untitled")
{
saveFileDialog1.Reset();
saveFileDialog1.Filter = "Rich Text Files|*.rtf";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
rtbMyText.SaveFile(saveFileDialog1.FileName);
this.Text = saveFileDialog1.FileName;
IsFileSaved = true;
}
}
else
{
rtbMyText.SaveFile(this.Text);
IsFileSaved = true;
}
}

private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog1.Reset();
saveFileDialog1.Filter = "Rich Text Files|*.rtf";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
rtbMyText.SaveFile(saveFileDialog1.FileName);
this.Text = saveFileDialog1.FileName;
IsFileSaved = true;
}
}

private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.Text != "Untitled")
{
printDialog1.Reset();
printDocument1.DocumentName = this.Text;
printDialog1.Document = printDocument1;
if (printDialog1.ShowDialog() == DialogResult.OK)
{
printDocument1.PrinterSettings = printDialog1.PrinterSettings;
printDocument1.Print();
MessageBox.Show("Printing started successfully!");
}





.NET 4.0 and Visual Studio 2010 Page 333 of 548
D. HARSHA VARDHAN






























}
}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}

private void undoToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbMyText.Undo();
}

private void redoToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbMyText.Redo();
}

private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbMyText.Cut();
}

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbMyText.Copy();
}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbMyText.Paste();
}

private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbMyText.SelectAll();
}

private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbMyText.SelectedText = "";
}

private void fontToolStripMenuItem_Click(object sender, EventArgs e)
{
fontDialog1.ShowDialog();
rtbMyText.SelectionFont = fontDialog1.Font;
}

private void backgroudColorToolStripMenuItem_Click(object sender, EventArgs e)
{






.NET 4.0 and Visual Studio 2010 Page 334 of 548
D. HARSHA VARDHAN






























colorDialog1.ShowDialog();
rtbMyText.SelectionBackColor = colorDialog1.Color;
}

private void foregroundColorToolStripMenuItem_Click(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
rtbMyText.SelectionColor = colorDialog1.Color;
}

private void rtbMyText_TextChanged(object sender, EventArgs e)
{
IsFileSaved = false;
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (IsFileSaved == false)
{
DialogResult dr = MessageBox.Show("Do you want to save the file", "Text
Editor 1.0", MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
if (this.Text == "Untitled")
{
saveFileDialog1.Reset();
saveFileDialog1.Filter = "Rich Text Files|*.rtf";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
rtbMyText.SaveFile(saveFileDialog1.FileName);
this.Text = saveFileDialog1.FileName;
IsFileSaved = true;
}
}
else
{
rtbMyText.SaveFile(this.Text);
IsFileSaved = true;
}
}
}
}








.NET 4.0 and Visual Studio 2010 Page 335 of 548
D. HARSHA VARDHAN

2 28 8) ) N No ot ti if fy yI Ic co on n


Creates an icon at the systems notification area (on the windows task bar).

API: System.Windows.Forms.NotifyIcon
Naming Convension: notifyxxxxxx

Set the Icon Property:
Display balloon tip message:
notifyIcon1.ShowBalloonTip(time out, title, message, ToolTipIcon.type);





















Design
notifyIcon1:
Name: notifyIcon1
Text: My Application
Icon: laptop.ico

Application 119: Demo on NotifyIcon
private void Form1_Load(object sender, EventArgs e)
{
notifyIcon1.ShowBalloonTip(5000, "My Application", "This is a sample message",
ToolTipIcon.Info);
}





.NET 4.0 and Visual Studio 2010 Page 336 of 548
D. HARSHA VARDHAN

2 29 9) ) T Ta ab bC Co on nt tr ro ol l

Displays multiple tab pages. Each tab page contains other
controls. Finally a tab page is a container for the other controls; A
tab control is a container of multiple tab pages.

API: System.Windows.Forms.TabControl
Naming Convension: tbCtrlxxxxxx

Properties of TabControl
Property Description
TabPages Contains the list of tab pages.
Alignment Top, Bottom, Left, Right
Name, BackColor, ForeColor, Enabled, Visible, Size, Location, ContextMenuStrip, BackgroundImage,
BackgroundImageLayout

Events of TabControl
Event Description
SelectedIndexChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter,
Leave




Design the form with the following 3 tabs.













Application 120: Demo on TabControl





.NET 4.0 and Visual Studio 2010 Page 337 of 548
D. HARSHA VARDHAN



































private void btnAdd_Click(object sender, EventArgs e)
{
int n1, n2, n3;
n1 = Convert.ToInt32(txtFirstValue.Text);
n2 = Convert.ToInt32(txtSecondValue.Text);
n3 = n1 + n2;
txtResult.Text = Convert.ToString(n3);
}
Design
tabPage1:
Text: Enter Numbers

tabPage2:
Text: Choose Action

tabPage3:
Text: Get Result

label1:
Name: lblFirstValue
Text: Enter First Value:

label2:

Name: lblSecondValue
Text: Enter Second Value:

textBox1:

Name: txtFirstValue

textBox2:

Name: txtSecondValue

button1:

Name: btnAdd
Text: +

button2:

Name: btnMultiply
Text: *

label3:

Name: lblResult
Text: Result:

textBox3:

Name: txtResult
ReadOnly: True






.NET 4.0 and Visual Studio 2010 Page 338 of 548
D. HARSHA VARDHAN










3 30 0) ) T Tr re ee eV Vi ie ew w

Displays the items in a tree format. The items of TreeView control,
are called as Nodes. The nodes can be expanded or collapsed at
run time.

API: System.Windows.Forms.TreeView
Naming Convension: treexxxxxx





Properties of TreeView
Property Description
Nodes Contains the list of nodes.
ShowLines Displays / hides the lines in the tree view.
ShowPlusMinus Enables / disables the plus and minus symbols.
Name, BackColor, ForeColor, Enabled, Visible, Size, Location, ContextMenuStrip, BorderStyle

Events of TreeView
Event Description
AfterSelect, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Run Time Properties of TreeView
Property Description
SelectedNode Represents the currently selected node in the tree view
SelectedNode.Text Gets the text of the currently selected node.
SelectedNode.FullPath Gets the full path of the currently selected node.
Nodes.Count Gets the count of all the nodes in the tree view.

private void btnMultiply_Click(object sender, EventArgs e)
{
int n1, n2, n3;
n1 = Convert.ToInt32(txtFirstValue.Text);
n2 = Convert.ToInt32(txtSecondValue.Text);
n3 = n1 * n2;
txtResult.Text = Convert.ToString(n3);
}





.NET 4.0 and Visual Studio 2010 Page 339 of 548
D. HARSHA VARDHAN






















Application 121: Demo on TreeView
private void treeMyTree_AfterSelect(object sender, TreeViewEventArgs e)
{
lblSelectedNode.Text = treeMyTree.SelectedNode.Text;
lblSelectedNodePath.Text = treeMyTree.SelectedNode.FullPath;
}
Design
treeView1:
Name: treeMyTree
Nodes: (as shown right side)

button1:
Name: btnExpandAll
Text: Expand All

button2:

Name: btnCollapseAll
Text: Collapse All

label1:

Name: lblSelectedNode
Text: Selected Node:

label2:

Name: lblSelectedNodePath
Text: Selected Node Path:






.NET 4.0 and Visual Studio 2010 Page 340 of 548
D. HARSHA VARDHAN








M MD DI I A Ap pp pl li ic ca at ti io on ns s

The windows applications are of two types.
1) SDI Applications (Single Document Interface)
2) MDI Applications (Multiple Document Interface)


private void btnExpandAll_Click(object sender, EventArgs e)
{
treeMyTree.ExpandAll();
}

private void btnCollapseAll_Click(object sender, EventArgs e)
{
treeMyTree.CollapseAll();
}






.NET 4.0 and Visual Studio 2010 Page 341 of 548
D. HARSHA VARDHAN

The SDI and MDI applications contain multiple forms. But in SDI applications, each
form will be executed as individual form; whereas in MDI applications, one form acts as Parent
Form, and the remaining forms act as Child Forms.

You can observe the visibility of MDI applications in the picture.


Features of MDI Applications:

1) All the child forms are contained by the parent form, so that the parent form is also
called as Container form.
2) Among several child forms, only one form acts as active child form.
3) Generally the parent form contains no UI design, it contains a menu.
4) Any child form cant be moved outside of its parent form.
5) In VB 6.0, only one form can be implemented as parent form in a project. But in C#.NET
and VB.NET, you can define multiple parent forms within the same project.
6) In VB 6.0, the parent form cant contain any type of controls. But in C#.NET and VB.NET,
you can drag any controls.
7) The child form icon is not displayed in the windows taskbar.
8) If the parent form is moved, all the child forms will be moved.
9) Whenever the parent form is minimized, all the child forms will be minimized.
10) Whenever the parent form is maximized, all the child forms will be restored.
11) Whenever the child form is minimized, an icon will be created at the bottom area of the
parent form.
12) Whenever the child form is maximized, the text of the parent form and child form will be
concatenated.
13) Whenever you close the parent form, all the child forms will be closed automatically.
14) The child form is able to access the reference of its parent form.
15) The parent form is able to access the references of its child forms.


Implementation of MDI Applications in C#:
1) Convert the Form as Parent Form.
To convert, set that forms property IsMDIContainer = True.







.NET 4.0 and Visual Studio 2010 Page 342 of 548
D. HARSHA VARDHAN

2) Invoke the child form at run time from the parent form.
Use the following code.
ChildFormClassName obj = new ChildFormClassName();
obj.MdiParent = this;
obj.Show();





























Application 122: Demo on MDI Applications
Form1.cs

private void Form1_Load(object sender, EventArgs e)
{
Form2 f = new Form2();
f.MdiParent = this;
f.Show();
}
Design
Form1:
IsMdiContainer: True






.NET 4.0 and Visual Studio 2010 Page 343 of 548
D. HARSHA VARDHAN


























Application 123: Demo on MDI Applications (with Menu)





.NET 4.0 and Visual Studio 2010 Page 344 of 548
D. HARSHA VARDHAN



































Form1.cs

private void form2ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.MdiParent = this;
f.Show();
}

private void form3ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form3 f = new Form3();
f.MdiParent = this;
f.Show();
}

private void form4ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form4 f = new Form4();
f.MdiParent = this;
f.Show();
}

private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.ActiveMdiChild != null)
{
this.ActiveMdiChild.Close();
}
}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}

private void pinkToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.ActiveMdiChild != null)
{
this.ActiveMdiChild.BackColor = Color.Pink;
}
}

private void cyanToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.ActiveMdiChild != null)
{
this.ActiveMdiChild.BackColor = Color.Cyan;
}
}





.NET 4.0 and Visual Studio 2010 Page 345 of 548
D. HARSHA VARDHAN








The MessageBox class
This is to generate the message boxes at run time, which displays a message to the user.
Library: System.Windows.Forms.MessageBox
Syntax:
MessageBox.Show(message);
MessageBox.Show(message, title);
MessageBox.Show(message, title, MessageBoxButtons.xxxxxx);

Possible MessageBoxButton Models:
1) MessageBoxButtons.OK
2) MessageBoxButtons.OKCancel
3) MessageBoxButtons.YesNo
4) MessageBoxButtons.YesNoCancel
5) MessageBoxButtons.RetryCancel
6) MessageBoxButtons.AbortRetryIgnore

Ex: MessageBox.Show(Do you want to save the file?, My App 1.0,
MessageBoxButtons.YesNo);
private void orangeToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.ActiveMdiChild != null)
{
this.ActiveMdiChild.BackColor = Color.Orange;
}
}






.NET 4.0 and Visual Studio 2010 Page 346 of 548
D. HARSHA VARDHAN

Adding Controls Programmatically
Usually, the controls are designed in the form, at design time.
Sometimes, you may need to add the controls programmatically at run time.
To generate the controls at run time, follow the below steps:
+ Create the control objectL
ControlClassname obj = new ControlClassname();
+ Assign the required properties (like name, text etc.):
obj.property = value;
+ Add the controls to the container:
containername.Add(value);







Application 124: Demo on Adding Controls at run Time
Design
button1:
Text: Add Exit Button






.NET 4.0 and Visual Studio 2010 Page 347 of 548
D. HARSHA VARDHAN









Output:









private void button1_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn.Text = "Exit";
btn.Location = new Point(130, 130);
btn.Click += new EventHandler(Exit_Click);
this.Controls.Add(btn);
}

private void Exit_Click(object sender, EventArgs e)
{
Application.Exit();
}





.NET 4.0 and Visual Studio 2010 Page 348 of 548
D. HARSHA VARDHAN



























Application 125: Demo on Adding Controls at run Time
Design
button1:
Name: btnShowNumbers
Text: Show Numbers

textBox1:
ReadOnly: True
TextAlign: Right







.NET 4.0 and Visual Studio 2010 Page 349 of 548
D. HARSHA VARDHAN














Output:

private void btnShowNumbers_Click(object sender, EventArgs e)
{
FlowLayoutPanel flp = new FlowLayoutPanel();
flp.Size = new Size(180, 150);
flp.Location = new Point(100, 140);
flp.BackColor = Color.Azure;
this.Controls.Add(flp);

for (int i = 0; i <= 9; i++)
{
Button btn = new Button();
btn.Text = i.ToString();
btn.Size = new Size(50, 30);
btn.BackColor = Color.Cornsilk;
btn.Click += new EventHandler(Number_Click);
flp.Controls.Add(btn);
}
}

private void Number_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text += btn.Text;
}





.NET 4.0 and Visual Studio 2010 Page 350 of 548
D. HARSHA VARDHAN

U Us se er r C Co on nt tr ro ol ls s

A user control is nothing but, user defined control.
That means you can create our own control, and you can use it in any form, wherever
required.
The user control may contain some user interface with controls like buttons, textboxes
etc.
So finally, you need to design the user interface only once in the User Control, and you
can use it any no. of times, in any form.
Advantage: Avoids repetition of design and code.
Generally, you can use it for designing the common header for all the forms in the
project (as given in the below example).

User Control (vs) Form
Sl. No User Control Form
1 Its a container for other controls Its also a container for other controls.
2 It cant run individually. It can run individually.
3
It inherits a pre-defined class called
System.Windows.Forms.UserControl.
It inherits a pre-defined class called
System.Windows.Forms.Form.
4 It is meant for re-usability. It is meant for direct execution.


Implementation of User Controls

Create the User Control:
Click on Project menu Add User Control.
Enter the name of the new user control.
Click on Add.

Design and Develop the User Control:
Design the UI in the user control, by dragging the controls from the toolbox.
Write the code in Code window. (User control also supports event handlers
similar to forms).





.NET 4.0 and Visual Studio 2010 Page 351 of 548
D. HARSHA VARDHAN

Invoke the User Control:
Open the required form and build the project.
Then the user control name will be displayed in the toolbox automatically.
To invoke the user control on a form, just drag it from the toolbox into the form
designer.
Then the control object will be created in the form.





Create the Windows Application Project.
Click Project menu Add User Control.
Enter the name as Title.
Click on Add.
Then design the user control as follows:

Application 126: Demo on User Controls





.NET 4.0 and Visual Studio 2010 Page 352 of 548
D. HARSHA VARDHAN

Set the properties of Timer1
Enabled: True
Interval: 1000
Double click on the user control and write the code.





Double click on the user control and write the code.





Come back to the Form1 and Build the project.
Then the user control name Title will be added to the toolbox, at the top.

private void Title_Load(object sender, EventArgs e)
{
label3.Text = DateTime.Now.ToLongDateString();
label4.Text = DateTime.Now.ToLongTimeString();
}
private void timer1_Tick(object sender, EventArgs e)
{
label3.Text = DateTime.Now.ToLongDateString();
label4.Text = DateTime.Now.ToLongTimeString();
}





.NET 4.0 and Visual Studio 2010 Page 353 of 548
D. HARSHA VARDHAN

Then drag and drop it from the toolbox into the form. Then its ready.
In the similar way, you can drag and drop the controls into any no. of forms, within the
same project.
Note: The current user control is called as Local User Control. So that it can be used
within the same project only. You cant use it in other windows application projects. But
if you want to utilize the same user control in other windows application projects also,
then you have to create this user control in Windows Forms Control Library.


W Wi in nd do ow ws s F Fo or rm ms s C Co on nt tr ro ol l L Li ib br ra ar ry y

Its a collection of global user controls.
If a user control is created in a windows application project, it can be used or accessed
within the same project only. If the user control is created in the Windows Forms
Control Library, that user control is accessible in any other windows application projects.
The user controls created in the windows forms control library, are called as Global
user controls.
When we compile the windows form controls library project, it will generate a .dll file
in the bin folder of the project.
Later, that dll file can be linked with any no. of windows application projects, and the
user control can be utilized in those forms.


Implementation Steps of Windows Forms Control Library

Create the Windows Forms Control Library:
In Visual Studio, click on File New Project.
In the New Project dialog box, select the project template as Windows Forms
Control Library.
Enter the name and location of the project.
Click on OK.
Then the new control library project will be created along a user control called
UserControl1.





.NET 4.0 and Visual Studio 2010 Page 354 of 548
D. HARSHA VARDHAN

Note: To add additional user controls within the same project, just click on
Project menu and choose Add User Control.

Design and Develop the User Control:
Design the UI in the user control, by dragging the controls from the toolbox.
Write the code in Code window. (User control also supports event handlers
similar to forms).
Build the project.
Then the .dll file will be created in the bin\Debug folder of the windows
forms control library project.

Invoke the User Control from other Windows Application Project:
Create a new windows application project.
Open the toolbox.
Right click anywhere on the toolbox and select Add tab.
Type any name for the tab. Ex: My Controls.
Right click on My Controls and select Choose Items.
Select the dll file from bin\Debug folder of windows forms control library
project..
Click on OK.
Then the user control name will be displayed in the toolbox automatically.
To invoke the user control on a form, just drag it from the toolbox into the form
designer.
Then the control object will be created in the form.










Application 127: Demo on WindowsFormsControlLibrary
Windows Forms Control Library Project Name: GlobalControlsLibrary
Windows Application Project Name: GlobalControlsTest





.NET 4.0 and Visual Studio 2010 Page 355 of 548
D. HARSHA VARDHAN

I) Windows Control Library Project Development:
Open Visual Studio.
File New Project.
Select Visual C# Windows Windows Forms Control Library.
Enter the name as GlobalControlsLibrary.
Select any location. Ex: D:\C#Apps
Click on OK.
Then it will create the windows forms control library project and it creates a user control
named UserControl1.
Then rename it as Title using Solution Explorer.
Then design the user control as follows:

Set the properties of Timer1
Enabled: True
Interval: 1000







.NET 4.0 and Visual Studio 2010 Page 356 of 548
D. HARSHA VARDHAN

Double click on the user control and write the code.





Double click on the user control and write the code.





The build the project. Build menu Build Solution.
Then in the dll file will be generated in the bin\Debug folder of the project.
Ex: D:\C#Apps\GlobalControlsLibrary\GlobalControlsLibrary\bin\Debug\GlobalControlsLibrary.dll


II) Client Application Development:

Create a new windows application project.
Name: GlobalControlsTest
Open the toolbox.
Right click anywhere on the toolbox and select Add tab.
Type any name for the tab. Ex: My Controls.
Right click on My Controls and select Choose Items.
Select the dll file from bin\Debug folder of windows forms control library project.
Ex: D:\C#Apps\GlobalControlsLibrary\GlobalControlsLibrary\bin\Debug\GlobalControlsLibrary.dll
Click on OK.
Then the user control name will be displayed in the toolbox automatically.
Then drag and drop it from the toolbox into the form. Then its ready.
private void Title_Load(object sender, EventArgs e)
{
label3.Text = DateTime.Now.ToLongDateString();
label4.Text = DateTime.Now.ToLongTimeString();
}
private void timer1_Tick(object sender, EventArgs e)
{
label3.Text = DateTime.Now.ToLongDateString();
label4.Text = DateTime.Now.ToLongTimeString();
}





.NET 4.0 and Visual Studio 2010 Page 357 of 548
D. HARSHA VARDHAN








.NET 4.0 and Visual Studio 2010 Page 358 of 548
D. HARSHA VARDHAN








.NET 4.0 and Visual Studio 2010 Page 359 of 548
D. HARSHA VARDHAN

G GD DI I+ + g gr ra ap ph hi ic cs s

GDI stands for Graphic Device Interface.
This concept is used to create user defined graphical elements in the form like lines,
rectangles, circles, triangles etc.
This is similar to graphics concept in C.

Library: System.Drawings.Graphics
This class object is able to write any graphics on its container. That means every graphic object
requires a container. The container may be either form or panel.

Note: The GDI graphics can be implemented in Paint() method.

Implementation:

private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = this.CreateGraphics();
}

In the above code, the CreateGraphics() method creates a graphics object, that is able to write
the GDI graphics in the container (form).

Drawing the GDI Graphics


1) Drawing Lines
g.DrawLine(Pens.xxxx, x1, y1, x2, y2);











.NET 4.0 and Visual Studio 2010 Page 360 of 548
D. HARSHA VARDHAN

2) Drawing Rectangles
g.DrawRectangle(Pens.xxxx, x1, y1, width,
height);






3) Drawing Circles / Elipses
g.DrawEllipse(Pens.xxxx, x1, y1, width, height);




4) Drawing Polygons
Point[] p = new Point[count];
p[0] = new Point(x,y);
p[1] = new Point(x,y);
p[2] = new Point(x,y);
..
g.DrawPolygon(Pens.xxx, p);

5) Drawing Curves
Point[] p = new Point[count];
p[0] = new Point(x,y);
p[1] = new Point(x,y);
p[2] = new Point(x,y);
..
g.DrawCurve(Pens.xxx, p);








.NET 4.0 and Visual Studio 2010 Page 361 of 548
D. HARSHA VARDHAN



































Application 128: Demo on GDI (Drawing Lines)
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = this.CreateGraphics();
g.DrawLine(Pens.RoyalBlue, 100, 100, 300, 100);
g.DrawLine(Pens.Red, 150, 150, 300, 150);
g.DrawLine(Pens.SandyBrown, 200, 200, 300, 200);
g.DrawLine(Pens.SlateGray, 250, 250, 300, 250);
}
Application 129: Demo on GDI (Drawing Lines)





.NET 4.0 and Visual Studio 2010 Page 362 of 548
D. HARSHA VARDHAN



































private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = this.CreateGraphics();
int h = this.Size.Height - 35;
int w = this.Size.Width - 9;
g.DrawLine(Pens.Coral, 0, 0, w, h);
g.DrawLine(Pens.Coral, w, 0, 0, h);
}
Application 130: Demo on GDI (Drawing Lines)
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = this.CreateGraphics();
int w = this.Size.Width - 9;
int h = this.Size.Height - 35;
for (int i = 0; i <= h; i += 4)
g.DrawLine(Pens.DarkGreen, 0, i, w, i);
for (int i = 0; i <= w; i += 4)
g.DrawLine(Pens.Red, i, 0, i, h);
}





.NET 4.0 and Visual Studio 2010 Page 363 of 548
D. HARSHA VARDHAN



































Application 131: Demo on GDI (Drawing Lines)
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
Graphics g = this.CreateGraphics();
g.DrawLine(Pens.Orange, 0, 0, e.X, e.Y);
}
Application 132: Demo on GDI (Drawing Lines, Rectangles, Circles, Triangles, Curves)





.NET 4.0 and Visual Studio 2010 Page 364 of 548
D. HARSHA VARDHAN



































private void Form1_Paint(object sender, PaintEventArgs e)
{
this.Size = new Size(409, 435);
Graphics g = this.CreateGraphics();
//dividing lines
g.DrawLine(Pens.Green, 200, 0, 200, 400);
g.DrawLine(Pens.Green, 0, 200, 400, 200);
//rectangle
g.DrawRectangle(Pens.Red, 50, 50, 100, 100);
//circle or ellipse
g.DrawEllipse(Pens.Red, 250, 50, 100, 100);
//triangle (with polygon)
Point[] p1 = new Point[3];
p1[0] = new Point(100, 250);
p1[1] = new Point(50, 350);
p1[2] = new Point(150, 350);
g.DrawPolygon(Pens.Red, p1);
//curve
Point[] p2 = new Point[6];
p2[0] = new Point(250, 350);
p2[1] = new Point(250, 250);
p2[2] = new Point(350, 250);
p2[3] = new Point(350, 350);
p2[4] = new Point(300, 300);
p2[5] = new Point(250, 350);
g.DrawCurve(Pens.Red, p2);
}
Application 133: Demo on GDI (Drawing Circles)





.NET 4.0 and Visual Studio 2010 Page 365 of 548
D. HARSHA VARDHAN



































private void Form1_MouseClick(object sender, MouseEventArgs e)
{
Graphics g = this.CreateGraphics();
int x = e.X;
int y = e.Y;
g.DrawEllipse(Pens.Brown, x-20, y-20, 40, 40);
}
Application 134: Demo on GDI (Drawing Filled Objects)
private void Form1_Paint(object sender, PaintEventArgs e)
{
this.Size = new Size(409, 435);
Graphics g = this.CreateGraphics();
//dividing lines
g.DrawLine(Pens.Green, 200, 0, 200, 400);
g.DrawLine(Pens.Green, 0, 200, 400, 200);
//rectangle
g.FillRectangle(Brushes.Violet, 50, 50, 100, 100);
//circle or ellipse
g.FillEllipse(Brushes.Salmon, 250, 50, 100, 100);
//triangle (with polygon)
Point[] p1 = new Point[3];





.NET 4.0 and Visual Studio 2010 Page 366 of 548
D. HARSHA VARDHAN



































Application 135: Demo on GDI (Drawing Filled Objects)
private void Form1_Paint(object sender, PaintEventArgs e)
{
this.Size = new Size(509, 535);
Graphics g = this.CreateGraphics();
g.FillRectangle(Brushes.Pink, 0, 0, 100, 500);
g.FillRectangle(Brushes.Purple, 101, 0, 100, 500);
g.FillRectangle(Brushes.LightGreen, 201, 0, 100, 500);
g.FillRectangle(Brushes.Linen, 301, 0, 100, 500);
g.FillRectangle(Brushes.MediumTurquoise, 401, 0, 100, 500);
}
p1[0] = new Point(100, 250);
p1[1] = new Point(50, 350);
p1[2] = new Point(150, 350);
g.FillPolygon(Brushes.Chocolate, p1);
//curve
Point[] p2 = new Point[5];
p2[0] = new Point(250, 350);
p2[1] = new Point(250, 250);
p2[2] = new Point(350, 250);
p2[3] = new Point(350, 350);
p2[4] = new Point(300, 300);
g.FillClosedCurve(Brushes.LightSeaGreen, p2);
}





.NET 4.0 and Visual Studio 2010 Page 367 of 548
D. HARSHA VARDHAN

SQL Server 2005 Basics

1. Open SQL Server:
Click on Start Programs Microsoft SQL Server 2005 SQL Server
Management Studio.
It displays Connect to Server dialog box.

Enter the following values:
1. Server type: Database Engine
2. Server name: Name of the system (You can see the computer name in
the My Computer properties)
3. Authentication: SQL Server Authentication
Login: sa
Password: xxxx (The password can be given at the time of SQL
Server software installation) Ex: 123
(or)
Authentication: Windows Authentication
After successful login to the server, it displays SQL Server Management Studio
window.





.NET 4.0 and Visual Studio 2010 Page 368 of 548
D. HARSHA VARDHAN








.NET 4.0 and Visual Studio 2010 Page 369 of 548
D. HARSHA VARDHAN


2. Object Explorer:
In SQL Server Management Studio, the
Object Explorer displays the
information about the databases, tables,
stored procedures and functions.
First of all, expand the option
Databases; then it displays list of
databases that currently exist on this
system.
If you expand any database (For ex:
sample), it displays some folders like
Tables, Views, Programmability
etc.
When you expand the Tables folder, it
displays the list of tables that exist the
selected database.
If you want to see the table structure,
right click on that table and choose
Modify option. There you can make
any changes in the table design
(structure).
If you want to open the table data, right
click on that table and choose Open Table. Then the table rows will be opened.
Here also you can make changes in the table data, and also you can add new
rows here.













.NET 4.0 and Visual Studio 2010 Page 370 of 548
D. HARSHA VARDHAN

3. Creating a new Database:
A database is a collection of tables.
To create a new database, right click on Databases and choose New
Database.
Then enter the new database name. Ex: mydata
Click on OK.






.NET 4.0 and Visual Studio 2010 Page 371 of 548
D. HARSHA VARDHAN


4. Creating a new Table:
Right click on Tables option in the Object Explorer and choose New Table.
Enter the table structure of the new table.

Click on Save button to save the table. Then it asks for the table name. Enter
the desired table name.

Close the window finally.






.NET 4.0 and Visual Studio 2010 Page 372 of 548
D. HARSHA VARDHAN

5. Important Data Types in SQL Server:
varchar(width)
datetime
numeric(width)
int
float
decimal(width,dec)
bit
image


6. Working with Query window:
Query window is a window, where you can enter the SQL queries and execute
them.
Open the Query window, by clicking on New Query window option in the
toolbar.
Select the database from the database list, in which your query is to be
executed.
Enter the required SQL query in the window.
To execute, press F5 (or) click on Execute button in the toolbar.





.NET 4.0 and Visual Studio 2010 Page 373 of 548
D. HARSHA VARDHAN


Then the SQL statement will be executed.



7. IMP SQL Statements:
DDL:
1. CREATE
create table tablename(column1 datatype(width), column2
datatype(width), );

2. DROP
drop table tablename;

3. ALTER
alter table tablename add columnname datatype(width);
alter table tablename drop column columnname;





.NET 4.0 and Visual Studio 2010 Page 374 of 548
D. HARSHA VARDHAN

alter table tablename alter column columnname
datatype(width);

DML:
1. SELECT
select * from tablename;
select column1, column2, .. from tablename;
select * from tablename where condition;
select column1, column2, from tablename where condition;

2. INSERT
insert into tablename values(value1, value2,);

3. DELETE
delete from tablename;
delete from tablename where condition;

4. UPDATE
update tablename set column1=value1, column2=value2;
update tablename set column1=value1, column2=value2 where
condition;


Some exercise on SQL:
use master
drop database test
GO

create database test
GO

use test
GO

create table Products
(ProductID int primary key,
ProductName varchar(40),
Price decimal(18,2))





.NET 4.0 and Visual Studio 2010 Page 375 of 548
D. HARSHA VARDHAN


insert into products values(101,'Monitors',7890)
insert into products values(102,'Keyboards',450)
insert into products values(103,'Mouses',590)
insert into products values(104,'Processors',6202)
insert into products values(105,'RAM',2829)

select * from products

select ProductID,ProductName from Products

select Price*10/100 Tax from Products

select * from Products where Productid=104

select * from Products order by price desc

select * from Products where price between 2000 and 8000

select * from Products where price not between 2000 and 8000

select * from Products where price like '%0.00'

select * from Products where price like '___.00'

update products set price=price+1000

select * from products

delete from products where price<1500

select * from products





.NET 4.0 and Visual Studio 2010 Page 376 of 548
D. HARSHA VARDHAN


8. T-SQL (Transaction SQL):
Procedures:
create procedure procedurename(@variable datatype(width),)
as begin
declare @variable datatype(width)
.
.
end

Functions:
create function functionname(@variable datatype(width),)
returns returndatatype
as begin
declare @variable datatype(width)
.
.
return returnvalue
end

Note: The procedure cant return any value; and a function should return any value. For every
variable in T-SQL, we have to prefix @ symbol without fail.





.NET 4.0 and Visual Studio 2010 Page 377 of 548
D. HARSHA VARDHAN

S So om me e e ex xe er rc ci is se e o on n T T- -S SQ QL L: :
















Procedure:

create procedure ShowSquare(@a int)
as begin
declare @sq int
set @sq = @a * @a
print @sq
end

GO
execute ShowSquare 5
Function:

create function GetCube(@a int) returns int
as begin
declare @cb int
set @cb = @a * @a * @a
return @cb
end

GO

select dbo.GetCube(5)





.NET 4.0 and Visual Studio 2010 Page 378 of 548
D. HARSHA VARDHAN

(ActiveX Data Objects.NET)


ADO.NET is known as Database Technology, which is used to connect with the
databases. That means some objects will work for interacting with the databases.
Basically, why we require database connection is: the frontend application itself, cant
store any data permanently. So that we require a storage mechanism. That storage
mechanism is nothing but our databases.
It can be used for database connections and offers to perform database manipulations
like inserting data to the tables, deleting un-necessary data, retrieving the required data
from the tables etc.
It can be used in any type of applications like console applications, windows forms
applications, web sites, web services, WCF services etc.
It can be used in any .NET language like C#.NET, VB.NET, VC++.NET etc.
It was developed based on its previous version called ADO.
It offers much efficient features to easily handle with the database tables, especially
when you are dealing with multiple tables.



What type of databases we can connect using ADO.NET:
File Databases:
dBASE, FoxPro, MS Access, MS Excel etc.
Server Databases:
SQL Server, Oracle, My SQL etc.









.NET 4.0 and Visual Studio 2010 Page 379 of 548
D. HARSHA VARDHAN

What we can do using ADO.NET:

Insert some data into the database table.
Delete some data from the database table.
Update the data of a table.
Retrieve some data from the table.
Execute a stored procedure / function, i.e. already created at backend using PL/SQL.





ADO.NET Database Connection Architecture






Note: Here, the driver acts as mediator between the frontend application and backend
databases. The driver can also be called as Provider. This provider may be released by Backend
Company or Frontend Company.


For various databases, we have respective providers.
Database Provider Released by
SQL Server sqloledb.1 Microsoft Corp.
Oracle
oraoledb.oracle.1 Oracle Corp.
msdaora.1 Microsoft Corp.
MS Access / MS Excel / FoxPro /
dBASE
microsoft.jet.oledb.4.0 Microsoft Corp.
MS Access 2007 / 2010 microsoft.ace.oledb.12.0 Microsoft Corp.



db

.NET Application
Driver





.NET 4.0 and Visual Studio 2010 Page 380 of 548
D. HARSHA VARDHAN

Understanding the Connection String:
The connection string provides the details about the connection string. That means, if
you want to connect with the database, you have to specify some details about the
connection like:
1. Server
2. User ID
3. Password
4. Provider
Server: Specify the name of the server system, which you want to connect. If you want
to connect with other server system on the network, you specify the name of that
system. Ex: myserver. If you want to connect with the same system, mention the server
name as localhost. The server name can also be called as data source.
User ID: Specify the user name for logging-in with the database.
Password: Specify the password for logging-in with the database.
Provider: Specify the name of the driver / provider, which you want to use with the
connection. You can see the available provider names, in the above table.

Syntax of Connection String:
provider=xxxxx; user id=xxxxx; password=xxxx; data source=xxxxx

Note: Just for separation of the individual values, we are using ;.


ADO.NET Library

To perform above mentioned database operations, ADO.NET technology offers some pre-
defined classes, organized in the form of namespaces.
Library: System.Data





.NET 4.0 and Visual Studio 2010 Page 381 of 548
D. HARSHA VARDHAN






















ADO.NET NameSpaces:

1) System.Data
Contains necessary classes and namespaces to manipulate the databases.
2) System.Data.SqlClient
Contains necessary classes, used to interact with the SQL Server database.
3) System.Data.OleDb
Contains necessary classes, used to interact with any other databases. Of course,
the OleDb namespace also supports to connect with SQL server database, but
we wont use it for SQL Server, because SqlClient namespace is especially
available for that.


Data
OleDb SqlClient
OleDbConnection
OleDbCommand
OleDbDataReader
OleDbDataAdapter
OleDbParameter
SqlConnection
SqlCommand
SqlDataReader
SqlDataAdapter
SqlParameter
DataSet
DataTable
DataRow
DataColumn





.NET 4.0 and Visual Studio 2010 Page 382 of 548
D. HARSHA VARDHAN


ADO.NET Classes:

1) Connection:
Maintains the connection with the database.
2) Command:
Executes a query statement (select statement), non-query statement (insert
statement / delete statement / update statement) or a stored procedure /
function at backend.
3) DataReader:
It acts as a buffer, which holds the data, after execution of a query statement at
backend.
4) DataAdapter:
Executes a query statement at backend.
5) Parameter:
Sends a parameter (argument) value to a backend stored procedure / function.
6) DataSet:
Acts as a buffer, which holds multiple tables at-a-time.
7) DataTable:
Acts as a buffer, which holds a single table (collection of rows and columns).
8) DataRow:
Acts as a buffer, which holds a single row.
9) DataColumn:
Acts as a buffer, which holds a single column.

Note: All of above are the classes; you need to create object(s) for those classes.






.NET 4.0 and Visual Studio 2010 Page 383 of 548
D. HARSHA VARDHAN

Connecting the Database


Library: SqlConnection / OleDbConnection






ConnectionString: This property contains the connection string, used for the
connection.
Open(): This method opens the database connection.
Close(): This method disconnects the database connection.



Connecting with SQL Server:
Import the Library (at the top):
using System.Data.SqlClient;
Construct the Connection class object:
SqlConnection cn = new SqlConnection();
Assign the Connection string:
cn.ConnectionString = data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>;
Note: The initial catalog specifies the name of the SQL Server database, in which
your table exists.
Open the connection:
cn.Open();
Close the connection:
cn.Close();




Connection
ConnectionString
Open()
Close()





.NET 4.0 and Visual Studio 2010 Page 384 of 548
D. HARSHA VARDHAN

Connecting with Oracle / MS Access / Fox Pro:
Import the Library (at the top):
using System.Data.OleDb;
Construct the Connection class object:
OleDbConnection cn = new OleDbConnection();
Prepare the Connection string:
Oracle
cn.ConnectionString = provider=oraoledb.oracle.1; data
source=<name of the server>; user id=<user name>;
password=<password>;
MS
Access /
dBASE /
FoxPro
cn.ConnectionString = provider=microsoft.jet.oledb.4.0;data
source=<path of the database file>;

Open the connection:
cn.Open();
Close the connection:
cn.Close();







Create a new Windows Forms Application. It automatically creates Form1.
Set the following properties of Form1:
1. WindowState: Maximized
2. IsMdiContainer: True
3. Text: ADO.NET Demo
Drag and drop MenuStrip control into the form.
Design the MenuStrip as shown in this screen:
Application 136: Demo on ADO.NET with SQL Server Database





.NET 4.0 and Visual Studio 2010 Page 385 of 548
D. HARSHA VARDHAN


Click on Project menu Add Windows Form.
Enter the form name as DatabaseConnectionDemo.
Click on Add.
Double click on Database Connection Demo menu item and write the code:








Open the DatabaseConnectionDemo form, from Solution Explorer and design it as
shown:
private void databaseConnectionDemoToolStripMenuItem_Click(object sender,
EventArgs e)
{
DatabaseConnectionDemo f = new DatabaseConnectionDemo();
f.MdiParent = this;
f.Show();
}






.NET 4.0 and Visual Studio 2010 Page 386 of 548
D. HARSHA VARDHAN


Write the code:





















.NET 4.0 and Visual Studio 2010 Page 387 of 548
D. HARSHA VARDHAN


















using System.Data.SqlClient;
using System.Data.OleDb;
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123";
cn.Open();
MessageBox.Show("Successfully Connected with SQL Server");
cn.Close();
}

private void button2_Click(object sender, EventArgs e)
{
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = "provider=oraoledb.oracle.1;user id=scott;password=tiger";
cn.Open();
MessageBox.Show("Successfully Connected with Oracle");
cn.Close();
}

private void button3_Click(object sender, EventArgs e)
{
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = "provider=microsoft.jet.oledb.4.0;data
source=c:\\database1.mdb";
cn.Open();
MessageBox.Show("Successfully Connected with MS Access");
cn.Close();
}






.NET 4.0 and Visual Studio 2010 Page 388 of 548
D. HARSHA VARDHAN

Sending Commands to the Database

After connecting the database, you can send the commands to the database.
ADO.NET supports to send the following types of commands.
1. Insertion Command
2. Deletion Command
3. Updation Command
4. Select Command / Query Command
5. Stored Procedure / Function Command

1) Insertion Command:
To insert a new row into the table.
SQL statement: insert into tablename values(value1, value2,)

2) Deletion Command:
To delete one or more rows from the table.
SQL statement: delete from tablename where condition

3) Updation Command:
To update (modify) the table data.
SQL statement: update tablename set column1=value1, column2=value2
where condition

4) Select Command:
To retrieve the data from the database table, into the frontend application.
SQL statement: select * from tablename

5) Stored Procedure / Function Command:
To call a stored procedure / function from the frontend application, that is
already created at backend.
SQL statement: No SQL statement is needed







.NET 4.0 and Visual Studio 2010 Page 389 of 548
D. HARSHA VARDHAN

Understanding the Command class:
In order to send the commands, you need to use Command class.
Library: SqlCommand / OleDbCommand








a) CommandText: This property contains the SQL statement (insertion statement
/ deletion statement / updation statement / select statement)

b) Connection: This property contains the reference of the connection object,
based on which, the above given SQL statement is to be executed.

c) CommandType: This property specifies the type of the command that you want
to execute. It is of two types:
^ Text: (default) This is used for any SQL statement (insertion statement /
deletion statement / updation statement / select statement)
^ StoredProcedure: This is used for Stored Procedure / Function only.

d) Parameters: This property contains the list of parameters (argument values),
that are to be sent to backend, while you are calling a stored procedure /
function. It is of collection type, so that you can add any no. of parameters.

e) ExecuteNonQuery(): This method is used to execute any SQL statement
(insertion statement / deletion statement / updation statement / select
statement) or a stored procedure / function also. In other words, this method
moves the execution flow to backend database, execute the command there and
then come back with some result. This method returns no. of rows affected,
which represents the count of the rows, which are affected by executing this
Command
CommandText
Connection
CommandType
Parameters
ExecuteNonQuery()
ExecuteReader()
Connection
ConnectionString
Open()
Close()





.NET 4.0 and Visual Studio 2010 Page 390 of 548
D. HARSHA VARDHAN

command. Suppose, after executing a delete statement, 2 rows are deleted. So it
returns the integer value 2.

f) ExecuteReader(): This method is used to execute select statement only. In
other words, it is used to retrieve some data from the database, based on the
given select statement. In other words, this method moves the execution flow to
backend database, execute the command there and then come back with some
result data. This method returns the table data, based on the given select
statement.



Implementation Code for SQL Server:
Import the Library (at the top):
using System.Data.SqlClient;
Construct the Connection class object:
SqlConnection cn = new SqlConnection();
Assign the Connection string:
cn.ConnectionString = data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>;
Open the connection:
cn.Open();
Construct the Command class object:
SqlCommand cmd = new SqlCommand();
Assign the SQL statement, which is to be executed:
cmd.CommandText = insert statement / delete statement / update statement;
Assign the reference of connection object, based which the command is to be
executed:
cmd.Connection = cn;
Execute the command and receive the no. of rows affected:
int n = cmd.ExecuteNonQuery();
Close the connection:
cn.Close();






.NET 4.0 and Visual Studio 2010 Page 391 of 548
D. HARSHA VARDHAN


Implementation Code for Oracle (or any other database):
Import the Library (at the top):
using System.Data.OleDb;
Construct the Connection class object:
OleDbConnection cn = new OleDbConnection();
Assign the Connection string:
cn.ConnectionString = provider=<provider name>;data source=<name of the
server>;user id=<user name>;password=<password>;
Open the connection:
cn.Open();
Construct the Command class object:
OleDbCommand cmd = new OleDbCommand();
Assign the SQL statement, which is to be executed:
cmd.CommandText = insert statement / delete statement / update statement;
Assign the reference of connection object, based which the command is to be
executed:
cmd.Connection = cn;
Execute the command and receive the no. of rows affected:
int n = cmd.ExecuteNonQuery();
Close the connection:
cn.Close();





.NET 4.0 and Visual Studio 2010 Page 392 of 548
D. HARSHA VARDHAN

Demo:
^ Open SQL Server 2005.
^ Create a new database, with name as demo.
^ In that database, create a table named Customers, as shown below.

^ Open the previous demo application.
^ Add the menu item Database Commands Demo and design the menu as shown below:





.NET 4.0 and Visual Studio 2010 Page 393 of 548
D. HARSHA VARDHAN


^ Click on Project menu Add Windows Form. Enter the form name as Insertion.
Click on Add.
^ Click on Project menu Add Windows Form. Enter the form name as Deletion. Click
on Add.
^ Click on Project menu Add Windows Form. Enter the form name as Updation.
Click on Add.
^ Double click on menu items one-by-one and write the following code in the Form1.cs:










Form1.cs

private void insertionToolStripMenuItem_Click(object sender, EventArgs e)
{
Insertion f = new Insertion();
f.MdiParent = this;
f.Show();
}






.NET 4.0 and Visual Studio 2010 Page 394 of 548
D. HARSHA VARDHAN













^ Design the Insertion form as follows:





private void deletionToolStripMenuItem_Click(object sender, EventArgs e)
{
Deletion f = new Deletion();
f.MdiParent = this;
f.Show();
}

private void updationToolStripMenuItem_Click(object sender, EventArgs e)
{
Updation f = new Updation();
f.MdiParent = this;
f.Show();
}







.NET 4.0 and Visual Studio 2010 Page 395 of 548
D. HARSHA VARDHAN

^ Write the code:

































Insertion.cs
using System.Data.SqlClient;
private void button1_Click(object sender, EventArgs e)
{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into customers values(5,'Arun','Male',8000)";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();
if (n > 0)
MessageBox.Show(n + " Row Inserted.");
else
MessageBox.Show("Insertion failed.");

cn.Close();
}

private void button2_Click(object sender, EventArgs e)
{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

string gen;
if (radioButton1.Checked == true)
gen = "Male";
else
gen = "Female";

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into customers values(" + textBox1.Text + ",' " +
textBox2.Text + " ',' " + gen + " '," + textBox3.Text + ")";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();





.NET 4.0 and Visual Studio 2010 Page 396 of 548
D. HARSHA VARDHAN








Note: While you are preparing the CommandText with user-entered values, to remember the
concatenation syntax in the above example, remember the following syntax:

" + textBox1.Text + "

^ Design the Deletion form as follows:

if (n > 0)
MessageBox.Show(n + " Row Inserted.");
else
MessageBox.Show("Insertion failed.");

cn.Close();
}





.NET 4.0 and Visual Studio 2010 Page 397 of 548
D. HARSHA VARDHAN

^ Write the code:






















Deletion.cs
using System.Data.SqlClient;
private void button1_Click(object sender, EventArgs e)
{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete from customers where customerid=" + textBox1.Text
+ " ";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();

//presentation logic
if (n > 0)
MessageBox.Show(n + " Row Deleted.");
else
MessageBox.Show("Deletion failed.");

cn.Close();
}





.NET 4.0 and Visual Studio 2010 Page 398 of 548
D. HARSHA VARDHAN

^ Design the Updation form as follows:


^ Write the code:














Updation.cs
using System.Data.SqlClient;
private void button1_Click(object sender, EventArgs e)
{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

string gen;
if (radioButton1.Checked == true)
gen = "Male";
else
gen = "Female";





.NET 4.0 and Visual Studio 2010 Page 399 of 548
D. HARSHA VARDHAN














//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "update customers set customername= ' " + textBox2.Text +
" ' ,gender= ' " + gen + " ' ,amount=" + textBox3.Text + " where customerid=" +
textBox1.Text + " ";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();

//presentation logic
if (n > 0)
MessageBox.Show(n + " Row Updated.");
else
MessageBox.Show("Updation failed.");

cn.Close();
}







.NET 4.0 and Visual Studio 2010 Page 400 of 548
D. HARSHA VARDHAN

Retrieving Data from the Database

For retrieving the table data from the database, you write a select statement (query
statement) in the frontend code.
Next, you need to pass it to backend using Command class object.
Then your select statement will be executed at backend. Then the DBMS (Oracle / SQL
Server / My SQL etc.), returns the result data, based on the executed query. For
example, if your statement is select * from departments, then the entire departments
table data will be returned as it is.
Then frontend, you have to receive the data into a temporary memory location (buffer).
To create a buffer in your code, you can use DataReader class.
After that, you can present the data on the screen for the user.
This is the flow of data. You can observe this flow in the following diagram.





















db
.NET
Application
Connection
(provider, data
source, user id,
password)

Command
(select stmt, cn)

DataReader





.NET 4.0 and Visual Studio 2010 Page 401 of 548
D. HARSHA VARDHAN

Library:
Connection: Maintains the connection with database.
Command: Sends a SQL statement and executes it at backend.
DataReader: Acts as a buffer. It holds the data, which is received from database.

Note: Here, to execute the select statement, you have to use ExecuteReader() method of
command class. After execution of the statement, it returns the entire data, i.e. retrieved from
the database, in the form of DataReader class object. So that we have to receive it into an
instance of DataReader class.


Classes, to be used in this concept:

















Understanding the DataReader class:
Its known as buffer. Its not visible; it stores the data in the memory.
It contains the data in the form of a table itself.
Command
CommandText
Connection
CommandType
Parameters
ExecuteNonQuery()
ExecuteReader()
Connection
ConnectionString
Open()
Close()
DataReader
Read()
[column_name]
[index]
Close()





.NET 4.0 and Visual Studio 2010 Page 402 of 548
D. HARSHA VARDHAN

Ex:


Library: SqlDataReader / OleDbDataReader

a) Read(): This method moves the record pointer, to the next record. For the first
time call of this method, the record pointer point-outs the first record. After that,
for every call it jumps to next record. If the next record is found, then it returns
true; if the next record is not found, that means whenever it is reached end of
the data, then it returns False.
Ex:


dr.Read();






(true)





.NET 4.0 and Visual Studio 2010 Page 403 of 548
D. HARSHA VARDHAN

dr.Read();


dr.Read();


dr.Read();


dr.Read();




(false)
(true)
(true)
(true)





.NET 4.0 and Visual Studio 2010 Page 404 of 548
D. HARSHA VARDHAN

b) [column name]: This indexer gets the value, at the specified column name,
in the current row, which is currently pointed-out by the record pointer.

c) [index]: This indexer gets the value, at the specified column index, in the
current row, which is currently pointed-out by the record pointer. The column
index always starts from 0.

d) Close(): This method closes the buffer. At the end of your code, you can close
it.




Implementation Code for SQL Server:
^ Import the Library (at the top):
using System.Data.SqlClient;
^ Construct the Connection class object:
SqlConnection cn = new SqlConnection();
^ Assign the Connection string:
cn.ConnectionString = data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>;
^ Open the connection:
cn.Open();
^ Construct the Command class object:
SqlCommand cmd = new SqlCommand();
^ Assign the SQL statement, which is to be executed:
cmd.CommandText = select statement;
^ Assign the reference of connection object, based which the command is to
be executed:
cmd.Connection = cn;
^ Construct the DataReader class object:
SqlDataReader dr;
^ Execute the command and receive the data into the buffer:
dr = cmd.ExecuteReader();





.NET 4.0 and Visual Studio 2010 Page 405 of 548
D. HARSHA VARDHAN

^ Read the next row.
dr.Read();
^ Get the value at specific column:
dr[column index];
(or)
dr[column_name];
^ Close the buffer:
dr.Close();
^ Close the connection:
cn.Close();



Implementation Code for Oracle (or any other database):
^ Import the Library (at the top):
using System.Data.OleDb;
^ Construct the Connection class object:
OleDbConnection cn = new OleDbConnection();
^ Assign the Connection string:
cn.ConnectionString = provider=<provider name>;data source=<name of the
server>;user id=<user name>;password=<password>;
^ Open the connection:
cn.Open();
^ Construct the Command class object:
OleDbCommand cmd = new OleDbCommand();
^ Assign the SQL statement, which is to be executed:
cmd.CommandText = select statement;
^ Assign the reference of connection object, based which the command is to
be executed:
cmd.Connection = cn;
^ Construct the DataReader class object:
OleDbDataReader dr;
^ Execute the command and receive the data into the buffer:
dr = cmd.ExecuteReader();





.NET 4.0 and Visual Studio 2010 Page 406 of 548
D. HARSHA VARDHAN

^ Read the next row.
dr.Read();
^ Get the value at specific column:
dr[column index];
(or)
dr[column_name];
^ Close the buffer:
dr.Close();
^ Close the connection:
cn.Close();







.NET 4.0 and Visual Studio 2010 Page 407 of 548
D. HARSHA VARDHAN

Demo:

^ Open the previous demo application.
^ Add the menu item Retrievals and design the menu as shown below:


^ Click on Project menu Add Windows Form. Enter the form name as
DataReaderDemo. Click on Add.
^ Double click on the View Data using Data Reader menu item and write the code:








Form1.cs

private void viewDataUsingDataReaderToolStripMenuItem_Click(object sender,
EventArgs e)
{
DataReaderDemo f = new DataReaderDemo();
f.MdiParent = this;
f.Show();
}





.NET 4.0 and Visual Studio 2010 Page 408 of 548
D. HARSHA VARDHAN

^ Design the DataReaderDemo form as follows:

^ Write the Code:





DataReaderDemo.cs
using System.Data.SqlClient;
private void DataReaderDemo_Load(object sender, EventArgs e)
{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from customers";
cmd.Connection = cn;

//DataReader impl
SqlDataReader dr;
dr = cmd.ExecuteReader();





.NET 4.0 and Visual Studio 2010 Page 409 of 548
D. HARSHA VARDHAN








O Sometimes, you may need to display the records one-by-one, when the user clicks Next
button. We take a demonstration like that:

^ Add the menu item View Data using Data Reader Record-by-Record as shown below:


//presentation / buffer logic
while (dr.Read() == true)
{
listBox1.Items.Add(dr[0] + " -- " + dr[1] + " -- " + dr[2] + " -- " + dr[3]);
}

dr.Close();
cn.Close();
}





.NET 4.0 and Visual Studio 2010 Page 410 of 548
D. HARSHA VARDHAN

^ Click on Project menu Add Windows Form. Enter the form name as
DataReaderDemo_RecordByRecord. Click on Add.
^ Double click on the View Data using Data Reader Record-by-Record menu item and
write the code:








^ Design the DataReaderDemo_RecordByRecord form as follows:

Form1.cs

private void viewDataUsingDataReaderRecordbyRecordToolStripMenuItem_Click(object
sender, EventArgs e)
{
DataReaderDemo_RecordByRecord f = new DataReaderDemo_RecordByRecord();
f.MdiParent = this;
f.Show();
}





.NET 4.0 and Visual Studio 2010 Page 411 of 548
D. HARSHA VARDHAN


^ Write the Code:





DataReaderDemo_RecordByRecord.cs
using System.Data.SqlClient;
public partial class DataReaderDemo_RecordByRecord : Form
{
public DataReaderDemo_RecordByRecord()
{
InitializeComponent();
}

SqlDataReader dr;
SqlConnection cn = new SqlConnection();

private void DataReaderDemo_RecordByRecord_Load(object sender, EventArgs e)
{
//Connection impl
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from customers";
cmd.Connection = cn;

//DataReader impl
dr = cmd.ExecuteReader();

//presentation / buffer logic
if (dr.Read() == true)
{
textBox1.Text = Convert.ToString(dr[0]);
textBox2.Text = Convert.ToString(dr[1]);
if (Convert.ToString(dr[2]) == "Male")
radioButton1.Checked = true;
else
radioButton2.Checked = true;
textBox3.Text = Convert.ToString(dr[3]);
}
else
MessageBox.Show("No Data Found...");
}

private void button1_Click(object sender, EventArgs e)
{
if (dr.Read() == true)





.NET 4.0 and Visual Studio 2010 Page 412 of 548
D. HARSHA VARDHAN













O Sometimes, you may need to display the records based on the user-entered value. For
example, when the user enters the customer id, then you need to display the respective
customer details. We take a demonstration like that:

^ Add the menu item View Data using Data Reader - Conditional Data as shown below:
{
textBox1.Text = Convert.ToString(dr[0]);
textBox2.Text = Convert.ToString(dr[1]);
if (Convert.ToString(dr[2]) == "Male")
radioButton1.Checked = true;
else
radioButton2.Checked = true;
textBox3.Text = Convert.ToString(dr[3]);
}
else
MessageBox.Show("No Data Found...");
}

private void DataReaderDemo_RecordByRecord_FormClosing(object sender,
FormClosingEventArgs e)
{
dr.Close();
cn.Close();
}
}








.NET 4.0 and Visual Studio 2010 Page 413 of 548
D. HARSHA VARDHAN



^ Click on Project menu Add Windows Form. Enter the form name as
DataReaderDemo_ConditionalData. Click on Add.
^ Double click on the View Data using Data Reader - Conditional Data menu item and
write the code:








^ Design the DataReaderDemo_ConditionalData form as follows:
Form1.cs

private void viewDataUsingDataReaderConditionalDataToolStripMenuItem_Click(object
sender, EventArgs e)
{
DataReaderDemo_ConditionalData f = new DataReaderDemo_ConditionalData();
f.MdiParent = this;
f.Show();
}





.NET 4.0 and Visual Studio 2010 Page 414 of 548
D. HARSHA VARDHAN



^ Write the Code:





DataReaderDemo_ConditionalData.cs
using System.Data.SqlClient;
private void button1_Click(object sender, EventArgs e)
{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select customername,gender,amount from customers where
customerid=" + textBox1.Text + "";
cmd.Connection = cn;

//DataReader impl
SqlDataReader dr;





.NET 4.0 and Visual Studio 2010 Page 415 of 548
D. HARSHA VARDHAN












dr = cmd.ExecuteReader();

//presentation / buffer logic
if (dr.Read() == true)
{
textBox2.Text = Convert.ToString(dr[0]);
if (Convert.ToString(dr[1]) == "Male")
radioButton1.Checked = true;
else
radioButton2.Checked = true;
textBox3.Text = Convert.ToString(dr[2]);
}
else
MessageBox.Show("No Data Found...");

dr.Close();
cn.Close();
}





.NET 4.0 and Visual Studio 2010 Page 416 of 548
D. HARSHA VARDHAN

ADO.NET Disconnected Model

ADO.NET database connection is of two types:
1. Connected Model:
Implemented with DataReader buffer.
2. Disconnected Model:
Implemented with DataSet, DataTable, DataRow buffers.

To overcome the limitations of Connected Model, ADO.NET introduces Disconnected
Model.
The main advantage of Disconnected Model is, even though the connected is not
opened, it works. That means, when you execute any statement, the connected will be
opened, then the statement will be executed and then finally the connected will be
closed.
But the connected model is not like that. If you take the buffer called data reader
which is used in the connected model, it works when the connection is opened only. But
the disconnected model buffers work even though the connection is opened or not.
In the connected model, we were using only one buffer.
1. DataReader
In the disconnected model, three buffers are used.
1. DataSet
2. DataTable
3. DataRow

Library:
Connection: Maintains the connection with database.

DataAdapter: Sends a sql statement and executes it at backend. Its just like Command
class, in the connection oriented model. The difference between Command class and
DataAdapter class is, the Command class is used to execute any type of statement
(insert statement, delete statement, update statement and select statement). But
adapter executes select statement only.





.NET 4.0 and Visual Studio 2010 Page 417 of 548
D. HARSHA VARDHAN

DataSet: Holds the data that is received from database, after execution of DataAdapter.
It can hold multiple tables data at-a-time. In other words, it contains an array of tables.

DataTable: Holds a single table, from the DataSet.

DataRow: Holds a single row, from the DataTable.



Limitations of Connection Oriented Model
(or)
Advantages of Disconnected Model

The DataReader works only when the connection is closed. But the DataTable works
even though the database is disconnected.
The DataReader buffer supports record travelling only once in its lifetime. But the
DataTable buffer supports record travelling any no. of times in its life time.
The DataReader buffer supports only forward record travelling. It doesnt supports
backward or random record travels. But DataTable supports forward, backward and
random record travels.
DataReader supports sequential records travels only. It doesnt supports to pick-up a
record directly with its index. But DataTable supports to pick-up a record directly with
its index.
DataReader supports only column indexing. DataTable supports both column and row
indexing.
DataReader data cant be assigned to DataGridView control. But the DataTable data
can be assigned to the DataGridView control.





.NET 4.0 and Visual Studio 2010 Page 418 of 548
D. HARSHA VARDHAN

Diagrammatical View of Disconnected Model:


































db
.NET
Application
Connection
(provider, data
source, user id,
password)

DataAdapter
(select stmt, cn)
DataSet











DataTable






DataRow




0
1
Fill()
0
1
2
3
0 1 2





.NET 4.0 and Visual Studio 2010 Page 419 of 548
D. HARSHA VARDHAN

Classes, to be used in this concept:























Understanding the DataAdapter class:
Tables[table_index]: Gets the entire table, from the Tables array, based on the
given index. So, Tables is an array here.

Clear(): Clears all the tables, and makes the dataset empty.



DataAdapter
DataAdapter(select statement, connection_object)
Fill(dataset_object)
Connection
ConnectionString
Open()
Close()
DataSet
Tables[table_index]
Clear()
DataTable
Rows.Count
Rows[row_index]
Columns.Count
Columns[column_index]
DataRow
[column_index]
[column name]





.NET 4.0 and Visual Studio 2010 Page 420 of 548
D. HARSHA VARDHAN

Understanding the DataTable class:
Rows.Count: Gets the no. of rows that exist in the current table.
Rows[row_index]: Gets the single row at the specified index.
Columns.Count: Gets the no. of columns that exist in the current table.
Columns[column_index]: Gets the single column at the specified index.


Understanding the DataRow class:
[column_index]: This indexer gets the value at the given column, based on the given
index.
[column_name]: This indexer gets the value at the given column, based on the
given column.




Implementation Code for SQL Server:
Import the Library (at the top):
using System.Data.SqlClient;
Construct the Connection class object:
SqlConnection cn = new SqlConnection();
Assign the Connection string:
cn.ConnectionString = data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>;
Construct the DataAdapter class object:
SqlDataAdapter adp = new SqlDataAdapter(select statement,cn);
Construct the DataSet class object:
DataSet ds = new DataSet();
Construct the DataTable class object:
DataTable dt;
Construct the DataRow class object:
DataRow drow;
Execute the adapter and receive the data into DataSet:
adp.Fill(ds);





.NET 4.0 and Visual Studio 2010 Page 421 of 548
D. HARSHA VARDHAN

Assign the particular table from DataSet into DataTable object:
dt = ds.Tables[table index];
Get the total no. of rows in the table:
dt.Rows.Count;
Get the total no. of columns in the table:
dt.Columns.Count;
Assign the particular row from DataTable into DataRow object:
drow = dt.Rows[row index];
Get the particular value in the DataRow:
drow[column index];
(or)
drow[column_name];


Implementation Code for Oracle (or any other database):
Import the Library (at the top):
using System.Data.OleDb;
Construct the Connection class object:
OleDbConnection cn = new OleDbConnection();
Assign the Connection string:
cn.ConnectionString = provider=<provider name>;data source=<name of the
server>;user id=<user name>;password=<password>;
Construct the DataAdapter class object:
OleDbDataAdapter adp = new OleDbDataAdapter(select statement,cn);
Construct the DataSet class object:
DataSet ds = new DataSet();
Construct the DataTable class object:
DataTable dt;
Construct the DataRow class object:
DataRow drow;
Execute the adapter and receive the data into DataSet:
adp.Fill(ds);
Assign the particular table from DataSet into DataTable object:
dt = ds.Tables[table index];





.NET 4.0 and Visual Studio 2010 Page 422 of 548
D. HARSHA VARDHAN

Get the total no. of rows in the table:
dt.Rows.Count;
Get the total no. of columns in the table:
dt.Columns.Count;
Assign the particular row from DataTable into DataRow object:
drow = dt.Rows[row index];
Get the particular value in the DataRow:
drow[column index];
(or)
drow[column_name];







.NET 4.0 and Visual Studio 2010 Page 423 of 548
D. HARSHA VARDHAN

Demo:

^ Open the previous demo application.
^ Add the menu item View Data using Data Set as shown below:


^ Click on Project menu Add Windows Form. Enter the form name as DataSetDemo.
Click on Add.
^ Double click on the View Data using Data Set menu item and write the code:








Form1.cs

private void viewDataUsingDataSetToolStripMenuItem_Click(object sender, EventArgs e)
{
DataSetDemo f = new DataSetDemo();
f.MdiParent = this;
f.Show();
}





.NET 4.0 and Visual Studio 2010 Page 424 of 548
D. HARSHA VARDHAN

^ Design the DataSetDemo form as follows:


^ Write the Code:





DataSetDemo.cs
using System.Data;
using System.Data.SqlClient;

private void DataSetDemo_Load(object sender, EventArgs e)
{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";

//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("select * from customers", cn);

//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);





.NET 4.0 and Visual Studio 2010 Page 425 of 548
D. HARSHA VARDHAN










O Sometimes, you may need to display the records one-by-one in flexible manner, depending on
the clicked buttons like First, Previous, Next, Last. We take a demonstration like that:

^ Add the menu item View Data using Data Set Flexible Records Presentation as shown
below:

//DataTable impl
DataTable dt;
dt = ds.Tables[0];

//presentation / buffer logic
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow drow;
drow = dt.Rows[i];
listBox1.Items.Add(drow["customerid"] + " -- " + drow["customername"] + " -- "
+ drow["gender"] + " -- " + drow["amount"]);
}
}






.NET 4.0 and Visual Studio 2010 Page 426 of 548
D. HARSHA VARDHAN

^ Click on Project menu Add Windows Form. Enter the form name as
DataSetDemo_FlexibleRecords. Click on Add.
^ Double click on the View Data using Data Set Flexible Records Presentation menu
item and write the code:










^ Design the DataSetDemo_FlexibleRecords form as follows:



Form1.cs

private void
viewDataUsingDataSetFlexibleRecordsPresentationToolStripMenuItem_Click(object sender,
EventArgs e)
{
DataSetDemo_FlexibleRecords f = new DataSetDemo_FlexibleRecords();
f.MdiParent = this;
f.Show();
}






.NET 4.0 and Visual Studio 2010 Page 427 of 548
D. HARSHA VARDHAN

^ Write the Code:





DataSetDemo_FlexibleRecords.cs
using System.Data;
using System.Data.SqlClient;

public partial class DataSetDemo_FlexibleRecords : Form
{
public DataSetDemo_FlexibleRecords()
{
InitializeComponent();
}

DataTable dt;
int RowIndex;
DataRow drow;

private void Display()
{
drow = dt.Rows[RowIndex];
textBox1.Text = Convert.ToString(drow[0]);
textBox2.Text = Convert.ToString(drow[1]);
if (Convert.ToString(drow[2]) == "Male")
radioButton1.Checked = true;
else
radioButton2.Checked = true;
textBox3.Text = Convert.ToString(drow[3]);
}

private void DataSetDemo_FlexibleRecords_Load(object sender, EventArgs e)
{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";

//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("select * from customers", cn);

//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);

//DataTable impl
dt = ds.Tables[0];

//display first record
RowIndex = 0;
Display();





.NET 4.0 and Visual Studio 2010 Page 428 of 548
D. HARSHA VARDHAN






























O Using with the DataSet buffer, it is possible to display the data in the DataGridView control.
In other words, the dataset data can be assigned into DataGridView control programmatically.
}

private void button1_Click(object sender, EventArgs e)
{
//display first record
RowIndex = 0;
Display();
}

private void button2_Click(object sender, EventArgs e)
{
//display previous record
RowIndex--;
if (RowIndex < 0)
{
RowIndex++;
MessageBox.Show("Already at first record.");
}
Display();
}

private void button3_Click(object sender, EventArgs e)
{
//display previous record
RowIndex++;
if (RowIndex == dt.Rows.Count)
{
RowIndex--;
MessageBox.Show("Already at last record.");
}
Display();
}

private void button4_Click(object sender, EventArgs e)
{
//display last record
RowIndex = dt.Rows.Count - 1;
Display();
}
}







.NET 4.0 and Visual Studio 2010 Page 429 of 548
D. HARSHA VARDHAN

The DataGridView control is one of the major famous controls, which displays the data in a
table format. It is easy to use it. To assign the data into this DataGridView control, write the
following statement:
dataGridView1.DataSource = dataset_obj;
(or)
dataGridView1.DataSource = datatable_obj;

Sample Output:

We take a demonstration like that:

^ Add the menu item View Data using Data Set - DataGridView as shown below:






.NET 4.0 and Visual Studio 2010 Page 430 of 548
D. HARSHA VARDHAN

^ Click on Project menu Add Windows Form. Enter the form name as
DataSetDemo_DataGridView. Click on Add.
^ Double click on the View Data using Data Set - DataGridView menu item and write the
code:










^ Design the DataSetDemo_DataGridView form as follows:


[Drag and drop the DataGridView control from the toolbox].
Form1.cs

private void viewDataUsingDataSetDataGridViewToolStripMenuItem_Click(object sender,
EventArgs e)
{
DataSetDemo_DataGridView f = new DataSetDemo_DataGridView();
f.MdiParent = this;
f.Show();
}





.NET 4.0 and Visual Studio 2010 Page 431 of 548
D. HARSHA VARDHAN


^ Write the Code:





















DataSetDemo_DataGridView.cs
using System.Data;
using System.Data.SqlClient;

private void DataSetDemo_DataGridView_Load(object sender, EventArgs e)
{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";

//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("select * from customers", cn);

//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);

//DataTable impl
DataTable dt;
dt = ds.Tables[0];

//grid logic
dataGridView1.DataSource = dt;
}





.NET 4.0 and Visual Studio 2010 Page 432 of 548
D. HARSHA VARDHAN

Working with Stored Procedures / Functions

This is to call a procedure / function from the frontend application.
This includes with:
1. First, create the procedure / function at backend using PL SQL.
2. Call it with its name, from the frontend code.
Note: PL SQL is supported by SQL Server, Oracle and My SQL.


Purpose / Advantages of Stored Procedures / Functions:
To perform multiple database transactions (insert / delete / update / select) at-a-time,
with a single database call.
To retrieve multiple tables data at-a-time, with a single database call.
To implement complex database logics, which is a collection of multiple if conditions,
loops etc.
To hide query / non-query statements in the code.
To have a faster execution, because the stored procedure is basically a pre-compiled
object.

For example, in your project you want to perform 2 insertions, 3 deletions at various
tables. If you implement the code with previous concepts, you require large code and moreover
at run time 5 database calls will be sent. That means the execution flow goes to the backend,
executes one statement and comes back. For all of these, it takes much time. So the application
will be executed slower. If the application is running multiple client systems simultaneously, it will
be slower. It that time, this Stored Procedure Calling concept is recommended. As an
advantage of this, those 5 transactions would be performed with a single database call.






.NET 4.0 and Visual Studio 2010 Page 433 of 548
D. HARSHA VARDHAN

Library:
Connection: Maintains the connection with database.
Command: Calls a database procedure / function.
Parameter: Represents the argument value for the procedure / function.















Implementation Code for SQL Server:
Import the Library (at the top):
using System.Data.SqlClient;
Construct the Connection class object:
SqlConnection cn = new SqlConnection();
Assign the Connection string:
cn.ConnectionString = data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>;
Open the connection:
cn.Open();
Construct the Command class object:
SqlCommand cmd = new SqlCommand();
Assign the reference of Connection class object to Command class object:
cmd.Connection = cn;
Assign the procedure / function name that is to be executed:
cmd.CommandText = xxxxx;
Assign the command type to Command class object:
cmd.CommandType = CommandType.StoredProcedure;

db
.NET
Application
Connection
(provider, data
Source, user id,
password)
Command
(procedure /
function name,
parameters)





.NET 4.0 and Visual Studio 2010 Page 434 of 548
D. HARSHA VARDHAN

Assign the parameters (if any) to the Command class object:
cmd.Parameters.AddWithValue(parameter_name, value);
.;
.;
Execute the procedure / function:
cmd.ExecuteNonQuery();
Close the connection:
cn.Close();






Implementation Code for Oracle (or any other database):
Import the Library (at the top):
using System.Data.OleDb;
Construct the Connection class object:
OleDbConnection cn = new OleDbConnection();
Assign the Connection string:
cn.ConnectionString = provider=<provider name>;data source=<name of the
server>;user id=<user name>;password=<password>;
Open the connection:
cn.Open();
Construct the Command class object:
OleDbCommand cmd = new OleDbCommand();
Assign the reference of Connection class object to Command class object:
cmd.Connection = cn;
Assign the procedure / function name that is to be executed:
cmd.CommandText = xxxxx;
Assign the command type to Command class object:
cmd.CommandType = CommandType.StoredProcedure;
Assign the parameters (if any) to the Command class object:
cmd.Parameters.AddWithValue(parameter_name, value);
.;
.;





.NET 4.0 and Visual Studio 2010 Page 435 of 548
D. HARSHA VARDHAN

Execute the procedure / function:
cmd.ExecuteNonQuery();
Close the connection:
cn.Close();


Demo:

^ Open SQL Server 2005.
^ Already you have created demo database. Confirm, whether it is exist or not.
^ In that database, create a table named Students, as shown below.


^ Click on New Query option in the toolbar.








.NET 4.0 and Visual Studio 2010 Page 436 of 548
D. HARSHA VARDHAN

^ Then type the following code:


^ Then Press F5.
^ It displays the following message:
Command(s) completed successfully.
^ Enter some sample data as follows:





.NET 4.0 and Visual Studio 2010 Page 437 of 548
D. HARSHA VARDHAN


^ Open the previous demo application in Visual Studio.
^ Add the menu item Stored Procedure Demo as shown below:





.NET 4.0 and Visual Studio 2010 Page 438 of 548
D. HARSHA VARDHAN



^ Click on Project menu Add Windows Form. Enter the form name as
StoredProcedureDemo. Click on Add.
^ Double click on the Stored Procedure Demo menu item and write the code:








^ Design the StoredProcedureDemo form as follows:
Form1.cs

private void storedProcedureDemoToolStripMenuItem_Click(object sender, EventArgs e)
{
StoredProcedureDemo f = new StoredProcedureDemo();
f.MdiParent = this;
f.Show();
}





.NET 4.0 and Visual Studio 2010 Page 439 of 548
D. HARSHA VARDHAN


^ Write the Code:











StoredProcedureDemo.cs
using System.Data.SqlClient;

private void button1_Click(object sender, EventArgs e)
{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "calculategrades";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();

//presentation logic
MessageBox.Show("Procedure Executed..");
cn.Close();
}





.NET 4.0 and Visual Studio 2010 Page 440 of 548
D. HARSHA VARDHAN

Demo on Retrieving Multiple Tables Data using Stored
Procedure:

^ Open SQL Server 2005.
^ Click on New Query option in the toolbar.
^ In the demo database, create the stored procedure as follows.


^ Then Press F5.
^ It displays the following message:
Command(s) completed successfully.

^ Open the previous demo application in Visual Studio.
^ Add the menu item Stored Procedure Demo Multiple Tables as shown below:





.NET 4.0 and Visual Studio 2010 Page 441 of 548
D. HARSHA VARDHAN



^ Click on Project menu Add Windows Form. Enter the form name as
StoredProcedureDemo_MultipleTables. Click on Add.
^ Double click on the Stored Procedure Demo Multiple Tables menu item and write the
code:









^ Design the StoredProcedureDemo_MultipleTables form as follows:
Form1.cs

private void storedProcedureDemoMultipleTablesToolStripMenuItem_Click(object
sender, EventArgs e)
{
StoredProcedureDemo_MultipleTables f = new
StoredProcedureDemo_MultipleTables();
f.MdiParent = this;
f.Show();
}






.NET 4.0 and Visual Studio 2010 Page 442 of 548
D. HARSHA VARDHAN


[Drag and drop two DataGridView controls into the form]

^ Write the Code:










StoredProcedureDemo_MultipleTables.cs
using System.Data;
using System.Data.SqlClient;

private void StoredProcedureDemo_MultipleTables_Load(object sender, EventArgs e)
{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";

//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("getdata", cn);

//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);





.NET 4.0 and Visual Studio 2010 Page 443 of 548
D. HARSHA VARDHAN









//DataTable impl
DataTable dt1, dt2;
dt1 = ds.Tables[0];
dt2 = ds.Tables[1];

//grid logic
dataGridView1.DataSource = dt1;
dataGridView2.DataSource = dt2;
}





.NET 4.0 and Visual Studio 2010 Page 444 of 548
D. HARSHA VARDHAN

Storing the Connection String in App.config file

In the live projects development, we may require to offer one or more customizable
values in the code.
For example, you can take a db server name. At the development time, we use the db
server in the s/w company. But when the project is issued to the customer, the project
should work under the db server, which is in the customers company.
At that, there should a facility to customize the server name, after installing the project in
the customers company.
But, we dont give the source code to the customer, so that the customer cant change
the db server name.
To solve this problem, this kind of application settings like this, would be maintained in
another file separately, which can be modified on the client system, even after installing
the project in the customers work station.
In .NET Framework, the application settings can be saved in a config file.
A config file contains .config extension.
In Console and Windows Applications, it is called as App.Config.
In Web Sites, it is called as Web.Config.
The config file is written is xml language.

Implementation of Config File
Add the configuration file.
Click on Project menu Add New Item.
Select Application Configuration File.
Click on OK.
Then App.config file will be created.
In the <config> tag, add the <appSettings> tag as follows.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>

</appSettings>
</configuration>

In the <appSettings> tag, use <add> tag to declare the actual application
configuration setting values.





.NET 4.0 and Visual Studio 2010 Page 445 of 548
D. HARSHA VARDHAN

Syn: <add key=name of the key value=actual value>
Ex: <add key=servername value=myserver>

Note: The key is used to access the configuration setting value in the code.

Access the configuration setting value with the help of key.
System.Configuration.ConfigurationSettings.AppSettings["key"];
It returns the value of the configuration setting, based on the given key in string mode.


























Application 138: Demo on App.Config
App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SqlServerConnection" value="user id=sa;password=123;data
source=localhost;initial catalog=demo"/>
</appSettings>
</configuration>





.NET 4.0 and Visual Studio 2010 Page 446 of 548
D. HARSHA VARDHAN












Form1.cs
using System.Configuration;
using System.Data.SqlClient;

private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = ConfigurationSettings.AppSettings["SqlServerConnection"];
cn.Open();
MessageBox.Show("Successfully Connected.");
cn.Close();
}





.NET 4.0 and Visual Studio 2010 Page 447 of 548
D. HARSHA VARDHAN

Crystal Reports

Crystal Reports is known as a reporting tool.
This is used for development of database reports in the projects.
A database report displays the database data, in a summary manner.
A database report is ready to print. The report file extension is .rpt.
That can be exported to Excel / HTML etc., formats.
Generally, in every live project, the data entered by the data entry operators, should be
displayed to the administrator in a Report format. That can be called as a Database
Report.
Crystal Reports are developed by Seagate Corporation, and has a strong integration
with Visual Studio.
Note: In Visual Studio 2010, the crystal reports are not available by default; we need to
install it separately. In the older versions (Visual Studio 2005 and 2008), Crystal reports
are in-built.



Implementation of Crystal Reports

1. Create a Crystal Report.

Click on Project menu Add New
Item.
Select Reporting Crystal Report.
Enter the name of the new report. Ex:
StudentsReport.rpt.
Click on Add.
A wizard will be displayed.
Select the report type as Standard and
click on OK.
The Standard Report Creation Wizard
dialog box will be appeared.
Application 149: Demo on Crystal Reports





.NET 4.0 and Visual Studio 2010 Page 448 of 548
D. HARSHA VARDHAN

There, expand the option Create New Connection and expand OLE DB (ADO)
Then OLE DB (ADO) dialog box will be appeared.
There, select the appropriate driver / provider name, based on the database which
you want to connect.
+ Sql Server Microsoft OLE DB Provider for Sql Server
+ Oracle Microsoft OLE DB Provider for Oracle
+ MS Access Microsoft Jet OLE DB 4.0 Provider


















After selecting the provider (Ex: Microsoft OLE DB Provider for Sql Server), click on
Next button.
Enter the server name (name of the system), user id, password and select database
name.
(Ex: classroom, sa, 123 and sample)





.NET 4.0 and Visual Studio 2010 Page 449 of 548
D. HARSHA VARDHAN

Click on Finish.
Then the OLE
DB (ADO) dialog
box will be closed
and the focus will
be come back to
Standard Report
Creation Wizard
dialog box. And
now, the OLE
DB (ADO) option
will be expanded.
Expand the
database name
and select the
table name,
which you want.





.NET 4.0 and Visual Studio 2010 Page 450 of 548
D. HARSHA VARDHAN

(Ex: students).
Click on > button to add the selected table into the right side list.
Click on Next.
Expand the table name. Then the list of columns will be displayed.
Now you have to add the require column(s), into the right side list, which you want to
display in the crystal report.
To add all the columns, click on >> button. To add the columns one-by-one, select
the column first and click on > button.
Click on Next.
Select the grouping column, based on which you want to group-up the data
(optional). If you dont want to group the data, simply leave it blank.
Click on Finish.
Then the report wizard will be completed and the report will be generated
automatically.
The report will be displayed in the design view. This can be called as Report Design
View.
Then the report file will be added into the Solution Explorer. Ex: studentsreport.rpt

2. Design the Crystal Report.
The Report Design View offers to change the design of the report.
The report design view contains 5 sections like:
Report Header: This section contains the objects that are to be displayed
only at the top of the report.
Page Header: This section contains the objects that are to be displayed at
the top of each page.
Details: This section contains the objects that are to be repeated for each
row of the database table. Generally, it displays the actual data values.
Report Footer: This section contains the objects that are to be displayed at
the bottom of the report.
Page Footer: This section contains the objects that are to be displayed at
the bottom of each page.








.NET 4.0 and Visual Studio 2010 Page 451 of 548
D. HARSHA VARDHAN









.NET 4.0 and Visual Studio 2010 Page 452 of 548
D. HARSHA VARDHAN

To change any font / border / alignment / colors / paragraph of the objects, right click
on the require object and choose the Format Object option.

To add new objects, right click on the empty area and choose Insert, where you can
select Special Field / Text Object / Summary / Line / Box / Chart /
Picture. After selecting any one of these options, click anywhere, where you want to
insert that object.

3. Invoke it in the Form.
The crystal report file cant be executed individually, it requires a form.
In other words, the crystal report can be executed on a windows form.
To contain the crystal report in the form, a control is required, that is called as
CrystalReportViewer.
This contains is able to display a crystal report on the form.
To implement this, come back to the form and drag CrystalReportViewer control
under Report category from the toolbox into the form.
For the control, set the following property.
ReportSource: Name of the report. (Ex: StudentReport)
Run the application. At run time, it asks for run-time authentication for security
purpose. Then you have to enter the password (Ex: 123) and click on Finish.
The CrystalReportViewer control offers the following features at run time.
Exporting the report to other formats like excel, pdf, doc etc.
Printing the report through a printer.
Refresh the report data.
Show/Hide the Group Tree.
Navigating the First / Previous / Next / Last Pages in the report.
Find the required text.
Change the Zoom of the data.











.NET 4.0 and Visual Studio 2010 Page 453 of 548
D. HARSHA VARDHAN


Output:







.NET 4.0 and Visual Studio 2010 Page 454 of 548
D. HARSHA VARDHAN

The Application Logic

While you are developing some applications you write some application logic (some
code).
That application logic can be divided as 3 types.
1. Presentation Logic
2. Business Logic
3. Database Logic

1. Presentation Logic:
+ This includes with reading the input values from the controls, updating the
UI by changing the properties, displaying some output messages etc.
+ For example, you take login form.

+ In that login form, after clicking on OK button, getting the user name and
password from the textboxes is called as Presentation Logic. In the similar
way, displaying the result message also called as Presentation Logic in this
example.

2. Business Logic:
+ This includes with validating the input values, performing some calculations,
implementing some formulas or algorithms etc.
+ In this login example, checking the username and password whether those
are entered properly or not is called as Business Logic.





.NET 4.0 and Visual Studio 2010 Page 455 of 548
D. HARSHA VARDHAN

3. Database Logic:
+ This includes with getting some data from the database or insert / modifying
some data in the database.
+ In this login example, getting the users data from the database is called as
Database Logic.



The Application Development Architectures

Based on the way, that you are implementing the presentation logic, business logic and
database logic in your application, there are 4 development architectures.
1) One-Tier Architecture / Monolithic Architecture
2) Two-Tier Architecture
3) Three-Tier Architecture
4) Multi-Tier Architecture / Distributed Architecture

1) One-Tier Architecture:
+ All types of logics (presentation logic, business logic and database logic) will be
implemented directly within the form.
+ That means there is no separation of presentation logic, business logic and database
logic.
+ This type of applications are not in the professional style.
+ There is no re-usability of business code and database code.










UI
Presentation Logic
Business Logic
Database Logic





.NET 4.0 and Visual Studio 2010 Page 456 of 548
D. HARSHA VARDHAN

2) Two-Tier Architecture:
+ The Presentation Logic and Business Logics are maintained separately.
+ The presentation logic is written in Presentation Layer and the business logic is
written in Business Layer / Business Access Layer.









+ Note: Here, the database logic also can be written in the Business Layer only,
even though its not a good manner.

3) Three-Tier Architecture:
+ The Presentation Logic, Business Logic and Database Logics are maintained
separately.
+ This is recommended for the professional projects in the software companies.















UI

Presentation Layer
Business Access
Layer

UI

Presentation Layer
Business Access
Layer
Data
Access
Layer

db





.NET 4.0 and Visual Studio 2010 Page 457 of 548
D. HARSHA VARDHAN

4) N-Tier Architecture / Distributed Architecture:
+ In the 3-tier architecture, the UI and presentation layer will be located in the client
system; and business access layer and data access layer will be maintained in the
server system.


















+ Here, there is the requirement of a technology that allows us to connect Business
Layer with Presentation Layer. That technology is called as Distributed
Technology.
+ The following are the well-known and important distributed technologies:
+ DCOM (Distributed Component Object Model)
+ .NET Remoting
+ Web Services
+ WCF (Windows Communication Foundation)

A. DCOM:
+ It is in usage, before .NET.
+ It is platform dependent.

UI

Presentation Layer
Business Access
Layer
Data
Access
Layer

db
Client System Server System





.NET 4.0 and Visual Studio 2010 Page 458 of 548
D. HARSHA VARDHAN

B. .NET Remoting:
+ It is introduced in .NET Framework.
+ It is platform independent.
+ It is suitable for the windows applications that run on LAN or intranet.
+ It supports TCP and HTTP protocols.

C. Web Services:
+ It is available in ASP.NET.
+ It is also platform independent.
+ It is supported for web only.
+ It is language independent (any .NET language).
+ It is supported for ASP.NET web sites only.
+ It supports SOAP and HTTP protocols.

D. WCF:
+ It is introduced in .NET 3.5.
+ It is platform independent.
+ It is language independent (any .NET language).
+ It is supported for other language applications also (java applications, php
applications etc.)
+ It is supported for any type of network (LAN, intranet and internet also).
+ It is supported in any type of applications (windows applications, web sites, WPF
applications etc.)






+ Create a new windows forms application.
Name: 3TierArchitectureDemo
+ It will create Form1 automatically.
+ Open solution explorer, right click on Form1 and rename it as LoginForm.cs.
+ Right click on the solution, select Add New Project.
Application 150: Demo on 3-Tier Architecture





.NET 4.0 and Visual Studio 2010 Page 459 of 548
D. HARSHA VARDHAN

Project Type: Class Library
Name: BusinessAccessLayer
+ Click on OK.
+ Right click on the solution, select Add New Project.
Project Type: Class Library
Name: DataAccessLayer
+ Click on OK.
+ Right click on 3TierArchitectureDemo project and choose Add Reference.
+ Select Project BusinessAccessLayer.
+ Click on OK.
+ Right click on BusinessAccessLayer project and choose Add Reference.
+ Select Project DataAccessLayer.
+ Click on OK.
+ Then the application framework is ready.

+ Now, we need to create the database.
+ Open Sql Server 2005.





.NET 4.0 and Visual Studio 2010 Page 460 of 548
D. HARSHA VARDHAN

+ Right click on Databases New Database Enter the database name as
RemotingTest Click OK.
+ Expand RemotingTest database Right click on Tables Select New Table.
+ Create the table as follows:

+ Save the table name as Users.
+ Expand RemotingTest Tables.
+ Right click on the Users table and choose Open Table.
+ Enter some sample data.





.NET 4.0 and Visual Studio 2010 Page 461 of 548
D. HARSHA VARDHAN


+ Come back to Visual Studio.
+ Now, we have to configure the connection string in App.config file.
+ Right click on 3TierArchitectureDemo Add New Item Application Configuration
File Add.
+ Then App.config file will be added. Then type the code as follows:









+ Now, we have to implement the code in DataAccessLayer.
+ In the DataAccessLayer project, right click on Class1.cs and rename it as
DatabaseLogic.cs.
App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="RemoteDatabase" value="user id=sa;password=123;data
source=localhost;initial catalog=RemotingTest"/>
</appSettings>
</configuration>





.NET 4.0 and Visual Studio 2010 Page 462 of 548
D. HARSHA VARDHAN

+ Then type the code in DatabaseLogic.cs.




























+ Now, we have to implement the code in BusinessAccessLayer.
+ In the BusinessAccessLayer project, right click on Class1.cs and rename it as
BusinessLogic.cs.
+ Then type the code in BusinessLogic.cs.

DataAccessLayer DatabaseLogic.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace DataAccessLayer
{
public class DatabaseLogic
{
public DataTable GetUsers(string Username, string Password)
{
//connection logic
string cnstr = ConfigurationSettings.AppSettings["RemoteDatabase"];
SqlConnection cn = new SqlConnection(cnstr);

//stmt logic
string sqlstr = "select * from users where username= ' " + Username + " ' and
password= ' " + Password + " ' ";

//adapter logic
SqlDataAdapter adp = new SqlDataAdapter(sqlstr, cn);
DataSet ds = new DataSet();
adp.Fill(ds);

//datatable logic
DataTable dt;
dt = ds.Tables[0];

return (dt);
}
}
}





.NET 4.0 and Visual Studio 2010 Page 463 of 548
D. HARSHA VARDHAN



















+ Open LoginForm.cs and design it as follows.


+ Write the code in LoginForm.cs as follows:


BusinessAccessLayer BusinessLogic.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace BusinessAccessLayer
{
public class BusinessLogic
{
public bool IsValidUser(string Username, string Password)
{
DataTable dt;
DataAccessLayer.DatabaseLogic dbl = new DataAccessLayer.DatabaseLogic();
dt = dbl.GetUsers(Username, Password);
if (dt.Rows.Count > 0)
return true;
else
return false;
}
}
}





.NET 4.0 and Visual Studio 2010 Page 464 of 548
D. HARSHA VARDHAN















+ Finally run the application.

3TierArchitectureDemo LoginForm.cs
private void button1_Click(object sender, EventArgs e)
{
BusinessAccessLayer.BusinessLogic bl = new BusinessAccessLayer.BusinessLogic();
bool result;
result = bl.IsValidUser(textBox1.Text, textBox2.Text);
if (result == true)
MessageBox.Show("Successfully Logged in!");
else
MessageBox.Show("Invalid Login");
}

private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}





.NET 4.0 and Visual Studio 2010 Page 465 of 548
D. HARSHA VARDHAN

.NET Remoting

It is introduced in .NET Framework.
It is platform independent.
It is suitable for the non-web applications (windows applications).
It is supported in LAN or intranet.
Def: A technology that makes an object accessible across application domains.
In other words, it implement the communication between one .NET application and .NET
application.






Understanding .NET Remoting:
To understand .NET Remoting completely, you should understand the following things:
1. .NET Remoting Architecture
2. Channels
3. Server Activated Object
4. Client Activated Object

i. .NET Remoting Architecture












.NET Application

.NET Application
Network
Client Application Server Application

.NET Assembly

.NET Assembly
Send a Request
Channels (TCP/HTTP)

Object
(Server Activated Object)
Class

Proxy
(Client Activated Object)
Send the Reference
Channels (TCP/HTTP)





.NET 4.0 and Visual Studio 2010 Page 466 of 548
D. HARSHA VARDHAN

In the above architecture, there is the communication between one .NET
assembly (Client application) and another .NET assembly (Server application).
At first the client application sends a request to the server application.
The server application receives the request.
In the server application, we have a class (for writing the business code). For an
object will be created for that class.
That object is called as Server Activated Object.
The reference of the Server Object will be given to the client application.
That reference is received and stored in a dummy object (The object, which acts
as reference of another object). That dummy object is called as Proxy.
Finally, the client application can utilize the proxy, to access the methods of the
server object.
In fact, the communication is possible using some communicators called as
Channels.

ii. Channels
It is the physical communication media used by the .NET Remoting System for
its communication between the client application and server application.
For example, if you want to move some goods from one place to another place
physically. Then we require to transport those goods, through some roads.
In the similar way, in Remoting also, we have to use some channels for
transportation of the object, across application domains (application boundaries).
.NET Remoting Technology supports two channels.
1. TCP Channel (Transfer Control Protocol)
2. HTTP (Hyper Text Transfer Protocol)

Sl. No TCP Channel HTTP Channel
1
It is used for LAN / intranet
based application.
It is used for LAN / intranet /
internet applications.
2
It is mandatory to define a
port explicitly for using the
TCP channel.
It can use the default port of the
web server and also it supports to
create the port explicitly.
3 Performance will be very fast.
Performance will be slower, when
compared with TCP channel.





.NET 4.0 and Visual Studio 2010 Page 467 of 548
D. HARSHA VARDHAN

Note: In the client application and server application, we have to register any
one of the channels compulsory.

To register the channel:
ChannelServices.RegisterChannel(channel_object);

To unregister the channel:
ChannelServices.UnregisterChannel(channel_object);


iii. Server Activated Object
The object, which is ready to be transmittable across the application domains,
using the channels.
To expose it to the client application:





In the above syntax, RemoteClass means, the class name for which you want
to create the remote object.
On receiving the request from the client, an object will be created for the
RemoteClass and it will be served to the client application. Before serving it will
be converted in binary mode, because the binary format data only is supported
by the channels. The process of converting the object into binary format is called
as Marshalling.
That remote class should be sub class of System.MarshalByRefObject
class; because the reference is to be passed to the client, instead of copying the
object into the client.
Server Object Modes:
1. SingleCall: A new object will be created for every client request.
2. SingleTon: The object will be created for the first client request; and
the same object will be served for all other client requests.


RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteClass), "alias_name",
WellKnownObjectMode.SingleCall / SingleTon);





.NET 4.0 and Visual Studio 2010 Page 468 of 548
D. HARSHA VARDHAN

iv. Client Activated Object
The object reference, which acts as reference to the server object.
It can also be called as Proxy.
It is nothing but the variable, created for the remote interface.
To get the reference of server object into a proxy:




In the above syntax, irem is the proxy.
Based on the given url, the server activated object reference will be received and
it will be assigned into irem.
The irem can call the methods of the server object.
Note: The port no is a 4 digit number, which should be greater than 1024.
We have to use a common port no in the client application and server
application.

IRemote irem;
irem = (IRemote)Activator.GetObject(typeof(IRemote), tcp://server:port/alias_name);





.NET 4.0 and Visual Studio 2010 Page 469 of 548
D. HARSHA VARDHAN

.NET Remoting




+ First, we have to create the database first.
+ Open SQL Server 2005.
+ Right click on Databases New Database Enter the database name as
RemotingTest Click OK.
+ Expand RemotingTest database Right click on Tables Select New Table.
+ Create the table as follows:

+ Save the table name as Users.
+ Expand RemotingTest Tables.
+ Right click on the Users table and choose Open Table.
+ Enter some sample data.
Application 151: Demo on .NET Remoting





.NET 4.0 and Visual Studio 2010 Page 470 of 548
D. HARSHA VARDHAN



+ Open Visual Studio 2010.
+ Create a new Console Application.
Name: RemoteServer
Location: E:\C#Apps
+ Open the solution explorer.
+ Right click on the solution; click Add New Project.
+ Select Visual C# Class Library.
Name: RemoteLibrary
+ Click on OK.
+ Right click on Class1.cs and delete it. Click on OK for confirmation.
+ Right click on RemoteLibrary and choose Add New Item.
+ Select Interface.
+ Enter the name as IRemote.
+ Click on Add.
+ Type the code in IRemote.cs.






.NET 4.0 and Visual Studio 2010 Page 471 of 548
D. HARSHA VARDHAN












+ Right click on RemoteServer and select Add Reference.
+ Select Projects RemoteLibrary.
+ Click on OK.
+ Then the reference of RemoteLibrary will be added to the RemoteServer console
application.
+ Now, we have to configure the connection string in App.config file.
+ Right click on 3TierArchitectureDemo Add New Item Application Configuration
File Add.
+ Then App.config file will be added. Then type the code as follows:








+ Right click on RemoteServer and select Add Class.
+ Enter the class name as DatabaseLogic and click on Add.
+ Then type the code in DatabaseLogic.cs file.



IRemote.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RemoteLibrary
{
public interface IRemote
{
bool CheckUserAvailability(string UserName);
}
}

App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="RemoteDatabase" value="user id=sa;password=123;data
source=localhost;initial catalog=RemotingTest"/>
</appSettings>
</configuration>





.NET 4.0 and Visual Studio 2010 Page 472 of 548
D. HARSHA VARDHAN



























+ Right click on RemoteServer and select Add Class.
+ Enter the class name as RemoteClass and click on Add.
+ Then type the code in RemoteClass.cs file.






Datab ba as se eL Lo og gi ic c.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace RemoteServer
{
class DatabaseLogic
{
public DataTable GetUsers(string Username)
{
//connection logic
string cnstr = ConfigurationSettings.AppSettings["RemoteDatabase"];
SqlConnection cn = new SqlConnection(cnstr);

//stmt logic
string sqlstr = "select * from users where username= ' " + Username + " ' ";

//adapter logic
SqlDataAdapter adp = new SqlDataAdapter(sqlstr, cn);
DataSet ds = new DataSet();
adp.Fill(ds);

//datatable logic
DataTable dt;
dt = ds.Tables[0];

return (dt);
}
}
}






.NET 4.0 and Visual Studio 2010 Page 473 of 548
D. HARSHA VARDHAN























+ In the solution explorer, right click on RemoteServer and choose Add Reference.
+ Select .NET System.Runtime.Remoting.
+ Click on OK.
+ Open the Program.cs from Solution Explorer.
+ Type the following code in Program.cs.







RemoteClass.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace RemoteServer
{
class RemoteClass: MarshalByRefObject, RemoteLibrary.IRemote
{
public bool CheckUserAvailability(string UserName)
{
DatabaseLogic dbl = new DatabaseLogic();
DataTable dt = dbl.GetUsers(UserName);
bool b;
if (dt.Rows.Count > 0)
{
//user data found.
b = false;
}
else
{
//user data not found.
b = true;
}
return (b);
}
}
}





.NET 4.0 and Visual Studio 2010 Page 474 of 548
D. HARSHA VARDHAN




















+ Note: The port no should be same for server and client application.
+ Run the application. Now, the server application is ready.
+ Now, we need to continue with client application development.

Client Application Development:
+ Create a new Windows Application Project.
Name: RemoteClient
+ Go to Project menu Add Reference. Select .NET System.Runtime.Remoting
Click on OK.
+ Again go to Project menu Add Reference. Select Browse Then select the
E:\C#Apps\RemoteServer\RemoteLibrary\bin\Debug\RemoLibrary.dll file Click on OK.
+ Design the form as shown:



Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace RemoteServer
{
class Program
{
static void Main(string[] args)
{
TcpServerChannel tsc = new TcpServerChannel(1234);
ChannelServices.RegisterChannel(tsc);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteClass),
"MyRemoteTest", WellKnownObjectMode.Singleton);
Console.WriteLine("Server started...\nPress Enter to stop!");
Console.Read();
ChannelServices.UnregisterChannel(tsc);
}
}
}






.NET 4.0 and Visual Studio 2010 Page 475 of 548
D. HARSHA VARDHAN



+ Write the code in the form:

















Form1.cs:

using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using RemoteLibrary;

private void button1_Click(object sender, EventArgs e)
{
TcpClientChannel tcc = new TcpClientChannel();
ChannelServices.RegisterChannel(tcc);
string url = "tcp://localhost:1234/MyRemoteTest";
IRemote irem;
irem = (IRemote)Activator.GetObject(typeof(IRemote), url);
bool result = irem.CheckUserAvailability(textBox1.Text);
if (result == true)
{
label3.Visible = true;
label3.Text = "Available!";
label3.ForeColor = Color.Green;
}
else
{
label3.Visible = true;





.NET 4.0 and Visual Studio 2010 Page 476 of 548
D. HARSHA VARDHAN






+ Then finally run the server application first. While it is running, then run the client
application.
+ Note: Without running the server application, client application will not work.

label3.Text = "Not Available!";
label3.ForeColor = Color.Red;
}
ChannelServices.UnregisterChannel(tcc);
}





.NET 4.0 and Visual Studio 2010 Page 477 of 548
D. HARSHA VARDHAN

Network Programming using Sockets

It includes with sending / receiving messages from server-to-client or client-to-sever on a
network, using Sockets technology.
The Socket Programming uses TCP protocol.
This is meant for Chatting Applications.

Library:
1) System.Net.Sockets
2) Some classes from System.IO


Implementation of Network Programming

i) Sending Messages to a System:
A chatting application includes with sending / receiving messages on the network. This
topic includes with sending a message to the specified host on the network. The host can
be recognized with the host name or IP address. The default IP address for
standalone systems is, 127.0.0.1. This requires to use a port no also. The port no is a 4
digit number, which should be greater than 1024.

Library: 1) System.Net.Sockets.TcpClient
This class object represents a client system on the network.
2) System.Net.Sockets.NetworkStream
This class object represents a stream on the network, which is able to
send the messages.

Implementation:
Import the API:
using System.Net.Sockets;
Construct TcpClient class object:
TcpClient tc = new TcpClient(host name, port no);





.NET 4.0 and Visual Studio 2010 Page 478 of 548
D. HARSHA VARDHAN

Note: Here you have to give target system (receiver system)
name. That means, the tc object represents the receiver
system here.
Get the network stream from TcpClient class object:
NetworkStream ns = tc.GetStream();
Write a byte on the network stream (send the byte to the target host):
ns.WriteByte(byte value);
Close the network stream:
ns.Close();
Close the tcp client:
tc.Close();



ii) Receiving Messages from a System:
This topic includes with receiving a message, sent for a specified host.

Library: 1) System.Net.Sockets.TcpListener
This class object is used to listen the message that is sent to the host.
2) System.Net.Sockets.TcpClient
This class object represents a client system on the network.
3) System.Net.Sockets.NetworkStream
This class object represents a stream on the network, which is able to
receive the messages.
4) System.IO.StreamReader
This class object represents a stream, which is able to receive the
messages.

Implementation:
Import the API:
using System.Net.Sockets;
using System.IO;
Construct TcpListener class object:
TcpListener tl = new TcpListener(ip address, port no);





.NET 4.0 and Visual Studio 2010 Page 479 of 548
D. HARSHA VARDHAN

Note: Here, you have to give the self system IP address
(receiver system IP address); and the same port no,
which you are using in the server application.

Start the listener:
tl.Start();
Accept the connected client and construct TcpClient class object:
TcpClient tc = tl.AcceptTcpClient();
Note: The above method will be executed after sending the
message from the sender system. Then the
AcceptTcpClient method returns the reference of the
sender system. That reference will be assigned into
TcpClient class object. That means, the tc object
represents the sender system.

Get the network stream from TcpClient class object:
NetworkStream ns = tc.GetStream();
Construct the StreamReader class object:
StreamReader sr = new StreamReader(ns);
Note: Here, you are using StreamReader; because
NetworkStream class doesnt support ReadToEnd()
method. So that if you are using NetworkStream, you
have to read the message byte-by-byte.
Write a byte on the network stream (send the byte to the target host):
string message = sr.ReadToEnd();
Close the network stream:
ns.Close();
Close the tcp client:
tc.Close();
Stop the listener:
tl.Stop();








.NET 4.0 and Visual Studio 2010 Page 480 of 548
D. HARSHA VARDHAN




Message Sender Application:













Note: In this code, the ASCII.GetBytes() method converts the given string value as an array of
bytes. This is required because, using WriteByte() method, you can pass the byte values
only.


Application 152: Demo on Message Passing between Client and Server using Sockets
using System.Net.Sockets;
private void btnSend_Click(object sender, EventArgs e)
{
string host = txtHost.Text;
string message = txtMessage.Text;
TcpClient tc = new TcpClient(host, 2025);
NetworkStream ns = tc.GetStream();
byte[] bytesarray = Encoding.ASCII.GetBytes(message);
foreach (byte b in bytesarray)
ns.WriteByte(b);
ns.Close();
tc.Close();
}





.NET 4.0 and Visual Studio 2010 Page 481 of 548
D. HARSHA VARDHAN


Message Receiver Application:


















using System.Net.Sockets;
using System.IO;
using System.Net;
private void btnStartListener_Click(object sender, EventArgs e)
{
TcpListener tl = new TcpListener(IPAddress.Parse("127.0.0.1"), 2025);
tl.Start();
TcpClient tc = tl.AcceptTcpClient();
NetworkStream ns = tc.GetStream();
StreamReader sr = new StreamReader(ns);
string receivedmessage = sr.ReadToEnd();
txtMessage.Text = receivedmessage;
ns.Close();
tc.Close();
tl.Stop();
}





.NET 4.0 and Visual Studio 2010 Page 482 of 548
D. HARSHA VARDHAN

Execution Steps:
1) First, run the Receiver application.
2) Click on Start Listener button.
3) Then run the Sender application.
4) Enter the host name as localhost / any system name on the network / IP address of
any system on the network / or the default IP address 127.0.0.1
5) Enter any message in the textbox.
6) Click on Send button.
7) Then the message will be appeared in the receiver application.

Note: ** Try to implement chatting application, with two-way interaction **






.NET 4.0 and Visual Studio 2010 Page 483 of 548
D. HARSHA VARDHAN

W Wi in nd do ow ws s S Se er rv vi ic ce es s

A windows service like a background-processed application.
It will be installed on the Services, and will be registered on the windows registry.
To open the list of currently installed services on your system, click on Start Control
Panel Administrative Tools Services.
Ex: Windows Time, Windows Audio, Plug and Play, Chatting services, anti-virus services,
database services etc.









D. HARSHA VARDHAN






.NET 4.0 and Visual Studio 2010 Page 484 of 548
D. HARSHA VARDHAN

F Fe ea at tu ur re es s o of f W Wi in nd do ow ws s S Se er rv vi ic ce es s

The windows service is configured to run on windows o/s only.
Most of the windows services will be started automatically, at system logon and will be
shut-down at system logoff.
Some other windows services can be configured to be started manually. To start / stop
the services, open Services window as shown above. Then right click on the required
service and choose Start / Stop option.
The windows services are best compatible with Threading; so that you are
recommended to write your code in threading.
The windows service cant contain any windows forms.
It is able to show a tray icon on the system tray (at windows taskbar).
It cant be run directly on your Visual Studio.
It is able to interact with Event Log service on the Windows operating system.
After the development of your application code in the windows service, you need a utility
software, called installutil.exe, which is used to install your windows service on the
system.
Before installing the service, it requires ProjectInstaller class, which provides additional
information, i.e. required for installing your service with installutil.exe.





.NET 4.0 and Visual Studio 2010 Page 485 of 548
D. HARSHA VARDHAN

D De ev ve el lo op pm me en nt t o of f W Wi in nd do ow ws s S Se er rv vi ic ce es s

For a better demonstration, we start with a demo application on this.





S St ta ag ge e 1 1: : C Cr re ea at ti in ng g a a W Wi in nd do ow ws s S Se er rv vi ic ce e

Open Visual Studio 2008.
Click on File New Project.
Select Windows Windows Service.
Name: MyWindowsService
Location: D:\
Click on OK.
Then windows service project will be created with the specified name and specified
location.
Then screen will be displayed like this:
You cant design anything, but you can add a notify icon, and that will be displayed in
the system tray, while the service is running.
To do this, open ToolBox and drag and drop the NotifyIcon control into the gray
colored area.
Set the following properties for NotifyIcon control.
Icon: any icon file. (Ex: system.ico)
Text: any text (Ex: My Windows Service)








Application 153: A Simple Demo on Windows Services





.NET 4.0 and Visual Studio 2010 Page 486 of 548
D. HARSHA VARDHAN


But especially when you set the Icon property, you cant compile your project
successfully, because it requires the System.Drawing assembly reference. But the
problem is, by default the System.Drawing assembly will not be added to the windows
services.
So that, simply you have to add the reference of System.Drawing assembly, by clicking
on Project menu Add Reference System.Drawing and clicking on OK.
Enter into the code window by pressing F7 (or) by right clicking and selecting View
Code option.
Write the following code, which writes an event log message at every 3 seconds.








using System.Threading;

namespace MyWindowsService
{
public partial class Service1 : ServiceBase
{
public Service1()
{





.NET 4.0 and Visual Studio 2010 Page 487 of 548
D. HARSHA VARDHAN





















Note: The event handlers for OnStart and OnStop events will be created
automatically. The OnStart event will be executed on starting the windows service; and
the OnStop event will be executed on stopping the windows
service.
Set the following properties for Service1:
ServiceName: My Windows Service
Up to this, windows service coding is over.
Then you need to add Installer for your windows service.
To do this, simply come back to the Design view and right click and then choose Add
Installer option.
Then you will have ProjectInstaller class in your project, along with two components
called serviceProcessInstaller1 and
serviceInstaller1.
Set the following properties for
InitializeComponent();
}

Thread th1;

protected override void OnStart(string[] args)
{
th1 = new Thread(WriteMessage);
th1.Start();
}

protected override void OnStop()
{
th1.Abort();
}

private void WriteMessage()
{
while (true)
{
string msg = "This message is generated using Windows Service!! Now, the
time is " + DateTime.Now.ToString();
System.Diagnostics.EventLog.WriteEntry("My Windows Service", msg);
Thread.Sleep(3000);
}
}
}
}






.NET 4.0 and Visual Studio 2010 Page 488 of 548
D. HARSHA VARDHAN

serviceProcessInstaller1:
Account: LocalSystem
Set the following properties for serviceInstaller1:
ServiceName: My Windows Service
Description: This is for demo purpose.
StartType: Automatic
Finally, Build the project. Then the MyWindowsService.exe file will be created in the
bin\Debug folder.


S St ta ag ge e 2 2: : I In ns st ta al ll li in ng g t th he e W Wi in nd do ow ws s S Se er rv vi ic ce e

To install your windows service, you require to use installutil.exe utility software, which
will be loaded into your system along with Visual Studio.
To do this, simply open Visual Studio Command Prompt by clicking on Start
Programs Microsoft Visual Studio 2010 Visual Studio Tools Visual Studio
Command Prompt (2010).
Then enter the following command.

installutil D:\MyWindowsService\MyWindowsService\bin\Debug\MyWindowsService.exe

On successful installation of your service, you will have the following messages at last:
The Commit phase completed successfully.
The transacted install has completed.
To confirm the service installation, open the Services window, by clicking on Start
Control Panel Administrative Tools Services.





.NET 4.0 and Visual Studio 2010 Page 489 of 548
D. HARSHA VARDHAN


You can see the service name called My Windows Service. It will be started
automatically, at system startup, because you already set the Startup Type as
Automatic.
To enable your service to be interacted with the desktop and create visual actions on
your system (Ex: displaying tray icons, displaying windows etc.), right click on the service
and choose Properties. Then click on Log on tab. There, select Allow service to
interact with desktop option; and finally click on OK.


S St ta ag ge e 3 3: : S St ta ar rt ti in ng g t th he e W Wi in nd do ow ws s S Se er rv vi ic ce e

To start the windows service now, simply right click on the service in the Services
window, and choose Start option.
Then the service will be started and it will be executed.
Output: (Control Panel Administrative Tools Event Viewer)




S St ta ag ge e 4 4: : S St to op pp pi in ng g t th he e W Wi in nd do ow ws s S Se er rv vi ic ce e

To stop the windows service now, simply right click on the service in the Services
window, and choose Stop option.
Then the service will be stopped.







.NET 4.0 and Visual Studio 2010 Page 490 of 548
D. HARSHA VARDHAN


S St ta ag ge e 5 5: : U Un n- -i in ns st ta al ll li in ng g t th he e W Wi in nd do ow ws s S Se er rv vi ic ce e

To un-install your windows service, simply open Visual Studio Command Prompt again,
by clicking on Start Programs Microsoft Visual Studio 2010 Visual Studio
Tools Visual Studio Command Prompt (2010).
Then enter the following command.

installutil/u D:\MyWindowsService\MyWindowsService\bin\Debug\MyWindowsService.exe

On successful installation of your service, you will have the following messages at last:

Service My Windows Service was successfully removed from the system.
The uninstall has completed.






.NET 4.0 and Visual Studio 2010 Page 491 of 548
D. HARSHA VARDHAN




S St ta ag ge e 1 1: : C Cr re ea at ti in ng g t th he e W Wi in nd do ow ws s S Se er rv vi ic ce e

Create the windows service.
o Name: ChatService
o Location: D:\
Drag and drop the NotifyIcon control and set the following properties:
Icon: satellite.ico
Text: Chat Service
Add the reference of System.Drawing to the project.
Write the following code in the code window.





















Application 154: Chat Service Application
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace ChatService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}

Thread th1;

protected override void OnStart(string[] args)
{
th1 = new Thread(StartListener);
th1.Start();
}

protected override void OnStop()
{
th1.Abort();
}

private void StartListener()
{





.NET 4.0 and Visual Studio 2010 Page 492 of 548
D. HARSHA VARDHAN






















Set the following properties for Service1:
ServiceName: Chat Service
Right click and then choose Add Installer option.
Then you will have ProjectInstaller class in your project, along with two components
called serviceProcessInstaller1 and serviceInstaller1.
Set the following properties for serviceProcessInstaller1:
Account: LocalSystem
Set the following properties for serviceInstaller1:
ServiceName: Chat Service
Description: This is for chatting.
StartType: Automatic
Finally, Build the project. Then the ChatService.exe file will be created in the
bin\Debug folder.
while (true)
{
//start listener
TcpListener tl = new TcpListener(IPAddress.Parse("127.0.0.1"), 2025);
tl.Start();
TcpClient tc = tl.AcceptTcpClient();
//get the message
NetworkStream ns = tc.GetStream();
StreamReader sr = new StreamReader(ns);
string receivedmessage = sr.ReadToEnd();
//stop listener
ns.Close();
tc.Close();
tl.Stop();
//write the message to a file
string filename = "d:\\message.txt";
FileInfo fobj = new FileInfo(filename);
if (fobj.Exists)
fobj.Delete();
StreamWriter sw = new StreamWriter(filename);
sw.WriteLine(receivedmessage);
sw.Close();
//open message receiver application
System.Diagnostics.Process.Start("D:\\MessageReceiver\\MessageReceiver\\bin\\Debug\\M
essageReceiver.exe");
}
}
}
}





.NET 4.0 and Visual Studio 2010 Page 493 of 548
D. HARSHA VARDHAN


Creating Windows Forms Application
Now, you need to create a windows application, which is associated with this application.
Name: MessageReceiver
Location: D:\














S St ta ag ge e 2 2: : I In ns st ta al ll li in ng g t th he e W Wi in nd do ow ws s S Se er rv vi ic ce e

Open Visual Studio Command Prompt by clicking on Start Programs Microsoft
Visual Studio 2010 Visual Studio Tools Visual Studio Command Prompt (2010).
Then enter the following command.

installutil D:\ChatService\ChatService\bin\Debug\ChatService.exe

using System.IO;
private void Form1_Load(object sender, EventArgs e)
{
string filename = "d:\\message.txt";
FileInfo fobj = new FileInfo(filename);
if (fobj.Exists)
{
StreamReader sr = new StreamReader(filename);
string msg = sr.ReadToEnd();
sr.Close();
txtMessage.Text = msg;
}
}





.NET 4.0 and Visual Studio 2010 Page 494 of 548
D. HARSHA VARDHAN

To confirm the service installation, open the Services window, by clicking on Start
Control Panel Administrative Tools Services.
You can see the service name called Chat Service. It will be started automatically, at
system startup, because you already set the Startup Type as Automatic.
Right click on the service and choose Properties. Then click on Log on tab. There,
select Allow service to interact with desktop option; and finally click on OK.

S St ta ag ge e 3 3: : S St ta ar rt ti in ng g t th he e W Wi in nd do ow ws s S Se er rv vi ic ce e
To start the windows service now, simply right click on the service in the Services
window, and choose Start option.
Then the service will be started and it will be executed.
Running the Application:
Open the TcpSender application (you have already developed it in the previous
chapter).
Enter the host name and message and click on Send button.
Then the given message will be appeared in the MessageReceier application
automatically.














S St ta ag ge e 4 4: : S St to op pp pi in ng g t th he e W Wi in nd do ow ws s S Se er rv vi ic ce e

To stop the windows service now, simply right click on the service in the Services
window, and choose Stop option.
Then the service will be stopped.









.NET 4.0 and Visual Studio 2010 Page 495 of 548
D. HARSHA VARDHAN

S St ta ag ge e 5 5: : U Un n- -i in ns st ta al ll li in ng g t th he e W Wi in nd do ow ws s S Se er rv vi ic ce e

To un-install your windows service, simply open Visual Studio Command Prompt again,
by clicking on Start Programs Microsoft Visual Studio 2010 Visual Studio
Tools Visual Studio Command Prompt (2010). Then enter the following command.

installutil/u D:\ChatService\ChatService\bin\Debug\ChatService.exe






.NET 4.0 and Visual Studio 2010 Page 496 of 548
D. HARSHA VARDHAN

P Pa ac ck ka ag ge e a an nd d D De ep pl lo oy ym me en nt t
+ After development of your application, finally you have to generate the Setup program, and
it can be given to the client.
+ The user (client) has to install the project, simply by double clicking on the Setup.exe file.
+ On installing the project in the client system, the following changes will be made in that
system:
Then the necessary files (such as exe files, dll files, images, configuration files) will be
copied in the c:\Program Files folder in that client system.
The necessary shortcuts to run the application will be created at the users desktop and
programs menu.







Development of Setup Project:
+ Create a new Windows Forms Application.
Name: DeploymentTest
+ Design the form as follows.
Application 155: Demo on Package and Deployment





.NET 4.0 and Visual Studio 2010 Page 497 of 548
D. HARSHA VARDHAN









+ Right click on the solution and choose Add New Project.
+ Select Other Project Types Setup and Deployment - Visual Studio Installer -
Setup Project.
+ Enter the name of the project. Ex: Deployment Test 1.0

private void timer1_Tick(object sender, EventArgs e)
{
if (label1.Visible == true)
label1.Visible = false;
else
label1.Visible = true;
}





.NET 4.0 and Visual Studio 2010 Page 498 of 548
D. HARSHA VARDHAN
























.NET 4.0 and Visual Studio 2010 Page 499 of 548
D. HARSHA VARDHAN

+ Then the following screen will be displayed.


+ Right click on Application
Folder option in the left side
panel and choose Add
Project Output.
+ Select the project name.
Ex: DeploymentTest.
+ Select Primary output.
+ Click on OK.
+ Right click on Primary output
from DeploymentTest (Active)
and select Create shortcut to
Primary output from
DeploymentTest (Active)
option.





.NET 4.0 and Visual Studio 2010 Page 500 of 548
D. HARSHA VARDHAN

+ Then the shortcut will be created in the same folder.
+ Rename the shortcut as your wish. Ex: Deployment Test 1.0
+ Set the Icon property if required.
+ Drag and drop the shortcut into Users Desktop folder.
+ Create another shortcut (same as above). Rename it as your wish. Ex: Deployment Test
1.0. Then set the Icon property for the shortcut.
+ Drag and drop that shortcut into Users Programs Menu folder.
+ In the Solution Explorer, right click on the Deployment Test 1.0 and choose Rebuild.
+ Then the setup files will be generated in the Debug folder of the project. To open the
folder, right click on DeployementTest and select Open Folder is Windows Explorer.




Installing the Project:

+ To install the application, simply double click on the Setup file and complete the wizard
steps.





.NET 4.0 and Visual Studio 2010 Page 501 of 548
D. HARSHA VARDHAN



Un-Installing the Project:

+ To un-install the project, go to Add/Remove Programs option in the Control Panel.
(or)
+ Double click on setup.exe file again and select Remove option.


Issuing the Project to the Client:

+ To issue the project to the client, simply issue the following two files.
1. setup.exe
2. Deployment Test 1.0.msi

Known Limitation: The above setup.exe file carries all the necessary executable files, dll files,
images, icons, App.config files etc., but cant carry the database tables and stored procedures.
You have to use Import / Export given by the DBMS software (SQL Server / Oracle).





.NET 4.0 and Visual Studio 2010 Page 502 of 548
D. HARSHA VARDHAN



C C# #. .N NE ET T 4 4. .0 0


F
F
r
r
e
e
q
q
u
u
e
e
n
n
t
t
l
l
y
y

A
A
s
s
k
k
e
e
d
d

Q
Q
u
u
e
e
s
s
t
t
i
i
o
o
n
n
s
s

(
(
F
F
A
A
Q
Q

s
s
)
)






.NET 4.0 and Visual Studio 2010 Page 503 of 548
D. HARSHA VARDHAN

.NET Framework FAQ's

When was .NET announced?
Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET 'vision'. The July 2000
PDC had a number of sessions on .NET technology, and delegates were given CDs containing a pre-release
version of the .NET framework/SDK and Visual Studio.NET.

When was the first version of .NET released?
The final version of the 1.0 SDK and runtime was made publicly available around 6pm PST on 15-Jan-
2002. At the same time, the final version of Visual Studio.NET was made available to MSDN subscribers.

What platforms does the .NET Framework run on?
The runtime supports Windows XP, Windows 2000, NT4 SP6a and Windows ME/98. Windows 95 is not
supported. Some parts of the framework do not work on all platforms - for example, ASP.NET is only
supported on Windows XP and Windows 2000. Windows 98/ME cannot be used for development.

IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.NET. However, the
ASP.NET Web Matrix web server does run on XP Home. The Mono project is attempting to implement the
.NET framework on Linux.

What is the CLR?
CLR = Common Language Runtime. The CLR is a set of standard resources that (in theory) any .NET program
can take advantage of, regardless of programming language. Robert Schmidt (Microsoft) lists the following
CLR resources in his MSDN PDC# article:

Object-oriented programming model (inheritance, polymorphism, exception handling, garbage
collection)
Security model
Type system
All .NET base classes
Many .NET framework classes
Development, debugging, and profiling tools
Execution and code management
IL-to-native translators and optimizers

What this means is that in the .NET world, different programming languages will be more equal in capability
than they have ever been before, although clearly not all languages will support all CLR services.






.NET 4.0 and Visual Studio 2010 Page 504 of 548
D. HARSHA VARDHAN

What is the CTS?
CTS = Common Type System. This is the range of types that the .NET runtime understands, and therefore that
.NET applications can use. However note that not all .NET languages will support all the types in the CTS.
The CTS is a superset of the CLS.

What is the CLS?
CLS = Common Language Specification. This is a subset of the CTS which all .NET languages are expected
to support. The idea is that any program which uses CLS-compliant types can interoperate with any .NET
program written in any language.

In theory this allows very tight interop between different .NET languages - for example allowing a C# class
to inherit from a VB class.

What is IL?
IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or CIL (Common
Intermediate Language). All .NET source code (of any language) is compiled to IL. The IL is then converted to
machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.

What does 'managed' mean in the .NET context?
The term 'managed' is the cause of much confusion. It is used in various places within .NET, meaning slightly
different things.

Managed code: The .NET framework provides several core run-time services to the programs that run within
it - for example exception handling and security. For these services to work, the code must provide a
minimum level of information to the runtime.

Such code is called managed code. All C# and Visual Basic.NET code is managed by default. VS7 C++
code is not managed by default, but the compiler can produce managed code by specifying a command-
line switch (/com+).

Managed data: This is data that is allocated and de-allocated by the .NET runtime's garbage collector. C#
and VB.NET data is always managed. VS7 C++ data is unmanaged by default, even when using the /com+
switch, but it can be marked as managed using the __gc keyword. Managed classes: This is usually referred
to in the context of Managed Extensions (ME) for C++.

When using ME C++, a class can be marked with the __gc keyword. As the name suggests, this means that
the memory for instances of the class is managed by the garbage collector, but it also means more than that.
The class becomes a fully paid-up member of the .NET community with the benefits and restrictions that





.NET 4.0 and Visual Studio 2010 Page 505 of 548
D. HARSHA VARDHAN

brings. An example of a benefit is proper interop with classes written in other languages - for example, a
managed C++ class can inherit from a VB class. An example of a restriction is that a managed class can
only inherit from one base class.

What is reflection?
All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is
packaged along with the module (modules in turn are packaged together in assemblies), and can be
accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be
used to interrogate the types for a module/assembly.

Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library
data in COM, and it is used for similar purposes - e.g. determining data type sizes for marshaling data
across context/process/machine boundaries.

Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create
types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).

What is the difference between Finalize and Dispose (Garbage collection)?
Class instances often encapsulate control over resources that are not managed by the runtime, such as
window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit
and an implicit way to free those resources. Provide implicit control by implementing the protected Finalize
Method on an object (destructor syntax in C# and the Managed Extensions for C++). The garbage collector
calls this method at some point after there are no longer any valid references to the object. In some cases,
you might want to provide programmers using an object with the ability to explicitly release these external
resources before the garbage collector frees the object. If an external resource is scarce or expensive,
better performance can be achieved if the programmer explicitly releases resources when they are no
longer being used. To provide explicit control, implement the Dispose method provided by the IDisposable
Interface. The consumer of the object should call this method when it is done using the object. Dispose can be
called even if other references to the object are alive. Note that even when you provide explicit control by
way of Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to
prevent resources from permanently leaking if the programmer fails to call Dispose.

What is Partial Assembly References?
Full Assembly reference: A full assembly reference includes the assembly's text name, version, culture, and
public key token (if the assembly has a strong name). A full assembly reference is required if you reference
any assembly that is part of the common language runtime or any assembly located in the global assembly
cache. Partial Assembly reference: We can dynamically reference an assembly by providing only partial





.NET 4.0 and Visual Studio 2010 Page 506 of 548
D. HARSHA VARDHAN

information, such as specifying only the assembly name. When you specify a partial assembly reference, the
runtime looks for the assembly only in the application directory.

We can make partial references to an assembly in your code one of the following ways:
Use a method such as System.Reflection.Assembly.Load and specify only a partial reference. The
runtime checks for the assembly in the application directory.
Use the System.Reflection.Assembly.LoadWithPartialName method and specify only a partial
reference. The runtime checks for the assembly in the application directory and in the global
assembly cache.

Changes to which portion of version number indicates an incompatible change?
Major or minor. Changes to the major or minor portion of the version numb er indicate an incompatible
change. Under this convention then, version 2.0.0.0 would be considered incompatible with version 1.0.0.0.
Examples of an incompatible change would be a change to the types of some method parameters or the
removal of a type or method altogether. Build. The Build number is typically used to distinguish between
daily builds or smaller compatible releases.

Revision. Changes to the revision number are typically reserved for an incremental build needed to fix a
particular bug. You'll sometimes hear this referred to as the "emergency bug fix" number in that the revision
is what is often changed when a fix to a specific bug is shipped to a customer.



C#.NET FAQ:

1. Whats the implicit name of the parameter that gets passed into the class set method?
Value, and its datatype depends on whatever variable were changing.
2. How do you inherit from a class in C#?
Place a colon and then the name of the base class. Notice that its double colon in C++.
3. Does C# support multiple inheritance?
No, use interfaces instead.
4. When you inherit a protected class-level variable, who is it available to?
Classes in the same namespace.





.NET 4.0 and Visual Studio 2010 Page 507 of 548
D. HARSHA VARDHAN

5. Are private class-level variables inherited?
Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited.
But they are.
6. Describe the accessibility modifier protected internal.
Its available to derived classes and classes within the same Assembly (and naturally from the base
class its declared in).
7. C# provides a default constructor for me. I write a constructor that takes a string as a
parameter, but want to keep the no parameter one. How many constructors should I write?
Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have
to write one yourself, even if theres no implementation in it.
8. Whats the top .NET class that everything is derived from?
System.Object.
9. Hows method overriding different from overloading?
When overriding, you change the method behavior for a derived class. Overloading simply
involves having a method with the same name within the class.
10. What does the keyword virtual mean in the method definition?
The method can be over-ridden.
11. Can you declare the override method static while the original method is non-static?
No, you cant, the signature of the virtual method must remain the same, only the keyword virtual is
changed to keyword override.
12. Can you override private virtual methods?
No, moreover, you cannot access private methods in inherited classes, have to be protected in the
base class to allow any sort of access.





.NET 4.0 and Visual Studio 2010 Page 508 of 548
D. HARSHA VARDHAN

13. Can you prevent your class from being inherited and becoming a base class for some other
classes?
Yes, thats what keyword sealed in the class definition is for. The developer trying to derive from
your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. Its the
same concept as final class in Java.
14. Can you allow class to be inherited, but prevent the method from being over-ridden?
Yes, just leave the class public and make the method sealed.
15. Whats an abstract class?
A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that
must be inherited and have the methods over-ridden. Essentially, its a blueprint for a class without
any implementation.
16. When do you absolutely have to declare a class as abstract (as opposed to free-willed
educated choice or decision based on UML diagram)?
When at least one of the methods in the class is abstract. When the class itself is inherited from an
abstract class, but not all base abstract methods have been over-ridden.
17. Whats an interface class?
Its an abstract class with public abstract methods all of which must be implemented in the inherited
classes.
18. Why cant you specify the accessibility modifier for methods inside the interface?
They all must be public. Therefore, to prevent you from getting the false impression that you have
any freedom of choice, you are not allowed to specify any accessibility, its public by default.
19. Can you inherit multiple interfaces?
Yes, why not.







.NET 4.0 and Visual Studio 2010 Page 509 of 548
D. HARSHA VARDHAN

20. And if they have conflicting method names?
Its up to you to implement the method inside your own class, so implementation is left entirely up to
you. This might cause a problem on a higher-level scale if similarly named methods from different
interfaces expect different data, but as far as compiler cares youre okay.
21. Whats the difference between an interface and abstract class?
In the interface all methods must be abstract; in the abstract class some methods can be concrete. In
the interface no accessibility modifiers are allowed, which is ok in abstract classes.
22. How can you overload a method?
Different parameter data types, different number of parameters, different order of parameters.
23. If a base class has a bunch of overloaded constructors, and an inherited class has another
bunch of overloaded constructors, can you enforce a call from an inherited constructor to an
arbitrary base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate
constructor) in the overloaded constructor definition inside the inherited class.
24. Whats the difference between System.String and System.StringBuilder classes?
System.String is immutable; System.StringBuilder was designed with the purpose of having a
mutable string where a variety of operations can be performed.
25. Whats the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings
are immutable, so each time its being operated on, a new instance is created.
26. Can you store multiple data types in System.Array?
No.
27. Whats the difference between the System.Array.CopyTo() and System.Array.Clone()?
The first one performs a deep copy of the array, the second one is shallow.





.NET 4.0 and Visual Studio 2010 Page 510 of 548
D. HARSHA VARDHAN

28. How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
29. Whats the .NET datatype that allows the retrieval of data by a unique key?
HashTable.
30. Whats class SortedList underneath?
A sorted HashTable.
31. Will finally block get executed if the exception had not occurred?
Yes.
32. Whats the C# equivalent of C++ catch (), which was a catch-all statement for any possible
exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter
data type in this case and just write catch {}.
33. Can multiple catch blocks be executed?
No, once the proper catch code fires off, the control is transferred to the finally block (if there are
any), and then whatever follows the finally block.
34. Why is it a bad idea to throw your own exceptions?
Well, if at that point you know that an error has occurred, then why not write the proper code to
handle that error instead of passing a new Exception object to the catch block? Throwing your own
exceptions signifies some design flaws in the project.
35. Whats a delegate?
A delegate object encapsulates a reference to a method. In C++ they were referred to as function
pointers.






.NET 4.0 and Visual Studio 2010 Page 511 of 548
D. HARSHA VARDHAN

36. Whats a multicast delegate?
Its a delegate that points to and eventually fires off several methods.
37. Hows the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run (which was
available under Win32), but also the version of the assembly.
38. What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.
39. Whats a satellite assembly?
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core
application separately from the localized modules, the localized assemblies that modify the core
application are called satellite assemblies.
40. What namespaces are necessary to create a localized application?
System.Globalization, System.Resources.
41. Whats the difference between // comments, /* */ comments and /// comments?
Single-line, multi-line and XML documentation comments.
42. How do you generate documentation from the C# file commented properly with a command-
line compiler?
Compile it with a /doc switch.
43. Whats the difference between <c> and <code> XML documentation tag?
Single line code example and multiple-line code example.
44. Is XML case-sensitive?
Yes, so <Student> and <student> are different elements.





.NET 4.0 and Visual Studio 2010 Page 512 of 548
D. HARSHA VARDHAN

45. What debugging tools come with the .NET SDK?
CorDBG command-line debugger, and DbgCLR graphic debugger. Visual Studio .NET uses the
DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.
46. What does the This window show in the debugger?
It points to the object thats pointed to by this reference. Objects instance data is shown.
47. What does assert() do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error
dialog if the condition is false. The program proceeds without any interruption if the condition is
true.
48. Whats the difference between the Debug class and Trace class? Documentation looks the
same.
Use Debug class for debug builds, use Trace class for both debug and release builds.
49. Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose and for some applications that are constantly running you
run the risk of overloading the machine and the hard drive there. Five levels range from None to
Verbose, allowing to fine-tune the tracing activities.
50. Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the constructor.
51. How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.
52. What are three test cases you should go through in unit testing?
Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper
handling), exception test cases (exceptions are thrown and caught properly).






.NET 4.0 and Visual Studio 2010 Page 513 of 548
D. HARSHA VARDHAN

53. Can you change the value of a variable while debugging a C# application?
Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.
54. Explain the three services model (three-tier application).
Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
55. What are advantages and disadvantages of Microsoft-provided data provider classes in
ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased
from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft
Access and Informix, but its a .NET layer on top of OLE layer, so not the fastest thing in the world.
ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.
56. Whats the role of the DataReader class in ADO.NET connections?
It returns a read-only dataset from the data source when the command is executed.
57. What is the wildcard character in SQL? Lets say you want to query database with LIKE for all
employees whose name starts with La.
The wildcard character is %, the proper query with LIKE would involve La%.
58. Explain ACID rule of thumb for transactions.
Transaction must be Atomic (it is one unit of work and does not dependent on previous and
following transactions), Consistent (data is either committed or roll back, no in-between case
where something has been updated and something hasnt), Isolated (no transaction sees the
intermediate results of the current transaction), Durable (the values persist if the data had been
committed even if the system crashes right after).
59. What connections does Microsoft SQL Server support?
Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL
Server username and passwords).






.NET 4.0 and Visual Studio 2010 Page 514 of 548
D. HARSHA VARDHAN

60. Which one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active
Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier
participating in the transaction.
61. Why would you use untrusted verificaion?
Web Services might use it, as well as non-Windows applications.
62. What does the parameter Initial Catalog define inside Connection String?
The database name to connect to.
63. Whats the data provider name to connect to Access database?
Microsoft.Access.
64. What does Dispose method do with the connection object?
Deletes it from the memory.
65. What is a pre-requisite for connection pooling?
Multiple processes must agree that they will share the same connection, where every parameter is
the same, including the security settings.




WinForms FAQ:

What base class do all Web Forms inherit from?
System.Windows.Forms.Form








.NET 4.0 and Visual Studio 2010 Page 515 of 548
D. HARSHA VARDHAN

What is the difference between Debug.Write and Trace.Write? When should each be used?
The Debug.Write call won't be compiled when the DEBUGsymbol is not defined (when doing a release
build). Trace.Write calls will be compiled. Debug.Write is for information you want only in debug builds,
Trace.Write is for when you want it in release build as well.

Difference between Anchor and Dock Properties?
Dock Property->Gets or sets which edge of the parent container a control is docked to. A control can be
docked to one edge of its parent container or can be docked to all edges and fill the parent container. For
example, if you set this property to DockStyle.Left, the left edge of the control will be docked to the left
edge of its parent control. Additionally, the docked edge of the control is resized to match that of its
container control.

Anchor Property: Gets or sets which edges of the control are anchored to the edges of its container. A
control can be anchored to one or more edges of its parent container. Anchoring a control to its parent
ensures that the anchored edges remain in the same position relative to the edges of the parent container
when the parent container is resized.

When would you use ErrorProvider control?
ErrorProvider control is used in Windows Forms application. It is like Validation Control for ASP.NET pages.
ErrorProvider control is used to provide validations in Windows forms and display user friendly messages to
the user if the validation fails.

E.g
If we went to validate the textBox1 should be empty, then we can validate as below
1) You need to place the errorprovide control on the form
private void textBox1_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
ValidateName();
}
private bool ValidateName()
{
bool bStatus = true;
if (textBox1.Text == "")
{
errorProvider1.SetError (textBox1,"Please enter your Name");
bStatus = false;
}
else





.NET 4.0 and Visual Studio 2010 Page 516 of 548
D. HARSHA VARDHAN

errorProvider1.SetError (textBox1,"");
return bStatus;
}

It checks the textBox1 is empty. If it is empty, then a message Please enter your name is displayed.


Can you write a class without specifying namespace? Which namespace does it belong to by default?
Yes, you can, then the class belongs to global namespace which has no name. For commercial products,
naturally, you wouldnt want global namespace.

You are designing a GUI application with windows and several widgets on it. The user then resizes the
app window and sees a lot of grey space, while the widgets stay in place. What's the problem?
One should use anchoring for correct resizing. Otherwise the default property of a widget on a form is top-
left, so it stays at the same location when resized.

How can you save the desired properties of Windows Forms application?
.config files in .NET are supported through the API to allow storing and retrieving information. They are
nothing more than simple XML files, sort of like what .ini files were before for Win32 apps.

So how do you retrieve the customized properties of a .NET application from XML.config file?
Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class,
passing in the name of the property and the type expected. Assign the result to the appropriate variable.

Can you automate this process?
In Visual Studio yes, use Dynamic Properties for automatic .config creation, storage and retrieval.

My progress bar freezes up and dialog window shows blank, when an intensive background process
takes over.
Yes, you should've multi-threaded your GUI, with taskbar and main form being one thread, and the
background process being the other.

What's the safest way to deploy a Windows Forms app?
Web deployment: the user always downloads the latest version of the code, the program runs within security
sandbox, properly written app will not require additional security privileges.







.NET 4.0 and Visual Studio 2010 Page 517 of 548
D. HARSHA VARDHAN

Why is it not a good idea to insert code into InitializeComponent method when working with Visual
Studio?
The designers will likely through it away, most of the code inside InitializeComponent is autogenerated.

What's the difference between WindowsDefaultLocation and WindowsDefaultBounds?
WindowsDefaultLocation tells the form to start up at a location selected by OS, but with internally specified
size. WindowsDefaultBounds delegates both size and starting position choices to the OS.


What's the difference between Move and LocationChanged? Resize and SizeChanged?
Both methods do the same, Move and Resize are the names adopted from VB to ease migration to C#.

How would you create a non-rectangular window, let's say an ellipse?
Create a rectangular form, set the TransparencyKey property to the same value as BackColor, which will
effectively make the background of the form transparent. Then set the FormBorderStyle to
FormBorderStyle.None, which will remove the contour and contents of the form.

How do you create a separator in the Menu Designer?
A hyphen '-' would do it. Also, an ampersand '&\' would underline the next letter.

How's anchoring different from docking?
Anchoring treats the component as having the absolute size and adjusts its location relative to the parent
form. Docking treats the component location as absolute and disregards the component size. So if a status
bar must always be at the bottom no matter what, use docking. If a button should be on the top right, but
change its position with the form being resized, use anchoring.

How do you trigger the Paint event in System.Drawing?
Invalidate the current form; the OS will take care of repainting. The Update method forces the repaint.

With these events, why wouldn't Microsoft combine Invalidate and Paint, so that you wouldn't have to
tell it to repaint, and then to force it to repaint?
Painting is the slowest thing the OS does, so usually telling it to repaint, but not forcing it allows
for the process to take place in the background.

How can you assign an RGB color to a System.Drawing.Color object?
Call the static method FromArgb of this class and pass it the RGB values.







.NET 4.0 and Visual Studio 2010 Page 518 of 548
D. HARSHA VARDHAN

What class does Icon derive from?
Isn't it just a Bitmap with a wrapper name around it? No, Icon lives in System.Drawing namespace. It's not a
Bitmap by default, and is treated separately by .NET. However, you can use ToBitmap method to get a
valid Bitmap object from a valid Icon object.

Before in my VB app I would just load the icons from DLL. How can I load the icons provided by .NET
dynamically?
By using System.Drawing.SystemIcons class, for example
System.Drawing.SystemIcons.Warning produces an Icon with a warning sign in it.

When displaying fonts, what's the difference between pixels, points and ems?
A pixel is the lowest-resolution dot the computer monitor supports. Its size depends on user's settings and
monitor size. A point is always 1/72 of an inch. An em is the number of pixels that it takes to display the
letter M.

Remoting FAQ's
What distributed process frameworks outside .NET do you know?
Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed Component
Object Model (DCOM), Common Object Request Broker Architecture (CORBA), and Java Remote Method
Invocation (RMI).

What are possible implementations of distributed applications in .NET?
.NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy
classes are in System.Runtime.Remoting and System.Web.Services.

When would you use .NET Remoting and when Web services?
Use remoting for more efficient exchange of information when you control both ends of the application. Use
Web services for open-protocol-based information exchange when you are just a client or a server with the
other end belonging to someone else.

What's a proxy of the server object in .NET Remoting?
It's a fake copy of the server object that resides on the client side and behaves as if it was the server. It
handles the communication between real server object and the client object. This process is also known as
marshaling.








.NET 4.0 and Visual Studio 2010 Page 519 of 548
D. HARSHA VARDHAN

What are remotable objects in .NET Remoting?
Remotable objects are the objects that can be marshaled across the application domains. You can marshal
by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal
by reference, where just a reference to an existing object is passed.

What are channels in .NET Remoting?
Channels represent the objects that transfer the other serialized objects from one application domain to
another and from one computer to another, as well as one process to another on the same box. A channel
must exist before an object can be transferred.

What security measures exist for .NET Remoting in System.Runtime.Remoting?
None. Security should be taken care of at the application level. Cryptography and other security techniques
can be applied at application or server level.
What is a formatter?
A formatter is an object that is responsible for encoding and serializing data into messages on one end, and
deserializing and decoding messages into data on the other end.

Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-
offs?
Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.

What's SingleCall activation mode used for?
If the server object is instantiated for responding to just one single request, the request should be made in
SingleCall mode.

What's Singleton activation mode?
A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is
determined by lifetime lease.

How do you define the lease of the object?
By implementing ILease interface when writing the class code.

Can you configure a .NET Remoting object via XML file?
Yes, via machine.config and application level .config file (or web.config in ASP.NET). Applicationlevel XML
settings take precedence over machine.config.

How can you automatically generate interface for the remotable object in .NET with Microsoft tools?
Use the Soapsuds tool.





.NET 4.0 and Visual Studio 2010 Page 520 of 548
D. HARSHA VARDHAN


What are CAO's i.e. Client Activated Objects?
Client-activated objects are objects whose lifetimes are controlled by the calling application domain, just as
they would be if the object were local to the client. With client activation, a round trip to the server occurs
when the client tries to create an instance of the server object, and the client proxy is created using an
object reference (ObjRef) obtained on return from the creation of the remote object on the server. Each time
a client creates an instance of a client-activated type, that instance will service only that particular reference
in that particular client until its lease expires and its memory is recycled. If a calling application domain
creates two new instances of the remote type, each of the client references will invoke only the particular
instance in the server application domain from which the reference was returned.

In COM, clients hold an object in memory by holding a reference to it. When the last client releases its last
reference, the object can delete itself. Client activation provides the same client control over the server
object's lifetime, but without the complexity of maintaining references or the constant pinging to confirm the
continued existence of the server or client. Instead, clientactivated objects use lifetime leases to determine
how long they should continue to exist. When a client creates a remote object, it can specify a default length
of time that the object should exist. If the remote object reaches its default lifetime limit, it contacts the client
to ask whether it should continue to exist, and if so, for how much longer. If the client is not currently
available, a default time is also specified for how long the server object should wait while trying to contact
the client before marking itself for garbage collection. The client might even request an indefinite default
lifetime, effectively preventing the remote object from ever being recycled until the server application
domain is torn down. The difference between this and a server-activated indefinite lifetime is that an
indefinite server-activated object will serve all client requests for that type, whereas the client-activated
instances serve only the client and the reference that was responsible for their creation. For more
information, see Lifetime Leases. To create an instance of a client-activated type, clients either configure
their application programmatically (or using a configuration file) and call new (New in Visual Basic), or they
pass the remote object's configuration in a call to Activator.CreateInstance. The following code example
shows such a call, assuming a TcpChannel has been registered to listen on port 8080.

How many processes can listen on a single TCP/IP port?
One.

What technology enables out-of-proc communication in .NET?
Most usually Remoting;.NET remoting enables client applications to use objects in other processes on the
same computer or on any other computer available on its network.While you could implement an out-of-proc
component in any number of other ways, someone using the term almost always means Remoting.







.NET 4.0 and Visual Studio 2010 Page 521 of 548
D. HARSHA VARDHAN

How can objects in two diff. App Doimains communicate with each other?
.Net framework provides various ways to communicate with objects in different app domains. First is XML
Web Service on internet, its good method because it is built using HTTP protocol and SOAP formatting. If the
performance is the main concern then go for second option which is .Net remoting because it gives you the
option of using binary encoding and the default TcpChannel, which offers the best interprocess
communication performance.

What is the difference between .Net Remoting and Web Services?
Although we can develop an application using both technologies, each of them has its distinct advantages.
Yes you can look at them in terms of performance but you need to consider your need first. There are many
other factors such authentications, authorizing in process that need to be considered.

Point Remoting Webservices
If your application needs interoperability with other platforms or operating systems
No
Yes, Choose Web Services because it is more flexible in that they are support SOAP. If performance is the
main requirement with security You should use the TCP channel and the binary formatter No Complex
Programming Yes No State Management Supports a range of state management, depending on what object
lifetime scheme you choose (single call or singleton call). Its stateless service management (does not
inherently correlate multiple calls from the same user) Transport Protocol It can access through TCP or HTTP
channel. It can be access only through HTTP channel.



C# and VB.NET FAQs
Explain the differences between Server-side and Client-side code?
Server side code executes on the server.For this to occur page has to be submitted or posted back.Events
fired by the controls are executed on the server. Client side code executes in the browser of the client
without submitting the page.

e.g. In ASP.NET for webcontrols like asp:button the click event of the button is executed on the server hence
the event handler for the same in a part of the code-behind (server-side code). Along the server-side code
events one can also attach client side events which are executed in the clients browser i.e. javascript events.

How does VB.NET/C# achieve polymorphism?
Polymorphism is also achieved through interfaces. Like abstract classes, interfaces also describe the methods
that a class needs to implement. The difference between abstract classes and interfaces is that abstract





.NET 4.0 and Visual Studio 2010 Page 522 of 548
D. HARSHA VARDHAN

classes always act as a base class of the related classes in the class hierarchy. For example, consider a
hierarchy-car and truck classes derived from four-wheeler class; the classes two-wheeler and four-wheeler
derived from an abstract class vehicle. So, the class 'vehicle' is the base class in the class hierarchy. On the
other hand dissimilar classes can implement one interface. For example, there is an interface that compares
two objects. This interface can be implemented by the classes like box, person and string, which are
unrelated to each other.

C# allows multiple interface inheritance. It means that a class can implement more than one interface. The
methods declared in an interface are implicitly abstract. If a class implements an interface, it becomes
mandatory for the class to override all the methods declared in the interface, otherwise the derived class
would become abstract.

Can you explain what inheritance is and an example of when you might use it?
The savingaccount class has two data members-accno that stores account number, and trans that keeps track
of the number of transactions. We can create an object of savingaccount class as shown below.
savingaccount s = new savingaccount ( "Amar", 5600.00f );

From the constructor of savingaccount class we have called the two-argument constructor of the account class
using the base keyword and passed the name and balance to this constructor using which the data member's
name and balance are initialised.

We can write our own definition of a method that already exists in a base class. This is called method
overriding. We have overridden the deposit( ) and withdraw( ) methods in the savingaccount class so that
we can make sure that each account maintains a minimum balance of Rs. 500 and the total number of
transactions do not exceed 10. From these methods we have called the base class's methods to update the
balance using the base keyword. We have also overridden the display( ) method to display additional
information, i.e. account number. Working of currentaccount class is more or less similar to that of
savingaccount class. Using the derived class's object, if we call a method that is not overridden in the derived
class, the base class method gets executed. Using derived class's object we can call base class's methods, but
the reverse is not allowed. Unlike C++, C# does not support multiple inheritance. So, in C# every class has
exactly one base class.

Now, suppose we declare reference to the base class and store in it the address of instance of derived class
as shown below.

account a1 = new savingaccount ( "Amar", 5600.00f ) ;
account a2 = new currentaccount ( "MyCompany Pvt. Ltd.", 126000.00f);






.NET 4.0 and Visual Studio 2010 Page 523 of 548
D. HARSHA VARDHAN

Such a situation arises when we have to decide at run-time a method of which class in a class hierarchy
should get called. Using a1 and a2, suppose we call the method display( ), ideally the method of derived
class should get called. But it is the method of base class that gets called. This is because the compiler
considers the type of reference (account in this case) and resolves the method call. So, to call the proper
method we must make a small change in our program. We must use the virtual keyword while defining the
methods in base class as shown below.
public virtual void display( ) { }

We must declare the methods as virtual if they are going to be overridden in derived class. To override a
virtual method in derived classes we must use the override keyword as given below.
public override void display( ) { }

Now it is ensured that when we call the methods using upcasted reference, it is the derived class's method
that would get called. Actually, when we declare a virtual method, while calling it, the compiler considers the
contents of the reference rather than its type.

If we don't want to override base class's virtual method, we can declare it with new modifier in derived
class. The new modifier indicates that the method is new to this class and is not an override of a base class
method.


How would you implement inheritance using VB.NET/C#?
When we set out to implement a class using inheritance, we must first start with an existing class from which
we will derive our new subclass. This existing class, or base class, may be part of the .NET system class
library framework, it may be part of some other application or .NET assembly, or we may create it as part
of our existing application. Once we have a base class, we can then implement one or more subclasses
based on that base class. Each of our subclasses will automatically have all of the methods, properties, and
events of that base class ? including the implementation behind each method, property, and event. Our
subclass can add new methods, properties, and events of its own - extending the original interface with new
functionality. Additionally, a subclass can replace the methods and properties of the base class with its own
New implementation - effectively overriding the original behavior and replacing it with new behaviors.
Essentially inheritance is a way of merging functionality from an existing class into our new subclass.
Inheritance also defines rules for how these methods, properties, and events can be merged. In VB.NET we
can use implements keyword for inheritance, while in C# we can use the sign ( :: ) between subclass and
baseclass.








.NET 4.0 and Visual Studio 2010 Page 524 of 548
D. HARSHA VARDHAN

How is a property designated as read-only?
In VB.NET:
Private mPropertyName as DataType
Public ReadOnly Property PropertyName() As DataType
Get Return mPropertyName
End Get
End Property

In C#
Private DataType mPropertyName;
public returntype PropertyName
{
get{
//property implementation goes here
return mPropertyName;
}
// Do not write the set implementation
}

What is hiding in CSharp?
Hiding is also called as Shadowing. This is the concept of Overriding the methods. It is a concept
used in the Object Oriented Programming.

E.g.
public class ClassA {
public virtual void MethodA() {
Trace.WriteLine("ClassA Method");
}
}
public class ClassB : ClassA {
public new void MethodA() {
Trace.WriteLine("SubClass ClassB Method");
}
}
public class TopLevel {
static void Main(string[] args) {
TextWriter tw = Console.Out;
Trace.Listeners.Add(new TextWriterTraceListener(tw));





.NET 4.0 and Visual Studio 2010 Page 525 of 548
D. HARSHA VARDHAN

ClassA obj = new ClassB();
obj.MethodA(); // Outputs Class A Method"
ClassB obj1 = new ClassB();
obj.MethodA(); // Outputs SubClass ClassB Method
}
}


What is the difference between an XML "Fragment" and an XML "Document."
An XML fragment is an XML document with no single top-level root element. To put it simple it is a part
(fragment) of a well-formed xml document. (node) Where as a well-formed xml document must have only
one root element.

What does it meant to say the canonical form of XML?
"The purpose of Canonical XML is to define a standard format for an XML document. Canonical XML is a
very strict XML syntax, which lets documents in canonical XML be compared directly. Using this strict syntax
makes it easier to see whether two XML documents are the same. For example, a section of text in one
document might read Black & White, whereas the same section of text might read Black & White in another
document, and even in another. If you compare those three documents byte by byte, they'll be different. But
if you write them all in canonical XML, which specifies every aspect of the syntax you can use, these three
documents would all have the same version of this text (which would be Black & White) and could be
compared without problem.

This Comparison is especially critical when xml documents are digitally signed. The digital signal may be
interpreted in different way and the document may be rejected.


Why is the XML InfoSet specification different from the Xml DOM? What does the InfoSetattempt to
solve?
"The XML Information Set (Infoset) defines a data model for XML. The Infoset describes the abstract
representation of an XML Document. Infoset is the generalized representation of the XML Document, which is
primarily meant to act as a set of definitions used by XML technologies to formally describe what parts of
an XML document they operate upon. The Document Object Model (DOM) is one technology for representing
an XML Document in memory and to programmatically read, modify and manipulate a xml document.
Infoset helps defining generalized standards on how to use XML that is not dependent or tied to a particular
XML specification or API. The Infoset tells us what part of XML Document should be considered as significant
information.






.NET 4.0 and Visual Studio 2010 Page 526 of 548
D. HARSHA VARDHAN

Contrast DTDs versus XSDs. What are their similarities and differences? Which is
preferred and why?
Document Type Definition (DTD) describes a model or set of rules for an XML document. XML Schema
Definition (XSD) also describes the structure of an XML document but XSDs are much more powerful. The
disadvantage with the Document Type Definition is it doesnt support data types beyond the basic 10
primitive types. It cannot properly define the type of data contained by the tag. An Xml Schema provides
an Object Oriented approach to defining the format of an xml document. The Xml schema support most
basic programming types like integer, byte, string, float etc., We can also define complex types of our own
which can be used to define a xml document.

Xml Schemas are always preferred over DTDs as a document can be more precisely defined using the XML
Schemas because of its rich support for data representation.

Speaking of Boolean data types, what's different between C# and C/C++?
There's no conversion between 0 and false, as well as any other number and true, like in C/C++.

How do you convert a string into an integer in .NET?
Int32.Parse(string)

Can you declare a C++ type destructor in C# like ~MyClass()?
Yes, but what's the point, since it will call Finalize(), and Finalize() has no guarantees when the memory will
be cleaned up, plus, it introduces additional load on the garbage collector.

What's different about namespace declaration when comparing that to package declaration in Java?
No semicolon.


What's the difference between const and readonly?
The readonly keyword is different from the const keyword. A const field can only be initialized at the
declaration of the field. A readonly field can be initialized either at the declaration or in a constructor.
Therefore, readonly fields can have different values depending on the constructor used. Also, while a const
field is a compile-time constant, the readonly field can be used for runtime constants as in the following
example:
public static readonly uint l1 = (uint) DateTime.Now.Ticks;









.NET 4.0 and Visual Studio 2010 Page 527 of 548
D. HARSHA VARDHAN

ADO.NET FAQ's
1. Advantage of ADO.Net?
ADO.NET Does Not Depend On Continuously Live Connections
Database Interactions Are Performed Using Data Commands
Data Can Be Cached in Datasets
Datasets Are Independent of Data Sources
Data Is Persisted as XML
Schemas Define Data Structures

2. How would u connect to database using .NET?
SqlConnection nwindConn = new SqlConnection("Data Source=localhost; Integrated Security=SSPI;"
+ "Initial Catalog=northwind");
nwindConn.Open();

3. What are relation objects in dataset and how & where to use them?
In a DataSet that contains multiple DataTable objects, you can use DataRelation objects to relate
one table to another, to navigate through the tables, and to return child or parent rows from a
related table. Adding a DataRelation to a DataSet adds, by default, a UniqueConstraint to the
parent table and a ForeignKeyConstraint to the child table.
The following code example creates a DataRelation using two DataTable objects in a DataSet.
Each DataTable contains a column named CustID, which serves as a link between the two
DataTable objects. The example adds a single DataRelation to the Relations collection of the
DataSet. The first argument in the example specifies the name of the DataRelation being created.
The second argument sets the parent DataColumn and the third argument sets the child
DataColumn.
custDS.Relations.Add("CustOrders",
custDS.Tables["Customers"].Columns["CustID"],
custDS.Tables["Orders"].Columns["CustID"]);

OR






.NET 4.0 and Visual Studio 2010 Page 528 of 548
D. HARSHA VARDHAN


private void CreateRelation()
{
// Get the DataColumn objects from two DataTable objects in a DataSet.
DataColumn parentCol;
DataColumn childCol;
// Code to get the DataSet not shown here.
parentCol = DataSet1.Tables["Customers"].Columns["CustID"];
childCol = DataSet1.Tables["Orders"].Columns["CustID"];
// Create DataRelation.
DataRelation relCustOrder;
relCustOrder = new DataRelation("CustomersOrders", parentCol, childCol);
// Add the relation to the DataSet.
DataSet1.Relations.Add(relCustOrder);
}

4. Difference between OLEDB Provider and SqlClient ?
Ans: SQLClient .NET classes are highly optimized for the .net / sqlserver combination and achieve
optimal results. The SqlClient data provider is fast. It's faster than the Oracle provider, and faster
than accessing database via the OleDb layer. It's faster because it accesses the native library
(which automatically gives you better performance), and it was written with lots of help from the
SQL Server team.

5. What are the different namespaces used in the project to connect the database? What data
providers available in .net to connect to database?
System.Data.OleDb classes that make up the .NET Framework Data Provider for OLE
DB-compatible data sources. These classes allow you to connect to an OLE DB data source,
execute commands against the source, and read the results.
System.Data.SqlClient classes that make up the .NET Framework Data Provider for SQL
Server, which allows you to connect to SQL Server 7.0, execute commands, and read
results. The System.Data.SqlClient namespace is similar to the System.Data.OleDb
namespace, but is optimized for access to SQL Server 7.0 and later.
System.Data.Odbc - classes that make up the .NET Framework Data Provider for ODBC.
These classes allow you to access ODBC data source in the managed space.





.NET 4.0 and Visual Studio 2010 Page 529 of 548
D. HARSHA VARDHAN

System.Data.OracleClient - classes that make up the .NET Framework Data Provider for
Oracle. These classes allow you to access an Oracle data source in the managed space.

6. Difference between DataReader and DataAdapter / DataSet and DataAdapter?
You can use the ADO.NET DataReader to retrieve a read-only, forward-only stream of data from
a database. Using the DataReader can increase application performance and reduce system
overhead because only one row at a time is ever in memory.
After creating an instance of the Command object, you create a DataReader by calling
Command.ExecuteReader to retrieve rows from a data source, as shown in the following example.
SqlDataReader myReader = myCommand.ExecuteReader();
You use the Read method of the DataReader object to obtain a row from the results of the query.
while (myReader.Read())
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
myReader.Close();
The DataSet is a memory-resident representation of data that provides a consistent relational
programming model regardless of the data source. It can be used with multiple and differing data
sources, used with XML data, or used to manage data local to the application. The DataSet
represents a complete set of data including related tables, constraints, and relationships among the
tables. The methods and objects in a DataSet are consistent with those in the relational database
model. The DataSet can also persist and reload its contents as XML and its schema as XML Schema
definition language (XSD) schema.
The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and
saving data. The DataAdapter provides this bridge by mapping Fill, which changes the data in the
DataSet to match the data in the data source, and Update, which changes the data in the data
source to match the data in the DataSet. If you are connecting to a Microsoft SQL Server database,
you can increase overall performance by using the SqlDataAdapter along with its associated
SqlCommand and SqlConnection. For other OLE DB-supported databases, use the DataAdapter
with its associated OleDbCommand and OleDbConnection objects.

7. Which method do you invoke on the DataAdapter control to load your generated dataset with
data?
Fill()






.NET 4.0 and Visual Studio 2010 Page 530 of 548
D. HARSHA VARDHAN

8. Explain different methods and Properties of DataReader which you have used in your project?
Read
GetString
GetInt32
while (myReader.Read())
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
myReader.Close();

9. What happens when we issue Dataset.ReadXml command?
Reads XML schema and data into the DataSet.

10. In how many ways we can retrieve table records count? How to find the count of records in a
dataset?
foreach(DataTable thisTable in myDataSet.Tables){
// For each row, print the values of each column.
foreach(DataRow myRow in thisTable.Rows){

11. How to check if a datareader is closed or opened?
IsClosed()

12. Differences between dataset.clone and dataset.copy?
Clone - Copies the structure of the DataSet, including all DataTable schemas, relations, and
constraints. Does not copy any data.
Copy - Copies both the structure and data for this DataSet.






.NET 4.0 and Visual Studio 2010 Page 531 of 548
D. HARSHA VARDHAN

SQL Server FAQ's

T-SQL Queries
1. 2 tables
Employee Phone
empid
empname
salary
mgrid
empid
phnumber
2. Select all employees who doesn't have phone?
SELECT empname
FROM Employee
WHERE (empid NOT IN
(SELECT DISTINCT empid
FROM phone))

3. Select the employee names who is having more than one phone numbers.
SELECT empname
FROM employee
WHERE (empid IN
(SELECT empid
FROM phone
GROUP BY empid
HAVING COUNT(empid) > 1))






.NET 4.0 and Visual Studio 2010 Page 532 of 548
D. HARSHA VARDHAN

4. Select the details of 3 max salaried employees from employee table.
SELECT TOP 3 empid, salary
FROM employee
ORDER BY salary DESC

5. Display all managers from the table. (manager id is same as emp id)
SELECT empname
FROM employee
WHERE (empid IN
(SELECT DISTINCT mgrid
FROM employee))

6. Write a Select statement to list the Employee Name, Manager Name under a particular
manager?
SELECT e1.empname AS EmpName, e2.empname AS ManagerName
FROM Employee e1 INNER JOIN
Employee e2 ON e1.mgrid = e2.empid
ORDER BY e2.mgrid

7. 2 tables emp and phone.
emp fields are - empid, name
Ph fields are - empid, ph (office, mobile, home). Select all employees who doesn't have
any ph nos.
SELECT *
FROM employee LEFT OUTER JOIN
phone ON employee.empid = phone.empid
WHERE (phone.office IS NULL OR phone.office = ' ')
AND (phone.mobile IS NULL OR phone.mobile = ' ')
AND (phone.home IS NULL OR phone.home = ' ')





.NET 4.0 and Visual Studio 2010 Page 533 of 548
D. HARSHA VARDHAN


8. Find employee who is living in more than one city.
Two Tables:
Emp City
Empid
empName
Salary
Empid
City
9. SELECT empname, fname, lname
FROM employee
WHERE (empid IN
(SELECT empid
FROM city
GROUP BY empid
HAVING COUNT(empid) > 1))

10. Find all employees who is living in the same city. (table is same as above)
SELECT fname
FROM employee
WHERE (empid IN
(SELECT empid
FROM city a
WHERE city IN
(SELECT city
FROM city b
GROUP BY city
HAVING COUNT(city) > 1)))






.NET 4.0 and Visual Studio 2010 Page 534 of 548
D. HARSHA VARDHAN

11. There is a table named MovieTable with three columns - moviename, person and role.
Write a query which gets the movie details where Mr. Amitabh and Mr. Vinod acted and
their role is actor.
SELECT DISTINCT m1.moviename
FROM MovieTable m1 INNER JOIN
MovieTable m2 ON m1.moviename = m2.moviename
WHERE (m1.person = 'amitabh' AND m2.person = 'vinod' OR
m2.person = 'amitabh' AND m1.person = 'vinod') AND (m1.role = 'actor') AND (m2.role =
'actor')
ORDER BY m1.moviename

12. There are two employee tables named emp1 and emp2. Both contains same structure
(salary details). But Emp2 salary details are incorrect and emp1 salary details are
correct. So, write a query which corrects salary details of the table emp2
update a set a.sal=b.sal from emp1 a, emp2 b where a.empid=b.empid

13. Given a Table named Students which contains studentid, subjectid and marks. Where
there are 10 subjects and 50 students. Write a Query to find out the Maximum marks
obtained in each subject.

14. In this same tables now write a SQL Query to get the studentid also to combine with
previous results.

15. Three tables student , course, marks how do go at finding name of the students who
got max marks in the diff courses.
SELECT student.name, course.name AS coursename, marks.sid, marks.mark
FROM marks INNER JOIN
student ON marks.sid = student.sid INNER JOIN





.NET 4.0 and Visual Studio 2010 Page 535 of 548
D. HARSHA VARDHAN

course ON marks.cid = course.cid
WHERE (marks.mark =
(SELECT MAX(Mark)
FROM Marks MaxMark
WHERE MaxMark.cID = Marks.cID))

16. There is a table day_temp which has three columns dayid, day and temperature. How do
I write a query to get the difference of temperature among each other for seven days of
a week?
SELECT a.dayid, a.dday, a.tempe, a.tempe - b.tempe AS Difference
FROM day_temp a INNER JOIN
day_temp b ON a.dayid = b.dayid + 1
OR
Select a.day, a.degree-b.degree from temperature a, temperature b where a.id=b.id+1

17. There is a table which contains the names like this. a1, a2, a3, a3, a4, a1, a1, a2 and
their salaries. Write a query to get grand total salary, and total salaries of individual
employees in one query.
SELECT empid, SUM(salary) AS salary
FROM employee
GROUP BY empid WITH ROLLUP
ORDER BY empid
18. How to know how many tables contains empno as a column in a database?
SELECT COUNT(*) AS Counter
FROM syscolumns
WHERE (name = 'empno')

19. Find duplicate rows in a table? OR I have a table with one column which has many
records which are not distinct. I need to find the distinct values from that column and
number of times its repeated.





.NET 4.0 and Visual Studio 2010 Page 536 of 548
D. HARSHA VARDHAN

SELECT sid, mark, COUNT(*) AS Counter
FROM marks
GROUP BY sid, mark
HAVING (COUNT(*) > 1)

20. How to delete the rows which are duplicate (dont delete both duplicate records).
SET ROWCOUNT 1
DELETE yourtable
FROM yourtable a
WHERE (SELECT COUNT(*) FROM yourtable b WHERE b.name1 = a.name1 AND b.age1
= a.age1) > 1
WHILE @@rowcount > 0
DELETE yourtable
FROM yourtable a
WHERE (SELECT COUNT(*) FROM yourtable b WHERE b.name1 = a.name1 AND
b.age1 = a.age1) > 1
SET ROWCOUNT 0

21. How to find 6th highest salary
SELECT TOP 1 salary
FROM (SELECT DISTINCT TOP 6 salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary

22. Find top salary among two tables
SELECT TOP 1 sal
FROM (SELECT MAX(sal) AS sal
FROM sal1
UNION





.NET 4.0 and Visual Studio 2010 Page 537 of 548
D. HARSHA VARDHAN

SELECT MAX(sal) AS sal
FROM sal2) a
ORDER BY sal DESC

23. Write a query to convert all the letters in a word to upper case
SELECT UPPER('test')

24. Write a query to round up the values of a number. For example even if the user enters
7.1 it should be rounded up to 8.
SELECT CEILING (7.1)

25. Write a SQL Query to find first day of month?
SELECT DATENAME(dw, DATEADD(dd, - DATEPART(dd, GETDATE()) + 1, GETDATE())) AS
FirstDay
Datepart Abbreviations
year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw
hour hh





.NET 4.0 and Visual Studio 2010 Page 538 of 548
D. HARSHA VARDHAN

minute mi, n
second ss, s
millisecond ms
26. Table A contains column1 which is primary key and has 2 values (1, 2) and Table B
contains column1 which is primary key and has 2 values (2, 3). Write a query which
returns the values that are not common for the tables and the query should return one
column with 2 records.
SELECT tbla.a
FROM tbla, tblb
WHERE tbla.a <>
(SELECT tblb.a
FROM tbla, tblb
WHERE tbla.a = tblb.a)
UNION
SELECT tblb.a
FROM tbla, tblb
WHERE tblb.a <>
(SELECT tbla.a
FROM tbla, tblb
WHERE tbla.a = tblb.a)

OR (better approach)

SELECT a
FROM tbla
WHERE a NOT IN
(SELECT a
FROM tblb)
UNION ALL
SELECT a
FROM tblb
WHERE a NOT IN





.NET 4.0 and Visual Studio 2010 Page 539 of 548
D. HARSHA VARDHAN

(SELECT a
FROM tbla)

27. There are 3 tables Titles, Authors and Title-Authors (check PUBS db). Write the query to
get the author name and the number of books written by that author, the result should
start from the author who has written the maximum number of books and end with the
author who has written the minimum number of books.
SELECT authors.au_lname, COUNT(*) AS BooksCount
FROM authors INNER JOIN
titleauthor ON authors.au_id = titleauthor.au_id INNER JOIN
titles ON titles.title_id = titleauthor.title_id
GROUP BY authors.au_lname
ORDER BY BooksCount DESC

28.
UPDATE emp_master
SET emp_sal =
CASE
WHEN emp_sal > 0 AND emp_sal <= 20000 THEN (emp_sal * 1.01)
WHEN emp_sal > 20000 THEN (emp_sal * 1.02)
END

29. List all products with total quantity ordered, if quantity ordered is null show it as 0.
SELECT name, CASE WHEN SUM(qty) IS NULL THEN 0 WHEN SUM(qty) > 0 THEN
SUM(qty) END AS tot
FROM [order] RIGHT OUTER JOIN
product ON [order].prodid = product.prodid
GROUP BY name
Result:
coke 60





.NET 4.0 and Visual Studio 2010 Page 540 of 548
D. HARSHA VARDHAN

mirinda 0
pepsi 10

30. ANY, SOME, or ALL?
ALL means greater than every value--in other words, greater than the maximum value. For
example, >ALL (1, 2, 3) means greater than 3.
ANY means greater than at least one value, that is, greater than the minimum. So >ANY
(1, 2, 3) means greater than 1. SOME is an SQL-92 standard equivalent for ANY.


31. IN & = (difference in correlated sub query)

INDEX
32. What is Index? Its purpose?
Indexes in databases are similar to indexes in books. In a database, an index allows the
database program to find data in a table without scanning the entire table. An index in a
database is a list of values in a table with the storage locations of rows in the table that
contain each value. Indexes can be created on either a single column or a combination of
columns in a table and are implemented in the form of B-trees. An index contains an entry
with one or more columns (the search key) from each row in a table. A B-tree is sorted on
the search key, and can be searched efficiently on any leading subset of the search key.
For example, an index on columns A, B, C can be searched efficiently on A, on A, B, and
A, B, C.







.NET 4.0 and Visual Studio 2010 Page 541 of 548
D. HARSHA VARDHAN

33. Explain about Clustered and non clustered index? How to choose between a Clustered
Index and a Non-Clustered Index?
There are clustered and nonclustered indexes. A clustered index is a special type of index
that reorders the way records in the table are physically stored. Therefore table can have
only one clustered index. The leaf nodes of a clustered index contain the data pages.
A nonclustered index is a special type of index in which the logical order of the index
does not match the physical stored order of the rows on disk. The leaf nodes of a
nonclustered index does not consist of the data pages. Instead, the leaf nodes contain
index rows.
Consider using a clustered index for:
o Columns that contain a large number of distinct values.
o Queries that return a range of values using operators such as BETWEEN, >, >=,
<, and <=.
o Columns that are accessed sequentially.
o Queries that return large result sets.
Non-clustered indexes have the same B-tree structure as clustered indexes, with
two significant differences:
o The data rows are not sorted and stored in order based on their non-clustered
keys.
o The leaf layer of a non-clustered index does not consist of the data pages.
Instead, the leaf nodes contain index rows. Each index row contains the non-
clustered key value and one or more row locators that point to the data row (or
rows if the index is not unique) having the key value.
o Per table only 249 non clustered indexes.
34. Disadvantage of index?
Every index increases the time in takes to perform INSERTS, UPDATES and DELETES, so the
number of indexes should not be very much.

35. Given a scenario that I have a 10 Clustered Index in a Table to all their 10 Columns.
What are the advantages and disadvantages?
A: Only 1 clustered index is possible.






.NET 4.0 and Visual Studio 2010 Page 542 of 548
D. HARSHA VARDHAN

36. How can I enforce to use particular index?
You can use index hint (index=<index_name>) after the table name.
SELECT au_lname FROM authors (index=aunmind)

37. What is Index Tuning?
One of the hardest tasks facing database administrators is the selection of appropriate
columns for non-clustered indexes. You should consider creating non-clustered indexes on
any columns that are frequently referenced in the WHERE clauses of SQL statements.
Other good candidates are columns referenced by JOIN and GROUP BY operations.
You may wish to also consider creating non-clustered indexes that cover all of the columns
used by certain frequently issued queries. These queries are referred to as covered
queries and experience excellent performance gains.
Index Tuning is the process of finding appropriate column for non-clustered indexes.
SQL Server provides a wonderful facility known as the Index Tuning Wizard which greatly
enhances the index selection process.

38. Difference between Index defrag and Index rebuild?
When you create an index in the database, the index information used by queries is
stored in index pages. The sequential index pages are chained together by pointers from
one page to the next. When changes are made to the data that affect the index, the
information in the index can become scattered in the database. Rebuilding an index
reorganizes the storage of the index data (and table data in the case of a clustered
index) to remove fragmentation. This can improve disk performance by reducing the
number of page reads required to obtain the requested data
DBCC INDEXDEFRAG - Defragments clustered and secondary indexes of the specified
table or view.
**







.NET 4.0 and Visual Studio 2010 Page 543 of 548
D. HARSHA VARDHAN

39. What is sorting and what is the difference between sorting & clustered indexes?
The ORDER BY clause sorts query results by one or more columns up to 8,060 bytes. This
will happen by the time when we retrieve data from database. Clustered indexes
physically sorting data, while inserting/updating the table.

40. What are statistics, under what circumstances they go out of date, how do you update
them?
Statistics determine the selectivity of the indexes. If an indexed column has unique values
then the selectivity of that index is more, as opposed to an index with non-unique values.
Query optimizer uses these indexes in determining whether to choose an index or not while
executing a query.
Some situations under which you should update statistics:
1) If there is significant change in the key values in the index
2) If a large amount of data in an indexed column has been added, changed, or removed
(that is, if the distribution of key values has changed), or the table has been truncated
using the TRUNCATE TABLE statement and then repopulated
3) Database is upgraded from a previous version

41. What is fillfactor? What is the use of it ? What happens when we ignore it? When you
should use low fill factor?
When you create a clustered index, the data in the table is stored in the data pages of
the database according to the order of the values in the indexed columns. When new rows
of data are inserted into the table or the values in the indexed columns are changed,
Microsoft SQL Server 2000 may have to reorganize the storage of the data in the
table to make room for the new row and maintain the ordered storage of the data. This
also applies to nonclustered indexes. When data is added or changed, SQL Server may
have to reorganize the storage of the data in the nonclustered index pages. When a new
row is added to a full index page, SQL Server moves approximately half the rows to a
new page to make room for the new row. This reorganization is known as a page split.
Page splitting can impair performance and fragment the storage of the data in a table.
When creating an index, you can specify a fill factor to leave extra gaps and reserve a





.NET 4.0 and Visual Studio 2010 Page 544 of 548
D. HARSHA VARDHAN

percentage of free space on each leaf level page of the index to accommodate future
expansion in the storage of the table's data and reduce the potential for page splits. The
fill factor value is a percentage from 0 to 100 that specifies how much to fill the data
pages after the index is created. A value of 100 means the pages will be full and will
take the least amount of storage space. This setting should be used only when there will
be no changes to the data, for example, on a read-only table. A lower value leaves more
empty space on the data pages, which reduces the need to split data pages as indexes
grow but requires more storage space. This setting is more appropriate when there will be
changes to the data in the table.



DATA TYPES
42. What are the data types in SQL
bigint Binary bit char cursor
datetime Decimal float image int
money Nchar ntext nvarchar real
smalldatetime Smallint smallmoney text timestamp
tinyint Varbinary Varchar uniqueidentifier
43. Difference between char and nvarchar / char and varchar data-type?
char[(n)] - Fixed-length non-Unicode character data with length of n bytes. n must be a
value from 1 through 8,000. Storage size is n bytes. The SQL-92 synonym for char is
character.
nvarchar(n) - Variable-length Unicode character data of n characters. n must be a value
from 1 through 4,000. Storage size, in bytes, is two times the number of characters
entered. The data entered can be 0 characters in length. The SQL-92 synonyms for
nvarchar are national char varying and national character varying.





.NET 4.0 and Visual Studio 2010 Page 545 of 548
D. HARSHA VARDHAN

varchar[(n)] - Variable-length non-Unicode character data with length of n bytes. n must
be a value from 1 through 8,000. Storage size is the actual length in bytes of the data
entered, not n bytes. The data entered can be 0 characters in length. The SQL-92
synonyms for varchar are char varying or character varying.

44. GUID datasize?
128bit

45. How GUID becoming unique across machines?
To ensure uniqueness across machines, the ID of the network card is used (among others) to
compute the number.

46. What is the difference between text and image data type?
Text and image. Use text for character data if you need to store more than 255
characters in SQL Server 6.5, or more than 8000 in SQL Server 7.0. Use image for binary
large objects (BLOBs) such as digital images. With text and image data types, the data is
not stored in the row, so the limit of the page size does not apply.All that is stored in the
row is a pointer to the database pages that contain the data.Individual text, ntext, and
image values can be a maximum of 2-GB, which is too long to store in a single data row.


JOINS
47. What are joins?
Sometimes we have to select data from two or more tables to make our result complete.
We have to perform a join.






.NET 4.0 and Visual Studio 2010 Page 546 of 548
D. HARSHA VARDHAN

48. How many types of Joins?
Joins can be categorized as:
Inner joins (the typical join operation, which uses some comparison operator like =
or <>). These include equi-joins and natural joins.
Inner joins use a comparison operator to match rows from two tables based on the
values in common columns from each table. For example, retrieving all rows where
the student identification number is the same in both the students and courses
tables.
Outer joins. Outer joins can be a left, a right, or full outer join.
Outer joins are specified with one of the following sets of keywords when they
are specified in the FROM clause:
LEFT JOIN or LEFT OUTER JOIN -The result set of a left outer join includes
all the rows from the left table specified in the LEFT OUTER clause, not just
the ones in which the joined columns match. When a row in the left table
has no matching rows in the right table, the associated result set row
contains null values for all select list columns coming from the right table.
RIGHT JOIN or RIGHT OUTER JOIN - A right outer join is the reverse of a
left outer join. All rows from the right table are returned. Null values are
returned for the left table any time a right table row has no matching row
in the left table.
FULL JOIN or FULL OUTER JOIN - A full outer join returns all rows in both
the left and right tables. Any time a row has no match in the other table,
the select list columns from the other table contain null values. When there
is a match between the tables, the entire result set row contains data
values from the base tables.
Cross joins - Cross joins return all rows from the left table, each row from the left
table is combined with all rows from the right table. Cross joins are also called
Cartesian products. (A Cartesian join will get you a Cartesian product. A
Cartesian join is when you join every row of one table to every row of another
table. You can also get one by joining every row of a table to every row of
itself.)






.NET 4.0 and Visual Studio 2010 Page 547 of 548
D. HARSHA VARDHAN

49. What is self join?
A table can be joined to itself in a self-join.

50. What are the differences between UNION and JOINS?
A join selects columns from 2 or more tables. A union selects rows.

51. Can I improve performance by using the ANSI-style joins instead of the old-style
joins?
Code Example 1:
select o.name, i.name
from sysobjects o, sysindexes i
where o.id = i.id
Code Example 2:
select o.name, i.name
from sysobjects o inner join sysindexes i
on o.id = i.id
You will not get any performance gain by switching to the ANSI-style JOIN syntax.
Using the ANSI-JOIN syntax gives you an important advantage: Because the join logic is
cleanly separated from the filtering criteria, you can understand the query logic more
quickly.
The SQL Server old-style JOIN executes the filtering conditions before executing the joins,
whereas the ANSI-style JOIN reverses this procedure (join logic precedes filtering).
Perhaps the most compelling argument for switching to the ANSI-style JOIN is that
Microsoft has explicitly stated that SQL Server will not support the old-style OUTER JOIN
syntax indefinitely. Another important consideration is that the ANSI-style JOIN supports
query constructions that the old-style JOIN syntax does not support.







.NET 4.0 and Visual Studio 2010 Page 548 of 548
D. HARSHA VARDHAN

52. What is derived table?
Derived tables are SELECT statements in the FROM clause referred to by an alias or a
user-specified name. The result set of the SELECT in the FROM clause forms a table used
by the outer SELECT statement. For example, this SELECT uses a derived table to find if
any store carries all book titles in the pubs database:
SELECT ST.stor_id, ST.stor_name
FROM stores AS ST,
(SELECT stor_id, COUNT(DISTINCT title_id) AS title_count
FROM sales
GROUP BY stor_id
) AS SA
WHERE ST.stor_id = SA.stor_id
AND SA.title_count = (SELECT COUNT(*) FROM titles)

Vous aimerez peut-être aussi