Professional Documents
Culture Documents
HARSHA VARDHAN
And
C#.NET
Hour 10 Introduction to OOP, Access Modifiers, Principles of OOP, Classes, Objects, Page 86
Fields, Methods
Hour 11 Read-only Fields, Ref parameters, Out parameters, this keyword, Named Page 96
Parameters
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 Page 130
Overriding
Hour 16 Abstract Classes and Methods, Interfaces, Structures Page 146
Hour 17 Extension Methods, Delegates Page 154
Hour 50 Setup Project Development, Installing and Un-installing the projects Page 496
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
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 Introduced in .NET 3.0
5. WWF Windows Workflow Foundation
6. AJAX Asynchronous JavaScript And Xml
Introduced in .NET 3.5
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.
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.
Modules of .NET
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 requires a .NET language (like C#, VB.NET, VC++.NET etc.) for server
side logic implementation.
It requires a .NET language (like C#, VB.NET, VC++.NET etc.) for logic
implementation.
Applications of .NET
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.
Doesnt contain any graphical features like mouse pointer, colors, fonts, buttons etc.
Offers graphical features like mouse pointer, colors, fonts, buttons, text boxes etc.
3. Windows Services
A Windows service is a long-running executable application.
Examples:
i. Windows Time.
iv. Database services like SQL Server, My SQL and Oracle etc.
etc.
To see the all the installed windows services on the system, click on Start
Control Panel Administrative Tools Services.
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/
6. Web Services
Web Services are simple and easy to understand.
The web services are used to implement SOA (Service Oriented Architecture) in
web applications.
Examples:
i. Online shopping requires credit card authentication, from back web site.
7. WPF Applications
WPF stands for Windows Presentation Foundation.
These Applications support more advanced graphical features like shapes, object
transformation, brushes etc.
C
(For General Programming Experience)
SQL
(For writing the database queries in ADO.NET)
HTML
(For web page designing in ASP.NET)
Promises by Microsoft:
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.
Versions of .NET
.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
Advantages of .NET
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.
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.
Similarities
Sl.
.NET and Java
No
Both of these support to develop console applications, windows applications, web
1
sites, web services etc.
Both use their own intermediate language. Java calls it as byte code and .NET
2
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.
Both support Garbage collection, which automatically clears the un-used
8
memory.
Both support to develop the applications for small devices like PDAs, mobile
9
phones, smart phones etc.
10 Both offer better security features in their own style.
Differences
Sl.
.NET Java
No
It is cost effective. Costs more than It is open source product, which can be
1
$700 (nearly Rs. 35,000) freely downloaded on the Internet.
2 Its a collection of multiple languages Its itself is a language.
Its partially platform independent (as
.NET applications can run on
3 Its fully platform independent.
Windows and LINUX operating
systems)
Offers IDE as Visual Studio by Doesnt offer any IDE. But other IDEs by
4
Microsoft. other vendors such as Eclipse etc.
Offers easiest and fastest application Requires much time for the application
5 development, which indirectly reduces development, which indirectly increases
the cost of the software. the cost of the software.
Designing the UI is very much easy UI Design requires much programmers
6
with Drag and Drop technique. effort and stress.
AJAX is implementation is much time
7 AJAX is implementation is much easy. taking process, requires much code to
write.
.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.
You can see the .NET Framework Architecture in the following diagram.
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).
Naming Convention
System
Windows Web Drawing Linq Xml Data Threading IO Text Speech Runtime
Configuration Remoting
Forms UI Printing OleDb SqlClient
HtmlControls WebControls
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.
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.
Types of Assemblies
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:
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();
}
}
}
The following VB.NET code displays the Hello, World message in the
console window:
Module Module1
Sub Main()
Console.WriteLine(Hello, World!)
Console.ReadLine()
End Sub
End Module
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).
Assembly (.exe)
MSIL Code
Just-in Time
Compiler
01010101010111010
01010101010111010
01010101010111010
01010101010111010
Operating System
Components of CLR
The CLR contains the following components.
2. JIT Compiler
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. Memory Manager
The Memory Manager component of CLR, allocates necessary memory for the
variables and objects that are to be used by the application.
4. Garbage Collector
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. Exception Manager
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.
Finally, Visual Studio 2010 will be opened. The initial screens looks like this:
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)
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)
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).
Build: Compilation of entire .NET Project (all the files will be compiled at-a-
time).
class class1
int mydatamember;
void mymethod()
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.
Ex:
namespace MyApplication
{
class class1
{
}
class class2
{
}
}
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
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.
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.
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.
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.
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.
Then enter the project name and location (with your choice) and click on OK.
C#.NET
Overview
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#.
File Extensions in C#
Project File Extension: .csproj (means C Sharp Project)
Code File Extension: .cs (means C Sharp)
Basic Terminology in 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.
data_type variable_name;
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).
(x == y)
class <classname>
{
//fields
//properties
//methods
}
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:
To run the application, simply press F5 key on the keyboard. Then the application will
be executed and output will be as follows.
Main() method
1. Importing section:
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;
using System.IO;
using System.Data;
etc.
2. Namespace declaration:
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. Class declaration:
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. Main() method:
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.
Syn:
1) Keywords
You can observe the available keywords in C#.
3) Comments
Single Line Comment:
//comment
Multi Line Comment:
/* comment line 1
comment line 2
comment line 3
*/
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();
System.Console.Read();
}
}
}
Output:
5) Data Types
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.
6) Variables
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.
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.");
Console.Read();
}
}
}
Output:
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.");
Output:
8) Constants
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;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Constants
{
//An application, that calculates area of circle
class Program
{
Output:
9) Type casting
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.
Implicit Casting
Implicit casting is possible in the following cases.
Explicit Casting
Explicit casting should be performed in the following cases:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Casting
{
class Program
{
static void Main(string[] args)
{
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();
}
}
}
Output:
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.
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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConversionMethods
{
class Program
{
static void Main(string[] args)
{
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();
}
}
}
Output:
IMP Note:
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.
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();
}
}
}
Output:
Strong Rule to follow: Multiple variables with same name within the same scope
cant be declared anywhere.
12) Operators
C# supports different kinds of operators.
Assignment operator
=
Arithmetical / Mathematical operators
+, -, *, /, %
Relational operators
==, !=, <, >, <=, >=
Logical operators
&&, ||, !
Comment operators
//xxxxxxxxxxxxxx
(or)
/* xxxxxxxxxxx
xxxxxxxxxxx
xxxxxxxxxxx*/
Concatenation Operator
+
Conditional operator
?:
Operator Precedence:
Note: All the syntaxes are same as C/C++. Just for idea, we recollect the syntaxes now.
if-else
if (condition)
{
----;
----;
}
else
{
----;
----;
}
else-if
if (condition)
{
----;
----;
}
else if (condition)
{
----;
----;
}
else if (condition)
{
----;
----;
}
else
{
----;
----;
}
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;
----------;
}
continue
for loop / while loop / do-while loop
{
----------;
----------;
continue;
----------;
}
goto
----------;
----------;
----------;
goto labelname;
----------;
----------;
labelname:
----------;
----------;
----------;
do-while
initialization;
do
{
----------;
----------;
----------;
Increment / decrement;
} while(condition);
for
for (initialization; condition; increment/decrement)
{
----------;
----------;
----------;
}
Note: You can also implement nested loops as you implemented in C/C++.
14) Enumerations
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
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
{
Output:
15) Arrays
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: Single-dim
array
datatype[] arrayname = new datatype[size];
With initialization:
datatype[] arrayname = {val1,val2,val3,..};
With initialization:
datatype[,] arrayname = {{val1,val2,}, {val1,val2,},};
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());
//calculate results
for (int i = 0; i < n; i++)
{
Output:
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();
}
}
}
Output:
foreach Loop
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);
}
Note: The arrayname.Length property gets the size of the array. We discuss about the Array
class in future.
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 };
Console.Read();
}
}
}
Output:
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.
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();
}
}
}
Output:
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();
}
}
}
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.
Property:
Its an extension to the field, which automatically performs the specified
code, whenever its value is changed.
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.
class employee
employee id Object1
name
phone
address
salary Object2
tax
net_salary
getdetails()
displaydetails()
Object3
calculate_net_salary()
By default, the objects are isolated. That means there is no any relation
between the data stored in one object and another object.
Object1 Object2
Object3
employee id = 103
name = pqr
phone = 7839403200
address = chennai
salary = 10380
tax = 1270
net_salary = 9110
C++ (vs) 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).
2) Data Abstraction
4) Polymorphism
5) Inheritance
2) Data Abstraction:
Access Modifiers:
= 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.
4) Polymorphism:
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.
Inherit
class classname
{
//fields
//properties
//methods
}
Note 2: The functional modifiers are static, readonly, virtual, override. We cover about these
modifiers also in further hours.
//memory allocation
objname = new classname();
(or)
obj.field
obj.property
obj.method()
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);
}
//access fields
Console.WriteLine(t.num);
Console.WriteLine(t.str);
//access methods
t.ReverseString();
t.ReverseNumber();
Console.Read();
}
}
}
Output:
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;
}
mm.SetValues(10, 3);
mm.Addition();
mm.Subtraction();
mm.Multiplication();
mm.Division();
Console.Read();
}
}
}
Output:
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;
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();
}
}
}
Output:
Ref Parameters
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++.
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();
}
}
}
Output:
Out Parameters
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;
return (big);
}
}
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();
}
}
}
Output:
this Keyword
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.
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();
}
}
}
Output:
Named Parameters
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 NamedParametersDemo
{
class User
{
//fields
public string FirstName;
public string LastName;
//methods
public void SetUserName(string FirstName, string LastName)
{
this.FirstName = FirstName;
this.LastName = LastName;
}
Console.Read();
}
}
}
Output:
Static Members
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.
Object1
p
q
Sample
class sample r
{ s
int p; Object2
double q; p
static int r; q
static double s;
}
Object3
p
q
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;
}
//static methods
public static void DisplayCollegeDetails()
{
Console.WriteLine(CollegeName);
Console.WriteLine(CollegeAddress);
}
}
class Program
{
static void Main(string[] args)
{
//access static members
Student.DisplayCollegeDetails();
Console.Read();
}
}
}
Output:
Static Classes
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).
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();
}
}
}
Output:
Rules of Constructors:
Types of Constructors:
i) Implicit constructor:
A constructor, offered by the compiler implicitly is called as "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()
{
---------------;
---------------;
}
Destructor
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.
The destructor is used to implement any process that is to be performed at the time of
object closing.
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);
}
//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();
Console.Read();
}
}
}
Object Initializer
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, };
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();
}
}
}
Output:
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();
}
}
}
Output:
Method Overloading
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.
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);
}
}
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();
}
}
}
Output:
Operator Overloading
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:
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.
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;
}
//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);
}
}
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);
Output:
Generics
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.
Types of Generics:
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.
According to generic classes, when an instance is created, the required type of values
could be stored as the data members.
According to generic methods, when you call a method, you can pass different types of
arguments to the same method, without overloading it.
Object Construction:
classname<data type> objname = new classname<data type>;
Method Calling:
methodname<data type>(value);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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();
Console.Read();
}
}
}
Output:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GenericMethodsDemo
{
class Sample
{
public void ReverseAndPrint<T>(T[] arr)
{
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 };
Console.Read();
}
}
}
Output:
Properties
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.
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.
Note: There should be some difference in the variable name and property name.
Ex:
private string name;
public string Name
{
set
{
name = value;
}
get
{
return (name);
}
}
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;
}
}
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();
}
}
}
Output:
Ex:
private string name;
public string Name
{
get
{
return (name);
}
}
Ex:
private string name;
public string Name
{
set
{
name = value;
}
}
Ex:
public string Name { get; set; }
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)
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;
namespace ClassDefInSeperateFiles
{
class Program
{
static void Main(string[] args)
{
Demo d = new Demo();
d.DemoMethod();
Console.Read();
}
}
}
Output:
Partial Classes
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
}
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.");
}
}
}
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();
}
}
}
Output:
Indexer
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()
{
//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.ShowCountries();
Console.Read();
}
}
}
Output:
Inheritance
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. BaseClass
That means the parent class members are re-usable in the child
class.
The parent class can also be called as "Base" / "Super" class. DerivedClass
The child class can also be called as "Derived" / Sub class.
1) Implementation Inheritance:
2) Interface Inheritance:
Types of Inheritance:
1) Single Inheritance
2) Hierarchical Inheritance
DerivedClass 1 DerivedClass 2
3) Multi-Level Inheritance
4) Multiple Inheritance
An inheritance relationship,
with only multiple super classes BaseClass 1 BaseClass 2
and only one sub class.
Multiple Implementation
Inheritance is not supported DerivedClass
by C#, but Multiple Interface
Inheritance is supported by C#.
BaseClass
5) Hybrid Inheritance
An inheritance relationship
that contains a
Intermediate Class 1 Intermediate Class 2
combination of any other
two types of inheritances.
Ex: DerivedClass
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.
Invoke members
obj.SuperClassMember
obj.SubClassMember
Example
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.
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();
Console.Read();
}
}
}
Output:
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();
}
}
}
Output:
Sealed Classes
}
class two : one //cant inherit this. Will give a compilation error.
{
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();
}
}
}
Output:
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();
}
}
}
Output:
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
{
Output:
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.
Implementation Syntax:
abstract class abstractclassname
{
//data members if any
//non-abstract methods if any
accessmodifier abstract returntype methodname(arguments);
}
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
{
Output:
Summary of Modifiers
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.
Modifier Applies to Description
No
The method hides a base class method with same
1 new Methods only
signature.
The member does not depends / instantiates with any of
2 static All members 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.
The abstract class cant be instantiated.
The abstract method is nothing but a virtual method that
Classes and
4 abstract contains only declaration with no definition. It should be
Methods only
implemented with override keyword in the derived
class.
The member overrides an inherited virtual or abstract
5 override Methods only
member of the base class.
Interfaces
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.
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();
}
}
}
Output:
Structures
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.
Implementation:
Define structure
struct structurename
{
//fields
//methods
}
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();
}
}
}
Output:
Extension Methods
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.
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();
}
}
}
Output:
Delegates
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:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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);
Console.Read();
}
}
}
Output:
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();
}
}
}
Output:
Manipulations on Arrays
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);
Note: Reverse is a static method of Array class. It exactly reverses the all
the array elements.
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);
//string array
Console.WriteLine("\nString array:");
//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();
}
}
}
Output:
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();
}
}
}
Output:
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");
//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);
//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);
Console.Read();
}
}
}
Output:
Object Implementation:
Date Comparisons
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.
Date Difference
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());
//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());
//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;
Console.WriteLine("\nThe difference between dt2 and dt1 is: " + ts.Days + " days.");
Console.Read();
}
}
}
Output:
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();
}
}
}
Output:
Collections
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.
Collection Classes:
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.
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];
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)
{
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.Read();
}
}
}
Output:
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");
al.Add("How r u");
al.Add(1000);
al.Add(true);
al.Add(DateTime.Now);
Console.Read();
}
}
}
Output:
Collection Initializer
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, . };
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
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();
}
}
}
Output:
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();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Printing;
namespace PrintingDemo
{
class Program
{
Output:
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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace DriveInfoDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the drive letter (a to z):");
string driveletter = Console.ReadLine();
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();
}
}
}
Output:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace GetDrivesDemo
{
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();
}
}
}
Output:
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.
GetFiles() Gets all the files in the directory as FileInfo class object array.
Gets the files in the directory as FileInfo class object array,
GetFiles(search pattern)
based on the given search pattern.
Gets all the directories in the directory as DirectoryInfo class
GetDirectories()
object array.
GetDirectories(search Gets the directories in the directory as DirectoryInfo class object
pattern) array, based on the given search pattern.
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();
}
}
}
Output:
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();
}
}
}
Output:
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();
}
}
}
Output:
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.
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();
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();
}
}
}
Output:
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
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();
Console.WriteLine("\nWritten successfully!");
}
else
Console.WriteLine("File already exists.");
Console.Read();
}
}
}
Output:
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();
}
}
}
Output:
Multi Threading
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
OS
Thread 1
CLR
Thread 2
Thread 3
Processor
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();
}
}
class Program
{
static void Main(string[] args)
{
ThreadingDemo td = new ThreadingDemo();
td.Display();
Console.Read();
}
}
}
Output:
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.
Ready
Start()
Running
Sleeping
Suspend()
Resume()
Suspended
Automatic / Abort()
Dead
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.
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();
}
}
Output:
Anonymous Methods
This is used to create a method, without any name.
Syntax:
delegate()
{
//some code
}
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();
}
}
class Program
{
static void Main(string[] args)
{
string name;
Console.WriteLine("Enter your name:");
name = Console.ReadLine();
Console.Read();
}
}
}
Output:
Speech Translation
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);
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();
ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Child);
ss.SpeakAsync(TextToSpeak);
Console.Read();
}
}
}
Output:
Memory Management
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 RAM
o Heap
Now, we need to understand, where the
application memory is getting allocated in the Stack
RAM.
The storage area in the RAM depends on the
data type that you are using for declaring the Heap
variable in the program.
The data types are two types in C#
o Value Types
o Reference Types
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:
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.
Object
ValueType
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();
if (x.Equals(y))
Console.WriteLine("x is equal to y");
else
Console.WriteLine("x is not equal to y");
string s = x.ToString();
Console.WriteLine("\nThe integer value after converting into string is: " + s);
Console.Read();
}
}
}
Output:
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.
Object 1
Object 2
Object 3
Object 4
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();
LINQ
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.
Introduction:
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..
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;
//output
foreach (var x in result)
Console.WriteLine(x);
Console.Read();
}
}
}
Output:
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.
LINQ Syntax:
Mandatory clauses:
from clause
in clause
select clause
Understanding Clauses:
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;
//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)};
Console.Read();
}
}
}
Output:
goes to
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)};
Console.Read();
}
}
}
Output:
Exception Handling
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.
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.
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();
}
}
}
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.
try
{
---------------------;
---------------------;
---------------------;
---------------------;
}
catch (Exception ex)
{
--------------------;
--------------------;
}
finally
{
--------------------;
--------------------;
}
1) try block:
The try block contains the actual code, which
is to be executed. try
{
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 catch (Exception ex)
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
3) finally block:
finally
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();
}
}
}
}
Output:
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
Exceptional Classes
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;
n3 = n1 / n2;
Output:
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;
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();
}
}
}
Output:
The EventLog
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);
Output:
Debugging
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.
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.
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.
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.
Assemblies
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.
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.
In this example,
Class Library Project: SharedAssemblyLibrary
Console Application Project: SharedAssemblyDemo
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;
}
}
}
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.
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();
Console.Read();
}
}
}
Output:
Almost all the softwares you are using today like Notepad, WordPad,
Paint, MS Word, My computer and My documents etc., are the GUI
applications.
A Windows Application
Form:
Then it will create a windows forms application, along with a form, named Form1.
Then the screen looks like this:
Development of a 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:
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:
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>
//
// 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();
#endregion
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).
Form1.cs
importing section;
namespace ProjectName
{
public partial class FormName : Form
{
public FormName()
{
InitializeComponent();
}
}
}
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.
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.
Application.Run(new Form1());
This statement creates a new Form1 class object and that object will be
shown on the screen.
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.
Specifies the mouse pointer style, when the mouse is over on the control at
Cursor
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.
Specifies the image that is to be displayed in the control along with the
Image
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
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.
Executes when any key is pressed on the keyboard, while the focus is on
KeyPress
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.
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
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:
TabIndex controlname.TabIndex = n;
button1.Image = Image.FromFile("c:\\flagindia.gif");
button1.ImageAlign = ContentAlignment.MiddleLeft;
button1.TextAlign = ContentAlignment.MiddleRight;
button1.Size = new Size(200, 60);
}
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 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.
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.
Design
button1:
Text: Click Me
BackColor: DarkRed
ForeColor: Yellow
Form1.cs
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
The System.Windows.Forms.Form class offers few properties, methods and events for each
user-defined form class.
While you are changing the property values, you remember and follow the following syntaxes:
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
(or)
WindowState this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
(or)
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
Cursor this.Cursor = System.Windows.Forms.Cursors.xxxxx;
Opacity this.Opacity = n;
Design
Form1:
Text: Click the form
Design
button1:
Text: Red
Name: btnRed
button2:
Text: Green
Name: btnGreen
button3:
Text: Blue
Name: btnBlue
Design
button1:
Text: Normal
Name: btnNormal
button2:
Text: Minimize
Name: btnMinimize
button3:
Text: Maximize
Name: btnMaximize
button3:
Text: Exit
Name: btnExit
this.WindowState = FormWindowState.Maximized;
}
Design
button1:
Text: Show Background Image
Name: btnShowBackgroundImage
button2:
Text: Clear Background Image
Name: btnClearBackgroundImage
1) Button
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.
Specifies the image that is to be displayed in the control along with the
Image
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.
Executes when any key is pressed on the keyboard, while the focus is on
KeyPress
the control.
Enter Executes when the focus is get into the control.
Leave Executes when the focus is out of the control.
2) Label
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.
Specifies the X and Y co-ordinations of the controls position on the
Location
form.
TextAlign Specifies the position of the text in the control.
Specifies the image that is to be displayed in the control along with
Image
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.
Enables / disables automatic sizing of the control, based on the
AutoSize
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.
Executes when any key is pressed on the keyboard, while the focus
KeyPress
is on the control.
Enter Executes when the focus is entered into the control.
Leave Executes when the focus is out of the control.
3) TextBox
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.
Specifies the X and Y co-ordinations of the controls position on the
Location
form.
Specifies the position of the text in the control (Left / Center /
TextAlign
Right)
Specifies the image that is to be displayed in the control along with
Image
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.
Enables / disables read-only nature of the textbox. In the read only
ReadOnly
textbox, the user can not enter any text.
Enables / disables multiple lines in the text box. By default, the text
MultiLine
box will be single-line textbox.
This is used in multi line textboxes, which automatically moves the
WordWrap
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: *
Specifies the maximum no. of characters that can be entered in the
MaxLength
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.
Executes when any key is pressed on the keyboard, while the focus
KeyPress
is on 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.
Design
label1:
Text: Enter First Value:
Name: lblFirstValue (Continued)
button3:
textBox1: Name: btnMultiply
Name: txtFirstValue Text: *
label2: button4:
Text: Enter Second Value: Name: btnDivide
Name: lblSecondValue Text: /
button1: label3:
Name: btnAdd Name: lblResult
Text: + Text: Result:
button2: textBox3:
Name: btnSubtract Name: txtResult
Text: - ReadOnly: True
Design
label1:
Text: Enter your text here:
Name: lblSourceText
textBox1:
Name: txtSourceText
label2:
Text: Copied Text:
Name: lblDestinationText
button1:
Name: txtDestinationText
ReadOnly: True
label3:
Text: To:
Name: lblTo
textBox2:
Name: txtTo
button1:
Name: btnGo
Text: GO
textBox3:
Name: txtNumbers
ReadOnly: True
MultiLine: True
ScollBars: Vertical
4) CheckBox
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.
Represents the current status of the check box, whether it is
Checked
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.
5) RadioButton
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.
Represents the current status of the check box, whether it is
Checked
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.
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
6) LinkLabel
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.
Design
linkLabel1:
Text: My Link Label:
Name: linkLabel1
7) PictureBox
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.
Specifies mode of the image sizing in the control.
SizeMode
(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
Design button2:
label1: Text: Clear Image
Text: Enter image path: Name: btnClearImage
Name: lblEnterImagePath
label2: radioButton3:
textBox1: Text: Size Mode: Text: Auto Size
Name: txtImagePath ForeColor: Red Name: rbAutoSize
button1: radioButton1: radioButton4:
Text: Show Text: Normal Text: Center
Name: btnShow Name: rbNormal Name: rbCenter
pictureBox1: radioButton2: radioButton5:
BorderStyle: Fixed3D Text: Stretch Text: Zoom
Name: picBoxImage Name: rbStretch Name: rbZoom
using System.IO;
8) Panel
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.
9) GroupBox
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
Design
textBox1:
Name: txtMyTextBox radioButton3:
Text: Yellow
groupBox1: Name: rbYellow
Name: grpBackgroundColor
Text: TextBox Background Color: radioButton4:
Text: Blue
groupBox2: Name: rbBlue
Name: grpForegroundColor
Text: TextBox Foreground Color: radioButton5:
radioButton1: Text: Green
Text: White Name: rbGreen
Name: rbWhite
radioButton6:
radioButton2: Text: Orange
Text: Red Name: rbOrange
Name: rbRed
10) ListBox
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.
Specifies mode of the item selection.
None No item can be selected.
SelectionMode 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
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,
Inserts a new item at the specified position.
xxxx)
ListboxName.Items.RemoveAt(index) Removes an item, based on its index.
ListboxName.Items.Clear() Removes all the items in the list box.
Searches the given string the items collection, and returns the
ListboxName.Items.IndexOf(xxxx)
index, if it is found; otherwise, it returns -1.
Design
label1:
Name: lblSelectCourse
Text: Select your Course:
label3:
listBox1: Name: lblSelectedCourse
Name: lstCourses Text: Selected Course Here
Items: .NET 4.0
Java label4:
Share Point Name: lblSelectedCourseIndexPrompt
Oracle DBA Text: Selected Course Index:
Sql Server label5:
QTP Name: lblSelectedCourseIndex
MS BI Text: Selected Course Index Here
label2:
Name: lblSelectedCoursePrompt
Text: Selected Course:
Design
groupBox1:
Name: grpCities
Text: Cities:
listBox1: button1:
Name: lstCities Name: btnAdd
Items: Hyderabad Text: Add
Pune
New Delhi button2:
Banglore Name: btnRemoveCity
Dehradun Items: Remove Selected City
groupBox2: button3:
Name: grpOptions Name: btnClearAll
Text: Options: Text: Clear All
label1: button4:
Name: lblNewCity Name: btnShowCount
Text: New City Name: Text: Show Count
textBox1:
Name: txtNewCity
Design
label1:
Name: lblAvailableBooks
Text: Available Books: label2:
listBox1: Name: lblSelectedBooks
Name: lstAvailableBooks Text: Selected Books:
Sorted: True listBox2:
SelectionMode: MultiSimple Name: lstSelectedBooks
Items: ASP.NET for Professionals Sorted: True
C# 4.0 for Beginners
HTML 4.0 button1:
Java Complete Reference Name: btnSend
JavaScript Bible
Let Us C
Let Us C++
11) ComboBox
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.
Simple: It looks like a text box, but the items can be accessed by pressing up / down
arrow keys.
DropDownStyle 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
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.
Searches the given string the items collection, and returns the
cmbObj.Items.IndexOf(xxxx)
index, if it is found; otherwise, it returns -1.
cmbObj.Clear() Clears the text entered in the combo box.
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
12) NumericUpDown
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
13) DomainUpDown
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
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.
Searches the given string the items collection, and returns the
domObj.Items.IndexOf(xxxx)
index, if it is found; otherwise, it returns -1.
domObj.Clear() Clears the text entered in the domainupdown.
Design
textBox1:
Name: txtMyText
label1:
label2:
Name: lblFont
Name: lblSize
Text: Font:
Text: Size:
domainUpDown1:
label3:
Name: domFont
Name: numSize
Text: Tahoma
Value: 10
Items: Times New Roman
Minimum: 1
Tahoma
Maximum: 100
Arial
Arial Black
Century Gothic
Trebuchet MS
Palatino Linotype
14) DateTimePicker
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)
Used to specify the customer date formats. (with words and symbols like dd,
CustomFormat
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
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
15) MonthCalendar
API: System.Windows.Forms.MonthCalendar
Naming Convension: monCalxxxxxx
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.
Design
label1:
Name: lblSelectAnyDate
Text: Select any Date:
monthCalendar1:
Name: monCalMyDate
label2:
Name: lblSelectedDate
Text: Select Date Here
16) TrackBar
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
Design
label1:
Name: lblFontSize
Text: Font Size:
trackBar1:
Name: trkFontSize
Minimum: 1
Maximum: 200
TickFrequency: 5
label2:
Name: lblMyText
Text: .NET Framework 4
17) Timer
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.
Design
label1:
Name: lblTime
Text: Time here
timer1:
Name: tmrTime
Interval: 1000
Enabled: True
Design
timer1:
Name: tmrBackColor
Interval: 500
Enabled: True
int n = 0;
18) ProgressBar
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
Design
label1:
Name: lblFileName
Text: Enter File Name:
textBox1:
Name: txtFileName textBox2:
Name: txtContent
button1: ReadOnly: True
Name: btnOpen WordWrap: False
Text: Open Multiline: True
label2: Scrollbars: Both
Name: lblLoading timer1:
Text: Loading Name: tmrFileOpen
ForeColor: Red Enabled: False
Visible: False Interval: 100
progressBar1:
Name: prgFile
Visible: False
using System.IO;
19) MenuStrip
API: System.Windows.Forms.MenuStrip
Naming Convension: mnuxxxxxx
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
20) ContextMenuStrip
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
contextMenuStrip1:
Name: conMnuForm
displayIconToolStripMenuItem:
Checked: True
showInTaskBarToolStripMenuItem:
Checked: True
contextMenuStrip2:
Name: conMnuTextBox
Form1:
ContextMenuStrip: contextMenuStrip
Text: conMnuForm
textBox1:
Name: txtMyText
ContextMenuStrip: conMnuTextBox
Dialog Controls
Note: All the dialog box controls are known as invisible controls.
21) ColorDialog
API: System.Windows.Forms.ColorDialog
Naming Convension: colorDlgxxxxxx
Design
button1:
Name: btnBackColor
Text: Back Color
colorDialog1:
Name: colorDlgBackColor
22) FontDialog
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
Design
textBox1:
Name: txtMyText
button1:
Name: btnFont
Text: Font
fontDialog1:
Name: fontDialogMyText
23) FolderBrowserDialog
API: System.Windows.Forms.FolderBrowserDialog
Naming Convension: folderBrowserDlgxxxxxx
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
using System.IO;
24) OpenFileDialog
API: System.Windows.Forms.OpenFileDialog
Naming Convension: openFileDlgxxxxxx
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
using System.IO;
25) SaveFileDialog
API: System.Windows.Forms.SaveFileDialog
Naming Convension: saveFileDlgxxxxxx
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
using System.IO;
26) PrintDialog
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
Design
label1:
Name: lblFileName
Text: Enter File Name:
textBox1:
Name: txtFileName
button1:
Name: btnBrowse
Text: Browse...
button2:
Name: btnPrint
Text: Print
using System.Drawing.Printing;
using System.IO;
27) RichTextBox
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
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.
rtbMyText.LoadFile(openFileDialog1.FileName);
this.Text = openFileDialog1.FileName;
IsFileSaved = true;
}
}
}
}
colorDialog1.ShowDialog();
rtbMyText.SelectionBackColor = colorDialog1.Color;
}
28) NotifyIcon
Creates an icon at the systems notification area (on the windows task bar).
API: System.Windows.Forms.NotifyIcon
Naming Convension: notifyxxxxxx
Design
notifyIcon1:
Name: notifyIcon1
Text: My Application
Icon: laptop.ico
29) TabControl
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
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
30) TreeView
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
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:
MDI Applications
The windows applications are of two types.
1) SDI Applications (Single Document Interface)
2) MDI Applications (Multiple Document Interface)
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.
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.
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();
Design
Form1:
IsMdiContainer: True
Form1.cs
Form1.cs
Library: System.Windows.Forms.MessageBox
Syntax:
MessageBox.Show(message);
MessageBox.Show(message, title);
1) MessageBoxButtons.OK
2) MessageBoxButtons.OKCancel
3) MessageBoxButtons.YesNo
4) MessageBoxButtons.YesNoCancel
5) MessageBoxButtons.RetryCancel
6) MessageBoxButtons.AbortRetryIgnore
Sometimes, you may need to add the controls programmatically at run time.
obj.property = value;
containername.Add(value);
Design
button1:
Text: Add Exit Button
Output:
Design
button1:
Name: btnShowNumbers
Text: Show Numbers
textBox1:
ReadOnly: True
TextAlign: Right
Output:
User Controls
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).
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.
Note: To add additional user controls within the same project, just click on
Project menu and choose Add User Control.
GDI+ graphics
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.
Implementation:
In the above code, the CreateGraphics() method creates a graphics object, that is able to write
the GDI graphics in the container (form).
1) Drawing Lines
g.DrawLine(Pens.xxxx, x1, y1, x2, y2);
2) Drawing Rectangles
g.DrawRectangle(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);
Application 132: Demo on GDI (Drawing Lines, Rectangles, Circles, Triangles, Curves)
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.
Click on Save button to save the table. Then it asks for the table name. Enter
the desired table name.
2. DROP
drop table tablename;
3. ALTER
alter table tablename add columnname datatype(width);
alter table tablename drop column columnname;
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;
use master
drop database test
GO
use test
GO
select * from Products where price not between 2000 and 8000
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.
Procedure:
GO
execute ShowSquare 5
Function:
GO
select dbo.GetCube(5)
ADO.NET
(ActiveX Data Objects.NET)
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.
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
Data
DataSet
DataTable
DataRow
DataColumn
SqlClient OleDb
SqlConnection OleDbConnection
SqlCommand OleDbCommand
SqlDataReader OleDbDataReader
SqlDataAdapter OleDbDataAdapter
SqlParameter OleDbParameter
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.
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.
Connection
ConnectionString
Open()
Close()
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.
using System.Data.SqlClient;
using System.Data.OleDb;
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
Connection Command
ConnectionString CommandText
Open() Connection
Close() CommandType
Parameters
ExecuteNonQuery()
ExecuteReader()
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.
Demo:
Open SQL Server 2005.
Create a new database, with name as demo.
In that database, create a table named Customers, as shown below.
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
Insertion.cs
using System.Data.SqlClient;
//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();
}
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();
if (n > 0)
MessageBox.Show(n + " Row Inserted.");
else
MessageBox.Show("Insertion failed.");
cn.Close();
}
Note: While you are preparing the CommandText with user-entered values, to remember the
concatenation syntax in the above example, remember the following syntax:
Deletion.cs
using System.Data.SqlClient;
//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();
}
Updation.cs
using System.Data.SqlClient;
string gen;
if (radioButton1.Checked == true)
gen = "Male";
else
gen = "Female";
//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();
}
Connection
.NET
Application
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.
Connection
ConnectionString
Open()
Close()
Command
CommandText
Connection
CommandType
Parameters
ExecuteNonQuery()
ExecuteReader()
DataReader
Read()
[column_name]
[index]
Close()
Ex:
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)
dr.Read();
(true)
dr.Read();
(true)
dr.Read();
(true)
dr.Read();
(false)
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.
Demo:
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
DataReaderDemo.cs
using System.Data.SqlClient;
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from customers";
cmd.Connection = cn;
//DataReader impl
SqlDataReader dr;
dr = cmd.ExecuteReader();
dr.Close();
cn.Close();
}
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:
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:
Form1.cs
DataReaderDemo_RecordByRecord.cs
using System.Data.SqlClient;
SqlDataReader dr;
SqlConnection cn = new SqlConnection();
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from customers";
cmd.Connection = cn;
//DataReader impl
dr = cmd.ExecuteReader();
{
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...");
}
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:
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:
Form1.cs
DataReaderDemo_ConditionalData.cs
using System.Data.SqlClient;
//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;
dr = cmd.ExecuteReader();
dr.Close();
cn.Close();
}
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.
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.
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.
Connection
DataSet
DataTable
0
1
2
3
.NET DataRow
Application 0 1 2
Connection
ConnectionString
Open()
Close()
DataAdapter
DataAdapter(select statement, connection_object)
Fill(dataset_object)
DataSet
Tables[table_index]
Clear()
DataTable
Rows.Count
Rows[row_index]
Columns.Count
Columns[column_index]
DataRow
[column_index]
[column name]
Clear(): Clears all the tables, and makes the dataset empty.
Demo:
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
DataSetDemo.cs
using System.Data;
using System.Data.SqlClient;
//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];
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:
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:
Form1.cs
private void
viewDataUsingDataSetFlexibleRecordsPresentationToolStripMenuItem_Click(object sender,
EventArgs e)
{
DataSetDemo_FlexibleRecords f = new DataSetDemo_FlexibleRecords();
f.MdiParent = this;
f.Show();
}
DataSetDemo_FlexibleRecords.cs
using System.Data;
using System.Data.SqlClient;
DataTable dt;
int RowIndex;
DataRow drow;
//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];
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.
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:
Add the menu item View Data using Data Set - DataGridView as shown below:
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:
Form1.cs
DataSetDemo_DataGridView.cs
using System.Data;
using System.Data.SqlClient;
//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;
}
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.
Library:
Connection: Maintains the connection with database.
Command: Calls a database procedure / function.
Parameter: Represents the argument value for the procedure / function.
Connection
Command
(provider, data (procedure / .NET
db Source, user id, function name,
parameters) Application
password)
Demo:
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:
Form1.cs
StoredProcedureDemo.cs
using System.Data.SqlClient;
//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();
}
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:
Form1.cs
StoredProcedureDemo_MultipleTables.cs
using System.Data;
using System.Data.SqlClient;
//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("getdata", cn);
//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);
//DataTable impl
DataTable dt1, dt2;
dt1 = ds.Tables[0];
dt2 = ds.Tables[1];
//grid logic
dataGridView1.DataSource = dt1;
dataGridView2.DataSource = dt2;
}
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.
</appSettings>
</configuration>
In the <appSettings> tag, use <add> tag to declare the actual application
configuration setting values.
Note: The key is used to access the configuration setting value in the code.
App.Config
Form1.cs
using System.Configuration;
using System.Data.SqlClient;
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.
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)
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.
(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
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.
Output:
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.
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.
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
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.
UI
Business Access
Presentation Layer
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
Data
Business Access Access
Presentation Layer
Layer Layer
db
UI
Data
Business Access Access
Presentation Layer
Layer Layer
db
A. DCOM:
It is in usage, before .NET.
It is platform dependent.
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.)
App.Config
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);
}
}
}
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;
}
}
}
3TierArchitectureDemo LoginForm.cs
.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.
Channels (TCP/HTTP)
.NET Assembly
.NET Assembly Send a Request
Class
Channels (TCP/HTTP)
Proxy Object
(Client Activated Object) (Server Activated Object)
Send the Reference
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)
Note: In the client application and server application, we have to register any
one of the channels compulsory.
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteClass), "alias_name",
WellKnownObjectMode.SingleCall / SingleTon);
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.
IRemote irem;
irem = (IRemote)Activator.GetObject(typeof(IRemote), tcp://server:port/alias_name);
.NET Remoting
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:
Datab
baseLogic.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);
}
}
}
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);
}
}
}
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.
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);
}
}
}
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.
Form1.cs:
using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using RemoteLibrary;
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.
Library:
1) System.Net.Sockets
2) Some classes from System.IO
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);
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);
Application 152: Demo on Message Passing between Client and Server using Sockets
using System.Net.Sockets;
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.
using System.Net.Sockets;
using System.IO;
using System.Net;
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.
Windows Services
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.
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()
{
InitializeComponent();
}
Thread th1;
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
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.
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.
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.
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)
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.
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:
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;
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");
}
}
}
}
using System.IO;
installutil D:\ChatService\ChatService\bin\Debug\ChatService.exe
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.
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.
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.
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
To install the application, simply double click on the Setup file and complete the wizard
steps.
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).
C#.NET 4.0
Frequently
Asked
Questions
(FAQs)
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 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.
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.
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
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).
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.
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.
Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited.
But they are.
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.
System.Object.
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?
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.
No, moreover, you cannot access private methods in inherited classes, have to be protected in the
base class to allow any sort of access.
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.
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.
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.
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.
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.
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.
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.
No.
The first one performs a deep copy of the array, the second one is shallow.
28. How can you sort the elements of the array in descending order?
29. Whats the .NET datatype that allows the retrieval of data by a unique key?
HashTable.
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 {}.
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.
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.
A delegate object encapsulates a reference to a method. In C++ they were referred to as function
pointers.
Its a delegate that points to and eventually fires off several methods.
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.
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.
System.Globalization, System.Resources.
41. Whats the difference between // comments, /* */ comments and /// comments?
42. How do you generate documentation from the C# file commented properly with a command-
line compiler?
43. Whats the difference between <c> and <code> XML documentation tag?
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.
It points to the object thats pointed to by this reference. Objects instance data is shown.
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.
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.
To the Console or a text file depending on the parameter passed to the constructor.
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).
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.
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.
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%.
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).
Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL
Server username and passwords).
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.
62. What does the parameter Initial Catalog define inside Connection String?
Microsoft.Access.
Multiple processes must agree that they will share the same connection, where every parameter is
the same, including the security settings.
WinForms FAQ:
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.
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.
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
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.
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.
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 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#.
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.
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).
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.
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.
How can you automatically generate interface for the remotable object in .NET with Microsoft tools?
Use the Soapsuds tool.
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 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.
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.
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.
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.
In C#
Private DataType mPropertyName;
public returntype PropertyName
{
get{
//property implementation goes here
return mPropertyName;
}
// Do not write the set implementation
}
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));
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.
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.
What's different about namespace declaration when comparing that to package declaration in Java?
No semicolon.
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
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
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.
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.
7. Which method do you invoke on the DataAdapter control to load your generated dataset with
data?
Fill()
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();
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){
T-SQL Queries
1. 2 tables
Employee Phone
empid
empname empid
salary phnumber
mgrid
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))
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
Emp City
Empid
Empid
empName
City
Salary
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)))
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
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.
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
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)
Datepart Abbreviations
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw
hour hh
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
(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
mirinda 0
pepsi 10
INDEX
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.
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
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
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.
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
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.