Presented By,: Aditya Ranjan Dutta

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 138

PRESENTED BY,

Aditya Ranjan Dutta

July 29, 2008 1


What is .NET?

 A new component of the Microsoft Corporation.

 It is a set of Software Technologies for connecting


Information, People, Systems and Devices.

 Now a days, . Net Framework is running on Pocket


PC,smart phone, desktop computer.

July 29, 2008 2


History of .NET
 Microsoft Started development of .NET Framework in the
late 1990’s with the Code name “Next Generation Windows
Services”.

 June 22, 2000 at Forum 2000 Bill Gates delivered a keynote


about .Net technology.

 The delegates were given CDs Containing a pre-release


version of The .Net Framework /SDK and Visual Studio.NET.

 The final version of the SDK 1.0 and Runtime was made
publicly available on 15-Jan-2002.

July 29, 2008 3


Different Versions of .NET
Version Name Release Date
1.0 Beta1 Nov-2000

1.0 Beta2 Jun-2001

1.0 RTM Jan-2002

1.0 Sp1 Mar-2002


1.0 Sp2 Aug-2002

1.0 Sp3 Aug-2004


1.1 Sp1 Aug-2004
1.1 Sp1(os2003) Aug-2005
2.0 RTM Mar-2005
3.0 RTM Nov-2006
July 29, 2008 3.5 RTM April-2008 4
Changes Happened in .NET

July 29, 2008 5


NET Provides
 The ability to make the entire range of computing devices
work together and to have user information automatically
updated and synchronized on all of them.

 Increase interactive capability of web site.

 Centralized data storage which will increase efficiency and


ease of access to information, as well as synchronization of
information among user and device.

 For developers, the ability to create reusable modules,


which will increase productivity and reduce the number of
programming errors.

July 29, 2008 6


Advantages of .NET

 Common Language Runtime (CLR).

 Common Library Management (CLM).

 Garbage Collection.

 Intermediate Language Support.

July 29, 2008 7


Scope of .NET

 Mobile Web Application

 Client-Server Utility

 Resource Technology

 Window Application converted to web Application

July 29, 2008 8


Overview

Is a platform environment.
.NET Languages:

 VB.NET

 ASP.NET

 C#.NET

 C++.NET

 J#.NET

July 29, 2008 9


APPLICATION TYPES

The CLR supports the following types of


applications:

 Console

 Windows Forms

 Web Forms

 Web Services

July 29, 2008 10


FRAME WORK OF .NET

VB.NET ASP.NET C# J#

SOURCE CODE S.C


S.C S.C S.C S.C

M.L M.L M.L M.L MACHINE LANGUAGE M.L

CLR (JUST IN TIME COMPILER)

MANGED CODE
M.C M.C M.C M.C M.C

NA TIVE CODE
N.C N.C N.C N.C N.C

Operating System

July 29, 2008 11


CLR(Common Language Runtime)

 Heart Of Dot Net.

 Memory management.

 Exception handling.

 Language Interswapping.

 Internal code to native code.

 Enforce type safety.

July 29, 2008 12


CIL (Common Intermediate Language )

 Common Intermediate Language (CIL) is previously known as


Microsoft Intermediate Language or MSIL.

 CIL is the lowest-level human-readable programming


language in the Common Language Infrastructure and in the
.NET Framework.

 Languages which target the .NET Framework compile to CIL,


which is assembled into byte code.

 CIL is an object-oriented assembly language, and is entirely


stack-based. It is executed by a virtual machine.

July 29, 2008 13


CTS

 CTS stands for Common type System.

 It Contains Set of common data types that are common to all


dot net languages

 The CTS defines the rules by which all types are declared,
defined and managed, regardless of source language.

 The CTS is designed to be rich and flexible enough to support a


wide variety of source languages, and is the basis for cross-
language integration, type safety, and managed execution
services.

July 29, 2008 14


CLS

 CLS stands for Common Language Specification.

 CLS contains rules that are to be followed for .net frame work
supported languages.

 The CLS defines the reasonable subset of the CTS that should
be sufficient to support cross-language integration, and
specifically excludes problem areas such as unsigned integers,
operator overloading, and more.

 The widely supported CLS has led to many languages being


adapted to target the .NET platform.

July 29, 2008 15


Assembly
 An Assembly may be an exe, a DLL, an application having an
entry point, or a library. It may consist of one or more files.

 It represents a group of resources, type definitions, and


implementation of these types. They may contain references to
other assemblies.

 These resources, types & references are compacted in a block


of data called manifest.

 The manifest is a part of the assembly, which makes it self-


describing. Assemblies also increase security of code in .NET.

 An assembly may be created by building the class (the .vb or


.cs file), thereby producing its DLL.……………………………………
………………………...
July 29, 2008 16
Assembly

Type of Assembly:
There are three types of Assembly. They are
• Private Assembly - This type of assembly is used by a
single application. It is stored in the application's directory or
the applications sub-directory. There is no version constraint
in a private assembly.
• Shared Assembly or Public Assembly - A shared
assembly has version constraint. It is stored in the Global
Assembly Cache (GAC). The shared assemblies may be used
by many applications.
• Satellite Assembly - is an assembly that contains only
resources, and no code. The resources are location specific.
A satellite assembly is associated with a main assembly, the
one that actually contains the code.
July 29, 2008 17
GAC Assembly

 GAC stands for Global Assembly Cache.

 A shared assembly has version constraints. It is stored in the


Global Assembly Cache (GAC).

 GAC is a repository of shared assemblies maintained by the


.NET runtime. The shared assemblies may be used by many
applications.

 It is located at C:\Windows\Assembly OR C:\Winnt\Assembly.

July 29, 2008 18


Metadata
 Metadata is binary information describing .NET program that is
stored either in a common language runtime portable executable
(PE) file or in memory.

 Every type and member defined and referenced in a module or


assembly is described within metadata.

 When code is executed, the runtime loads metadata into


memory and references it to discover information about the
programs code's classes, members, inheritance, and so on.

 Metadata describes every type and member defined in your code


in a language-neutral manner.
July 29, 2008 19
Metadata

Metadata stores the following information:


1. Description of the assembly.
 Identity (name, version, culture, public key).
 The types that are exported.
 Other assemblies that this assembly depends on.
 Security permissions needed to run.

2. Description of types.
 Name, visibility, base class, and interfaces implemented.
 Members (methods, fields, properties, events, nested types).

3. Attributes.
 Additional descriptive elements that modify types and
Julymembers.
29, 2008 20
Metadata
Benefits of Metadata:
1. Self-describing files
 Common language runtime modules and assemblies are self-describing.
 A module's metadata contains everything needed to interact with another
module.
 Metadata automatically provides the functionality of IDL in COM, allows to use
one file for both definition and implementation.
 Runtime modules and assemblies do not even require registration with the
operating system.
 The descriptions used by the runtime always reflect the actual code in the
compiled file, which increases application reliability.

2. Language Interoperability and easier component-based design


 Metadata provides all the information required about compiled code to inherit a
class from a PE file written in a different language.
 You can create an instance of any class written in any managed language

3. Attributes
 Attributes can be found throughout the .NET Framework and are used to control
in more detail how your program behaves at run time.
July 29, 2008 21
Versioning

 Versioning enables to solve the DLL hell problem in .NET which is


found in ASP and VB. DLL hell is nothing but a higher version of
DLL overwrites the older version.

 .NET maintain one application with more then one version and
also solve DLL HELL problem because it can run same application
with different version at a same time.

 The NET Framework helps by minimizing conflicts between


components with a new versioning strategy involving public and
private components. Private components reside in the same
directory as the application using them. Applications don't
consider component version when they re using private
components.
July 29, 2008 22
Namespaces

Major Namespaces and their use:


System: Includes essential classes and base classes for commonly used data types,
events,
exceptions
System.Collections: Includes classes and interfaces that define various collection of
objects
System.Data: Includes classes which lets us handle data from data sources
System.Data.OleDb: Includes classes that support the OLEDB .NET provider
System.Data.SqlClient: Includes classes that support the SQL Server .NET provider
System.Diagnostics: Includes classes that allow to debug application and to step throug
our code
System.Drawing: Provides access to drawing methods
System.Globalization: Includes classes that specify culture-related information
System.IO: Includes classes for data access with Files
System.Net: Provides interface to protocols used on the internet
System.Reflection: Includes classes and interfaces that return information about types,
method
and fields
System.Security: Includes classes to support the structure of CLR security system.
System.Threading: Includes classes and interfaces to support multithreaded application
System.Web: Includes classes and interfaces that support browser-server
communication
July 29, 2008
System.Web.Services: Includes classes that let us build and use Web Services 23
System.Windows.Forms: Includes classes for creating Windows based forms
Difference between VB and VB.NET

 Interpreter – Compiler.

 Non - Type Safety Language.

 On Error GOTO - Try Catch.

 Not - support Multithread Application.

 Only Window Application - In web application code behind


can be developed in VB.NET .

July 29, 2008 24


Difference between ASP and ASP.NET

 Object based – Object oriented.

 Interpreter – Compiler.

 Server side scripting – Server side programming


language.

 HTML controls – server .

July 29, 2008 25


C#

It’s an Object Oriented Programming


Language.
It supports:

1. Multithreading.
2. Networking.
3. Graphics.
4. File Systems.

July 29, 2008 26


Advantages of C# over C++
C++ C#
Main Method have Integer return Can have Integer or Void return
type type
Chances of uninitialized variables Variables are initialized with a
default value
Doesn't support String types Supports String Types and String
Classes.
All casting operations are not All casting operations are type
typeSafe Safe
Overflow of Arithmetic Operations Can be Controlled using Checked
cannot be controlled statement
Coding written has direct contact First converted to IL code to
with compiler contact with compiler
Switch statement allows Doesn't allow Automatic Fall
automatic Fall Through Through
July 29, 2008 27
Advantages of C# over Java
C# Java
Support more Software Support less Software Languages
Languages
Different Classes can have Main Only One Class can have Main
method method
Supports Structure data type Doesn't support Structure Data
type
Garbage collection and destructor Only Garbage collection is
both are available here available
Operator Overloading is Operator Overloading is not
supported supported
Supports Pointer using Unsafe Doesn't support Pointer and
Codes Unsafe code
Support Properties and Indexers Doesn't support Properties and
Indexers
Checks Arithmetic Overflow Doesn't Check Arithmetic
July 29, 2008 Overflow 28
CLR Executable

 Microsoft .NET executables are different from typical Windows


executables in that they carry not only code and data, but also
metadata.

Hello, World: Managed C++ :


 Managed C++ is a Microsoft .NET extension to the C++
language.
 Managed C++ includes a number of new CLR-specific keywords
that permit C++ programs to take advantage of CLR features,
including garbage collection.

Program:
#using <mscorlib.dll>
using namespace System;
void main( )
{
Console::WriteLine(L"C++
July 29, 2008 Hello, World!"); 29
}
CLR Executable
 #using makes all types accessible from the specified DLL,
similar to a #include directive in C or C++. However, unlike
#include, which imports C or C++ types, #using imports types
for any .NET assembly.

 The L that prefixes the literal string tells the C++ compiler to
convert the literal into a Unicode string.

 When we compile this new C++ command-line compiler shipped


with the .NET SDK: cl hello.cpp /CLR /link /entry:main

 The /CLR command-line option is extremely important, because


it tells the C++ compiler to generate a .NET PE file instead of a
normal Windows PE file.

 When this statement is executed, the C++ compiler generates


an executable called hello.exe. When we run hello.exe, the CLR
loads, verifies, and executes it.
July 29, 2008 30
CLR Executable

Hello, World: C#:


Coding:
using System;
public class MainApp
{
public static void Main( )
{
Console.WriteLine("C# Hello, World!");
}
}

 C# doesn't have the concept of a header file and class


definitions and implementations are stored in the same .cs file.

 In C#, Main() is the public, static function of the particular


class.

 C# compile this program as: csc hello.cs

July 29, 2008 31


CLR Executable

 In this command, csc is the C# compiler that comes with the


.NET SDK.

 The result of executing this command is an executable file


called hello.exe, which is like a normal EXE but it's managed by
the CLR.

Hello, World: VB.NET:


Coding:
Imports System
Public Module MainApp
Public Sub Main( )
Console.WriteLine ("VB Hello, World!")
End Sub
End Module

 To import library file in VB.NET we use Imports keyword.

July 29, 2008 32


CLR Executable

 VB.NET compile this program as: vbc /t:exe /out:hello.exe


hello.vb

 Microsoft provides a command-line compiler, vbc, for VB.NET.

 The /t option specifies the type of PE file to be created.

 In this case, since we have specified an EXE, hello.exe will be


the output of this command.

 In all the cases Console.WriteLine is common. So in .NET


framework we can easily sift from one language to another.

July 29, 2008 33


ADO.NET

 ActiveX Data Objects (ADO)

 ADO. Net to help connect applications to databases

 Class library to:


 Acces data
 Acces data services

 MS ACCESS, MS SQL Server, Oracle are connected to .NET

July 29, 2008 34


ADO.NET versus ADO

ADO ADO.NET
The ADO Recordset was a huge The ADO.NET object is a light
object in ADO weight object
It provided the ability to support It provided the ability to support
multiple types of cursors multiple types of classes.
It provided fast lightweight ADO.NET DataReader is
"firehose" cursor equivalent to the "firehose"
cursor.
It is a disconnected client-side The DataSet is a disconnected
cursor that supported tracking, cache with tracking and control
optimistic locking, and automatic binding functionality.
batch updates of a database.
all of this functionality was The DataAdapter provides the
difficult to customize. ability to completely customize
July 29, 2008 35
ADO.NET Architecture

July 29, 2008 36


ADO.NET Architecture

 Data Access in ADO.NET relies on two components: DataSet


and Data Provider.

DataSet:
 The dataset is a disconnected, in-memory representation of
data.

 It can be considered as a local copy of the relevant portions of


the database.

 The DataSet is persisted in memory and the data in it can be


manipulated and updated independent of the database.

 The data in DataSet can be loaded from any valid data source
like Microsoft SQL server database, an Oracle database or from
a Microsoft Access database.
July 29, 2008 37
ADO.NET Architecture

Data Provider:
 The Data Provider is responsible for providing and maintaining
the connection to the database.

 A Data Provider is a set of related components that work


together to provide data in an efficient and performance driven
manner.

 The .NET Framework currently comes with two Data Providers:


the SQL Data Provider which is designed only to work with
Microsoft's SQL Server 7.0 or later and the OleDb Data Provider
which allows us to connect to other types of databases like
Access and Oracle.

July 29, 2008 38


ADO.NET Architecture

Each DataProvider consists of the following component classes:

 The Connection object which provides a connection to the


database

 The Command object which is used to execute a command

 The DataReader object which provides a forward-only, read


only, connected recordset.

 The DataAdapter object which populates a disconnected


DataSet with data and performs update

July 29, 2008 39


Database

 A database is a collection of information that is organized so


that it can easily be accessed, managed, and updated.

 A database is a structured collection of records or data.

 Mainly we are using three types of database is .NET. They are

1. SQL
2. Oracle
3.MS Access

July 29, 2008 40


Database
Coding for creating a SQL Table:

Create database dotnet


use dotnet
create table login(name varchar(20),no numeric(6))
insert into login values(‘siva’,621)
Select * from login
update login set name=‘ram’ where no=621
delete from login where name=‘ram’

 We have to write this coding in SQL Query Analyzer.


 After writing each line we have to select the line and we have to
execute the line.
 Here dotnet is the database name and login is the table name

July 29, 2008 41


ADO.NET Connection String

Database Provider Name Connection String


Name
User id=sa; database=Database
SQL MSdaora 1 name;
data source=computer name.
User Name=scott; pwd=tiger;
Oracle MSoledb data source=computer name.

Provider=microsoft.jet.oledb 4.0;
MS Access Microsoft. Jet data source=File location

July 29, 2008 42


The Command Object

 The Command object is represented by two corresponding


classes: SqlCommand and OleDbCommand.

 Command objects are used to execute commands to a database


across a data connection.

 The Command objects can be used to execute stored procedures


on the database, SQL commands, or return complete tables
directly.

 Command objects provide three methods that are used to


execute commands on the database:
 ExecuteNonQuery: Executes commands that have no return values such as INSERT,
UPDATE or DELETE
 ExecuteScalar: Returns a single value from a database query
 ExecuteReader: Returns a result set by way of a DataReader object

July 29, 2008 43


The DataReader Object
 The DataReader object provides a forward-only, read-only,
connected stream recordset from a database.

 Unlike other components of the Data Provider, DataReader


objects cannot be directly instantiated. Rather, the DataReader
is returned as the result of the Command object's
ExecuteReader method.

 The SqlCommand.ExecuteReader method returns a


SqlDataReader object, and the OleDbCommand.

 ExecuteReader method returns an OleDbDataReader object.

 The DataReader can provide rows of data directly to


application logic when you do not need to keep the data
cached in memory.

Because
 July 29, 2008 only one row is in memory at a time, the DataReader
44
provides the lowest overhead in terms of system performance.
The DataAdapter Object
 The DataAdapter is the class at the core of ADO .NET's
disconnected data access.

 It is essentially the middleman facilitating all communication


between the database and a DataSet.

 The DataAdapter is used either to fill a DataTable or DataSet


with data from the database with it's Fill method.

 The DataAdapter provides four properties that represent


database commands:
 SelectCommand
 InsertCommand
 DeleteCommand
 UpdateCommand

July 29, 2008 45


Connecting database to .NET

WebForm Design:

July 29, 2008 46


Connecting database to .NET
Coding:
using System.Data.SqlClient;
public class Class1
{
public static void Main()
{
sub Button1_Click()
{
SqlConnection con=New SqlConnection (“user id=sa;database=“dotnet” data
source=“s1”);
SqlCommand com=New SqlCommand();
SqlDataAdapter ad=New SqlDataAdapter (“select * from login”);
DataSet ds=new DataSet();
con.open();
com=new SqlCommand (“Insert into login values(‘ “ + textBox1.Text + “ ‘,” +
textBox2.Text
+ “)”,con);
com.ExecuteNonQuery();
Messagebox.Show (“Inserted”);
ad.Fill(ds);
dataGrid1.DataSource=ds.Tables[0];
con.Close();
July 29, 2008 47
}}}
SQL Server 2000
 Microsoft SQL Server 2000 is an environment used to create
computer databases on a Microsoft Windows operating system.

 It can deal with small databases such as a personal list of


contacts.

 It can be used for a medium business such as a car repair shop.

 It is also used for a larger than medium set of records such as a


super market or a local bank.

 It can also handle a very large database such as a country's


census.

July 29, 2008 48


What is SQL?
 SQL stands for Structured Query Language

 SQL allows you to access a database

 SQL is an ANSI standard computer language

 SQL can execute queries against a database

 SQL can retrieve data from a database

 SQL can insert new records in a database

 SQL can delete records from a database

 SQL can update records in a database

 SQL is easy to learn


July 29, 2008 49
DML

 DML stands for SQL Data Manipulation Language

 SQL (Structured Query Language) is a syntax for executing


queries. But the SQL language also includes a syntax to
update, insert, and delete records.

 These query and update commands together form the Data


Manipulation Language (DML) part of SQL:

 SELECT - extracts data from a database table


 UPDATE - updates data in a database table
 DELETE - deletes data from a database table
 INSERT INTO - inserts new data into a database table

July 29, 2008 50


DDL

 DDL stands for SQL Data Definition Language (DDL)

 The Data Definition Language (DDL) part of SQL permits


database tables to be created or deleted.

 We can also define indexes (keys), specify links between


tables, and impose constraints between database tables.

 The most important DDL statements in SQL are:


 
 CREATE TABLE - creates a new database table
 ALTER TABLE - alters (changes) a database table
 DROP TABLE - deletes a database table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index

July 29, 2008 51


DDL Query
Syntax for Creating a Database:
CREATE DATABASE database_name
E.g.: create database dotnet
Syntax for Creating a Table:
CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, .......
)
E.g.: create table login (name varchar(20), Number Numeric(10), age int(20))

 The data type specifies what type of data the column can hold.
The table below contains the most common data types in SQL:
Data Type Description
int(size) Hold integers only. The maximum number of digits are specified in
parenthesis.
decimal(size,d) Hold numbers with fractions. The maximum number of digits are specified
numeric(size,d) in "size". The maximum number of digits to the right of the decimal is
specified in "d".
char(size) Holds a fixed length string

varchar(size) Holds a variable length string

date(yyyymmdd) Holds a date

July 29, 2008 52


DDL Query
Drop Table:
Syntax for deleting a table:
DROP TABLE table_name
E.g.: DROP TABLE login

Syntax for deleting a database:


DROP DATABASE database_name
E.g.: DROP DATABASE dotnet

Syntax for Truncate a Table:


It will delete the Content of the Table not the Table itself.
TRUNCATE TABLE table_name

Alter Table:
The ALTER TABLE statement is used to add or drop columns in an existing table.

Syntax for Alter a table:


ALTER TABLE table_name ADD column_name datatype
ALTER TABLE table_name DROP COLUMN column_name
E.g.: alter table login add address varchar(20), alter table login drop chennai
address
July 29, 2008 53
DDL Query
Create Index:
 Indices are created in an existing table to locate rows more
quickly and efficiently.

 It is possible to create an index on one or more columns of a


table, and each index is given a name.

 The users cannot see the indexes, they are just used to speed
up queries. 

 Syntax for creating an Index:


CREATE INDEX index_name ON table_name (column_name)
E.g.: CREATE INDEX loginIndex ON login (name)

 Syntax for Drop the Index:


DROP INDEX table_name.index_name
E.g.: DROP INDEX login.loginIndex

July 29, 2008 54


DCL
 DCL is abbreviation of Data Control Language.

 The Data Control Language is the subset of Transact-SQL used


to manage security in databases.

 It is used to create roles, permissions, and referential integrity


as well it is used to control access to database by securing it.

 DCL SQL statements are more part of the DBMS and have large
differences between the SQL variations.

 The three statements that comprise the Data Control Language


are

 GRANT to allow specified users to perform specified tasks.


 DENY to disallow specified users from performing specified
tasks.
REVOKE
 July 29, 2008 to cancel previously granted or denied permissions.55
Stored Procedure
 Microsoft SQL Server provides the stored procedure mechanism
to simplify the database development process by grouping
Transact-SQL statements into manageable blocks.

 Transact-SQL is Microsoft's proprietary extension to the


Structured Query Language. It includes additional functionality
designed to support Microsoft SQL Server.

Benefits of Stored Procedures:


 Precompiled execution: SQL Server compiles each stored
procedure once and then reutilizes the execution plan. This
results in tremendous performance boosts when stored
procedures are called repeatedly.
 Reduced client/server traffic: If network bandwidth is a
concern then Stored Procedure helps to reduce that.
 Efficient reuse of code and programming abstraction:
Stored procedures can be used by multiple users and client
programs.
Enhanced
 July 29, 2008 security controls: We can grant users permission
56
to execute a stored procedure independently of underlying table
Stored Procedure

Query:

Create database dotnet


Use dotnet
Create table login(name varchar(10), no numeric(10))
Create procedure sp_login(@name varchar(10), @no numeric(10))
Begin
as
If (exist (select* from login) where name=@name, no=@no))
Update login set name=@name and no=@no
End
Else
Begin
Insert into login values (@name, @no)
End
exec sp_login ‘siva’,121
Select* from login

July 29, 2008 57


Keys
Tables in a database can be related to each other with keys. Keys
are of two type: Primary Key and Foreign Key.

Primary Key:

 Each primary key value must be unique within the table; no


two values are the same.

 The purpose is to bind data together, across tables, without


repeating all of the data in every table.

 Good database design starts with the right primary key.


Choosing a primary key is one of the most important steps in
good database design.

 Each database table needs a primary key because it ensures


row-level accessibility.
July 29, 2008 58
Keys
 Each table has one and only one primary key, which can consist
of one or many columns.

 A concatenated primary key comprises two or more columns. In


a single table, you might find several columns, or groups of
columns, that might serve as a primary key and are called
candidate keys.

 A table can have more than one candidate key, but only one
candidate key can become the primary key for that table.

Foreign Key:

 A foreign key (FK) is a link between two tables. A foreign key is


usually link to a primary key in a different table.

 A primary key can be targeted by multiple foreign keys from


other tables. But a primary key does not necessarily have to be
the29,target
July 2008 of any foreign keys. 59
Joins

 Joins are used to link more than one table.

 Joins are of three type. They are: Inner Join, Left Join and Right
Join.

Inner Join:
 The INNER JOIN returns all rows from both tables where there is
a match.

 If there are rows in first table that do not have matches in


second table, those rows will not be listed.

Syntax:
SELECT field1, field2, field3 FROM first_table LEFT JOIN second_table ON
first_table.keyfield
July 29, 2008 = second_table.foreign_keyfield 60
Joins

Left Join:
 The LEFT JOIN returns all the rows from the first table, even if
there are no matches in the second table.

Syntax:
SELECT field1, field2, field3 FROM first_table LEFT JOIN second_table ON
first_table.keyfield = second_table.foreign_keyfield

Right Join:
 The RIGHT JOIN returns all the rows from the second table, even
if there are no matches in the first table.

Syntax:
SELECT field1, field2, field3 FROM first_table RIGHT JOIN second_table ON
first_table.keyfield = second_table.foreign_keyfield

July 29, 2008 61


SQL Functions
 SQL has a lot of built-in functions for counting and calculations.

 Syntax:
SELECT function(column) FROM table

 There are two basic types and categories of functions in SQL.


They are Aggregate Functions and Scalar Functions.

Aggregate Functions:

 Aggregate functions operate against a collection of values, but


return a single value.

 If used among many other expressions in the item list of a


SELECT statement, the SELECT must have a GROUP BY clause.
July 29, 2008 62
SQL Functions

Aggregate functions in SQL Server2000:

Function Description
AVG(clmnnam Returns the average value of a column
e)
COUNT(colum Returns the number of rows (without NULL) of a
n)
COUNT(*) column
Returns the number of selected rows
COUNT(DISTIN Returns the number of distinct results
CT column)
FIRST(column) Returns the value of the first record in a specified
LAST(column) field
Returns the value of the last record in a specified
MAX(column) field
Returns the highest value of a column
MIN(column) Returns the lowest value of a column
SUM(column) Returns the total sum of a column
July 29, 2008 63
VB.NET

July 29, 2008 64


Windows Form

July 29, 2008 65


Label, Textbox and Button
Designing Output

Textbox

Label

Button

Coding

July 29, 2008 66


Radio Button Tool
Designin Output
g

Coding

July 29, 2008 67


Checkbox Tool
Designing with O/P

Coding

July 29, 2008 68


Combo box

July 29, 2008 69


ASP.NET

Active Server Pages (ASP).

ASP.NET Supports the following Set of technologies:


 Web Sites
 Web Applications
 Web Services

 To run ASP.NET we need Internet Information Services (IIS) in


our system.

July 29, 2008 70


IIS

 IIS stands for Internet Information Service

 To properly use the ASP files and ASP.NET files you need to
create a virtual Directory for each application.

 This can be mapped to your physical directory.

July 29, 2008 71


ASP.NET Controls

There are Two Type of Controls in ASP.NET. They are:

3. HTML Control
1.1 FTP
1.2 HTTP
1.3 SMTP

8. Server Side Control


2.1 Intrinsic Control
2.2 Control Transfer
2.3 Validation Control
2.4 Selection Control
2.5 Rich Control

July 29, 2008 72


ASP.NET Server Side Control

2.1 Intrinsic Control :


 If we want to change the control of a existing thing then it is
done with the help of Intrinsic Control.
 eg: to change the size of a existing text box we have to go to
the property of the text box and then we have to make the
following changes: TextMode = MultiLine

2.2 Control Transfer :


 These are the different types of controls. If we click it the control
will transfer to another place and the task will be performed.
 Eg: button, link button etc.

July 29, 2008 73


ASP.NET Server Side Control

2.3 Selection Control:


 Selection Controls are used to select the required or
appropriate value from a range of values.
 Eg: Radio button, check box, Dropdown List or Combo box,
Radio button list etc.

2.4 Rich Control:


 Microsoft. net framework provides the developer with more
advanced controls like rich controls.
 Eg: Calendar control, AdRotator control and the Xml Control.

July 29, 2008 74


ASP.NET Server Side Control

2.5 Validation Control:

 Validation controls are used to make a field mandatory or check


the validity of a user.

 ASP.NET validation controls also provide two ways of validation:


Server-side or Client-side.

 Validation controls will perform client-side validation when it


detects the browser is able (unless client-side validation has
been disabled). Thus reducing roundtrips.

 And it will perform server-side where necessary. This client-


side/server-side detection and validation is done without extra
work by the developer.
July 29, 2008 75
ASP.NET Validation Control

Different types of Validation Controls are:

2.5.1 Required Field Validation

2.5.2 Compare Field Validation

2.5.3 Range Validation

2.5.4 Regular Expression Validation

2.5.5 Validation Summary

2.5.6 Custom Validation

July 29, 2008 76


ASP.NET Validation Control
Required Field Validation:

 The first control we have is the Required Field Validation


Control. As it's obvious, it make sure that a user inputs a value.

 First we have to design a textbox in the ASP.NET page.

 Then we have to Drag a Required Field Validation control tool


from the toolbar.

 Then we have to go to the html tag present at the bottom of the


ASP.NET page and then we have to include the following
coding:

Required field: <asp:textbox id="textbox1" runat="server"/>


<asp:RequiredFieldValidator id=“r1" runat="server"
ControlToValidate="textbox1" ErrorMessage=" You must enter a value into
textbox1“> </asp:RequiredFieldValidator>

July 29, 2008 77


ASP.NET Validation Control
Compare Field Validation:

 Usage of the Compare Validator is for confirming new


passwords, checking if a departure date is before the arrival
date, etc. In Compare validation we compare the value with the
existing one.

 First we have to design two textbox in the ASP.NET page.

 Then we have to Drag a Required Field Validation tool for the


first text box and a compare field validation tool for the second
textbox from the toolbar

 Then we have to go to the html tag present at the bottom of the


ASP.NET page and then we have to include the following
coding:
CompareValidator: <asp:textbox id="textbox1" runat="server"/>
<asp:CompareValidator id=“r1" runat="server" ControlToValidate="textbox1“
ControlToCompare=“textbox2” ErrorMessage=" You must enter the same
value“>
July 29, 2008</asp:CompareValidator> 78
ASP.NET Validation Control
Range Validation:

 Range validator control is another validator control which


checks to see if a control value is within a valid range. The
attributes that are necessary to this control are:
MaximumValue, MinimumValue, and Type.

 First we have to design a textbox in the ASP.NET page. And we


have to go to property window and then change the type as
integer.

 Then we have to Drag a Range Validation tool from the toolbar.

 Then we have to go to the html tag present at the bottom of


the ASP.NET page and then we have to include the following
coding:

Enter a date within 10 to 100: <asp:textbox id="textbox1" runat="server"/>


<asp:RangeValidator id=“r1" runat="server" ControlToValidate="textbox1"
July 29, 2008
MaximumValue=100 MinimumValue=10 Type=“Integer" ErrorMessage="The 79
number must be between 10 to 100" ></asp:RangeValidator>
ASP.NET Validation Control
Regular Expression Validation:

 Regular expression validator control is another validator control


which checks to see if a control value is within a valid range
and it will give the format and number of values we have to
enter.

 First we have to design a textbox in the ASP.NET page. And we


have to go to property window and then change the type as
integer, character.

 Then we have to Drag a Range Validation tool from the toolbar.

 Then we have to go to the html tag present at the bottom of


the ASP.NET page and then we have to include the following
coding:

<asp:textbox id="textbox1" runat="server"/> <asp:RagularExpressionValidator


id=“r1"
July runat="server" ControlToValidate="textbox1"
29, 2008 80
ValidationExpression=IT[0-5]{3} ErrorMessage=“Check the ID"
></asp:RangeValidator>
ASP.NET Validation Control

Validation Summary:

 The validation summary control will collect all the error


messages of all the non-valid controls and put them in a tidy
list. The list can be either shown on the web page (as shown in
the example above) or with a popup box.

 First we have to design three textbox in the ASP.NET page.

 Then we have to Drag Required Field Validation control tool


from the toolbar for all the textbox.

 Then we have to go to the html tag present at the bottom of


the ASP.NET page and then we have to include the following
coding:

July 29, 2008 81


ASP.NET Validation Control

Validation Summary:

Required field: <asp:textbox id="textbox1" runat="server"/>


<asp:RequiredFieldValidator id=“r1" runat="server“ Text=“*” ErrorMessage=" You
must
enter a value into textbox1“ ControlToValidate="textbox1“>
</asp:RequiredFieldValidator>
Required field: <asp:textbox id="textbox2" runat="server"/>
<asp:RequiredFieldValidator id=“r2" runat="server“ Text=“*” ErrorMessage=" You
must
enter a value into textbox2“ ControlToValidate="textbox2“>
</asp:RequiredFieldValidator>
Required field: <asp:textbox id="textbox3" runat="server"/>
<asp:RequiredFieldValidator id=“r3" runat="server“ Text=“*” ErrorMessage=" You
must
enter a value into textbox3“ ControlToValidate="textbox1“>
</asp:RequiredFieldValidator>
<asp:ValidationSummary id=“v1” runat=“server” Headertext=“error”
DisplayMode=“
July 29, 2008 Boolet-List” EnableClientScript=“true”> 82
</asp:ValidationSummary >
ASP.NET Validation Control
Custom Validation:
 This is the only Server Side Validation

Required field: <asp:textbox id="textbox1" runat="server"/>


<asp:CustomValidation id=“c1" runat="server“ ErrorMessage=" You must enter
your name
within 8 to 16 character“ OnServerValidate=“user”
ControlToValidate="textbox1“>
</asp:CustomValidator>

 Then go to top of the html Page coding and write the following
coding:
<Script language=“vbScript” runat=“server”>
sub user (s as object,e as ServarValidateEventargs)
If .len(e.value)<8 and .len(e.value)>16
then
e.isvalid=False
else
July 29, 2008
e.isvalid=True 83
End sub
ASP.NET Objects

Different types ASP.NET Objects are:

3. Application Objects

5. Server Objects

7. Session Objects

9. Request Objects

11. Response Objects

13. Global Objects

July 29, 2008 84


ASP.NET Objects

Application Objects:

 When we used a particular web form for the first time the first
value we used is stored in the system as cookies with the help
of application object.

 It supports three tasks:


1. Application.add (For adding o assigning any value)
2. Application.set (For assigning the value during runtime)
3. Application.get (For getting the value that is assigned during
runtime)

July 29, 2008 85


ASP.NET Objects
Application Objects Coding:

Designing:

Coding:
Imports System.IO
Imports System.Data
Sub button1_Click()
Application.add(“Code”,Textbox1.Text)
Response.Write(“The application Object is Created”)
Application.set(“Code”,Textbox1.text)
Response.Write(“Application.get(“Code”))
End Sub

July 29, 2008 86


ASP.NET Objects

Server Objects:

 Server Objects are used to communicate in between the


webforms.

 It supports three tasks:


1. Response.Redirect(“webform2.aspx”)
 It will call the next webform
2. Server.Execute(“webform2.aspx”)
 It will compile the code in the second form and show
the
result in the first form
3. Server.Transfer(“webform2.aspx”)
July 29, 2008
 It is used to transfer the control to the second form.87
ASP.NET Objects

Server Objects Coding:

Designing: webform1 webform2

Webform1 Coding: webform3


Imports System.IO
Imports System.Data
Sub button1_Click()
If Textbox1.Text=“siva” and Textbox2.Text=“ram”
Then Server.Transfer(“webform2.aspx”)
else
Server.Execute(“webform3.aspx”)
End If

July 29, 2008 88


ASP.NET Objects

Server Objects Coding:

Webform2 Coding:
Page_load()
If not.IspostBack Then
label1.Text=“You need all the Information”
End If

Webform3 Coding:
Page_load()
If not.IspostBack Then
Response.Write(“Session Created”)
Response.Write(Session.Sessionid)
Response.Write (“Timeout”&Session.Timeout.Tostring())
End If

July 29, 2008 89


ASP.NET Objects
Session Objects:

 Session object is used to fixed the time for a particular task.

 Eg: In Online exam time for each question is fixed with the help
of Session object

Designing: Webform1

July 29, 2008 90


ASP.NET Objects
Webform2

Session Objects Coding:


Webform1 Coding:
Session(“Name”)=Textbox1.Text
Session(“Password”)=Textbox2.Text
Response.Redirect(“webform2.aspx”)
Webform2 Coding:
Textbox1.Text=Session(“Name”)
Textbox2.Text=Session(“PassWord”)

July 29, 2008 91


ASP.NET Objects

Request Objects:
 Request Objects are used for requesting the task from client to
server.

Designing:

Coding:
Page_load()
Dim bc as httpBrowserCapabilities= Request.Browser
Response.Write(“Browser Type of the Server” &bc.Type)
Response.Write(“The Name of the Server” &bc.Name.ToString())
Response.Write(“The VB Script” &bc.vbscript.ToString())
Response.Write(“The Java Script” &bc.Javascript.ToString())
Response.Write(“The Cookies” &bc.cookies.ToString())
July 29, 2008 92
ASP.NET Objects

Response Objects:

 Response object is used by Server for respond to task to Client

 Syntax: Response.(cookies) [Cooki-Name] (key)= Request. Form(label1.Text)

Designing: Webform1

July 29, 2008 93


ASP.NET Objects
Designing: Webform2

Coding:
Webform1 Coding:
Sub button1_Click()
Response.cookies(“Cricket”) (Textbox1.Text)= Request.Form(label1.Text)
Response.cookies(“Cricket”) (Textbox2.Text)= Request.Form(label2.Text)
Response.cookies(“Cricket”) (Textbox3.Text)= Request.Form(label3.Text)
Response. Redirect(“webform2.aspx”)

Webform2 Coding:
Page_load()
If (Request.cookies (“Cricket”).Haskeys) then
Response.Write(Request.cookies (“Cricket”)value)
End If

July 29, 2008 94


ASP.NET Objects

Global Object:

 It is the combination of Application and Session Object.

 We have to Go to Solution Explorer window and there we have


to click the global.aspx form.

 There we have to write the following coding

July 29, 2008 95


ASP.NET Objects

Coding:

Webform:
Sub Page_load()
Response.Write (“Count”, &Application.Get(“Count”))

July 29, 2008 96


ASP.NET Directives

Different types ASP.NET Directives are:

1. Page Directives
Page Directives are used when we want to write C# code in ASP.NET<%@pageload= C #>

2. Import Directives
When ever we are writing VB.NET code behind we have to import the library file with the help
of Import
directive from .NET Common Library Management.

3. Output Cache Directives


For getting fast output we are using Output Catch Directives.

4. Register Directives
If We want the same design and same code again and again in ASP.NET we are using Register
Directives.

5. #Include Directives
If the code behind is written in C# then we have to import the library files with the help of this
directives.
July 29, 2008 97
Web Services
 Web services are used for security purpose and if there is a
possibility of using the same code is there.

 Web services are designed to handle a limited set of tasks

 Web services use XML based communicating protocols

 Web services are independent of operating systems

 Web services are independent of programming languages

 Web services connect people, systems and devices

July 29, 2008 98


Benefits of Web Services

 Easier to communicate between applications

 Easier to reuse existing services

 Easier to distribute information to more consumers

 Rapid development

 More Secure.

July 29, 2008 99


Web Services

Eg: Adding two numbers using Web Service

 First Open one Normal ASP.NET Web form.

 Go to Solution Explorer and right click the Web Application.

 Now add New ItemWebService1.

 Now write the following coding:


Public Class Service1
<WebMethod>
Public Function add(ByVal a As Integer, ByVal b As Integer) As Integer
Return a + b
End Function
End Class

July 29, 2008 100


Web Services
 Now to run the form Go to Solution Explorer window, right click
the Service1.asmx form and select it as “Set as Start Page” and
run the form.

 Next it will display the following window. Here Click the add
button.

 Now the following window will display. Enter the value of a and
b.

July 29, 2008 101


Web Services

 Now press the Invoke Button to get the output. It will display
the
following Result.

July 29, 2008 102


C#.NET

C# is derived from C and C++. It is the Enhanced version of


C++. It
is a modern Object Oriented Programming Language. It has
the power
of C++ and simplicity of Visual Basic.

C# Supports following Applications:

 Window Application

 Web Application

 Console Application

July 29, 2008 103


Characteristics of C#

 Simple

 Consistent

 Modern

 Object Oriented

 Type Safety

 Versionable

 Compatible

 Flexible
July 29, 2008 104
C# Statements
 If Statement
Executes statement based on the value of a Boolean expression.
 Switch Statement
Based on the value of a variable allows to switch to different cases.
 Do Loop
The purpose of the do loop is to Execute some code and then examine the
condition.
If the condition is not satisfied then the execution is stopped.
 While Loop
Evaluate the condition first and then execute the code if the condition is
true.
 For Loop
Executes the statement based on the condition within the for statement.
 Foreach Statement
Moves through the elements of a collection of elements.

July 29, 2008 105


Namespace
 Namespace is a logical collection of Classes and their related
Functions

 .NET base classes are grouped into different groups through


Namespaces

 A single C# file can declare several Namespaces

 The Namespaces are Implicitly public

 With a Namespace we can declare another Namespace, Class,


Interface,
Struct,Enum,Delegates

 A Namespace is referenced in a C# program by the “using”


statement
July 29, 2008 106
Basic Knowledge needed to learn C#

Class
 Class is the central element in Object Oriented Language.
 Class is the collection of Objects and Methods.
 Class is the blueprint of Objects.
 A Class is declared using the class keyword.

Object
 In object-oriented programming, an object is an instance of
a class
 Object is a kind of module containing data and subroutines.
 An object is a kind of self-sufficient entity that has an
internal state (the data it contains) and that can respond to
messages (calls to its
subroutines).
July 29, 2008 107
Basic Knowledge needed to learn C#
Function
 A function is a block of code that performs a calculation and
returns a value.

 A function is written when there's a certain portion of code that


will be executed more than once, or maybe even just to
separate certain portion of code from the rest of the code.

Syntax:
returntype fn_name(parameterdef1, parameterdef2, )  
 

local variables  
function code
July 29, 2008 108
}
Constructor in C#
 A constructor can be used, where every time an object gets
create and if we want some code to be executed automatically.
The code that we want to execute must be put in the
constructor.

 The general form of a C# constructor is as follows 


modifier constructor_name (parameters)
{
//constructor body
}

 The modifiers can be private, public, protected or internal.

 The Constructor name and the class name should be same.

 When we create object of a Class, it automatically calls the


constructor and initializes its data members of that Class
July 29, 2008 109
Constructor in C#

 A constructor with no-argument is known as default


constructor.

 There is no return type for a constructor

 If we don't provide a constructor with a class, the C# provides


a default constructor with an empty body to create the objects
of the class.

 If we provide our own constructor, C# do not provide the


default constructor.

 Just like member functions, constructors can also be


overloaded in a class.
July 29, 2008 110
C# Constructor Example
using System;
class Complex
{
private int x;
private int y;
public Complex(int i, int j) // constructor with 2 arguments
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine(x +"i+" + y);
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(20,25);
c1.ShowXY();
}
}

July 29, 2008 111


Destructor in C#

 Destructor is used to free the memory space Instantly.

 The Destructor implements the statements to be executed


during the garbage collection process.

 A destructor is a function with the same name as the name of


the class but starting with the character ~.

 A Destructor can't have any modifiers like private, public etc.

 There is no parameterized destructor in C#. 

July 29, 2008 112


Destructor in C#

 Destructors are invoked automatically and can't be invoked


explicitly.

 Example:
class Complex
{
public Complex()
{
// constructor
}
~Complex()
{
// Destructor
}
}

July 29, 2008 113


OOPS Concept in C#

 All the programming language supporting Object oriented


Programming will be supporting these four main concepts:

1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction

 C# also supports all these Concepts.

July 29, 2008 114


Encapsulation in C#

 In Object Oriented Programming, Encapsulation is an attribute of


object design. It means that all of the object's data is contained
and hidden in the object and access to it restricted to members
of that class. Different type of encapsulation concepts are:

1. Public: Public is visible to everyone. A public member can be


accessed using an instance of a class, by a class's internal code,
and by any descendants of a class.

July 29, 2008 115


Encapsulation in C#

2. Private: Private is hidden and usable only by the class


itself. No code using a class instance can access a private
member directly and neither can a descendant class.

July 29, 2008 116


Encapsulation in C#

3. Protected: Protected members are similar to private ones


in that they are accessible only by the containing class.
However, protected members also may be used by a
descendant class. So members that are likely to be needed
by a descendant class should be marked protected.

July 29, 2008 117


Encapsulation in C#

4. Internal: Internal is public to the entire application but private


to any outside applications. Internal is useful when you want to
allow a class to be used by other applications but reserve
special functionality for the
application that contains the class.

July 29, 2008 118


Encapsulation in C#

5. Protected Internal: Protected Internal may be accessed only


by a descendant class that's contained in the same application
as its base class. You use protected internal in situations where
you want to deny access to parts of a class functionality to any
descendant classes found in other applications.

July 29, 2008 119


Inheritance in C#
 Inheritance is one of the most important, and most powerful, of
the object-oriented programming concepts.

 Using Inheritance, one class can be derived from another.  The


derived class, also known as the child class or subclass, inherits
functionality from the base class, also known as the parent
class or superclass.
 
 When using Inheritance, all of the base class' methods,
properties, events, indexers, operators and some internal
variables are all automatically provided to every subclass.

 Using Inheritance, classes become grouped together in a


hierarchical tree structure. 

 This reduces maintenance problems, as changes need only to


be made in one class, rather than throughout a series of
related classes.
July 29, 2008 120
Inheritance in C#
Types of Inheritance: The following are the types of
inheritance exist in C# programming.

1. Single Inheritance:

Here we have single base class that is inherited by the derived


class. Here the derived class has all the features of the base
class and can add new features or modify existing features.
The inheritance also depends on the access specifier that is
used at the time of base class inheritance.

2. Multi-level Inheritance:

In the multi-level inheritance, here we having a chain of


inheritance i.e. the base class A is inherited by derived class B,
and it is further inherited by another derived class C. So, the
feature we have in base
July 29, 2008 121
Inheritance in C#

class A, is also there in Derived class B, and all the combination


features of class A and class B are there in derived class C.

3. Multiple Inheritance:

In C#, we don't have multiple inheritance where one class can


inherit two base classes. So, the multiple inheritance can be
done by using the concept of interfaces. Here one class can
inherit one class and can implements more than one interface.

4. Hybrid Inheritance:

The hybrid inheritance can also be done through with the help
of interface. Here the derived class cans implements more than
two interfaces and only one class.

July 29, 2008 122


Inheritance in C#
1. Single Inheritance Example:

using System;
class Base
{
public void fun() class Main
{ {
Console.WriteLine(“Base Class”); public static void Main()
} {
} derived obj=new derived();
class derived : Base obj.run();
{ }
public void run() }
{
Console.WriteLine(“Derived Class”);
fun();
}
}

July 29, 2008 123


Inheritance in C#
2. Multi-level Inheritance Example:

using System; class derived2 : Base


class Base {
{ public void nun()
public void fun()
{
{ Console.WriteLine(“ 2nd Derived
Console.WriteLine(“Base Class”);
Class”);
}
run();
}
class derived : Base }
{ }
public void run() class Main
{ {
Console.WriteLine(“Derived Class”); public static void Main()
fun(); {
}
derived2 obj1=new derived2();
}
obj1.nun();
}
}
July 29, 2008 124
Inheritance in C#

3. Multiple Inheritance using Interface Example:

using System;
Interface i1 Public void put();
{ {
public void Accept(); Console.WriteLine(“Microsoft”);
}
} }
Interface i2 class Main
{ {
public void put() ; public static void Main()
}
{
Public class A : i1,i2
{ i1 obj=new A();
public void Accept() i2 obj1=new A();
{ obj.Accept();
Console.WriteLine(“ C# dot net”); obj1.put();
}
}
}
July 29, 2008 125
Polymorphism in C#

 Polymorphism is nothing but one interface which can be used


for more then one method

Polymorphism

Static Polymorphism Dynamic Polymorphism

Function Overloading Operator Overloading Function Overriding

Sequence Virtual Method

Function
Type Cast Abstract Class
Signatur
e
Number of Type
July 29, 2008 126
Polymorphism in C#

1. Static Polymorphism: It can be decide only at static or


compile time.

3. Dynamic Polymorphism: It can be decide only at dynamic or


run time.

Function Overloading :
 C# allows us to define multiple functions with the same
name differing in the number type and order of arguments.
This is termed as function overloading.

 This way, one does not have to remember the names of


multiple functions that serve a similar core purpose.
July 29, 2008 127
Polymorphism in C#
Function Overloading Example:

using System;
class Overloading
{
public void fun(int a)
{
int num=a;
Console.WriteLine(num);
}
public void fun(int a,float b)
{
int num1=a;
float num2=b;
Console.WriteLine("{0}{1}",num1,num2);
}
public static void Main()
{
Overloading obj=new Overloading();
obj.fun(10);
obj1.fun(100,200f);
Console.ReadLine();
}
}
July 29, 2008 128
Polymorphism in C#

Different Types Function Overloading:

Sequence Type: If the first function datatype is (int,float) then the


next
function datatype should be (float,int).

Cast Type: Function data type are in the sequence of (int ),


(int,float), (int, float, double)

Number of Type: Function of data type are in the sequence of


(int ),(float).

July 29, 2008 129


Polymorphism in C#

Operator Overloading:

 The mechanism of giving a special meaning to a standard C#


operator with respect to a user defined data type such as
classes or structures is known as operator overloading.

 It is not possible to overload all operators in C#.

 In C#, a special function called operator function is used for


overloading purpose.

 Operator function can take only value arguments. The ref and
out parameters are not allowed as arguments to operator
functions.

 These special function or method must be public and static.


July 29, 2008 130
Polymorphism in C#

Operators Overloadability
All C# binary operators can be
+, -, *, /, %, &, |, <<, >>
overloaded.
All C# unary operators can be
+, -, !, ~, ++, --, true, false
overloaded.
All relational operators can be
==, !=, <, >, <= , >=
overloaded, but only as pairs.
&&, ||, () They can't be overloaded
In C#, these operators are
+=, -=, *=, /=, %= automatically overloaded when the
respective binary operator is
=, . , ?:, ->, new, is, as, overloaded.
These operators can't be overloaded
sizeof

July 29, 2008 131


Polymorphism in C#
Operator Overloading Example:
using System;
public struct Complex
{
public int real;
public int imaginary;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public static Complex operator +(Complex c1, Complex c2) // Declare which operator to
overload // (+), the types that can be added
{ // (two Complex objects), and the return
type (Complex)
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
public override string ToString()
{
return(String.Format("{0} + {1}i", real, imaginary));
}

July 29, 2008 132


Polymorphism in C#

public static void Main()


{
Complex num1 = new Complex(2,3);
Complex num2 = new Complex(3,4);
Complex sum = num1 + num2;
Console.WriteLine ("First complex number: {0}",num1);
//2+3
Console.WriteLine ("Second complex number: {0}",num2);
//3+4
Console.WriteLine ("The sum of the two numbers: {0}",sum);
//5+7i
}
}

July 29, 2008 133


Polymorphism in C#
Function Overriding:

 A derived class can override a base-class member function by


supplying a new version of that function with the same
signature.

 Function Overriding can be done with the help of either using


Virtual class or by using abstract class.

 Abstract class can contain only abstract method.

 We can implement abstract methods only in Derived class not


in Base class.

 Virtual method can run under both class and Structure.


July 29, 2008 134
Polymorphism in C#
Function Overriding using Virtual Method:

using System;
class BC
{ class Demo
public virtual void Display() {
{ public static void Main()
System.Console.WriteLine("BC::Display"); {
} BC b;
} b = new DC();
class DC : BC b.Display(); //DC ::
{ Display
public override void Display() }
{ }
System.Console.WriteLine("DC::Display");
}
}

July 29, 2008 135


Polymorphism in C#
Function Overriding using Abstract Class:
using System;
abstract class BC
{ class Demo
public abstract void Display() {
public static void Main()
} {
class DC : BC DC obj=new DC();
{
DA obj1=new DA();
public override void Display()
obj.Display();
{
obj1.Display();
System.Console.WriteLine(“abstract1");
}
} }
class DA : BC }
public override void Display()
{
System.Console.WriteLine(“abstract2");
}
}
July 29, 2008 136
Abstraction in C#

 Abstraction is a process of taking only essential information.

 For eg: The car salesman giving only the relevant information to
the customer.

 Abstraction is "the process of identifying common patterns that


have systematic variations;

July 29, 2008 137


Thank You………

July 29, 2008 138

You might also like