C#Web Basics SQL

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

RI-TECH

Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Microsoft.Net Basics
What is Microsoft.Net?
Microsoft.Net is object oriented & Service Oriented application development platform which allow
you design and develop computer applications. As we say it is application development platform that
means it contains set of tools, compilers, programming languages, editors, debuggers and so many
other facilities using which you can design and develop the Computer/IT Applications.
Currently Micrsofot.NET comes in two flavours –
A. .NET Framework
B. .NET Core

Microsoft .NET Framwork:-


Microsoft.NET Framework released in 2001/2002 is pure object oriented with service oriented
application development platform it will have the following featues –

Basics about Application Development / Software Development:-


Every software application development process goes through some set of steps or stages or
methodologies. Those set of steps or stages are called software development life cycle (SDLC).
SDLC provides you following set of steps –
1. Analysis
2. Design
3. Development
4. Testing
5. Implementation
6. Maintenance
To follow the SDLC we have following three approaches –
1. Functional Approach
2. Object Oriented Approach
3. Service Oriented Approach

Functional Approach:-
This is classical and simple approach to design and develop the software. Throughout this approach
our whole concentration will be on functions. At every step of SDLC we think about the functions and
create design, development of the system in terms of functions. We find the functions. We draw
DFD, DT, Flow Chart etc to create the functional model of the system. We also implement the system
by writing the functions. Over a period it had been found that the system designed and developed
using the functional approach are difficult to enhance or maintain since functions are tightly coupled
with each other (more dependent).
Object Oriented Approach:-
This is new approach designed to solve the problems of functional approach. In case of object
oriented approach we think about system in terms objects and their interactions. We analyze the
system in terms of object. We create the design of the system in terms of objects as well as we
implement the system using object oriented programming language. Over a period it had been found
by the computer scientist that system designed and developed using object oriented approach is
easy to maintain and enhance since the objects are less coupled (dependent) on each other.
Object oriented approach is little bit complex to implement and cannot consume the dynamic
business logic.
Service Oriented Approach:-
Service oriented approach allow you to design develop the applications or software’s by considering
services or Service Oriented Architecture (SOA). SOA is very simple and power full architecture it has
three stake holders Service, Service Producer & Service Consumer. Service is any in tangible thing

RI-TECH Url: www.ritechpune.com Page No: - 1


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
that is supposed to be exchanged between the producer and consumer as per defined contract or
specifications. Application designed or developed using service oriented approach is very easy to
maintain and enhance because services has 0% coupling as well these applications are capable to
consume the dynamic business logic.

Why Microsoft.Net Framework? (Features of .Net Framework)


Microsoft.Net Framework is result of the several errors effort of the Microsoft Team who had done lot
of studies and market research which has following measure features –

Microsoft.Net is Object Oriented & Service Oriented: -


Microsoft.Net Support Object Oriented and Service Oriented Methodology to Develop various types of
applications.
Multi Lanague Support:-
.Net Supports Multile Programming Lanagues like C#,VB,F#,VC,Python etc, any language who
follows CLS & CTS Specifications we ca use it with .NET Framework.
Sinle Language Command: -
Even though .Net Framwork Support Multiple Progrmaming Languages it has feature called single
language command. Single language command says you learn only one programming language and
you can develop any type of .NET Framework Based Appliation.
Common Language Runtime: -
.NET Framework Support Common Languge Runtime, even though .Net Framework support multiple
programming languages you do not need to install multiple language runtimes on computer where
you want to run the .net application, you need to install only one lanaguge runtime called CRL. CRL
is the only language runtime which manages the execution of .NET Framework Applications ir
respective of weather it is developed using C#/VB/F# etc.
XML + SOAP: -
COM & DCOM Problem
Com (Component Object Model) and DCOM (Distributed Component Object Model) are the standards
used on windows platform for process or component communication. Com is used on single computer
while DCOM is used when components or processes present on different machines. Com and DCOM
standard has following problems –

 It is binary standard so data exchange or communication is always in binary format so it


takes larger amount of time to travel over the network as well as it may be blocked by the
security software’s.
 This standard is available only on windows platform.
 Execution of COM / DCOM application may need extra infra structure arrangement, can have
security problems, and little bit slow.
XML & SOAP: -
.Net Supports XML Standard for data exchange and communication which is pure text based
standard hence it will not have any kind of security software or network travel problem and it is open
source standard can be used on any platform. Beside this the XML works with new protocol called
SOAP (Simple Object Access Protocol) where the communication will be done using small messages
which reduces the overhead of the communication and again client do not need the extra
environment for execution of the applications.

.NET Assemblies used to solve DDL Hell Problem: -


DLL:-
Dynamic Link Library is windows library facility using which we can implement the reusable function
libraries. To use the DDL files developed using MS6.0 you have to follow the following steps –
 Create DLL file with reusable functions/ classes
 Register it in windows registry. (It is windows respiratory, a central program running in
windows which maintains the references with the windows resources.)

RI-TECH Url: www.ritechpune.com Page No: - 2


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
 Any application want to use the dll file have to create the reference of that DLL using windows
registry then it can use the functions from those DLL files.
 Windows registry has a problem, that we can not have the more than one DLL file with same
name. If you try to register the DLL with same name the latest DLL will overwrite the previous
DLL entry with latest.
 Which may create the trouble, as if there is any application using old DLL may not work since
their might be the possibility that new DLL may not contain those functionalities. The problem
is called the DLL HELL.
.NET Assemblies: -
.Net use concept of the Assemblies for DLL’s , in case of Assemblies you can have more than one DLL
with same name, since Assembly maintains the meta data which tells the information about the DLL
files where we can refer the more than one DLL having same name with different version no.
Code Based Security: -
.Net support Code Based Security. In general we have security levels called user level security where
user need the user name and password to access the system, another type of the security level
called object level security where to access the components of the objects we need the permission
(Authorization). .Net support these both security levels beside this Microsoft.Net support the code
based security where to execute the small program code blocks we need the authorization called
code based security.

.Net Framework Architecture:-


.Net framework is a program which can be downloaded from the Microsoft website needed for the
proper execution of the Microsoft.Net programs or application has following layers in it’s architecture

Programming Languages (Multi Language): -


This layer contains the multiple programming languages where from user can choose only one
programming language for the application development and using which you can develop any type of
application..Net framework is multiple languages for application development.

RI-TECH Url: www.ritechpune.com Page No: - 3


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Common Language Specification/ System (CLS): -
Microsoft.Net is multi language support that means the multiple languages code will be processed by
the Microsoft.Net framework, every programming language has its own syntax and grammar which
needs to be converted to common language code (MSIL), this conversion will be done according to
the specification specified by common type specification or system. Common type specification or
system provides you the set of rules or guide lines that should be followed every time when you can
to convert the language specific code to the common language code.
Common Type Specifications (CTS): -
Similar to language grammar every language also has different types of data types; hence it is also
necessary for Microsoft.Net framework to convert different types of data types in a common data
type using specification provided into common data type system or specification.
WinForm (Available Microsoft.Net 2.0): - WinForm is facility provided by Microsoft.NEt using
which we can design the user interface of windows application, this facility is based on basic windows
API using which you can design GUI for windows application.GUI generated by winform technology is
resolution dependent as resolution changes GUI get disturbed and changes it look and feel. GUI
generated using winform is basic and fast which cannot used to design and develop applications
having rich user interface.
WPF (Windows Presentation Foundation) (Available Microsoft.Net 2.0):- WPF is again GUI
development facility using which you can design the GUI of windows based applications. WPF is
based on direct x technology of Microsoft which is device independent hence GUI generated using
WPF will be resolution independent. WPF comes with XAML GUI programming language using which
you can design the GUI of your WPF application, it is xml based programming language and first step
taken by the Microsoft to introduce a programming language to design the GUI of windows
application by writing xml code. In short it has following features –
 Rich GUI.
 2D/3D Graphics.
 Animations.
 XAML Declarative GUI Programming.
 Styles and Templates
 Events and Commands
 Modern Style Data Binding.
Web Forms (Available Microsoft.Net 2.0): - Webform is facility provided by Microsoft.Net
framework 2.0 to design the GUI of web application, it is Microsoft’s first approach to provide new
brand GUI technology to design the GUI of web application. It has following features –
 Event Driven Model for Web Development.
 Built in GUI controls with server side event handling.
 Themes and Skins
 Master Pages
ASP.MVC (4.0):- ASP.NET MVC also provides you facility to design and develop the web based
applications. In case of webform there is server side event handling and event driven programming
model which is very comfortable for application developers to design and develop the applications
which is against of the web architecture (Request / Response). ASP.Net MVC using Model View
Controller Design Pattern which reduces loads on the application and generate results very fast. In
MVC design pattern Model is responsible or data management, view is responsible for presentation of
data and controller is responsible for managing flow logic. Beside this asp.net MVC provides following
facilities –
 Centralized GUI Rules
 Centralized Validations (Model Validation)
 Extensible
 Built in GUI Engines
ASP.NET web Pages (HTML5) (Available Microsoft.Net 4.0):- This technology provided by
Microsoft.Net again allows you to design and develop the web applications using HTML 5. HTML 5 has
following features –

RI-TECH Url: www.ritechpune.com Page No: - 4


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
 No need of plug-ins
 Built in 2d/3d Graphics
 Audio and Video Support
 Less scripting and more tags.
 Geo Location API.
 Local Database etc.

Silver light Framework:-


Silverlight is a powerful cross-browser & cross-platform technology for building the next generation
web experience & rich internet applications for the web. You can run Silverlight in most of all the
popular browsers like Internet Explorer, Firefox, Chrome, Safari etc. Silverlight can run in various
devices and operating systems like Windows, Apple Mac OS-X and Windows Phone 7. Using
Silverlight you can create rich, visually stunning web applications like flash. Also you can create
smooth animations using Storyboards; you can stream media over the net etc. Silverlight framework
will have the following advantages –
 XAML
 2D/3D on Web
 Fast Since XAP Files
 Cross Browser and Platform
 Templates and Modern Style Data binding.

Windows 8 Metro Style Application (WIN RT):-


If you want to leverage your existing .NET knowledge and start developing Windows 8 apps, you
must understand the new .NET Profile tailored for apps and the new native API Windows Runtime
(WinRT). WinRT (sometimes also called WRT) replaces the well-known Win32 APIs for Windows 8
apps. Microsoft designed WinRT with multiple languages in mind, and therefore, it isn't like Win32
APIs, which were written to be consumed by the C programming language. WinRT is object-oriented
from scratch and projects out objects to the different programming languages that consume it. Thus,
WinRT represents a huge change for those used to thinking about making Win32 calls from different
programming languages.
You can use many languages to create Windows 8 apps and interact with WinRT:
C# and XAML
C++ and XAML
Visual Basic and XAML
JavaScript, HTML5, and CSS3
C++ and DirectX

XML and Web Services (Available Microsoft.Net 2.0): - XML web services is facility provided by
.net framework using which you can design and develop the service oriented applications or
applications based on SOA architecture. XML web services has following features –
 Open Source.
 Communicate using XML.
 Can be secure with the help of the SOAP.

ADO.NET & XML:-
ADO.Net is new technology for data manipulation from the databases; this technology comes with
Microsoft.Net framework. This technology is also based on the XML standard and we had already
seen the advantages of XML. ADO.NET has following advantages –
 Object Oriented
 Language Independent
 Supports Connected as well as disconnected architecture.
 Huge support for XML

RI-TECH Url: www.ritechpune.com Page No: - 5


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
ADO.NET uses SQL at the end to communicate with the DBMS or RDBMS software’s , SQL has some
draw backs like –
 SQL can query only tabular format of data
 SQL is structured
 SQL interpreted separately than your application
 Cannot use any language native facilities.
LINQ (Language Integrated Query): -
Linq is new brand technology introduced by Microsoft which allows you to write the queries using a
programming language in which you are developing the application instead of SQL. Linq not only
provides you the facility to query databases as well it also provides you facility to query the -
objects, collections, xml data. Linq also allow you lambda expressions which makes the execution of
the query faster. LINQ has following features –
 Lazy loading and In Memory Processing
 Expression Trees
 Can Query Table, XML, Objects, Collections, and Entities etc.
 Type Inference and Lambda Expressions.
 Can use native language features.
Entity Framework:-
Entity framework is more advance step taken by Microsoft to enhance the data query and access
technologies. Entity framework allows you to create or develop the applications, against the
conceptual model, not according to the relation model or data storage engine, which will reduce the
errors and maintenance problems from your applications. Entity framework has one facility called
model first approach where you can generate the relational model for data storage from the
conceptual model of the data. Entity framework provides you following features –
 Manipulation of Conceptual model than actual data.
 Database Independent ORM.
 Supports Data First, Model First, Code First Approaches.
ADO.NET Data Services (ODATA):-
AdoMicrosoft.Net data services know known as WCF Data Services enables you to create services
that use the Open Data Protocol (OData) to expose and consume data over the Web or intranet by
using the semantics of representational state transfer (REST). OData exposes data as resources that
are addressable by URIs. Data is accessed and changed by using standard HTTP verbs of GET, PUT,
POST, and DELETE. OData uses the entity-relationship conventions of the Entity Data Model to
expose resources as sets of entities that are related by associations.
Task Parallel API:-
The Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading and
System.Threading.Tasks namespaces in the .NET Framework 4. The purpose of the TPL is to make
developers more productive by simplifying the process of adding parallelism and concurrency to
applications. The TPL scales the degree of concurrency dynamically to most efficiently use all the
processors that are available. In addition, the TPL handles the partitioning of the work, the
scheduling of threads on the ThreadPool, cancellation support, state management, and other low-
level details. By using TPL, you can maximize the performance of your code while focusing on the
work that your program is designed to accomplish.
> More efficient and more scalable use of system resources.
> More programmatic control than is possible with a thread or work item.
SignalR API:-
ASP.NET SignalR is a new library for ASP.NET developers that makes it incredibly simple to add real-
time web functionality to your applications. What is "real-time web" functionality? It's the ability to
have your server-side code push content to the connected clients as it happens, in real-time.
You may have heard of WebSockets, a new HTML5 API that enables bi-directional communication
between the browser and server. SignalR will use WebSockets under the covers when it's available,
and gracefully fallback to other techniques and technologies when it isn't, while your application code
stays the same.

RI-TECH Url: www.ritechpune.com Page No: - 6


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
SignalR also provides a very simple, high-level API for doing server to client RPC (call JavaScript
functions in your clients' browsers from server-side .NET code) in your ASP.NET application, as well
as adding useful hooks for connection management, e.g. connect/disconnect events, grouping
connections, authorization.
Base Class Library: -
.Net provides you huge amount of built in classes using which you can implement n number of
facilities like IO, Networking etc. This reusable built in classes together called as framework class
library or base class library.
Common Language Runtime: -
This is core component of the Microsoft.Net framework without this there is no use of the
Microsoft.Net framework. CLR manages every activity from loading the Microsoft.Net program in
computer memory to its execution. We will study this component in short time.

CLR Architecture:-
CLR is core component of the .Net, it has responsibility from loading the program into the computer
memory till its execution. It has various components dedicated for specific execution task those are –
Class Loader and Class Specifier: -
Class specifier finds the details or specifications of the classes used by the Microsoft.Net application
from the Framework Class Library and class loader will load it, in memory. Class specifier and class
loader works together to perform this task.

Fig. CLR Architecture


Thread Manager:-
Thread is the smallest unit of the execution. Thread has its life cycle; thread also has concurrency
and communication. So when you implement the threads you inside your application or program you
have to manage these threads and this activity will be performed by the Thread Manager.
Exception Manager: -
Exception is runtime situation occurs inside the program which causes the abnormal termination of
the program, should be handled to avoid the abnormal termination of the application. Exception
handling involves the identification of exceptions, and execution the action specified by the CLR or
user defined code block defined by the user. All these activities will be managed by the exception
manager component of the CLR.
Garbage Collector: -
This is very important component of the CLR, garbage collector is responsible for collecting the
memory of those objects those are not in use. In case of CLR we have two way parsing mechanism
to handle the exceptions where in first part the GC will search those objects those are not in use and

RI-TECH Url: www.ritechpune.com Page No: - 7


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
mark them a special mark called dispose mark, In second parse it will check for dependency of that
object on other object, if dependency does not exits then it will collect it. The Garbage collector from
Microsoft.Net 4.0 has parallel garbage collection facility where it wills check and collect garbage
collected objects simultaneously (Parallel).
Security Manager: -
This component of the CLR is responsible for managing the authentication and authorization from
user level security, object based security to code based security. Security manager is also
responsible for managing the application execution security where it scans every activity performed
by .net application against local machine security policies, if any .net application performs any invalid
activity it blocks it’s execution.
Type Checker: -
This component of the CLR is responsible for evaluating the expression for type safety (No data loss)
as well as provides the facilities using which we can have the conversion from one data type to
another data type.
Debug Engine: -
Debug Engine component of the CLR allow to debug the application, as well as it exposes the set of
facilities using which you can trace the program execution, provides you break point and watches
which will help you to debug the application.
Language Compilers: -
Language compiler component of CLR will provide you set of compilers using which you can compile
the language specific code the MSIL. (Microsoft Intermediate Language) also called as IL. It invokes
the appropriate compiler as the requirement as well as it provides the facility by which we can
add/remove/edit exiting compilers. Whenever you add any new compiler or edit exiting compiler
form the .net framework the language compiler validates it against the CTS and CLS specification.
JIT: -
Just in time compiler will convert the IL code generated by the language compilers to native code or
executable code and executes it on the target computer. JIT in 4.0 uses concept of caching due to
which application executable generation is very fast.
COM Marshalar and Introp: -
Before Microsoft.Net com standard was popular in Microsoft.Net framework. So there is n number of
exiting Microsoft applications are their using that standard, hence if Microsoft.Net application want to
use those com based components or applications, it have to relay on the com marshaler since CLR
can not execute the binary code. So com marshaler will be responsible for executing the com code
from the Microsoft.Net application beside this Microsoft.Net application exposes set of built in
libraries ( facilities) using which you can use the com components in your application called interop (
Inter Opera ability).

Some Concepts: -
What is Side by Side Execution?
In case of Microsoft.Net we can have more than one versions of dll files used in single application
due to the concept of the assembly. Their might be the possibility that two same dll files with
different version will be used and executed by Microsoft.Net application and both of them will be
loaded simultaneously and will be executed. This execution is called Side by Side Execution.
What is Managed and Unmanaged Code?
Manage code is that code which runs under the control of CLR. The code that will be executed by CLR
(Intermediate Language Code) is called the Managed Code. The code other than IL code like com
code will be executed without CLR with the Help of the COM Marshalar called Unmanaged Code.

Compilation and Execution Process of C#.Net:-


To compile and execute C#.net program we have to follow the following steps –
 Create C#.net file any editor and same it with .cs extension
 Compile the file with csc complier of the c#.net.

RI-TECH Url: www.ritechpune.com Page No: - 8


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
 Compiler will generate windows PE format executable file which contains IL (Intermediate
Language Code)
 This file then will be executed by JIT, by converting IL code to Native or executable Code, JIT
is part of the CLR.
Process is show in following diagrams –

.NET Core 2.0:-

What is .net Core?


.NET Core is an open-source, general-purpose development platform maintained by Microsoft and
the .NET community on GitHub. It's cross-platform (supporting Windows, macOS, and Linux) and can
be used to build device, cloud, and IoT applications.
.NET Core is supported by Microsoft, on Windows, macOS and Linux. It's updated for security and
quality several times a year, typically monthly. .NET Core binary distributions are built and tested on
Microsoft-maintained servers in Azure and supported just like any Microsoft product.

Why .NET Core?


.NET Core has the following characteristics:
Cross-platform:
Runs on Windows, macOS and Linux operating systems.
Consistent across architectures: Runs your code with the same behavior on multiple architectures,
including x64, x86, and ARM.
Command-line tools:
Includes easy-to-use command-line tools that can be used for local development and in continuous-
integration scenarios.
Flexible deployment:
Can be included in your app or installed side-by-side user- or machine-wide. Can be used with
Docker containers.
Compatible:
.NET Core is compatible with .NET Framework, Xamarin and Mono, via .NET Standard.
Open source: The .NET Core platform is open source, using MIT and Apache 2 licenses. .NET Core is
a .NET Foundation project.
Supported by Microsoft:
.NET Core is supported by Microsoft, per .NET Core Support.

API’s Supported By .NET CORE

RI-TECH Url: www.ritechpune.com Page No: - 9


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------

Uiversal Windows MVC 6 Web API Signal R


Platform
ASP.NET Core
Desktop Web App & API
Core Base Class Library
.NET Core CLR

.NET Core CLR:-


We’re excited to announce that CoreCLR is now open source on GitHub. CoreCLR is the .NET
execution engine in .NET Core, performing functions such as garbage collection and compilation to
machine code. .NET Core is a modular implementation of .NET that can be used as the base stack for
a wide variety of scenarios, today scaling from console utilities to web apps in the cloud.

Core Base Class Library


.NET implementations include classes, interfaces, delegates, and value types that expedite and
optimize the development process and provide access to system functionality. To facilitate
interoperability between languages, most .NET types are CLS-compliant and can therefore be used
from any programming language whose compiler conforms to the common language specification
(CLS).

Universal Windows Platform


Universal Windows Platform is an open source API created by Microsoft and first introduced in
Windows 10. The purpose of this platform is to help develop universal apps that run on Windows 10,
Windows 10 Mobile, Xbox One and HoloLens without the need to be re-written for each.

ASP.NET Core(MVC 6)
ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern,
cloud-based, Internet-connected applications. With ASP.NET Core, you can:
 Build web apps and services, IoT apps, and mobile backends.
 Use your favorite development tools on Windows, macOS, and Linux.
 Deploy to the cloud or on-premises.
 Run on .NET Core or .NET Framework.

ASP.NET Web API


The new MVC 6 that ships with ASP.NET Core merges the best of both MVC and Web API worlds from
ASP.NET. From any controller, you can return a View or object and MVC will take care of serializing it
for you. Multiple different routing styles enable you to implement basic MVC web applications or
more REST-style APIs.
Signal R

RI-TECH Url: www.ritechpune.com Page No: - 10


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
ASP.NET SignalR is a new library for ASP.NET developers that makes it incredibly simple to add real-
time web functionality to your applications. What is "real-time web" functionality? It's the ability to
have your server-side code push content to the connected clients as it happens, in real-time.

C#.NET:-
C#.Net is a programming language supported by Microsoft.Net framework has n number of
features -
C#.NET Features:-
> C# is pure object oriented programming language.
> Compatible with Microsoft.Net framework. So whatever features that we have with Microsoft.Net
frame work will be also available in C#.
Like –
 Assemblies
 CTS (Common Type Specification),
 CLS (Common Language Specification),
 Code Based Security
 XML, SOAP (Simple Object Access protocol)
 CLR (Common Language Runtime) etc.
 C# inherits all it’s syntax from C++.

Other Features of C#:-


 C# support Concept of Generics.
 C# also Support unsafe data types (like pointers)
 C# is case sensitive programming language.
 Every Statement in C# terminates with; operator.
 C# provides you facility to implement Threading.
 C# has facility to implement the Exception Handling.
 C# allows you to implement properties and indexers.
 C# allows you to implement attributes.
 C# allows you to use the task parallel library.
 C# allows you to use the collections and generics.
 C# allows you to use the events and delegates
 C# allows you to use the variable value and number argument functions.
 C# allows you to use the concrete, variant and tupes.
 C# supports lambda Expressions. Etc.

In C# you can develop two types of applications –


 Windows Application.
 Console Application.

A. Console Application:-
Console Application will have CUI where user has to interact with application or software using
character commands.

Basics C#.NET:-
When we say any programming it is going to provide you following facilities –
Keywords: -
Keywords are the predefined words whose meaning can not be changed.
Constants: -
These are the defined keywords or symbols whose values can not be changed.
Operators: -

RI-TECH Url: www.ritechpune.com Page No: - 11


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
C# provides you following types of operators
 Arithmetic Operators: - +,-,/,*,%,=, ++, --
 Logical Operators: - && (and), || (or),! (Not)
 Relational Operators: - >, <, >=, <=, !=,==
 Special operators: - , (separator), ; (statement terminator), . (Membership operator), {
} block definer etc.
Variable Declaration Statement:-
Variable is a facility by which we can use computer memory inside our program. In case of C# we
can create variables using following syntax –
[Access type/Access Specifier/Access Modifier] Data Type Variable Name [= Initial Value];

Data Type: -
Data types are the keywords by which we tell computer what type of value should be stored in a
memory block allocated by variable so that computer will make all arrangements in memory. In case
of C# data types are divided into two types –
Reference type:-
The variables created using reference type of data type will be get created into heap section of the
data segment of the program hence before using reference type of variable we should have to
allocate memory for that variable explicitly. If you do not allocate memory explicitly you will not be
able to use it. In case of reference type of data type we use new and delete keywords to allocate or
de allocate memory for the variable. Reference type of data types includes-
1. Arrays.
2. Classes.
Value type: -
Value type of variable will be getting created on stack; stack is auto data structure so we do not
need to allocate memory for these types of variables explicitly. When where you create the variable
it will get memory automatically. In case of value type we have following data types –
3. Numeric Data Types: - int (int16, int32, int64), double, single, decimal etc.
4. boolean:- true /false
5. char
e. g. int num=10;

Program structure of C#: -


C# has following program structure –

Libraries
Namespace name space name
{
class class name
{
static void Main(String [] args) // Starting point of the C# Program.
{
statements;
}
}
}

Input and Output:-


In Case of C# for input and output you have to use the built in class called console. Console class
has following methods –
Read(): - is used to read a single character and returns the numeric representation of the specified
character in Unicode format.

RI-TECH Url: www.ritechpune.com Page No: - 12


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
ReadLine(): - is used to read a line text (string) from the user and returns the string.
Write (string/int etc.):- It is used to display some output on console prompt with specified values.
WriteLine (string/int etc):- It is just similar but it will move to new line after displaying the data on
console.

Write and WriteLine also support the format strings and escape sequence characters, you
can specify the format string in {} brackets.

Convert Class:-
C# provides you one built in class called the convert class which allow you to convert one data type
to another data type,. It has some following methods –
ToInt16(parameter):- It will convert given parameter to int16.
ToInt32(parameter):- It will convert given parameter to int32.
ToInt64(parameter):- It will convert given parameter to int64.
ToString(parameter):- It will convert it to string.
ToDate(parameter): - It will convert given parameter to date.

How to Create, Compile and Execute the C#.Net Program: -


1. Go to Start  Programs  Microsoft Visual Studio 2005 -> Microsoft Visual Studio 2005
and Click you will get following environment –

2. Click on the file and new project menu It will get you following window –
3. In project types select Visual C# and Console Application.
4. In Name specify the name of the project.
5. In Location specify the directory where you want to store the project or application. It will
get you following environment where you can type the code in main window –

RI-TECH Url: www.ritechpune.com Page No: - 13


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------

6. To build the solution we use F6 (go to Built menu and Click on Built).
7. To run the application or solution press ctl + F5 key or go to debug and Start, it will show
you output.

E.g. accept two numbers from the user and display its Addition.
namespace FirstProgram
{
class Program
{
static void Main(string[] args)
{
int a, b, c;
Console.Write("Enter First Number:");
a = Convert.ToInt16(Console.ReadLine());
Console.Write("Enter SEcond Number:");
b = Convert.ToInt16(Console.ReadLine());
c = a + b;
Console.WriteLine("Addition is :" + Convert.ToString(c));
Console.Read();
}
}
}

E.g. accept the radius of the circle from the user and display area of the circle.
namespace secondprogram
{
class Program
{
static void Main(string[] args)

RI-TECH Url: www.ritechpune.com Page No: - 14


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
{
int radius;
double area;
Console.Write("Enter radius of Circle==>");
radius = Convert.ToInt16(Console.ReadLine());
area = 3.14 * radius * radius;
Console.WriteLine("Area of Circle is==>" + Convert.ToString(area));
Console.ReadLine();
}
}
}

Conditional Statements:-
Condition is an expression when evaluated will generate any of the two values that are true or false.
To implement the conditions C# provides us following statements -
if Statement: - This is used to implement the condition but able to handle only true part of the
condition. It has following syntax –
if(condition)
{
Statements;
}
if-else: - This is used to implement the condition which is able to handle both the parts of the parts
of the condition that are true or false. It has following syntax -
if(condition)
{
Statements;
}
else
{
Statements;
}

e.g. Accept a number from user and display weather it is odd or even.
namespace ConditionExample
{
class Program
{
static void Main(string[] args)
{
int num;
Console.Write("Enter Number:");
num = Convert.ToInt32(Console.ReadLine());

if (num % 2 == 0)
Console.WriteLine("Even Number");
else
Console.WriteLine("Odd Number");
}
}
}

RI-TECH Url: www.ritechpune.com Page No: - 15


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Nested Condition: -
Conditions inside the conditions are called nested conditions. In case C# we do not have any type of
special arrangements to implement the nested conditions. You have depend on if and if-else
statements.
e. g.
if(condition)
{
if(condition)
{
Statements;
}
else
{
Statements;
}
}
else
{
if (codintion)
{
Statements;
}
}

Use of Logical Operators: -


You can use logical operators to combine the conditions in C# conditional statements.

e.g. Accept a number from user and display weather it is odd or even.
namespace ConditionExample{
class Program
{
static void Main(string[] args)
{
int num;
Console.Write("Enter Number:");
num = Convert.ToInt32(Console.ReadLine());
if (num % 2 == 0)
Console.WriteLine("Even Number");
else
Console.WriteLine("Odd Number");
}
}
e.g. Accept three numbers from the user and display the maximum from it.
namespace ConsoleApplication1{
class Program
{
static void Main(string[] args)
{
int a, b, c;
Console.Write("Enter first numbers==>");
a = Convert.ToInt16(Console.ReadLine());
Console.Write("Enter second numbers==>");
b = Convert.ToInt16(Console.ReadLine());

RI-TECH Url: www.ritechpune.com Page No: - 16


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Console.Write("Enter third number==>");
c = Convert.ToInt16(Console.ReadLine());
if(a>b)
{
if(a>c)
{
Console.WriteLine(" a is greatest");
}
else
{
Console.WriteLine(“c is greater”);
}
}
else
{
if(b>c)
{
Console.WriteLine("b is greatest");
}
else
{
Console.WriteLine("c is greatest");
}
}
Console.ReadLine();
}
}
}

Looping Statements:-
loop is a mechanism which will take care of performing the any task again and again. Every loop will
have –

 Starting point (initial value)


 Terminating Condition (End Point)
 Next Step ( Iteration )

The loop that do not have end point then we will call it as the inifnite loop. C# provides you following
looping statements –
For loop :-
is generally used when you know in advance how many times loop is going to execute. It has
following syntax –

for([initial value];[terminating condition];[next value])


{
Statements;
}

At initlization part we can declare the multiple varaibles as well as we can do the multiple varaible
initilization. Similar the case with next value. But every for loop will have only one terminating
condition, if you want to use more than one condition then you have to use the logical operators.

RI-TECH Url: www.ritechpune.com Page No: - 17


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
++ , -- Operators :- ++ is incement operator which will increment the vlaue of given
variable by one and – will be decrement operator where we will decrment the value of
given varaible by one.

e.g. Accept 10 numbers from the user and display the addition of them.
namespace AdditionofDigits
{
class Program
{
static void Main(string[] args)
{
int num;
int add = 0;
// int cnt;

for (int cnt = 0; cnt < 10; cnt++)


{
Console.Write("Enter Numnber");
num=Convert.ToInt16(Console.ReadLine());
add = add + num;
}
Console.WriteLine("Addition of Numbers is :" + Convert.ToString(add));
Console.Read();
}
}
}

While :-
While loop is used when you do not know in advance how many times loop is going to execute. It
will have the following syntax –
while(condition)
{
Statements;
}
e.g. Accept one number form the user and display the addition of digits of the number.
namespace AdditionDigits1
{
class Program
{
static void Main(string[] args)
{
int num,dig,add=0;
Console.Write("Enter Number");
num = Convert.ToUInt16(Console.ReadLine());
while(num!=0)
{
dig = num % 10;
add = add + dig;
num = num / 10;
}
Console.WriteLine("Addition of Digits :" + Convert.ToString(add));
Console.Read();
}

RI-TECH Url: www.ritechpune.com Page No: - 18


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
}
}

Do-while:-
In case of do while loop, the loop will be executed at least for one time and it’s next exectuion
depends on condition. If condition is true then it will execute it, if condition is not true then it will not
execute it. It has following syntax –
do
{
Statements;
}while(condition);

e.g. Accept charcters from user till user do not say no, and display how many vowels and
consonents are their.
namespace Dowhile
{
class Program
{
static void Main(string[] args)
{
char ch,option='n';
int vcnt=0,ccnt=0;
do
{
Console.Write("Enter Character:");
ch = Convert.ToChar(Console.ReadLine());
if( ch =='a' || ch =='e' || ch=='i' || ch=='o' || ch=='u')
vcnt ++;
else
ccnt ++;
Console.Write("Do you want to Continue?[y/n]") ;
option =Convert.ToChar(Console.ReadLine());
}while(option == 'y');
Console.WriteLine("Vowels are :" + Convert.ToString(vcnt) + " Consonent:" +
Convert.ToString(ccnt));
Console.Read();
}
}
}

Accept a number and replace its odd digits by zero. E.g. 12345 – 2040
namespace odddigit
{
class Program
{
static void Main(string[] args)
{
int num,dig;
Console.Write("enter number");
num = Convert.ToInt32(Console.ReadLine());
Console.Write("Output is:");
do
{

RI-TECH Url: www.ritechpune.com Page No: - 19


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
dig = num % 10;
if (dig % 2 != 0)
Console.Write("0");
else
Console.Write(dig);
num = num / 10;
}while(num!=0);
}
}
}

For Each Loop: -


for each loop is used to travel the collection of elements, generally used to traverse the collections,
has syntax –
foreach(data type variable name in collection)
{
Statements;
}
We will see the example in array.
Nested Loops: -
Loops inside the loop are called as nested loop. You can nest the loop by placing for inside for or
while inside for depending on your requirement. Nested loops will be executed as similar to the C++
nested loops.

Break and Continue: - Break statement is used to come out from the loop and continue
statement will be going to skip the statements just similar to C++.

e. g. Find prime numbers from 1 to 100


using System;
using System.Collections.Generic;
using System.Text;
namespace PrimeExample
{
class Program
{
static void Main(string[] args)
{
// Prime numbers from 1 to 100
int i,j,f;
for (i = 1; i <= 100; i++)
{
f = 0;
for (j = 2; j < i; j++)
{
if (i % j == 0)
{
f = 1;
break;
}
}
if (f == 0)
Console.WriteLine(" Prime :" + i);
}

RI-TECH Url: www.ritechpune.com Page No: - 20


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
}
}
}
Switch – Case Statements:-
This statement is used when you want to compare single value with set of values at that time switch
case statement is used, it has following syntax –
switch (variable)
{
Case value:
Statements;
Break;
Case value:
Statements;
Break;

Default:
Statements;
Break;
}
e. g. Accept a character and find out weather it is vowel or consonant.
using System;
using System.Collections.Generic;
using System.Text;
namespace CosoOvewl
{
class Program
{
static void Main(string[] args)
{
char ch;
Console.Write("Enter Character");
ch =(char)Console.Read();
switch (ch)
{
case 'a':
// Console.WriteLine("Ovwel");
// break;

case 'e':
// Console.WriteLine("Ovwel");
// break;
case 'i':
// Console.WriteLine("Ovwel");
// break;
case 'o':
//Console.WriteLine("Ovwel");
//break;
case 'u':
Console.WriteLine("Ovwel");
break;
default:
Console.WriteLine("Conso");
break;

RI-TECH Url: www.ritechpune.com Page No: - 21


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
}
}
}
}
Arrays in C#: -
Array is a facility provided by any programming language by which we can
refer(manipulate) the colleciton of values using single variable name. In case of C# colleciton refered
by array will have following two characterstic –

 The elements of the array should allocate continous memory locations.


 The elements of the array should of similar data type.

We use the indexing mechanism to access the elements of the array. In case indexing mechanism
when array get created inmemory every element of array will get one unique index number assigned
to it starting from 0 and goes up to size-1. Now to refer individual element of array we use folllwoing
synatx –
Arrayname[indexnumber];

In case of C# Array is refrence type of data type,it means before using array variale we have to
allocate the memory to array explicitly. In C# We can define the array as follows –
Data type [] arrayname=[new datatype[size]];

int [] num=new int[10];


you can do it as follows –
int []num;
num =new int[10];
again we can define it like this –
int []num={1,2,3,4,5,6,7,8,9,10};

e.g. Accept 10 numbers from the users in array and replace ith position element with
l+1th position and vice versa.
namespace Array1
{
class Program
{
static void Main(string[] args)
{
int[] num = new int[10];
int cnt,temp;
//Accepting 10 elements from user
for (cnt = 0; cnt < 10; cnt++)
{
Console.Write("Etner Number:");
num[cnt] = Convert.ToInt16(Console.ReadLine());
}
// Swaping
for (cnt = 0; cnt < 10; cnt+=2)
{
temp = num[cnt];
num[cnt] = num[cnt + 1];
num[cnt + 1] = temp;
}
// Displaying Array Elements.

RI-TECH Url: www.ritechpune.com Page No: - 22


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
for (cnt = 0; cnt < 10; cnt++)
Console.WriteLine("Element:" + Convert.ToString(num[cnt]));
Console.Read();
}
}
}

Object Oriented Programming with C#: -


Any programming language which supports following concepts is called as object oriented
programming language.
Object: -is any thing which has some meaning in problem domain which has some role or activity to
be played in system or problem solution. In coding object is nothing but the instance or
representative of the class.
Class: -It is nothing but the collection of objects having similar properties and methods. In coding
class is template or format for object, using which we can instantiate the object or create the object
in program memory.
Abstraction: -is a facility or utility provided by any object oriented programming language using
which we can implement or develop the applications in such a way that user of those applications do
not have to know the internal details of that application and this mechanism is called abstraction.
Encapsulation: - It is mechanism by which we can hide the internal details from the user so that
abstraction can be implemented and it also provides you a facility by which you can combine more
than one unit in a single unit without change in its original form.
Inheritance: - Inheritance is a mechanism by which we can enhance or reuse the functionalities
developed in previous applications. It allows you to reuse the code.
We can inheritance is the process by which we can acquire the properties and methods of one object
into another object. Inheritance should be natural; it should be always through the process of
generalization or specialization.
Polymorphism: - is a mechanism using which you can implement any thing in such a way that it is
going to show multiple behaviors depending on external interface.
e. g. Mobile
Class and Objects:-
Implementing Class in C#:-
To implement the class in C# we use the following syntax –

[Access specifier/modifier] class classname


{Members of Class; }

C# class can have following members –


1. Data Members:- are the variables which holds specific information about the object will have
following syntax –
[Access specifier(types) /modifiers] Data type variable name [=initial value];
2. Properties & Indexers: - are the methods through which we can set or get the value of only
specified data members generally used to expose the data members outside the class.
[Access type/modifier] return data type propertyname
{
Set
{
}
Get
{
}

RI-TECH Url: www.ritechpune.com Page No: - 23


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
}
3. Methods: - are the functions implemented in side the class has following syntax –

[Access type /modifier] return data type function name([parameters])


{
Statements;
}
4. Indexers: - are just similar to property which allows you to expose such data members
which needs index number and value. Indexers are created using this keyword has following
syntax –

[Access type/modifier] return data type this[index variable]


{
Set
{
}
Get
{
}
}
Access type/modifier: - These are the keywords using which we can define the scope/visibility and
accessibility of the members of the class. e.g. static, public, private, friend.
In case of C# we have following access type –

1. Public.
2. Private.
3. Protected.
4. Internal.

Access For Class For Members of Class


type
Same Child Inside Outside
Class Class Assembly Assembly
Public Every Where Yes Yes Yes Yes
Private In a File Yes No Yes Yes
Protected Not Yes Yes Yes – In child Yes-In child only
Applicable only
Internal In Assembly Yes Yes Yes No

Note: - if you do not use any access type by default it will be private for members of the
class and internal for class.

e. g. Implement the class student


class Student
{
//Data Members
private int rollno;
private string sname;
private string address;
private string phone;
//Methods
public void setStudent(int r, string nm,string ad,string ph)

RI-TECH Url: www.ritechpune.com Page No: - 24


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
{
rollno = r;
sname = nm;
address = ad;
phone = ph;
}
public void dispStudent()
{
Console.WriteLine(" Roll no:" + rollno);
Console.WriteLine(" NAme :" + sname);
Console.WriteLine(" Address:" + address);
Console.WriteLine(" Phone :" + phone);
}
}

Continue ..
Using the class:-
To use the class you have to create the object or instance of that class and it can be created using
following syntax –
Classname objectname[=new classname()];

Once you create the object of the class you can access the properties and methods of the class using
dot operator.

class Program
{
static void Main(string[] args)
{
Student s = new Student();
int r; string sn, ad, ph;
Console.Write("Plz Enter RollNo:");
r =Convert.ToInt32(Console.ReadLine());

Console.Write("Plz Enter Name:");


sn = Console.ReadLine();
Console.Write("Plz Enter Address:");
ad = Console.ReadLine();
Console.Write("Plz Enter Phone");
ph = Console.ReadLine();
s.setStudent(r,sn,ad,ph);
s.dispStudent();
}
}
}

Constructors and Destructors:-


These are the special functions provided by any programming language using which we can initialize
and de initialize class object. In case of C# we use the contractors and we do not need the
destructors since the de initialization task will be performed by the CLR. We can implement the
constructors in C# as follows –
 C# constructor function is a function which gets called automatically when you create and
initialize the instance of the class.
 C# constructors will not have any type of return data type.

RI-TECH Url: www.ritechpune.com Page No: - 25


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
 C# constructor function will have the same name as that of class name.
 C# constructors can have the parameters.
 C# constructors can be static.

If you want to define and use the destructors you have to do it explicitly , while creating the
destructors you have to again has following rules –
 Destructor Name should be same as that of class name but prefixed with ~ symbol.
 Their can be only one destructor in side the class.
 In case of C# we do not guarantee that when destructors will be executed.
Use destructors; explicitly in C# class is bad idea because object collection task will be conducted
automatically by the C# garbage collector component.

e. g. Using Constructor and Destructor


namespace ConstExmaple
{
class Course
{
private int courseid;
private string coursename;
private double cduration;
private double cfees;
public Course() // default constructor
{
Console.WriteLine("Default Constructor Called");
courseid = -1;
coursename = "NA";
cduration = -1;
cfees = -1;
}
public Course(int cid) //Constructor with one integer type of parameters
{
courseid = cid;
coursename = "NA";
cduration = -1;
cfees = -1;
}
public Course(int cid, string cn, double cd, double cf) // constructor with all
parameters
{
courseid = cid;
coursename = cn;
cduration = cd;
cfees = cf;
}
public void AddCourse(int ci, string cn, double cd, double cf)
{
courseid = ci;
coursename = cn;
cduration = cd;
cfees = cf;
}
public void DispCourse()
{

RI-TECH Url: www.ritechpune.com Page No: - 26


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Console.WriteLine(" Course ID :" + courseid.ToString());
Console.WriteLine(" Course NAme :" + coursename);
Console.WriteLine(" Course Duration :" + cduration.ToString());
Console.WriteLine(" Course Fees:" + cfees.ToString());
}
}
class Program
{
static void Main(string[] args)
{
Course cn = new Course();
cn.AddCourse(1, "C++ Programming", 12000, 10000);
cn.DispCourse();
Course cn1 = new Course(12);
cn1.DispCourse();
Course cn2 = new Course(12, "Vb Programming", 12000, 1000);
cn2.DispCourse();
}
}
}

Array of Objects: -
Just like normal array we can also create the array of objects as follows –
Classname [] objectname=new classname[size];
In case of normal array you have to initialize only the array, in case of array of objects we not only
have to initialize the array but also the elements of the array since the elements of the array is of
again type reference.

using System;
namespace ArrayOfObjects
{
class Flight
{
private int Fno;
private string Fname;
private string Fsource;
private string Fdestination;
private double Fair;
public void AddFlight(int fn,string fnm,string fs,string fd,double ff)
{
Fno = fn;
Fname = fnm;
Fsource = fs;
Fdestination = fd;
Fair = ff;
}
public void Dispflight()
{
Console.WriteLine("Flight No:" + Fno.ToString () );
Console.WriteLine("Flight Name:" + Fname );
Console.WriteLine("Flight Source:" + Fsource);
Console.WriteLine("Flight Destination:" + Fdestination);
Console.WriteLine("Flight Fair:" + Fair.ToString());

RI-TECH Url: www.ritechpune.com Page No: - 27


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
}
public bool SearchFlight(string fs,string fd)
{
if (Fsource.Equals(fs) && Fdestination.Equals(fd))
return true;
else
return false;
}
}
class Program
{
static void Main(string[] args)
{
Flight[] f = new Flight[10];

// Initilizating Array of objects


for (int cnt = 0; cnt < 10; cnt++)
f[cnt] = new Flight();

//Accepting Information
string fnm;
int fn;
string fs;
string fd;
double fr;

for (int cnt = 0; cnt < 10; cnt++)


{
Console.Write("Enter Flight No:");
fn = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Flight Name:");
fnm = Console.ReadLine();
Console.Write("Enter Flight Source");
fs = Console.ReadLine();
Console.Write("Enter Flight Destination:");
fd = Console.ReadLine();
Console.Write("Plz Enter Fair");
fr = Convert.ToDouble(Console.ReadLine());
f[cnt].AddFlight(fn,fnm,fs,fd,fr);
}

//Enter Flight info to Search


string fss;
string fsd;
Console.Write("Enter Flight Soruce:");
fss = Console.ReadLine();
Console.Write("Enter Flight Destination:");
fsd =Console.ReadLine();

//Searching Flight Information


for (int cnt = 0; cnt < 10; cnt++)
{
if (f[cnt].SearchFlight(fss, fsd))

RI-TECH Url: www.ritechpune.com Page No: - 28


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
f[cnt].Dispflight();
}
}
}
}

Properties and Indexers in C#:-


In certain situations you have to expose the private data members of the class outside the class,
exposing private data members directly outside the class is always a security risk as well as we can
not restrict or validate the user inputted value for that data member.

Properties enable a class to expose a public way of getting and setting values, while hiding
implementation or verification code.
In C# properties can be created using following syntax –
Access type property data type propertyname
{
set
{
Allow you to write the value.
}
get
{
Allow you to read the value.
}
}

Set Accessor allows you to write the value, where you can use the value keyword which will get the
value assigned to the property.
Get Accessor allows you to read the value of the property which can be returned using return
keyword.

Depending on weather you use set or get properties are classified as –


Read Only Properties: - these are the properties whose values can be read, hence this property
will not contain set block so you will not be able to write the value in C# properties.
Write Only Properties: - these are the properties whose values can be writing but can not be read.
Hence these properties will not have the get block will have only set block.
Read Write Properties: - these properties will allow you to read, write values of the properties will
have both the accessors set as well as get.

Why properties?
Properties allow you to expose the private data members of the class outside the class, it also
provides you extra arrangement (blocks where you can write C# code to validate the property value
assigned to property or the value read from the property) by which you can control the value
assigned to property or value read from the property.

e. g. c# properties example
namespace Properties
{
class Myclss
{
private int dval;
public int propdval

RI-TECH Url: www.ritechpune.com Page No: - 29


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
{
get
{
return dval;
}
set
{
if(value > 0) //validation
dval = value;
}
}
public void disp()
{
Console.WriteLine(dval.ToString());
}
}
class Program
{
static void Main(string[] args)
{
Myclss mc = new Myclss();
mc.propdval = 12;
Console.WriteLine(mc.propdval.ToString());
}
}
}

Indexers in C#:-
Indexers are the facility provided by c# using which you can access class objects as an array,
indexers can be used at two level to expose the field from the class which is of type collection out
side the class or to expose whole class object as array. Defining an indexer allows you to create
classes that act like "virtual arrays." Instances of that class can be accessed using the [] array
access operator
Properties can not expose members of the class outside the class which contains more than one
element (arrays / collections etc), instead of that you can use the indexers.
To create the indexer in C# we use the following syntax –
Access type data type this[int index]
{
set
{
Write the value inside the indexer.
Value keyword can be used to assign the value.
}

get
{
Get the value from indexer;
}
}

e. g. Using indexers.

RI-TECH Url: www.ritechpune.com Page No: - 30


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
namespace IndexerExample
{
class Arraycls
{
private int[] data;
public Arraycls()
{
data = new int[10];
}
public int this[int index]
{
get
{
if (index < 10)
return data[index];
else
return -1;
}
set
{
if(index <10 && value > 0)
data[index] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Arraycls ac = new Arraycls();
ac[0] = 23;
ac[4] = 56;
ac[3] = 45;
Console.WriteLine(ac[3]);
Console.WriteLine(ac[0]);
Console.WriteLine(ac[4]);
}
}
}

Static Keyword:-
It is an access modifier can be used with class data members, method, constructor and class as well.

Static with members of the class:-


The first advantage we will get if we use the static keyword is that we will be able to access the
members of the class directly using class name we does not need the object of the class, since static
members will not be get created with object of the class.

Static data Members: - when you use the static keyword with data members of the class those
data members will be get created before creation of the first object of the class in memory only once
and all the objects of the class is going to use those data members. Generally we create the static

RI-TECH Url: www.ritechpune.com Page No: - 31


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
data members if you want to store some common data that is supposed to be shared by all the
objects of the class.
Static data members since does not get create individually with every object of the class, those can
be accessed only using class name, i.e. to access the static data members of the class you have to
use the class name.

Static methods: - static keyword when used with method those methods will become static, what it
means you will be able to invoke those methods with class name, it will not have the reference inside
the class object. Static methods are basically created to process static data members. When you
create the static method you will not able to invoke the non static method in static method.

Static constructors: - static constructors are the constructor functions from the class those will be
define using the static keyword those will have following features –
Static constructors will be gets executed only once before creation of object of the class generally
used to initialize the static data members of the class. Static constructors will not have the
parameters. One class can contain only one static constructor.

Static class: - you can also use the static access type with class, when you use the static access
type with class that class will become static with following rules –
 static class can contain only static members
 You will not be able to create the object of the static class.

E.g. static methods, data members and constructor.


namespace StaticKeywor
{
class Process
{
private int pid;
private string procname;
private int indmem;
private static int totalmem=256;
private static int consumedmem = 0;
public void CreateProcess(int id,string pn,int idm)
{
pid = id;
procname = pn;
indmem = idm;
consumedmem = consumedmem + idm;
}
public void DispProcess()
{
Console.WriteLine("PI :" + pid);
Console.WriteLine(" Proc Name :" + procname);
Console.WriteLine(" Ind Mem :" + indmem);
}
public static void DispMemStatus()
{
Console.WriteLine(" Total Mem:" + totalmem);
Console.WriteLine("Consumed Mem:" + consumedmem);
Console.WriteLine("Free :" + (totalmem - consumedmem));
}
}
class Program

RI-TECH Url: www.ritechpune.com Page No: - 32


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
{
static void Main(string[] args)
{
Process p1, p2, p3;
p1=new Process();
p1.CreateProcess(1, "Word", 10);
p2 = new Process();
p2.CreateProcess(2, "Notepad", 12);
p3 = new Process();
p3.CreateProcess(3, ".NET", 50);
p1.DispProcess();
p2.DispProcess();
p3.DispProcess();
Console.WriteLine(" Mem Status ");
Process.DispMemStatus();
}
}
}

e. g . Create a team class with pid, pname, pindscore with proper data members and
methods to accept and display –
- Player Information
- Team Score Information
Use static keyword.
namespace teamstatic
{
class team
{
private int pid;
private string pname;
private int indscore;
private static int totalscore=0;
public void accept(int id, string pn, int inds)
{
pid = id;
pname = pn;
indscore = inds;
totalscore = totalscore + indscore;
}
public void disp()
{
Console.WriteLine("\n pid="+pid);
Console.WriteLine("name=" + pname);
Console.WriteLine("ind score=" + indscore);
}
public static void disptotal()
{
Console.WriteLine("\n\ntotal score=" + totalscore);
}
}
class Program
{
static void Main(string[] args)

RI-TECH Url: www.ritechpune.com Page No: - 33


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
{
team t = new team();
t.accept(1, "xyz", 45);
team t1 = new team();
t1.accept(2, "pqr", 90);
t.disp();
t1.disp();
team.disptotal();
}
}
}

e. g. Static Class Example.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication5
{
static class Math
{
public static int AddNums(int a, int b)
{
return a + b;
}
public static int SubNum(int a, int b)
{
return a - b;
}
}
class Program
{
static void Main(string[] args)

{
int r = Math.AddNums(45, 56);
Console.WriteLine(r);
r = Math.SubNum(34, 56);
Console.WriteLine(r);
}
}
}

Inheritance: -
Is the process by which we acquire the properties and methods of one class into another class. In
case of C# we can not implement the multiple inheritances. To implement the inheritance we use
following syntax-

class child : parent class


{
Members;
}

RI-TECH Url: www.ritechpune.com Page No: - 34


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------

In case of inheritance child will inherit all the properties of parent including private, public and
protected but can not access private properties. Inheritance provides you two advantages –
 Reusability of code.
 Enhancements.

e. g.
namespace Inheritance
{
class Salesmen
{
protected int salesid;
protected string sname;
protected int target;
}
class SalesmenSales : Salesmen
{
private int totalsales;
private string date;
private double comm;
public void setSalesmenSales(int si, string sn, int t, int ts, string dt, double cm)
{
salesid = si;
sname = sn;

target = t;
totalsales = ts;
date = dt;
comm = cm;
}
public void dispSalesmenSales()
{
Console.WriteLine("Salesmen ID:" + salesid);
Console.WriteLine("Salesmen Name:" + sname);
Console.WriteLine("Salesmen Target:" + target);
Console.WriteLine("Total Sales:" + totalsales);
Console.WriteLine(" Date :" + date);
Console.WriteLine(" Commission:" + comm);
}
}
class Program
{
static void Main(string[] args)
{
SalesmenSales s = new SalesmenSales();
s.setSalesmenSales(1, "Rajesh", 12000, 10000, "1/2/2009", 12);
s.dispSalesmenSales();
}
}
}

RI-TECH Url: www.ritechpune.com Page No: - 35


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Constructor Execution Sequence in Inheritance: -
When ever you create an object of the child class it always execute the default constructor of the
parent first and then it will execute child constructor.
namespace ConstructorExecutionSequenceininheritance
{
class Test
{
public Test()//defualt
{
Console.WriteLine("Parent Default Constructor Called");
}
public Test(int a)
{
Console.WriteLine("Parent Parameterized Constructor Called");
}
}
class Child : Test
{
public Child()
{
Console.WriteLine("Child Constructor Called");
}
public Child(int x)
{
Console.WriteLine(" Child Parametrized Consturctor Called");
}
}
class Program
{
static void Main(string[] args)
{
Child c = new Child(12);
}
}
}

What ever may be the type of object of child class, it will always first execute the default constructor
of parent, if you want to execute the parent parameterized constructor then you have to use the
base keyword as follows –

namespace ConstructorExecutionSequenceininheritance
{
class Test
{
public Test()//defualt

{
Console.WriteLine("Parent Default Constructor Called");
}
public Test(int a)
{
Console.WriteLine("Parent Parameterized Constructor Called");

RI-TECH Url: www.ritechpune.com Page No: - 36


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
}
public Test(int a, int b)
{
Console.WriteLine("Two Parameterized Constructor Called");
}
}
class Child : Test
{
public Child():base(10,23)
{
Console.WriteLine("Child Constructor Called");
}
public Child(int x):base(x)
{
Console.WriteLine(" Child Parametrized Consturctor Called");
}
}
class Program
{
static void Main(string[] args)
{
Child c1 = new Child();
Child c = new Child(12);
}
}
}

Polymorphism:-
It is mechanism by which we can implement any thing in such a way that , that particular thing is
going to change it’s behavior (functionality) depending on external interface. There are two types of
polymorphisms, compile time polymorphism and runtime polymorphism. In case of C# we can
implement the polymorphism by two ways –
1. Overloading.
2. Overriding.

Overloading: - It allows you to implement the compile time polymorphism. Overloading is a process
by which we can create multiple implementations with single identity. Overloading can be
implemented by two ways –
Function Overloading: - Function overloading is a mechanism using which we can implement
multiple functions having same name. When you create multiple functions with same name, to avoid
the ambiguity we differentiate them using any of the following criteria –
 Number of parameters should be different
 Data Types of the parameter should be different
 Sequence of data types of the parameter should be different.

But we will not be able to differentiate them using variable names or return data type.
e. g.
namespace Overloading
{
class Student
{
private int sid;

RI-TECH Url: www.ritechpune.com Page No: - 37


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
private string sname;
private string sclass;
public void SetStudent(int i, string sn, string sc)
{
sid = i;
sname = sn;
sclass = sc;
}
public void DispStudent()
{
Console.WriteLine("Student ID:" + sid);
Console.WriteLine("Student Name:" + sname);
Console.WriteLine("Student Class:" + sclass);
}
public string GetClass()
{
return sclass;
}
}
class Teacher
{
private int tid;
private string tname;
private int texp;
public void SetTeacher(int i, string tn, int e)
{
tid = i;
tname = tn;
texp = e;
}
public void DispTeacher()
{
Console.WriteLine("Teacher ID:"+ tid);
Console.WriteLine("Teacher Name:" + tname);
Console.WriteLine("Teacher Exp: " + texp);
}
public int GetExp()
{
return texp;
}
}
class login
{
public int CheckLogin(string l, string p, Student s)
{
if (s.GetClass() == "MCA")
if (l == "Scott" && p == "Tiger")
return 0;
else
return 1;
else
return 2;
}

RI-TECH Url: www.ritechpune.com Page No: - 38


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
public int CheckLogin(string l, string p, Teacher t)
{
if (t.GetExp() > 10)
if (l == "SA" && p == "SA")
return 0;
else
return 1;
else
return 2;
}
}
class Program
{
static void Main(string[] args)
{
Student s = new Student();
s.SetStudent(1, "Ramesh", "MCA");
login l = new login();
int r;
r = l.CheckLogin("Scott", "Tiger", s);

if (r == 0)
Console.WriteLine("Logged In");
else
if (r == 1)
Console.WriteLine("Wrong User Name and Password");
else
Console.WriteLine("Not Qualified");
Teacher t = new Teacher();
t.SetTeacher(1, "Rakesh", 12);
r = l.CheckLogin("SA", "S", t);
if (r == 0)
Console.WriteLine("Logged In");
else
if (r == 1)
Console.WriteLine("Wrong User Name and Password");
else
Console.WriteLine("Not Qualified");
}
}
}

In case of function overloading compiler can decide at compile time which function will be
called at which place, hence it is also called as static binding or compile time binding and
the process is called compile time polymorphism.
Operator Overloading:-
Here we enhance the basic functionalities of the operator so that they can operate on different type
of data. To implement the operator overloading we have to define the function inside the class called
operator overloaded function having following syntax –
Access type static return data type operator operator symbol (parameters)
{

RI-TECH Url: www.ritechpune.com Page No: - 39


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------

This function will be executed in place of operator specified by the operator symbol.
namespace OperatorOverloading{
class weight {
private int gm;
private int kg;
public void setWeight(int k, int g)
{
kg = k;
gm = g;
}
public void dispWeight()
{
Console.WriteLine("Kg:" + kg);
Console.WriteLine("Gn :" + gm );
}
public static weight operator +(weight wt,weight wt1)
{
int tkg = 0;
weight temp = new weight();

temp.gm = wt1.gm + wt.gm;


if(temp.gm >= 1000)
{
tkg = temp.gm / 1000;
temp.gm = temp.gm % 1000;
}
temp.kg = wt1.kg + wt.kg + tkg;
return temp;
}
}
class Program {
static void Main(string[] args) {
weight w1, w2, w3;
w1 = new weight();
w2 = new weight();
w3 = new weight();
w1.setWeight(12, 800);
w2.setWeight(34, 800);
int a = 10 + 23;
string str = "abc" + "stq";
w3 = w1 + w2; // weight.operator+(w1,w2);
w1.dispWeight();
w2.dispWeight();
Console.WriteLine("-------------");
w3.dispWeight();
Console.Read();
}
}
}

RI-TECH Url: www.ritechpune.com Page No: - 40


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
In case of Operator overloading we can decide at compile time which function will be
called at which place, hence it is also called as static binding or compile time binding and
the process is called compile time polymorphism.
Note: - =, . , ?, :,new, is, as, size of These operators can’t be overloaded

Overriding:-
Basically when you inherit any class from some another class, all the things (properties /methods)
will be get inherited in child, some times the parent methods inherited by the child are not sufficient
according to the child, so child need to redefine those methods from scratch or child want to add
some new features to those methods, that is possible by redefining the inherited parent methods in
child. Hence overriding is a process by which child can redefine the virtual or abstract methods of the
parent.
If child redefine any non abstract or non virtual method of the parent the process is not overriding
but it is called as method hiding. Hence when child want to redefine the virtual or abstract method of
parent child have to use override keyword to redefine those methods.

e. g. Method Overriding
using System;
namespace ConsoleApplication11
{
class ParentClass
{
public virtual void DispMethod()
{
Console.WriteLine("Parent Class");
}
}
class ChildClass:ParentClass
{
public override void DispMethod()

{
Console.WriteLine("Child Class");
}
}
class Program
{
static void Main(string[] args)
{
ChildClass sc = new ChildClass();
sc.DispMethod();
}
}
}
To Make Method hiding explicit you have to define the overridden method using new keyword in child
class otherwise c# compiler will give you warning.
e. g. Method hiding
namespace ConsoleApplication5{
class Parent {
public void SampleMethod()
{
Console.WriteLine("Sample parent method");

RI-TECH Url: www.ritechpune.com Page No: - 41


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
}
}
class Child : Parent
{
public new void SampleMethod() // Method hiding
{
Console.WriteLine("Child Sample Method");
}
}
class Program
{
static void Main(string[] args)
{
Child c = new Child();
c.SampleMethod();
}
}
}

Object Slicing: -
When we assign the child object in parent object the child initialize the parent by parent portion of
the child object and the process is called object slicing and when you call the overridden method of
parent when parent has the reference of child object and it will not execute the method of parent,
instead of the it will execute the method from child.
namespace ConsoleApplication11{
class ParentClass {
private int x;
public virtual void DispMethod()
{
Console.WriteLine("Parent Class");
}
}
class ChildClass:ParentClass
{
private int y;
public override void DispMethod()
{
Console.WriteLine("Child Class");
}
}
class Program
{
static void Main(string[] args)
{
ChildClass sc = new ChildClass();
// sc.DispMethod();
ParentClass pc = new ParentClass();
pc = sc; // object slicing
pc.DispMethod();
}
}
}

RI-TECH Url: www.ritechpune.com Page No: - 42


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Runtime Polymorphism:-
In runtime polymorphism we can not able to predict the behavior or functionality of the object at
compile time, we use these facts to implement the runtime polymorphism as follows –
e. g.
namespace ConsoleApplication12{
class Animal
{
public virtual void create()
{
Console.WriteLine("Parent Created");
}
}
class Dog : Animal
{
public override void create()
{
Console.WriteLine("Dog Created");
}
}
class Cat : Animal
{
public override void create()
{
Console.WriteLine("Cat Created");
}
}
class Rat : Animal
{
public override void create()
{
Console.WriteLine(" Rat Created");
}
}
class Program
{
static void Main(string[] args)
{
int opt;
Animal a = new Animal();
Console.WriteLine("1 -- Dog ");
Console.WriteLine("2 -- Cat");
Console.WriteLine("3 -- Rat");
Console.WriteLine("Plz Enter Option:");
opt = Convert.ToUInt16(Console.ReadLine());
switch (opt)
{
case 1:
a = new Dog();
break;
case 2:

a = new Cat();

RI-TECH Url: www.ritechpune.com Page No: - 43


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
break;
case 3:
a = new Rat();
break;
default :
Console.WriteLine("Invalid Option");
break;
}
a.create();
}
}
}

In Above example if you see, you will not be able to predict which function will be get called at
a.create() at compile time, since which function call at this point depends on user input and it will
be available at run time and then we can predict which function will be get called hence here function
call bind to function definition at run time called runtime or dynamic binding and the polymorphism is
called Run Time Polymorphism.
Abstract keyword can be used with class as well as class method, when you use the abstract
keyword with class, you can not create the instance or that class. You can use the abstract keyword
with class as follows –

Abstract Class: -
namespace ConsoleApplication2
{
abstract class Student
{
private int rollno;
private string sname;
private string address;
private string sclass;
public void setStudent(int r, string sn, string add, string scl)
{
rollno = r;
sname = sn;
address = add;
sclass = scl;
}
public void dispStudent()
{
Console.WriteLine("Roll No:" + rollno.ToString());
Console.WriteLine("Student Name :" + sname);
Console.WriteLine("Student Address:" + address);

Console.WriteLine("Student Class :" + sclass);


}
}

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

RI-TECH Url: www.ritechpune.com Page No: - 44


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Student s = new Student(); // this will get you error
}
}
}

Abstract Method:-
When you use the abstract keyword with method, the method will become abstract it means method
can not have the body, such methods can be defined only in abstract class which should be
overridden by the child classes of the abstract class. It means it will be compulsory to child class to
override all abstract methods from the parent, if child does not override any abstract method from
the parent then it will also become abstract class.

e.g.
namespace ConsoleApplication2
{
abstract class Search
{
public abstract Boolean search(int a, int[] nm);
public void disp()
{
Console.WriteLine(" Display method from search");
}
}
class SeqSearch : Search
{
public override bool search(int a, int[] nm)
{
{
bool flag = false;
for (int i = 0; i < nm.Length ; i++)
{
if (a == nm[i])
{
flag = true;
break;
}
}
return flag;
}

}
}
class Program
{
static void Main(string[] args)
{
SeqSearch sq = new SeqSearch();
int[] nm ={ 1, 2, 3, 4, 56 };
if (sq.search(23, nm))
Console.WriteLine(" Element is found ");
else
Console.WriteLine(" Element is not Found ");

RI-TECH Url: www.ritechpune.com Page No: - 45


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
}
}
}

Sealed Keyword:-
Sealed keyword in C# can be used with method or class. When you use the sealed keyword with
class that class can not be inherited, it means you wiil not be able to do the modification or
enhancement in the sealed class. When you define the method using sealed keyword that method
can not be overriden, so can not be modified.
namespace ConsoleApplication2
{
sealed class Student
{
private int rollno;
private string sname;
private string address;
private string sclass;
public void setStudent(int r, string sn, string add, string scl)
{
rollno = r;
sname = sn;
address = add;
sclass = scl;
}
public void dispStudent()
{
Console.WriteLine("Roll No:" + rollno.ToString());
Console.WriteLine("Student Name :" + sname);

Console.WriteLine("Student Address:" + address);


Console.WriteLine("Student Class :" + sclass);
}
}
class StudentAttendance : student // will give you error
{
}
class Program
{
static void Main(string[] args)
{
}
}
}

Exception Handling in C#.Net:-


Exception is runtime condition or situation occurs inside program due to unavailability of any
prerequisite for the proper execution or program, can not be solved by the programmer but
programmer can handle it To handle the exceptions we have two ways –
1. Classical Approach: -It is old approach generally used in no object oriented programming
languages where we can handle the exceptions by comparing the return values of the
functions. Depending on the return values of the function we decide weather exception
occurred here or not occurred.

RI-TECH Url: www.ritechpune.com Page No: - 46


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
e. g. int *pt=malloc(szieof(int));
where we compare the value of pt if it is null that means the memory is not allocated, since
malloc will return NULL if it failed to allocate the memory. This type of exception handling is
called classical way of exception handling. It has one drawback that, every time it is not possible
to return the special value from the function to identify the exception. Hence we use the
structured approach.

2. Structured Approach : - This is most popular way of exception handling in object oriented
programming languages where it provides us following keywords –
 try
 catch
 finally
 throw

Try: - Try keyword is used to define the try block which contains statements or instructions where
exception supposed to occur. Try block contains normal program statements.

Catch: - Catch keyword allows you to define the code block that will be executed as an action when
exception occurs. It contains statement that is action to the exception.
Try and Catch works together to define the try catch block as follows –

try
{
Statements;
}catch(Exception Object)
{
Statements;
}
Where exception object is exception identifier using which we can identify that the action specified in
a catch block will be for specified exception. It is necessary to use the Exception identifier in catch
block since try contains multiple statements which may generates the multiple exceptions hence
multiple exceptions needs multiple actions and single catch block can specify only a action. Hence we
need to use the multiple catch blocks with single try block for specifying different and unique action
for different type of exception and hence needs the exception identifier. We can use multiple catch
blocks with single try as follows –

try
{
Statements;
}catch(Exception object1)
{
Statements;
}
catch(Exception object2)
{
Statements;
}
catch(Exception object3)
{
Statements;
}
….

RI-TECH Url: www.ritechpune.com Page No: - 47


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Note: - With single try we can use multiple catch blocks but with single catch we can not use the
multiple try blocks as well as every try block will have at least one catch block.

Finally keyword: - Finally keyword is used to define the finally block, finally block will contains the
statements those supposed to be executed in both situations weather exception occurs or weather
exception does not occurs. It is used to define the compulsory actions. Single try block can have only
one finally block.

Throw keyword: - throw keyword is used to raise the exceptions if it is not begin raised by the
CLR.

Execution Process:- try block contains the normal program statements those will be executed by
the CLR one after another, if any exception occurs then it will identify that exception and transfer the
program control to the catch block where the action for that exception is being specified by skipping
the rest of the statements from the try block. Once program control transferred to catch block then it
will be executed in response to the exception and it will terminate the program normally.

In case of C#.Net we divide exception handling process in two ways –


1. Built in Exceptions.
2. User Defined Exceptions.

1. Built in Exceptions: - are the exceptions provided by CLR, to whom CLR can identify, raise
as well as can handle. For built in exceptions CLR provides you a exception class using which
we can create exception object to identify the exception and transfer the execution control to
the catch block. What ever may be the type of exception there is class called Exception; it will
be super class of all exception classes.
Built in Exceptions Example: -
namespace ExceptionHan
{
class Program
{
static void Main(string[] args)
{
int n;
int[] nm = new int[3];
try
{
Console.Write("Enter Number");
n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("VAlue of N:" + n);
nm[3] = 23;
}
catch (FormatException ex)
{
Console.WriteLine(" Plz Enter Proper Value");
Console.WriteLine(ex.ToString());
}

catch (IndexOutOfRangeException ex)


{
Console.WriteLine("Index not found");
Console.WriteLine(ex.ToString());
}

RI-TECH Url: www.ritechpune.com Page No: - 48


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------

finally
{
Console.WriteLine(“ Finally block Executed “);
}
}
}
}
User defined exception: -
These are the exceptions those can not be provided by CLR, but generated and identified by the
User, depending on some custom conditions. User can generate the user defined exception using
throw keyword. To implement the user defined exception you have to follow –
> Create special class dedicated to handle the exception
> This class Should Inherit from Exception class
> Throw its object from the normal class where exception occurs.
> Catch the object in catch block where perform the action

e. g. Built in Exception
namespace UserDefined
{
class PriceException : Exception
{
private string str;
public PriceException(string s)
{
str = s;
}
public void DispPriceException()
{
Console.WriteLine("Price Exception Occured" + str);
}
}
class Product
{
private int pid;
private string pname;
private double price;
public void SetProduct(int pi, string pn, double pr)
{
if (pr <= 0)
throw new PriceException("Price Should Be Greater Than Zero");
pid = pi;

pname = pn;
price = pr;
}
public void DispProduct()
{
Console.WriteLine(" Product ID:" + pid);
Console.WriteLine(" Product Name :" + pname);
Console.WriteLine(" Product Price :" + price);
}

RI-TECH Url: www.ritechpune.com Page No: - 49


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
}
class Program
{
static void Main(string[] args)
{
Product p = new Product();
try
{
p.SetProduct(1, "Keybord", -12);
p.DispProduct();
}
catch (PriceException ex)
{
ex.DispPriceException();
}
}
}
}

Note: - You can also use the catch block without exception identifier, if you use the catch
block without exception identifier it is just similar to catch with exception as a parameter.

Namespaces in C#:-
Namespace is facility provided by C# using which you can logically group the classes, together.
Namespace allow you to implement the modularity inside your application.
Namespace can contain definitions of –
>Class
>Interface
>Delegates
>Structures
>Enumerations

Default access type or modifier of the namespace is public which can not be modified. By namespace
you will be able to create and maintain more than one type in C# having same name but define in
different namespace.

To create the namespace in c# we have to use the following syntax –


Namespace namespacename

{
// create definitions here.
}
To use the namespace C# provides us using statement, it can be used as follows –
Using namespace name;
Namespace can contain the nested namespaces those can be accessed using dot operator (.) as –
Using namespace firstnamespace.innernamespace;
e. g.
using x;
will allow you to use all the definitions from x.
using x.y;
Will allow you to use all the definitions from y;

RI-TECH Url: www.ritechpune.com Page No: - 50


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
e. g. Create a namespace searchnm which has a searchclass which will search the
element in a array of element, create it in separate file and use it.
File : - Searchnm.cs
namespace searchnm
{
class searchclass
{
// private Boolean flag;
public int search(int []a,int n)
{
for (int i = 0; i < a.Length;i++)
{
if (a[i] == n)
{
// flag = 1;
return 1;
}
}
return 0;
}
}
}
File : - Searchnamspace1.cs
namespace searchnamespace1
{
class Program
{
static void Main(string[] args)
{
int[] a=new int[5] ;
Console.WriteLine("Enter 5 elements:");
for (int i = 0; i < 5; i++)
{
a[i] = Convert.ToInt32(Console.ReadLine());
}
searchclass s = new searchclass();
Console.WriteLine("Enter no. to be search:");
int n = Convert.ToInt32(Console.ReadLine());
int m=s.search(a,n);
if (m == 1)
Console.WriteLine("Element found");
else
Console.WriteLine("element not found");
}
}
}

Structures:-
A structure in C# is simply a composite data type consisting of number elements of other types
(different type). C# structure is hybrid type since it is get created as value type on stack, so
member accessibility will be just like value type. By default structure members will not be get

RI-TECH Url: www.ritechpune.com Page No: - 51


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
initialized when you create the structure variable where you have to use the new keyword to initialize
the structure elements. C# structure can contain –
Data Members (Fields)
Methods
Constructors
To create structure you have to use syntax-
[Access type] struct structure name
{
Members of the structure;
}

Structure has following characteristics –


- Structure members can be public, private, and internal but can not be protected

- Structure can not implement inheritance means you can not inherit structure as well as structure
in class or class in structure etc.
- Structure can not contain default constructor, structure can have parameterized constructor.
- Structure can use the static keyword for methods, fields.
- Structure is light weight than class, hence used instead of class if there is less behavior.

e. g.
namespace Structures
{
struct item
{
public int itemid;
public string itemname;
public double itemprice;
public void setItem(int id, string nm, double pr)
{
itemid = id;
itemname = nm;
itemprice = pr;
}
public void dispItem()
{
Console.WriteLine("Item id :" + itemid);
Console.WriteLine("Item Name:" + itemname);
Console.WriteLine("Item Price :" + itemprice);
}
}
class Program
{
static void Main(string[] args)
{
item t = new item();
t.setItem(1, "Pen", 234);
t.dispItem();
}
}
}

RI-TECH Url: www.ritechpune.com Page No: - 52


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Interfaces in C#:-
Interfaces are the classes, without definition, you can create the interface in c# using interface
keyword. Interface can not contain any definition or implementation, it will
contain only declaration. Interfaces are generally used to enforce the programmer some kind of
specifications or rules.

>Interfaces consist of methods, properties, events, indexers, or any combination of those four
member types
> An interface cannot contain constants, fields, operators, instance constructors, destructors, or
types.
> It cannot contain static members. Interfaces members are automatically public, and they cannot
include any access modifiers.
> When a class or struct implements an interface, the class or struct provides an implementation for
all of the members defined by the interface.
> The interface itself provides no functionality that a class or struct can inherit in the way that base
class functionality can be inherited.
> However, if a base class implements an interface, the derived class inherits that implementation.
The derived class is said to implement the interface implicitly.
> You can not create the object of interface directly.

e. g. interface
namespace BiilSpecificationExample
{
interface billint
{
void GenBill(int bn, string cn, string fd, string td);
}
class msebbill : billint
{
private int meterno;
private int noofunits;
private int rateperunit;
public void SetBill(int mn, int nfu, int rpu)
{
meterno = mn;
noofunits = nfu;
rateperunit = rpu;
}
public void GenBill(int bn,string cn,string fd,string td)
{
Console.WriteLine("Bill No:" + bn.ToString());
Console.WriteLine("Customer Name :" + cn);
Console.WriteLine(" From Date :" +fd);
Console.WriteLine(" To Date:" + td);
Console.WriteLine("Meter No: " + meterno.ToString() );
Console.WriteLine(" N of Units :" + noofunits.ToString());

Console.WriteLine(" Amount :" + (noofunits * rateperunit));

}
}

RI-TECH Url: www.ritechpune.com Page No: - 53


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
class mbill : billint
{
public void GenBill(int bn, string cn, string fd, string td)
{
}
}
class Program
{
static void Main(string[] args)
{
msebbill msb = new msebbill();
msb.SetBill(12, 2300, 12);
msb.GenBill(1, "Ramesh", "12/4/2009", "1/2/2008");

}
}
}

Generics in C#: -
Generic: this is facility provided by C#.net using which you can implement any thing that will be data
type independent. To implement the generic we have to type symbol that will be act as temp. data
type will be replaced by the actual data type. To use the generic you have to specify the type symbol
with class declaration –
Class classname <A,B> A!=B
{
A a;
B b;
}
e. g. Create stack class to push and pop the integers using array.
namespace StackExample
{
class gstack<A>
{
A [] data;
int top;
public gstack()
{
data = new A[10];
top = -1;
}

public void push(A a)


{
if (top < 9)
{
top++;
data[top] = a;
}
else
{
Console.WriteLine("Stack Full");
}

RI-TECH Url: www.ritechpune.com Page No: - 54


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
}
public A pop()
{
A d=default(A);
if (top != -1)
{
d = data[top];
top--;
}
else
{
Console.WriteLine("Stack Empty");
}
return d;
}
}
class student
{
private int rollno;
private string sname;
public void setstudent(int r, string sn)
{
rollno = r;
sname = sn;
}
public void dispstudent()
{
Console.WriteLine("Roll no:" + rollno);
Console.WriteLine("Name :" + sname);
}
}
class Program
{
static void Main(string[] args)
{
gstack<int> gt = new gstack<int>();

gt.push(23);
gt.push(45);
Console.WriteLine(gt.pop());
Console.WriteLine(gt.pop());
gstack<string> gtstr = new gstack<string>();
gtstr.push("Hello");
gtstr.push("Bye");
Console.WriteLine(gtstr.pop());
Console.WriteLine(gtstr.pop());
gstack<student> gstd = new gstack<student>();
student[] s = new student[3];
for (int i = 0; i < 3; i++)
{
s[i] = new student();
}
s[0].setstudent(1, "Ramesh");

RI-TECH Url: www.ritechpune.com Page No: - 55


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
s[1].setstudent(2,"Rajesh");
s[2].setstudent(3,"Rakesh");
gstd.push(s[0]);
gstd.push(s[1]);
gstd.push(s[2]);
student temp = new student();
temp=gstd.pop();
temp.dispstudent();
temp = gstd.pop();
temp.dispstudent();
temp = gstd.pop();
temp.dispstudent();
}
}
}
Eg2: addition of 2 value having different data type
namespace Addition
{
class Test<A, B>
{
public void dispAddition(A a, B b)
{
double d;
d = Convert.ToInt32(a) + Convert.ToDouble(b);
Console.WriteLine(d.ToString());
}
}
class Program
{
static void Main(string[] args)
{
Test<int,double > t = new Test<int, double>();
t.dispAddition(23,23432.333);
}
}
}

E.g. Class which will have the search method implement that search method using generic.
namespace GenericSearch1
{
class search1<T>
{
public void search(T[] a, T n)
{
int f = 0;
for (int i = 0; i < a.Length; i++)
{
if (Convert.ToString (a[i])==Convert.ToString(n))
{
f = 1;
//Console.WriteLine("Element Found");
break;
}

RI-TECH Url: www.ritechpune.com Page No: - 56


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
}
if (f == 1)
Console.WriteLine("Element found");
else
Console.WriteLine("Element not found");
}
}
class Program
{
static void Main(string[] args)
{
search1 <int> sr =new search1<int>();
int[] a={23,45,67};
sr.search (a,234);
}
}
}

You can apply restrictions to generic classes, by using where clause but you can restrict
the generic types only up to class, structure or interface.

Object as Universal Type:-


C# provides us object type called universal type, object is called universal type since you will be able
to store any type of value in object weather it is value type, reference type of value. Object is
capable to store any data type value form C#, hence object is called reference type of data type.

Boxing and UnBoxing:-


Boxing and unboxing process happens automatically when you assign the value type to object and
object to value.
Boxing :- boxing is process which happens when you store the value type variable value to object or
reference.
e.g. int a=10;
object obj=a; // Boxing occurs

UnBoxing: - unboxing is process which happens when you store reference (object type) of value back
to value type of variable.
e. g.
object obj=34;
int a=(int)obj;
While doing unboxing you have to explicitly type cast the value.

Collections
Collection is facility provided by the C#.net using which you can manipulate group of objects or
values using built in methods. C#.net provides you two types of collections generic and non generic
collections, generic collections are the collections those are data type independent and non generic
collections are not data type independent.
C# provides you so many built in collections those are generic and or of object type. What ever may
be the type of the collection it follows following ways to manipulate those collections –
Generic Collections: -
these are the collections implemented using generic concept capable to store any type of value.
> List , Stack, Queue are generic collection

RI-TECH Url: www.ritechpune.com Page No: - 57


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Generic collections are strictly type, while creating collection variable you have to specify the type of
value.
Non Generic (Universal Collections):- these are the collections which are being created using
universal type object; it is also able to store any type of value.
> Arraylist and hastables are non generic collections.

To use the collections and generic collections you have to use the namespaces –
System.Collections;
System.Collections.Generic;
In general every collection will have following facilities –

 Internally collection implements indexing mechanism using which you can refer the
collection elements, it always starts with zero.
 It provides you following methods(general collection): –
Add: - to add the element.
Remove: - to remove the element.
Count: - property used to count how many elements are their.
Clear: - allow you to clear all the elements of the collection.
Contains: -allows you to find the element in a collection.
IndexOf: - will give the index number of the specified element.
Etc.
Notes: To use the collections you have to use the namespace system. Collections

Some collections provided by C#:-


1. ArrayList: -
This is array which can grow and shrink dynamically according to the elements present into it.
namespace Collection
{
class Program
{
static void Main(string[] args)
{
ArrayList ar = new ArrayList();
ar.Add("First");
ar.Add("Second");
ar.Add("Third");
ar.Add(2234);
ar.Add("Fifth");
for (int i = 0; i < ar.Count; i++)
{
Console.WriteLine(ar[i]);
}
ar.RemoveAt(3);
ar.Add("NEw Element");
for (int i = 0; i < ar.Count; i++)
{
Console.WriteLine(ar[i]);
}
}
}
}

RI-TECH Url: www.ritechpune.com Page No: - 58


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Hashtable,Stack& Queue
namespace htable
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add("1", "First");
ht.Add("2", "Second");
ht.Add("3", "Third");
ht.Add("4","Fourth");
Console.WriteLine(ht["4"]);
Stack s = new Stack();
s.Push(23);
s.Push(34);
s.Push(45);
s.Push(56);
Console.WriteLine(s.Pop());
Console.WriteLine(s.Pop());
Queue q = new Queue();
q.Enqueue("First");
q.Enqueue("Second");
q.Enqueue("Third");
Console.WriteLine(q.Dequeue());
Console.WriteLine(q.Dequeue());
Console.WriteLine(q.Dequeue());
//Console.WriteLine(q.Dequeue());
}
}
}

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace HCollection
{
class emp
{
private int eno;
private string name;
public void setEmp(int no, string nm)
{
eno = no;
name = nm;
}
public void dispEmp()
{
Console.WriteLine("Emp No:" + eno);
Console.WriteLine("Emp Name:" + name);
}
}

RI-TECH Url: www.ritechpune.com Page No: - 59


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
emp e=new emp();
e.setEmp(1,"Ramesh");
ht.Add("First", e);
emp e1 = new emp();
e1.setEmp(2, "Rajesh");
ht.Add("Second", e1);
emp e2 = new emp();
e2.setEmp(4, "Rakesh");
ht.Add("Third", e2);
ICollection ic = ht.Keys;
foreach (string s in ic)
{
emp temp = new emp();
temp = (emp)ht[s];
temp.dispEmp();
}
Hashtable ht1 = new Hashtable();
ht1.Add("a", "234234");
ht1.Add("b", "2342342");
ht1.Add("c", "43534");
ICollection ic1 = ht1.Keys;
foreach (string t in ic1)
{
Console.WriteLine(ht1[t].ToString());
}
}
}
}
List Collection:-
namespace CollectionExample
{
class Program
{
static void Main(string[] args)
{
List<string> lst =new List<string>();
lst.Add("First");
lst.Add("Second");
lst.Add("Third");
lst.Add("Fourth");
lst.Add("Fifth");
lst.Add("Sixth");
Console.WriteLine("Count : " + lst.Count);
// displaying all elements
foreach (string s in lst)
Console.WriteLine(s);
}
}

RI-TECH Url: www.ritechpune.com Page No: - 60


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
}

Delegate – Event and Lambda Expressions:-


Delegate is type provided by C# using which you can store the method reference on object of
delegate type. Once the method reference is stored in delegate object then that delegate object
behaves exactly same as that of method. To create the delegates in C# we have to use the syntax –

[Access type] returndatatype delegatename([parameters])

In case of C# delegate you can store reference of static method or instance method who matches
the delegate signature, delegate in c# will not worry about the other details of the methods to create
the reference. Delegate can store reference of any method whose signature matches with delegate
type.

1 Delegates are just similar to function pointers in C++ but are type safe
2 Delegate type in case of C# is sealed.
3 Delegates allow you to send the methods as a parameter to the functions.
4 Delegates are used to implement the events.
5 Due Covariance and Contra variance method does not need to be match delegate signature
exactly.
6 Delegates allow you to implement and use Anonymous methods.

Anonymous Methods: - Anonymous methods are the methods without name, just a code method
code block without any kind of functions specifications. By using anonymous methods, you reduce
the coding overhead in instantiating delegates by eliminating the need to create a separate method.

e. g. Delegate Example
namespace DelegateExample
{
public delegate void Test();
public delegate int TestM(int a,int b);
public delegate void TestR(bool b);
class Method
{
public void Method1()
{
Console.WriteLine(" Method 1 invoked");
}
public int Method2(int a, int b)
{
Console.WriteLine("Method2 Invoked");
return a+b;
}
public void Method3(bool t)
{
Console.WriteLine("Method3 invoked");
}
public int Method4(int a, int b, int c)
{
Console.WriteLine("Method4 invoked");

RI-TECH Url: www.ritechpune.com Page No: - 61


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
return a + b + c;
}
}
class MethodNew
{
public void MNew()
{
Console.WriteLine(" Method new invoked");
}
}
class Invoker
{
public void InvokeMethod(TestM tm,int a,int b)
{
int r = tm(a,b);
Console.WriteLine(r);
}
}
class Program
{
static void Main(string[] args)
{
Method m = new Method();
Test tdel = m.Method1; // storing refrence of mthod1 in tdel
tdel();

TestM tdel1 = m.Method2;


int r = tdel1(34, 45);
TestR tr = m.Method3;
tr(true);
//Test td = new MethodNew().MNew;
MethodNew mnn = new MethodNew();
Test td = mnn.MNew;
td();
Invoker inv = new Invoker();
inv.InvokeMethod(tdel1,23,34);
}
}
}

e. g. Anonymous Method Example:-


namespace AMethods
{
public delegate void TDel();
public delegate int TDel1(int a,int b);
public delegate void TDel2(int a);

class Program
{

static void Main(string[] args)


{

RI-TECH Url: www.ritechpune.com Page No: - 62


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
TDel td = delegate
{
Console.WriteLine("Method without paramter");
};
td();
TDel1 td1 = delegate(int a, int b)
{
return a + b;
};
int r =td1(23,34);
Console.WriteLine(r);

TDel2 td2 = delegate(int a)


{
Console.WriteLine(a);
};
td2(23);
}
}
}

Lambda Expressions:-
Lambda Calculus is formal system for function definition, function application and recursion it was
introduced in 1930. The expressions developed using Lambda Calculus area called Lambda
Expressions (pronounced Expression Lambda).

All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the
lambda operator specifies the input parameters (if any) and the right side hold the expression or
statement block. The lambda expression x => x * x is read "x goes to x times x."

Lambda Expression:-
Without parameters: () => expression
With One Parameter: (parameter) => expression
With Two parameters: (parameter1, parameter2) =>expression
Lambda Statements: parameters => {Statements}

Lambda Expression can use parameter inference:-


Generally Lambda expression can infer the parameter type directly using expression body or
expression statements.

Advantages:-
Help to reduce the complexity of the anonymous methods, Executes faster than normal sequential
statements.

e. g.
namespace LExpessions
{
public delegate void Test();
public delegate int TestM(int a, int b);
public delegate void TestR(bool b);
class Program
{
static void Main(string[] args)

RI-TECH Url: www.ritechpune.com Page No: - 63


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
{
Test t = delegate { Console.WriteLine("Hello"); };
Test t1 = () => { Console.WriteLine("Bye"); };
t();
t1();

TestM tm = delegate(int a, int b) { return a + b; };


TestM tm1 = (a, b) => { return a + b; };

int r= tm1(23, 34);


Console.WriteLine(r);
}
}
}

Multi Cast Delegates: -


Delegate is called multicast delegate, if it stores the reference of more than one method which can
be invoked at a time. Multi Cast Delegates allow you to store the reference of more than one method
at a time so that you can invoke all these methods simultaneously. Multi Cast delegates will be
created from single delegate by adding or removing more than one method in delegate. Multi Cast
delegates provides us two method combine and remove to add and remove multiple methods from
delegates. In case of C# we have += and -= operators are overloaded to add the method reference
to multicast delegate and to remove the method reference from multicast delegates.

using System;
namespace MultiCastDelegateEx
{
public delegate void Tdel(int a,int b);
class MathC
{
public void addNum(int a, int b)

{
Console.WriteLine(" Addition is : " + (a+ b));
}
public void mulNum(int a,int b)
{
Console.WriteLine(" Multification is : " + (a * b));
}
public void divNum(int a, int b)
{
Console.WriteLine(" Division is :" + (a / b));
}
}
class Program
{
static void Main(string[] args)
{
MathC mc = new MathC();
Tdel td =mc.addNum;
td += mc.mulNum;
td += mc.divNum;
td(200, 10);

RI-TECH Url: www.ritechpune.com Page No: - 64


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Console.WriteLine(" After Rremove" );
td -= mc.mulNum;
td(200, 10);
}
}
}

Events: -
Events are the process by which object notify about some change or activity or user action to the
application. Event will be generally a member of the object which enables object to notify some
change or activity. All GUI based applications are event based, without event we can not implement
the events. Event is best way to implement inter process communication. Event processing involves
two classes one who publish events those can be used by another class to subscribe or register its
methods called event subscriber. So when that event occur the method who had registered to that
will be invoked automatically. Event does not know which method is going to handle or execute the
code when event occurs hence we have to use the delegates so that any method can be invoked
when event occurs automatically.

Events in C# can be created as follows –


public delegate void newdelegate();
public event newdelegate newevent;
namespace EventExample
{
public delegate void EventDel();

// publisher class
class EventPublisher
{
public event EventDel customevent;
public void Execute()
{
customevent();
}
}
// class FirstSubsc
class FirstSub
{
public void FirstHandler()
{
Console.WriteLine("First handler executed ");
}
}
class SecondSub
{
public void SecondHandler()
{
Console.WriteLine("Second Hander Executed ");
}
}
class Program
{
static void Main(string[] args)
{

RI-TECH Url: www.ritechpune.com Page No: - 65


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
FirstSub fs = new FirstSub();
SecondSub sc = new SecondSub();
EventPublisher ep = new EventPublisher();
ep.customevent += fs.FirstHandler;
ep.customevent += sc.SecondHandler;
ep.Execute();
}
}
}

Extension Methods in C#:-


Extension methods allow existing classes to be extended without relying on inheritance or having to
change the class's source code. This means that if you want to add some

methods into the existing String class you can do it quite easily. Here's a couple of rules to consider
when deciding on whether or not to use extension methods:

> Extension methods cannot be used to override existing methods


> An extension method with the same name and signature as an instance method will not be called
> The concept of extension methods cannot be applied to fields, properties or events
> Use extension methods sparingly....overuse can be a bad thing!

e. g. Extension methods
namespace ExtensionMethods
{
public static class ExString
{
public static string CapChar(this string s, int i)
{
char [] temp = s.ToCharArray();
if (s.Length > i)
{
for(int j=0;j<s.Length;j++)
if (i == j)
{
if (Char.IsLower(temp[j]))
temp[j]= Char.ToUpper(temp[j]);
}
}
string t="";
for(int k=0;k<temp.Length;k++)
t+=temp[k].ToString();
return t;
}
}
}

.NET Reflections:-
Assemblies contain modules, modules contain types, and types contain members. Reflection provides
objects that encapsulate assemblies, modules, and types. You can use reflection to dynamically
create an instance of a type, bind the type to an existing object, or get the type from an existing

RI-TECH Url: www.ritechpune.com Page No: - 66


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
object. You can then invoke the type's methods or access its fields and properties. Reflection is
facility which allow you to extract the type informaiton from exiting type at run time.

In .net reflection you will be able to find the fllowing informaiton -


> Assembly
> Module
> ConstructorInfo
> MethodInfo
> Attributes
Etc
It provides you a namespace System.Relection which provides you the classes –
>MemberInfo
>MethodInfo
>ConstructorInfo
Which can be used to extract the informaiton about that specified type.

Attributes in C#:-
Attribute facility provided by C# allow you to specify extra information about C# type that can not be
specified while decleration or defination of that type. C# Attributes can be used with–
> Types
>methods
> Properties
Etc.
You can restrict the attribute uses by using attributeuses tag, you can restrict attribute uses to -
> Class
> Struct
> Enum
> Method
> Property
Etc.
To create the attributes you have to create a public class which inherits form the attribute class. It
should contain public constructors and positional or named paramters. It can have following types of
paramters –
> Simple types (bool, byte, char, short, int, long, float, and double)
> String
> System.Type
> Enums
>object (The argument to an attribute parameter of type object must be a constant value of one of
the above types.)
> One-dimensional arrays of any of the above types

e. g.
using System;
namespace AttributesExample
{
[AttributeUsage(AttributeTargets.All)]
class HelpAttribute:Attribute
{
private string _version;
private string _mgname;
public string Version
{

RI-TECH Url: www.ritechpune.com Page No: - 67


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
set
{
_version = value;
}
get
{
return _version;
}
}
public HelpAttribute(string value)
{
_mgname = value;
}
}
[HelpAttribute("Revolution Infosytoems",Version="1.2")]
class UseAttribute
{
public void SampleMethod()
{
Console.WriteLine("Sample Method Created");
}
}
class Program
{
static void Main(string[] args)
{
System.Reflection.MemberInfo info = typeof(UseAttribute);
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i++)
{
System.Console.WriteLine(attributes[i]);
}
}
}
}

RI-TECH Url: www.ritechpune.com Page No: - 68


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------

HTML / CSS / JavaScript

RI-TECH Url: www.ritechpune.com Page No: - 69


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Introduction to HTML, CSS & JavaScript: -
What is Web Page?
Web page is collection of static information that can be viewed using web browser, the
information from web page is interlinked to each other using the special text called hyper
text. To create web pages we use the hyper text mark up language (HTML).

What is Web Browser?


It is software using which you can access the internet as well as you can view the web
pages. There is n number of browsers like internet explorer, firefox, netsacape called web
browsers. In web browsers we can view only web pages.

What is Web Site or Web?


Web site is collection of web pages interlinked through each other using a special text called
hyper text. Indirectly we can say website is nothing but the web pages which contains
information and text which provides the linking between web pages.

How Web Works or Execute?


To access the website we open the web browser like internet explorer, we type the address of
the website (e.g. www.revolutioninfosystems.biz ) in the address bar. Once you type the
website address in the address bar of the website and your internet is on, it will take that
address to a server computer of ISP (Internet Service Provider) where that address will be
converted to specific IP Address and the request will be diverted to that computer whose IP
address is generated, this request will diverted to port 80 of requested server computer
where it will be process by special software and result will be generated in html format and
sent back to the user.

What is Web Server?


Web server is special software running on the server computer which processes the request
coming on the port 80 with http protocol (Hyper Text Transfer Protocol).
E. g. IIS, Apache etc.

What is an HTML and HTML File?


HTML stands for Hyper Text Markup Language.
A HTML file is a text file containing small markup tags.
The markup tags tell the Web browser how to display the page.
A HTML file must have an htm or html file extension.
A HTML file can be created using a simple text editor.

HTML Tags:-
HTML tags are used to mark-up HTML elements
HTML tags are surrounded by the two characters < and >
The surrounding characters are called angle brackets
HTML tags normally come in pairs like <b> and </b>

RI-TECH Url: www.ritechpune.com Page No: - 70


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
The first tag in a pair is the start tag, the second tag is the end tag
Paired tags are the tag which has start tag and end tag.
Unpaired tag is tag which has start tag but no end tag.
The text between the start and end tags is the element content
HTML tags are not case sensitive; <b> means the same as <B>

Layout Tags:-
Html provides you following layouts –
1. Table : - <table> tag is used for table layout, which is fixed layout attached with
borders of the container.
2. Div: - <div> tag is used for floating layout, the layout that is not attached to the
borders of the table.
3. Frame (Not used in ASP.NET): - allow you to divide the browser area into sections
where you can load another html documents or web supported files, this is attached
with the borders.
4. IFrame(Not Used in ASP.NET): - allow you to divide the browser area into sections
where you can load other html documents which is floating, not attached with the
borders of the browser.

HTML Tables:-
To create tables in HTML we use the <Table> tag with </Table>. Table tag is used to
represent the tabular format of data (data in rows and columns).
Table tag has following attributes:-
Bgcolor: - Allow you to specify the background color to the table.
Background: - allow you to specify the URL of the image that will be displayed in
background.
Width: - Allow you to specify the numeric value to decide the width of the table in pixel.
Height: - Allow you to specify the height of the table in pixel.
Cell Padding: - allow you to specify how much space should be left blank between the
content of the cell and the borders of the cell.
Cell Spacing: - allow you to specify the space that should be left between two cells of the
table.
Border: - allow you to specify the thickness of the border, 0 means now border.
Align: - can take values right, left or center to align the table in page.
Brodercolor: - you can specify the border color here.

Table Architectures:-
Table contains rows and rows contains cells. Cells can be of two types – (Heading / Normal).
As Table -> Rows -> Cells (Threading / Normal).

Rows (<TR> </TR>):- rows will be created using the <tr> tag. Rows can contain the table
data or heading. TR tag has following attributes –
Align: - allow you to specify values left,right or center to align the content of the row.
Bgcolor: - Allow you to specify the background color to the row.

RI-TECH Url: www.ritechpune.com Page No: - 71


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Background: - allow you to specify the URL of the image that will be displayed in
background.
Height: - Allow you to specify the height of the row in pixel.

Cells :- Html table row can contain the cells of tow types the cells for heading and the cells
containing the data. The cells containing the heading can be defined using tags <th>
</th> as follows –
<th> hading of cell or coloumn </th>
The cells containing the cell data can be defined using tag <td> </td> as follows –
<td> data </td>

Table cells will have the following attributes –


Bgcolor: - allow you to specify the background color of the cell.
Align: - allow you to specify the alignment of the cell like left, right and center.
Rowspan: - allow you to specify the by how much rows you want to increment the height of
the cell. (used to increment the height of the cell).
Colspan: - allow you to specify by how much cells you want to increment the width of the
cell.
Background: - allow you to specify the background image that will be displayed in cell.

e.g. Normal table with border 1:-


<html>
<body>
<table border="1">
<tr> <td> row 1, cell 1 </td>
<td> row 1, cell 2 </td> </tr>
<tr> <td> row 2, cell 1 </td>
<td> row 2, cell 2 </td> </tr>
</body>
</html>
Output:-

e.g. Table with colspan and rowspan.


<html>
<body>
<h4>Cell that spans two columns:</h4>
<table border="1">
<tr>
<th>Name</th>

RI-TECH Url: www.ritechpune.com Page No: - 72


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
<th colspan="2">Telephone</th>
</tr>
<tr>
<td>Bill Gates</td>
<td>555 77 854</td>
<td>555 77 855</td>
</tr>
</table>
<h4>Cell that spans two rows:</h4>
<table border="1">
<tr>
<th>First Name:</th>
<td>Bill Gates</td>
</tr>
<tr>
<th rowspan="2">Telephone:</th>
<td>555 77 854</td>
</tr>
<tr>
<td>555 77 855</td>
</tr>
</table>
</body>
</html>

Div Tag (Floating Layers):-


Div tag is used to create the floating layers those are not attached with the borders; you can
place div any where in document using CSS positioning attributes. The <div> tag defines a
division or a section in an HTML document. The <div> tag is often used to group block-
elements to format them with styles.
Div tag is just like your body tag can content the content or another html tags.

RI-TECH Url: www.ritechpune.com Page No: - 73


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Forms and Inputs:-
Forms are the invisible rectangular area provided by html document where you can make
an arrangement of form elements using which you can accept the input, this input will be
submitted to the server using form where it will be processed by the processing application.

To create the html form in html document we use the form tag as follows –

<form name=”value” action=”Url” method=”value”>


Form elements
</form>

Form tag has following attributes all are optional –


Name: - is used to identify the form since a single html document can contain multiple
forms depending on the application need.
Action: - is used to specify the URL to which this form will be submitted and processed by
the server.
Method: - is used to specify how you want to submit that form to the user. In methods we
can use any of the following two values –
Get: - this method is used if you want to submit limited input the server and non secure
input. If you use the get method their will be limitation of the number of input values as
well as input values will be shown in the client browser.
Post: - this method is used if you want to submit unlimited input to the server as well as
secure input, the input sent using post method will not be visible to the user.

Form Elements:-
Html elements are html tags using which you can create the graphical components; those
can be used to accept the input from the user. Html form can have the following elements to
accept the input from the user –

A. Input Tag: - input tag is used to provide user html elements (controls) using which user
can provide the input (data, event) has following syntax –

<input type=”value” name=”value” width=”value” height=”value”>

Where
Type: - is used to specify what type of input you want to create. Html provides you following
types –
Text: - is used if you want to provide the Text Field (Editable Rectangular Area) to the
user where user can input data. By default size of the Text Field in most browsers will be 20
characters. Can be used as follows –

<input type=”text” width=”20” value=”initial value”>

RI-TECH Url: www.ritechpune.com Page No: - 74


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Password: - is used if you want to provide the password box to the user where user can enter
password. The data entered in password box will be show in default password character of
the windows. It can be used as follows –

<input type=”password” width=”10” value=”initial value”>

Button: - is used if you want to provide user button where user can click to generate the
click event. It can be used as follows –

<input type=”button” value=”click to check”>

Submit: - is used if you want to provide such button when user click on this button it will
submit form automatically to the server. It can be used as follows –

<input type=”submit” value=”Click to submit the form”>

Reset: - is used if you want to provide the button when you click on that button the content
of the form will be get automatically cleared or all the values of the html elements present
on the form will be get cleared. It can be used as follows –

<input type=”reset” value=”Clear the text”>

Radio: - is used if you want to provide the user the options and where from user can select
only on at a time. When we say options we have to create the multiple radio buttons every
button from which provides some option where from user can select only one at a time. In
case of radio buttons user can select only one from the group of radio buttons only if name
attribute value of the radio button will be same for all radio buttons.

<input type=”radio” value=”C”>

Checkbox: - This is used if you want to show the check box in your website, checkbox are
again used to provide the options to the user where from user can select multiple at a time.

<input type=”checkbox” value=”CPP”>

File:-allow you to create the file upload box that can be used to upload the files to the server.

<input type=”File” >

Hidden: - Allow you to store some value in html form that will be submitted to the server
but will not visible to the user.

RI-TECH Url: www.ritechpune.com Page No: - 75


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
<input type=”hideeen” value=”value” >

TextArea tag: - Text Area tag allows you to display the muti column and multi row box
where user can input multiple line of text. It can be used as follows –
<TextArea name=”ta” cols=”value” rows=”value”> </TextArea>

Select tag: - Select tag allows you to create a facility where from you can provide the options
to the user where user can select one or multiple. Select will contain the options those can
be created using the options tag. It can be used as follows –

<select >
<option> First Option </option>
<option> Second Option </option>
<option> Third Option </option>
<option> Fourth Option </option>
</select>

select has following attributes –


name :- allow you to specify the name of a control.
multiple: - allow you if you want to provide the multiple selection.
Size: - allow you to specify the size of the given multiple selection option.

CSS:-
Cascading Style Sheet is a web technology which provides you huge amount of attributes
those attributes can be used to format the content of the html tags.
Html tags has very less amount of attributes those attributes does not allow you to create
the complex design hence we use the CSS. Cascading style sheets those can be used to
generate or extend the attribute capabilities of the browser to generate the complex
presentation structure of the html document. Collection of CSS attribute placed together in
file is called Style Sheet.

CSS Enables us:-


>Provides us large amount of attributes those can be used to create the complex
presentation of the html document.
>Greater Reusability and Inheritance.
>Complete control over loop and feel of website.
>Compatible with all browsers.
>Approved by W3.

CSS attribute can be applied directly to html tag using style attribute or using selectors.
All CSS attributes are in small case and their values are also in small case, when ever you
use the attribute and value together those should be separated using : operator and if you
want to use more than one attributes those should be separated using ;.

Some common attributes in CSS:-

RI-TECH Url: www.ritechpune.com Page No: - 76


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
background-color:- allow you to specify background color.
background-image:- allow you to specify background image.
color: allow you to specify the fore color.
border-width: allow you to specify the border width.
border-style: will allow you to specify the border style.
border-color: will allow you to specify the border color.
font-size : allow you to specify the font size
font-family: allow you to specify the font family.
text-align: allow you to specify the alignment of text
vertical-align: allow you to specify the vertical alignment.
margin, margin-top, margin-bottom, margin-left, margin-right, padding, padding-top,
padding-left, padding-right, padding-bottom, position, left, top, right, bottom, text-
decoration

CSS can be used in html page by three ways –


> Inline CSS.
> Internal CSS.
> External CSS.
Inline CSS:-
In case of Inline Cascading Style Sheet we use attributes using style attribute of the html
tag. The style attribute in html tag allow you to define the CSS attributes, style attribute
can be used in any html tag as follows –
<tagname style=”attribute1:value1;attribute2:value2;” > Content </tagname>
E.g. Create a table with following border info (solid border, 1px border, orange border)
<Html>
<head>
<title> Embedded Style </title>
</head>
<body>
<html >
<table style=”border-width:1px;border-color:orange;border-style:solid;”>
<tr> <td> Sample table </td> </tr>
<tr> <td> Sample table </td> </tr>
</table>
</html>
</body>
</Html>
Output:-

Internal and External CSS:-


Internal or External CSS can be used with selectors using following syntax –
Selector { attribute:value; attribute:value;};

RI-TECH Url: www.ritechpune.com Page No: - 77


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Where selectors can be: - Html Tag, ID or Class.
ID Selectors: - id is the identifiers used as selector in CSS starts with # and can be used in
html tag using id attribute.
Class Selectors: - class selector names starts with dot operators (.) can be used in html tag
using class attribute.
Internal CSS:
Internal CSS allow you define the style in head section of html document which will be get
applied to html document automatically depending on selector uses and tag uses. To create
the internal CSS we use style tag in head section of html document where we will define the
style using any selector.
e. g. Apply following inline style to the following tags –
h1 – background color should be red and fore color should be white.
p – Background color should be blue and fore color white and font size 12.
Table – background color cyan.
<html>
<head>
<title>Div Ex2 </title>
<style>
h1
{
background-color:red;
color:white;
}
p
{
background-color:blue;
color:white;
}
table
{
background-color:cyan;
}
</style>
</head>
<body>
<h1> Heading with style </h1>
<table>
<tr> <td> Table with style </td> <td> Table with style </td> </tr>
</table>
<p>
Hello this is test tag used for long time duration. <br>
dfsdf
sdfsfs<br>
</p>

RI-TECH Url: www.ritechpune.com Page No: - 78


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
</body>
</html>
<style>
.classname
{
attributes and values;
}
.classname
{
attributes and values;
}
</style>

In case of css class name always starts with dot (.). Then you will have the freedom to use
those classes according to your requirements as follows –
<tag class=”name of class without dot”> Content </tag>
e.g. implement above example with inline style classes.
<html>
<head>
<title>Div Ex2 </title>
<style>
.head
{
background-color:red;
color:white;
}
#admin
{
background-color:blue;
color:white;
}
.test
{
background-color:cyan;
}
</style>
</head>
<body>
<h1 class="head"> Heading with style </h1>
<h1> heading without style </h1>
<table id="admin">
<tr> <td> Table with style </td> <td> Table with style </td> </tr>
</table>

RI-TECH Url: www.ritechpune.com Page No: - 79


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
<table>
<tr> <td> Table without style </td> <td> Table without style </td> </tr>
</table>
</body>
</html>

External CSS:-
in case of external style sheet we define the external file which contains the css style which
can be style with tag or style with class. In case of external style sheet you will get the
flexibility to apply it to any html document according to your need. To use the external style
sheet we have to use the link tag as follows –

<link href=”path or name of css file” rel=”stylesheet”>

You have to place this tag in head section of the html document.

E.g.
Creating CSS file with name “MyCSS.css” with following content -
h1
{
background-color:orange;
font-size:14px;
color:blue;
}
p
{
background-color:yellow;
font-size:16px;
color:orange;
}
table
{
border-style:solid;
border-width:2px;
border-color:yellow;
background-color:#000aaaa;
}
.admin
{
background-color:navy;
height:100px;
weight:100px;
}
Creating html file where we want to apply “MyCSS.css”

RI-TECH Url: www.ritechpune.com Page No: - 80


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
<html>
<head>
<title> This is test title </title>
<link href="MyCSS.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1> First Heading </h1>
<p> This is para </p>
<table> <tr><td> This is first Cell</td><td>Second Cell </td></tr>
</table>
<div class="Admin">
First
</div>
</body>
</html>

What is DOM and DOM Objects? : -


Document object model defines hierarchy of objects from html document / web browser those
can be accessed using scripting languages like java script / vb script etc. DOM provides you
built in objects which reference the html document elements those can be modified
dynamically using scripting languages. Three DOMS being provided by W3 those are –
Core DOM
HTML DOM

HTML DOM has following structure or tree of objects or elements those can be accessed by
javascript or vbscript.

Window

Frames[] History Navigation Document

Applet Images Links Forms

Button, Checkbox, Input, Select, File,


Submit Reset Radio Password Text Area

Right know we should have to worry about only document object, document object provided
by DOM will have following methods –
getElementByID(id): - will return you reference of element if found by id.
getElementByName(name): - will return you reference of element if found by name.
getElementByTagName(name):- will return you reference of element if found by tag name.

RI-TECH Url: www.ritechpune.com Page No: - 81


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
DOM also provides us following set of common properties –
innerText:- allow you to reference the inner text of html tag.
innerHtml:- allow you to reference the inner html of the html tag.

Java Script Programming:


Scripting Languages: - Scripting languages are the small subset of the programming
languages. Scripting languages are used to add the dynamic ness to the web pages
developed using html. Scripting languages are not complete programming languages, but it
is subset of programming languages using which you can write small code blocks those will
be used to add the dynamic ness to the web pages. Depending on where the scripting will be
executed scripting languages are divided into two sets –

A. Client Side Scripting: - the programs or code blocks those will be executed on the
client (in web browser), using which we can provide some dynamic ness to the exiting
html representation of the data. Some are the popular client side scripting languages
are javascript, vbscript etc.

B. Server Side Scripting: - these are the small script code block those will be executed
on the server computer. This is generally used to process data sent from the client to
the server. It will be executed on the server by the special program called web server.
Some of the popular scripts are php, asp, jsp etc.

HTML SCRIPT TAG:-to use the client side scripting in the html document the html
provides us script tag can be used as follows-
<script language=”langaguge name” >
Script code
</script>
You can place the script tag any where in the html document but in general we place
the script tag in head section of the html document.

Java Script Programming:-


 Java script is case sensitive scripting language.
 Java script is sub set of java programming language.
 Java script is object based programming language.
 Java script is not strongly typed programming language.
 Every statement in java script terminates with ;
 Javascript is default programming language of the internet explorer.

Variables in JavaScript: - to create the variables in java script we use the following
syntax –
var variablename[=initial value];
var statement is used to create the variable in javascript. Javascript variables will be of
variant data type.

RI-TECH Url: www.ritechpune.com Page No: - 82


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
e.g. var test=”Hello”; will create a viable which contains the string hello.
Operators: -
Arithmetic: - +, -, /, %, =
Relational: - >, <,>, <=, >=, !=, ==
Logical: - &&, ||, !

Input: - To accept the input in javascript we have two ways, you can use the html controls
like input. Java script also has a function called prompt used to accept the input from the
user.
prompt:- prompt function of java script is used to accept the input from the user. It shows
you the rectangular box using which you can accept the input from the user. It has following
syntax-
prompt(“Message”,”Title”);
prompt returns you string type of the value.

Output: - to generate the output from the javascript, we have two ways –
1. document.write: - write method of the document object from the dom model
can be used to write some content on the client browser.
2. alert: - alert box is used to show the message to the user in a box with ok
button. It has following syntax –
alert (“Message”);

Some javascript functions:


1. confirm: - confirm function of javascript will show you a box which contains the buttons
ok and cancel with some message where user can confirm the message by clicking on ok
button and user can disconfirm the message by clicking cancel button.
confirm (“Message”);
2.. pareInt: - this function is used to convert any value into integer can be used as follows –
parseInt(value);
3. parseFloat:- this function is used to convert the given value into the float can be used as
follows –
parseFloat(value);
e. g. program to display hello this is javascript in client browser.
<html>
<head>
<script language="javascript">
document.write("Hello this is java script ");
</script>
</head>
<body>
</body>
</html>

e. g. Accept two numbers from the user using prompt and display it’s addition.

RI-TECH Url: www.ritechpune.com Page No: - 83


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
<html>
<head>
<title> Addition of two numbers </head>
<script language=”javascript” >
var num1 = parseInt(prompt(“Plz Enter Number”));
var num2= parseInt(prompt(“Plz Enter Second Number”));
var num3 =num1 +num2;
alert(“Addition of Num1 and Num2 is “ + num3);
</script>
<body>
</body>
</html>

Conditional Statements: - Javascript provides us if and if-else statements to implement


the conditions can be used as follows –
if(condition)
{
statements;
}
else
{
statements;
}

e.g. Accept a number from the user and display weather it is odd or even.
<html>
<head>
<title> Even and odd digit </title>
<script language=”javascript”>
var num;
num = parseInt(prompt(“Plz enter number”));
if(num%==0)
alert (“Even”);
else
alert(“Odd”);
</script>
</head>
<body>
</body>
</html>

Nested Conditions: - Javascript allow us to nested if and if-else statements according to


our need to implement the nested conditions.
e.g. Accept three numbers from the user and display the greatest number from it.

RI-TECH Url: www.ritechpune.com Page No: - 84


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
<html>
<head>
<title> Greatest Number </title>
<script language=”javascript”>
var a,b,c;
a= parseInt(prompt(“Enter value for A”));
b=parseInt(prompt(“Enter value for B”));
c=parseInt(prompt(“Enter value for C”));
if(a>b)
if(a>c)
alert (“ A is Greater”);
else
if(b >c )
alert(“B is Greater”);
else
alert(“C is Greater”);
</script>
</head>
<body>
</body>
</html>

Logical Operators:-Javascript provides us following logical operators (&& || ! ) can be


used as follows –
e.g. Accept a number from the user and find out weather it is two digit number or not a two
digit number.
<html>
<head>
<title> Greatest Number </title>
<script language=”javascript”>
var a
a= parseInt(prompt(“Enter Number”));
if(a>9 && a <100)
alert(“It is two digit number”);
else
alert(“It is not two digit number”);
</script>
</head>
<body>
</body>
</html>
Switch Case: - it is used to compare single value with set of values, has
following syntax –
switch(value)
{

RI-TECH Url: www.ritechpune.com Page No: - 85


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
case value1:
statements;
break;
case value2:
statements;
break;
case value3:
statements;
break;
default:
statements;
break;
}
e. g. Accept a character from the user and display weather it is vowel or
consonant.
<html>
<head>
<title> consonent or oval </title>
<script language="javascript">
var ch;
ch = prompt("Plz Enter Character");
switch(ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
alert("Vowel");
break;
default:
alert("Conso");
break;
}
</script>
</head>
<body>
</body>
</html>

Increment and Decrement Operators (++/--):-


++ operator in case of javascript is used to increment given value by one and – operators in
case of javascript will be used to decrement the given value by one.
Looping Statements: looping statements are used to perform any given task repeatedly.
Javascript provides us following loops to perform the looping.

RI-TECH Url: www.ritechpune.com Page No: - 86


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
A. For Loop: - used when you know in advance how many times the loop is going to
execute. It has following syntax-
for(initial value; terminating condition; increment or declrement)
{
Statements;
}

B. while loop:- used when you do not know how many times the given loop is going to
execute. It has following syntax –
while(condition)
{
Statements;
}
C. do-while loop:- used when you want to execute the loop at least for one time and
later execution depends on condition.
do
{
Statements;

}while(condition);
break and continue Statement:- break and continue statements is used to break the loop or
continue the execution of the loop just similar to c and c++.
e .g. for loop (write a program Number is prime or Not)
<html>
<head>
<script language="javascript">
var nm,cnt,f=0;
nm=parseInt(prompt("Plz Enter Value"));
for(cnt=2;cnt<nm;cnt++)
{
if(nm % cnt==0)
{
f=1; break;
}
}
if(f==1)
alert("Not an prime number");
else
alert("Prime number");
</script>
</head>
<body>
</body>
</html>
e. g. while (accept a number from the user and display the addition of digits of that
number)
Write a program Number is prime or Not

RI-TECH Url: www.ritechpune.com Page No: - 87


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
<html>
<head>
<script language="javascript">
var nm,dig,sum=0;
nm=parseInt(prompt("Plz Enter Value"));
while(num!=0)
{
dig = num % 10;
sum = sum +dig;
num = num /10;
}
alert(“Addition is :” + sum);
</script>
</head>
<body>
</body>
</html>
e.g do-while(e.g. addition of given numbers till user says continue )
<html>
<head>
<script language="javascript">
var opt,num,sum=0;
do
{
num= parseInt(prompt("Plz Enter number"));
sum =sum +num;
opt=confirm("Do you want to continue");
}while(opt==true);
document.write("<b> <font color=blue>Addition of numbers :"+ sum +"</font></b>");
</script>
</head>
<body>
</body>
</html>
Nested Loops: - you can also nest the loops according to your requirements.
e.g. display all prime number from 1 to 100 on html document.
<html>
<head>
<script language="javascript">
var cnt,cnt1,f;
for(cnt=1;cnt<=100;cnt++)
{
f=0;
for(cnt1=2;cnt1<cnt;cnt1+)
{
if(cnt % cnt1==0)
{
f=1; break;

RI-TECH Url: www.ritechpune.com Page No: - 88


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
}
}
if(f==0)
document.write(cnt +” is prime <br>”);
}
</script>
</head>
<body>
</body>
</html>
Arrays: - array is a facility using which we can refer the multiple values or elements by
sing name. To use the array in javascript we have to use the keyword Array as follows –
Var variablename =new Array(size);
It will create the array with the specified size where every array element can be accessed
using the index number as –
Arrayname[index]
In case of javascript array index ranges from 0 to size -1.
Eg. Accept 10 numbers from the user in array and find the maximum from it.
<html>
<head>
<title> Array example max</title>
<script language="javascript">
var ar =new Array(10);
var cnt=0;
// Accepting numbers
for(cnt=0;cnt<10;cnt++)
{
ar[cnt]=parseInt(prompt("Plz Enter value"));

}
var max=ar[0];
for(cnt=1;cnt<10;cnt++)
{
if(max < ar[cnt])
max =ar[cnt];
}
alert(max);
</script>
</head>
<body>
</body>
</html>
Functions: - just like c you can also create the functions in java, to create the functions in
java we use function keyword with the name of the functions you can also return the value

RI-TECH Url: www.ritechpune.com Page No: - 89


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
from the function using return value and functions can have the parameters, you can create
the function as follows –
function functionname(parameters)
{
statements;
return value;
}
E.g. write a function in javascript which will display power of the given number.
<html>
<head>
<title> Array example max</title>
<script language="javascript">
function power(a)
{
return a*a;
}
var c=parseInt(prompt("Enter number"));
var t=power(c);
alert(t);
</script>
</head>
<body>
</body>
</html>
e. g. Accept a number from the user and display it’s reverse using function.
<html>
<head>
<script language="javascript">
function getrev(n) {
var r=0;
var dig;
while(n!=0)
{
dig= n % 10;
r =r * 10 +dig;
n = parseInt(n/10);
}
return r;
}
var num = parseInt(prompt("Plz Enter numbe"));
var s= getrev(num);
alert("Reverse is :" + s);
</script>
</head>

RI-TECH Url: www.ritechpune.com Page No: - 90


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
<body>
</body>
</html>

HTML Form elements and Event Handling: - Html provides you the form which will
have the elements those ca n be used by the javascript for any kind of processing using
DOM. While accessing the form elements in javascript we have to follow
document.form.element structure where we can access the value of that element. There is
no use of access the elements in normal script block of javascript, instead of that we can
access it in a javascript function and that functions can be called on any of the html
elements events.
HTML Elements (Controls Events):- All html events start with on keyword. Html elements
supports following events –
OnClick: - will occur when you click the button or hyper link or submit or reset button.
OnDblClick: - will be executed when you double click on the html form element.
OnBlur: - it will occur when you move the courser from given control out or in.
OnFocus: - it will be executed when you move the cursor inside the control.
OnKeyUp: - it will be executed when you pressed key is in up state.
OnKeyDown: - it will be executed when you press the key.
OnKeyPresss: - will be executed when you press or release the key.
OnMouseOver: - will be executed when you move the mouse over the control.
OnmouseOut: - will be executed when you move the mouse out from the control.
Onload: - will be executed when the page get loaded.
OnSubmit: - will be executed when you submit the form.
OnReset: - will be executed when you reset the form.

To Access the html elements in Javascript we use DOM.


1. Design the following form to accept two numbers from the user in text and
display their addition in text on the click of button.

E.g.
<html>
<head>
<title> Addition of numbers </title>
<script language=”javascript”>
function DoAddition() {
var fnum = parseInt(document.additionfrm.firstnumber.value);
var snum= parseInt(document.additionfrm.secondnumber.value);

RI-TECH Url: www.ritechpune.com Page No: - 91


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
var resnum = fnum + snum;
document.additionfrm.result.value=resnum;
}
</script>
</head>
<body>
<form name=”additionfrm”>
First Number: <input type=text name=”firstnumber” > <br>
Second Number: <input type=text name=”secondnumber”> <br>
Result: <input type=text name=”result”> </br>
<input type=button onclick=”DoAddition()” value=”Addition”>
</form>
</body>
</html>
E.g Accept a number in text and display it’s factorial on alert box on the click of
button.
<html>
<head>
<title> factorial of numbers </title>
<script language=”javascript”>
function GetFact() {
var fnum = parseInt(document.factfrm.number.value);
var fact=1;
var cnt;
for(cnt=1;cnt<fnum;cnt++)
fact = fact * cnt;
alert(“Factorial is :” + fact);
}
</script>
</head>
<body>
<form name=”factfrm”>
Enter Number: <input type=text name=”number” > <br>
<input type=button onclick=”GetFact()” value=”Addition”>
</form>
</body>
</html>
E.g. Show list of colors in select box and apply the selected color to the document
background on the click of button.
<html>
<head>
<title> Change Color Example </title>
<script language="javascript">
function changecolor() {

RI-TECH Url: www.ritechpune.com Page No: - 92


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
var c=document.frm.color.value;
document.bgColor=c; }
</script>
</head>
<body>
<form name="frm">
Select Color:
<select name="color">
<option value="red" > red </option>
<option value="green"> green </option>
<option value="blue"> blue </option>
<option value="cyan"> cyan </option>
<option value="gold"> gold </option>
</select>
<br>
<input type="button" value="Change Color" onclick="changecolor()">
</form>
</body>
</html>
e.g. Accept two numbers in two text fields and show the list of operators (+, - , * , /)
in a select and show the result of selected operation in the third textbox on the
click button.

<html>
<head>
<title> Select Ex </title>
<script language="javascript">
function opr() {
var v=document.frm.op.value;
var a,b,c;
a= parseInt(document.frm.fn.value);
b= parseInt(document.frm.sn.value);
switch(v)
{

case "+":
c=a+b;
break;

RI-TECH Url: www.ritechpune.com Page No: - 93


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
case "-":
c=a-b;
break;
case "*":
c=a*b;
break;
case "/":
c=a/b;
break;
}
document.frm.res.value=c;
}
</script>
</head>
<body>
<form name="frm">
First No: <input type=text name="fn"> <br>
Second No:<input type=text name="sn"> <br>
Select Operator :
<select name="op">
<option value="+"> + </option>
<option value="-"> - </option>
<option value="*"> *</option>
<option value="/"> / </option>
</select>
<br>
<input type="text" name="res"> <br>
<input type="button" value="click" onclick="opr()"> <br>
</body>
</html>

RI-TECH Url: www.ritechpune.com Page No: - 94


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------

SQL Server

RI-TECH Url: www.ritechpune.com Page No: - 95


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
SQL Server:-
Microsoft SQL Server is RDBM (Relational Database Management System) which allow you
to create the databases and manipulate the data from databases. Hence we first have to
understand DBMS and RDBMS then we can have the insight into SQL Server.

DBMS: -
A database management system (DBMS) is a software package with computer programs
that control the creation, maintenance, and use of a database. It allows organizations to
conveniently develop databases for various applications by database administrators (DBAs)
and other specialists. A database is an integrated collection of data records, files, and other
objects. A DBMS allows different user application programs to concurrently access the same
database. DBMSs may use a variety of database models, such as the relational model or
object model, to conveniently describe and support applications. It typically supports query
languages, which are in fact high-level programming languages, dedicated database
languages that considerably simplify writing database application programs.

DBMS maintains data only in tabular format; it was having some draw backs so computer
scientist had developed RDBMS Software.

RDBMS:-
RDBMS stands for Relational Database Management System. RDBMS data is structured in
database tables, fields and records. Each RDBMS table consists of database table rows.
Each database table row consists of one or more database table fields.

RDBMS store the data into collection of tables, which might be related by common fields
(database table columns). RDBMS also provide relational operators to manipulate the data
stored into the database tables. Most RDBMS use SQL as database query language.

Edgar Codd introduced the relational database model. Many modern DBMS do not conform
to the Codd’s definition of a RDBMS, but nonetheless they are still considered to be
RDBMS.

The most popular RDBMS are MS SQL Server, DB2, Oracle and MySQL
Every RDBMS has following two important features –
 Every RDBMS supports a Database Independent Programming Language, which allows you
to manipulate the data by writing commands.
 Every RDBMS stores data only in the form table, everything that exits in RDBMS will be in
the form of table.

SQL SERVER 2005/2008:-


SQL Server 2005, Microsoft's next-generation data management and analysis solution,
represents a huge leap forward. It comes with a myriad of changes that deliver increased
security, scalability, and power--making it the complete data package. Used properly, SQL
Server 2005 can help organizations of all sizes meet their data challenges head on.

RI-TECH Url: www.ritechpune.com Page No: - 96


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------

MS SQL Server Security Basics:-


To access the SQL MS Server you should know the name of the server, user id and
password.

SQL: - (Structured Query Language)


SQL stands for ‘Structured Query Language,’ which is an ANSI compliant language for
accessing and manipulating database systems. Well, it’s MOSTLY standard across different
proprietary DB systems like MS SQL Server, Oracle, My SQL, etc – but each company likes
to write its own quirks and general wackiness into each of their database platforms. So a
query written in SQL Server will not always work out-of-the-box on an Oracle Server unless
you mess with the query a bit.

TSQL: - (Structured Query Language)


Transact SQL is query language which comes with SQL Server, using which you can
manipulate the data from databases. Basically it is divided into following sections –

DDL: - data definition language provides you commands, and queries using which you can
create the structure of database or db.
DCL: - data control language provides you command using which you can control inflow and
outflow of the data from database.
DML: - data manipulation language provides you command using which you can
manipulate the data from database.

DDL: -
Data Definition Language, which provides us following, set of statements. DDL gives
you Create, Alter and Drop statements can be used to create, modify and remove database
objects as follows –
Create Table: - this statement is used to create the table, can be used as follows –

Create table tablename (fieldname data type (Size), fieldname datatype (Size),
fieldname datatype (Size) ….)

In case of Sql we can use following data types –


Numeric: - int, bigint, small int, tiny int, bit, numeric, decimal
Text and Char: - char, varchar, text, nchar, nvarchar, ntext (where n means support for
Unicode characters).
Other: - DateTime, Money, Binary, Image etc.

Identity: - this is facility provided by SQL server using which you can generate the
automatic numbers where first value indicates seed and next value indicates the
increment(e.g. identity(seed, increment).

RI-TECH Url: www.ritechpune.com Page No: - 97


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
e. g. to create emptbl with coloumns for ID, Name, Address, Phone with join date we
can use following create query –

Create table emptbl (empid bigint identity(1,1),empname varchar(30),address


varchar(100),phone varchar(10));

Alter Table: - this statement is used for following purposes –


To add new column:-

To drop existing column:-

ALTER TABLE table_name ADD column_name Datatype (size) constraints;

e. g. to add test column in empttbl we use the following commands –


alter table emptbl add test bigint;

To modify the exiting column:-


ALTER TABLE table_name ALTER COLUMN column_name Datatype(size) ;

To delete exiting column from table:-


ALTER TABLE table_name DROP COLUMN column_name;

Drop Statement: - this statement is used to remove the table as follows –

Drop table talename;

DML: -

It provides you following set of statements where used to manipulate the data –
Select: - this statement is used to fetch the data from the databases. It can be used as
follows –
Select [top n] * /field names from table name where condition order by field name1, field
name2 group by fieldname1, fieldname2 having condition.

Simple select:-
Select * from tablename;

This will select all the records and all columns from the specified table.
e. g. select * from emptbl

Column Filter:-
You can apply the column filter, to the selected data from the column as-
Select column_name1, column_name2 … from table_name.

RI-TECH Url: www.ritechpune.com Page No: - 98


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------

e. g. select emp_no,emp_name from emptbl

Top clause: - T SQL provides you top clause, using which you can select the specified
number of top records from the database, it can be used as follows –

Select top n from table_name;

e. g.
Select top 3 from table_name;

This will select top 3 records from the specified table.

Condition: - conditions are generally used to filter the rows. In case of T SQL we can use
the conditions with where clause we can use the relational operators (>, <=, >=,!=, ==, >), we
can also use the logical operators (and , or , not), beside this the TSQL provide us following
operators for conditions –
Like: - is used to find the pattern of strings.
And between: - is used to find the value between the specified range.
Not in: - check the existence of the specified value in given list of data.
In: - check the existence of the specified value in given list of data.

Exists: -
This is used with inner queries, to find out the existence of the record in database.
e. g.
select * from empttbl where emp_salary >1000.

This will select all information of employee whose salary is greater than 1000.
select * from empttbl where emp_salary between 1000 and 10000.

This will select all the information of employee whose salary is in the range >=1000 and
<=10000.

Select * from emptbl where emp_name like ‘R%’

This will select all information of employee whose name starts with R and contains any
number of characters.

Select * from emptbl where emp_name in (‘Pune’,’Mumbai’,’Delhi’)


This will select information of all employees leaving in pune, Mumbai and delhi.

RI-TECH Url: www.ritechpune.com Page No: - 99


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Order by: - is used to sort the data according to specified field in ascending or descending
order, you can use the keywords ASC,DESC.

e. g. select * from emptbl order by emp_name

This will display the employee information in ascending order emp_name.

Group by: - is used to group the data selected using select so that we can apply the
aggregate functions to find the summary of the data. We can use the following aggregate
functions as follows –
Avg: - average is used for finding the average of the data.
Sum: - to find the sum of data
Count: - to count the number of records.
Min: - to find the minimum
Max: - to find the maximum

e. g. select city_name,sum(salary) from empttbl group by city_name

This will display all the cities and total salary paid to employee from that city.

Insert Statement: - Insert statement is used to add the new data in database table. It can
be used as follows -
Insert into tablename( List of fields) values(List of values).

Here list of fields, will be optional if you want to insert all the values.

e.g. to insert all values in emptbl


insert into emptbl values(1,’Ramesh’,’Pune’,12000);
or
insert into
emptbl(emp_no,emp_name,emp_city,emp_salary)values(2,’Rajesh’,’mumbai’,14000);
If I just want to insert emp_no and emp_name in database I can use the query.
insert into emptbl(emp_no,emp_name) values(1,’Ravi’);

Update Statement: - update is DML statement used to update the data from the database.
It is used as follows –

Update tablename set fieldname=value,fieldname=value,fieldname=value … where


condition.

Inner Queries/Nested Query: -


Query inside query is called as nested or inner query. Some times when data present into
more than one table and you need to result of one query into another query where you have
to use the queries called inner queries. In case of inner queries inner query will be executed

RI-TECH Url: www.ritechpune.com Page No: - 100


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
first and then outer query, inner query should be always the part of outer query used in
where clause. When you use the inner query you have to take care of the operator and the
return values of the inner queries, since inner queries are the part of where clause and if
inner query returns some value or values the operator used in where clause should be
compatible with inner query return values.
If inner query returns single value then operator used in outer query should be capable to
compare the single value otherwise the operator used should be capable to compare more
than one value.

e. g.
Consider following structure –

Table Name: AreaTbl


Column Names:-
AreaID
AreaName

Table Name: EmpTbl


Column Names:-
EmpID
EmpName
EmpAddress
EmpSalary
EmpPhone
AreaID
Suppose now you want to find out the information of employees leaving in area
nigdi you have to fire the query –

Select * from emptbl where areaid = (select Areaid from araetbl where
areaname=’nigdi’)

This query will first find the areaid of the nigid and then it will find out the
employee details.

Suppose now you want to find out the information of employees leaving in area
nigdi, pimpri, pune then you can not use the equal to operator in inner query.
Query can be created and used as follows –

Select * from emptbl where araeid in (select areaid from areatbl where areaname
in(‘nigdi’,’pimpri’,’pune’);

DCL: -
DCL is used to control the inflow and outflow of the data. It also defines the accessibility of
the data. Basically here we apply the constraints, or we define the permissions to the users.

RI-TECH Url: www.ritechpune.com Page No: - 101


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Constrains: -
Constraints are the rules that we can enforce on tables, some of them are –
1. Primary key: -
You can enforce the primary key to such table field which you want to use to uniquely
identify the records. Primary key constraints will not allow you to have duplicate values in
the specified field.

create table coursetbl(courseid bigint primary key,coursename


varchar(30),duration bigint,fees numeric(10,2))

2. Foreign key: -
This constraints forces referential integrity ( i.e. when you define the foreign key constraint
it will take values from only specified column which should be created using primary key
constraints), it can take duplicate values.

Create table coursesubjecttbl(coursesubjectid bigint primary key,subjectname


varchar(30),courseid bigint references coursetbl(courseid))

3. null and not null: -


You can use this if you want to allow the null value in the specified field, by default every
field is null. Not null is used if you do not want to allow null value in the specified field.
Create table student (sid bigint primary key, sname varchar (30), address
varchar(30) null)

create table student(sid bigint primary key,sname varchar(30),address varchar(30)


not null)

5. Unique: -
This will allow forcing the column value to be unique.
create table student(sid bigint primary key,sname varchar(30) unique, address
varchar(30))

6. check: -
This constraint allows you to specify any condition that will be checked for specified field
value.

Create table item(itemid bigint primary key,itemname varchar(30) unique,


itemprice bigint check(itemprice >0 and itemprice<200))

You can also use the alter statement to alter the constraints those can be used as follows -

alter table coursetbl add constraint ad unique(coursename)


alter table coursetbl drop constraint ad
alter table coursetbl add constraint dconst check(duration > 0)

RI-TECH Url: www.ritechpune.com Page No: - 102


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Solved Assignments:-
1. Assume following table.
CustomerTbl
> CustomerID
> CustomerName
> AreaName
> CreditLimitAmount
> Address
> Phone

Q1. Display total number of customers


Ans: select count(*) from customertbl
Q2. Display areaname and total number of customers
Ans: select areaname,count(customerid) from customertbl group by areaname
Q3. Display areaname and total creadit given to customer in that area.
Ans: select areaname,sum(creditlimit) from customertbl group by areaname
Q4. Display name of customer having maximum creditlimit
Ans: select customername from customertbl where creditlimit = (select
max(creditlimit) from customertbl)

2. Assume following table structure –

CityTbl AreaTbl
CityId AreaID
CityName AreName
CityID
DeptTbl Employee
DeptID EmployeeID
DeptName EmployeeName
AreaID DeptId
Address
Phone
Salary

Q1. Display names of all employees working in nigdi area.


Asn:
Select * from employee where deptid in (select deptid from depttbl where areaid in
(select areaid from areatbl where areaname=’nigdi’))

RI-TECH Url: www.ritechpune.com Page No: - 103


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Q2. Display all employees working pune city.
Ans: -
select * from employee where deptid in (select deptid from depttbl where areaid in
(select areaid from areatbl where cityid=(select cityid from citytbl where
cityname='Pune'))

Q3. Display all employees working in computer department and pune city.
Asn:-
select * from employee where deptid in (select deptid from depttbl where areaid in
(select areaid from areatbl where cityid=(select cityid from citytbl where
cityname='Pune'))
and deptid =(select deptid from depttbl where deptname='Computer')

Q4. Update salary of all employees by 10% working computer department from
city mumbai.
Ans:
upate employee set salary=saalry + salary*0.1 where deptid in (select deptid from
depttbl where areaid in (select areaid from areatbl where cityid=(select cityid from
citytbl where cityname='Mumbai'))
and deptid =(select deptid from depttbl where deptname='Computer')

Q5. Find out cityname , total salary paid in that city.


> find out number of employees working in computer department
select count(empid) from employee where deptid=(select deptid from depttbl where
deptname='Computer')

SQL Server Joins: -


If you want to fetch the data from more than one table at that time we have to use the
joins, when you want to create the joins there should be a common field between tables in
which we want to create the join

SQL Server supports following joins -

1. Inner Join: -
This join allow you to fetch data from more than one table if the matching data present
into both the tables on join field. To create the inner join we use the following syntax -

select fieldnames,fieldnames ... from firsttbale inner join second table on


firsttable.commfield=secondtbl.commonfield

select Atbl.*,BTbl.* from Atbl inner join BTbl on atbl.aid=btbl.aid

Inner join between three tables:

RI-TECH Url: www.ritechpune.com Page No: - 104


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
e. g.
select atbl.*,btbl.*,ctbl.* from (atbl inner join btbl on atbl.aid=btbl.aid) inner join
ctbl on atbl.aid=ctbl.aid

Outer join:-
Outer joins are used when you want to get the dat from both the tables. Outer join is
classified into following types of joins –

Left Outer Join: -


Left outer join when used with more than one tale, it will fetch all records from left table
and all matching records from right table, if there is no match in right table, it will return
you null.

e. g.
select atbl.*,btbl.* from atbl left outer join btbl on atbl.aid=btbl.aid
It will fetch all records from atbl and only matching records from btbl.

Right Outer Join: -


Right outer join is used if you want to fetch all records from right table and matching
records from left table if there is no match then it returns you null.
e. g.
select atbl.*,btbl.* from atbl right outer join btbl on atbl.aid=btbl.aid

It will fetch all records from btbl and matching records from atbl.

Full Outer Join: -


Full Outer join when used between two tables , it will fetch all records from both the tables,
if there is no match in right table or left table then it will return you null, Otherwise it will
get you matching records.

e.g.
select atbl.*,btbl.* from atbl full outer join btbl on atbl.aid=btbl.aid

It will fetch all records from atbl as well as btbl and replace remaining by null if there is no
match.

Cross Join: -
When you implement the Cross Join
It will preform the cross product of the records , in case of cross join we does not require on
clause
e.g.

RI-TECH Url: www.ritechpune.com Page No: - 105


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
select atbl.*,btbl.* from atbl cross join btbl

It fetch all records for the single record of atbl from btbl.
Self Join:-
We create join in same table on same field or diff field. Self join can be inner join/left outer
join/right outer join/full outer join but it should be on same table (only on table involved in
join), here you have to use the alias since same table name cannot be used on both the side
in on clause.
e.g.
select A.* from btbl as A inner join btbl as B on A.aid =B.aid

Join Examples:-
T-SQL Inner Join example:

SELECT orders.orderdate, products.orderid, products.productsku


FROM Products
INNER JOIN Orders on products.orderid=orders.orderid
ORDER BY ProductSKU ASC;

We have two tables: Orders and Products. The Orders table has the column orderdate and
we want to see the date each productsku is ordered on. The way to do this is INNER JOIN
with the Products table. Now will will see the date that each productsku was ordered on.

T-SQL Left Join example:

Select products.sku, oldproducts.sku


from products
Left Join oldproducts on products.sku=oldproducts.sku
ORDER BY ProductSKU ASC;

We have two tables: Products and OldProducts. We want to see all the oldproducts.sku that
are in the products table. A LEFT JOIN will shows every products.sku and all the matching
oldproducts.sku

T-SQL Right Join example:

Select products.sku, oldproducts.sku


from products
Right Join oldproducts on products.sku=oldproducts.sku
ORDER BY ProductSKU ASC;

We have two tables: Products and OldProducts. The RIGHT JOIN in the example will show
us every oldproducts.sku and any products.sku that match.

RI-TECH Url: www.ritechpune.com Page No: - 106


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------

SQL Server and PLSQL:-


PL/SQL stands for Procedural Language extension of SQL.
PL/SQL is a combination of SQL along with the procedural features of programming
languages. It is being develop to provide the programming enhancements and capabilities to
SQL.

PL/SQL is a small set of programming constructs using which you can write the programs
which are suppose to manipulate the data from databases. In case of SQL server to write
the pl/sql block we use keywords -

Begin
SQL Statements or PL SQL Code.
End

Variables: - in TPLSQL we can have two types of variables -


User Defined Variables: -
These are the variables created by the user, can be created using syntax –

declare @variablesname data types

where you can use all SQL server data types.


set Keyword:- set keyword is used to write the value in the variable. We can not assign the
value to variable directly, we have to use the set keyword.
e. g. set @num=12

Built in Variables: -
These variables are being provided by the SQL server we can write the value in them, but
we can read the value. All built in variables will starts with @@ symbol.
e.g. declare @num int

Output Statement: -
Plsql provides us the statment print using which you can output string or varchar type of
data can be used as follows -
print 'Message'
Convert:
Convert function allow you to convert from one data type to another data type can be used
as follows -
convert(datatype,value)
It will convert the specified value to specified data type.

e. g. Write a program to do addition of two numbers using pls sql –


Begin
declare @num1 int

RI-TECH Url: www.ritechpune.com Page No: - 107


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
declare @num2 int
declare @res int
set @num1=23
set @num2=45
set @res=@num1 + @num2
print 'Addition is :' + Convert(varchar,@res)
END

Conditional Statements:-
Imposes conditions on the execution of a Transact-SQL statement. The Transact-SQL
statement that follows an IF keyword and its condition is executed if the condition is
satisfied: the Boolean expression returns TRUE. The optional ELSE keyword introduces
another Transact-SQL statement that is executed when the IF condition is not satisfied: the
Boolean expression returns FALSE.

Only if:-
IF Boolean_expression
Begin
Statements
End

Will handle only true part of the condition, begin and end is needed only if there is more
than one statement.

If and Else:-
IF Boolean_expression
Begin
sql_statement | statement_block
End
ELSE
Begin
sql_statement | statement_block
End

e. g. Even number program using if and else.


begin
declare @num int
set @num=26
if(@num % 2 =0)
begin
print 'Even Number'
end
else
begin

RI-TECH Url: www.ritechpune.com Page No: - 108


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
print 'Odd number'
end
end

Looping :-
PLSQL provides you the while loop using which we can perform the repeat.
It can be used as follows -
while(condition)
Begin
Statements
End
With while you can use breaks and continues statement to break and continue the loop.

e. g. Addition digits of given number.


Begin
Declare @num int
Declare @dig int
Declare @sum int
Set @sum=0
Set @num=2222
while(@num <> 0)
Begin
set @dig= @num % 10
set @sum =@sum + @dig
set @num=@num/10
End
print 'Addition of Digits:' + convert(varchar,@sum)
End

e. g. while loop example


Assume following table –
Table Name: Employee
> ID
>Name
> Salary
>Start_date
>City
>Region

Program:-
DECLARE @Counter Int
SET @Counter = 1
WHILE @Counter < 4

RI-TECH Url: www.ritechpune.com Page No: - 109


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
BEGIN
PRINT 'Loop'
PRINT 'SubCategory'+ CONVERT(VarChar(10), @Counter) + ':'
SELECT Name, ID, Salary FROM Employee WHERE ID = @Counter
SET @Counter = @Counter + 1
END

Fetching the table data in variables:-


In certain situation you need to fetch the values of the columns into variables of pl sql block
for some kind of processing, for that we need into statement can be used as follows –
specifying variablename=fieldname in select list.

e.g. fetching value into variable example.


Assume table:-
CustTbl
 Cust_ID
 Cust_Name
 Cust_Address
 Cust_Phone

Begin
Declare @nm varchar(30)
Declare @ad varchar(30)
select @nm=cust_name,@ad=cust_address from custtbl where cust_id=2
print 'Customer Name :' + @nm
print 'Customer Address : ' + @ad
End

User Define Functions can be created using following syntax -


Create Function FunctionName(paramters) returns return data type
as
Begin
Statements
End

PLSQL fuction can return only one value.

e. g. PL SQL functions to add two numbers.


Function Declaration -
Create function AddNum(@a as int,@b as int) returns int
as
Begin

RI-TECH Url: www.ritechpune.com Page No: - 110


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
return @a+@b
End

Calling Function -
Begin
Declare @c int
set @c=dbo.addnum(12,23)
print 'Value is' + convert(varchar,@c)
End

e.g. Function to find student name using rollno.


Declaration:-
alter function getroll(@r as int)returns varchar(30)
as
begin
declare @nm varchar(30)
select @nm=sname from student where sno=@r
return @nm
end

Calling:-
begin
declare @sn varchar(30)
set @sn=dbo.getroll(4)
print 'Student Name' + convert(varchar,@sn)
end

Stored Procedures in T PL SQL: -


These are the precompiled code block, stored in a database as object, which can be used
again and again.

-> Self executable code block (can be called from font end application)
-> Stored as a database object in database.
-> Compiled once and executed again and again.
-> Maintains internal transaction.
To create the stored procedure we use the following syntax –
Create procedure procedurename(parameters)
as
Begin
Statements
End
Where parameters can be three types –
In: - it is default type, means when do not specify any parameter type, it will be by default
in used for getting the value of parameter inside the procedure.

RI-TECH Url: www.ritechpune.com Page No: - 111


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Out: - it is used for generating value from stored procedure indirectly we can say stored
procedure can return multiple values using multiple out type of parameters.
To execute the stored procedure we use the execute command with procedure name and
while sending the parameters we do not use ().
e. g. Create Procedure to add two numbers.
Asn:- Create proc procaddnum(@a as int,@b as int)
as
Begin
print 'Addition is ' + convert(varchar,(@a+@b))
End
Exec procaddnum 12,23

e.g.
create proc procsq(@num as int,@sq as int out)
as
begin
set @sq= @num * @num
end

begin
declare @s int
exec procsq 12,@s out
print 'Squre is:' + convert(varchar,@s)
end

e.g.
Create proc incnum(@n as int out)
as
Begin
set @n=@n + 10
End

Begin
Declare @v int
set @v=12
exec incnum @v out
print 'Value is' + convert(varchar,@v)
end
e.g.
Create procedure which accept the employeeid and display the total salary of that
employee.
Create procedure which will display the employeenames and total salary from
specified department
alter proc procacc(@empid as int)

RI-TECH Url: www.ritechpune.com Page No: - 112


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]
RI-TECH
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
as
begin
declare @empn varchar(30)
declare @bs as bigint
declare @hr as bigint
declare @t1 as bigint
declare @d1 as bigint
declare @de as bigint
declare @gros as bigint
select @empn=emp_name,@bs=Basic_sal,@hr=hra,@t1=ta,@d1=da,@de=deduc from
emptbl inner join empsaltbl on
emptbl.emp_id=empsaltbl.emp_id where
emptbl.emp_id=@empid set @gros = (@bs+@hr+@t1+@d1)-@de
print 'empname'+ @empn + 'grosssal'+ convert(varchar,@gros)
end
Begin
exec procacc 1
End

e.g.
alter proc dept(@depnm as varchar(30))
as
begin
declare @empn varchar(30)
declare @bs as bigint
declare @hr as bigint
declare @t1 as bigint
declare @d1 as bigint
declare @de as bigint
declare @gros as bigint
declare @deptname as bigint
select
@empn=emp_name,@bs=Basic_sal,@hr=hra,@t1=ta,@d1=da,@de=d
educ
from emptbl inner join empsaltbl
on emptbl.emp_id=empsaltbl.emp_id where emptbl.dept_id=(select dept_id from
depttbl where dept_name=@depnm)
set @gros = (@bs+@hr+@t1+@d1)-@de
print 'empname: '+ @empn + ' grosssal:'+
convert(varchar,@gros)+' deptname=>'+@deptname
end

RI-TECH Url: www.ritechpune.com Page No: - 113


Tuljai Classic, Main Road, Akurdi – Pune -35 Mobile: 9762059130 , 02027240087 [email protected]

You might also like