You are on page 1of 72

Aprash Technologies

+91-9953904262

Net stands for Network Enabled Technologies.


It is a system, which can be used for developing applications of various types like Console,
Windows, Web Apps and Mobiles Applications.

.Net Contains Three major things:

1. Languages: -- c-sharp, V.B etc.


2. Technologies:--Ado.Net, Asp .Net etc.
3. Servers: -- Web Servers, Database Servers etc.

Why .Net Introduce?

It was introduced for two major reasons:


1. To overcome the drawbacks in its own traditional technology i.e. (Component Object Model)
which is used for developing apps?
2. To compete Java language.

.Net:- It is a collection of languages where a programmer can choose a language as per his
requirements.
Any .Net language compiled with an appropriate language compiler will generate the same type of
Intermediate language (IL) code, which is Platform Independent.

Compilation and Execution Process

C-# .Net ---->CSC -----> CIL ------>CLR ------->Machine Code


V.B. Net ---->VBC------> CIL ------>CLR ------>Machine Code

CSC: - C Sharp Compiler


VBC: - VB Compiler

CIL:-Common Intermediate language.


CLR:-Common language Runtime

Note:
The CIL code can be executed on any Machine provided the CLR is Available for thr Machine,
which will take the responsibility of converting IL Code to Machine Code.

Language Interoperability:
C#.Net -----> CSC ---CIL ---Reverse in Any .Net Language.
The Advantage of all languages generating same type of I.L Code is called Language
Interoperability. i.e. the IL Code generated from in any .Net Language can be Re-Used from the
Others remaining .Net languages

Any .Net Language -----Compile------CIL Code------Reuse in Any .Net Language

MailId:ashvin.kumar01@gmail.com 1
Aprash Technologies
+91-9953904262

Features of 2.0 versions

1. Partial classes, which allows class implementation across more than one source files.
2. Generic and Parameterized type.
3. Static classes cannot be Instantiated.
4. The accessibility of property assessors can be se independently.
5. Nullable value types, which provide improved interaction with SQL Server.
6. Coalesse operator (??), which returns the first of its operands that, is not null or null if no
such operands exist.
7. Anonymous Delegates.

Features of 3.0 versions

1. LINQ
2. Object Initializes and collections
3. Implicit Type Array
4. Lambda Expressions
5. Automatic properties
6. Partial methods

Goals of C-Sharp language

1. It is intended to be simple, modern, Genarl purpose and oops language.


2. Language should include strong type checking array bound checking; detection of attempts,
to use UN initialized variables, source code portability and Automatic Memory management
by Garbage Collection.
3. The language is intended for use in developing software components that can take advantage
of Distributor Environment. (Sql)
4. Programmer portability is very important for those programmers already familiar with c, c++
than c –Sharp.
5. It is intended to be suitable for writing applications to both Hosted and Embedded Systems.

Data types can be classified in two ways.

Value type:
1. It store data in stack form.
2. It is a place where data stores in affixed length such as int, float ,
3. Every program has its own stack no other program can share its.
4. It allocate at the time of program execution.
5. Stack works as a principal LIFO and it was under control of operating systems, which
doesn’t support dynamic memory allocation and destruction

Reference type:
1. It stores references in a heaped form. In .net heap is now more managed and is called
managed heaped.

MailId:ashvin.kumar01@gmail.com 2
Aprash Technologies
+91-9953904262
2. When an application is created, the first reference type memory allocated for the type at the
base address of managed heaped.

3. When the application is created the next object then the garbage collector allocates the
memory for it in the address space immediately following the first object.As soon as address
is available the garbage collector continues to allocate space for new object in this manner.

Note must read: string and object type only comes under the category of reference type

String str=null;
Int x=null; ----------invalid

If u wants to store null values in data type, you can us nullable value types like.

Int? X=null ------------ valid


Float? X=null----------valid;

Nullable value type: - It was a new featured added from 2.0 version specification, which allows
storing null values in value type also (traditionally not possible) this provides improved interaction
while communicating with any databases.

Data types categories:


Integer:
Byte
Short
Int
Long
Sbyte
Ushort
Uint
Ulong

Decimal or Float:

Float ------------------------ 4 bytes


Double --------------------- 8 bytes
Decimal --------------------16 bytes

Boolean type:

Bool ----------true or false

MailId:ashvin.kumar01@gmail.com 3
Aprash Technologies
+91-9953904262
Character Type:
Char--------------------------2 byte
String------------------------variable length (depend on input text, dynamic)

Root type:

Object------------------------variable length (dynamic)


String type: It was not a fixed length type like int, float char, it was variable length, and it can change
according to number of characters assign.

Object type: It was a type, which can store anytype of value in it.its length, is also variable.

Implicit type Variables:


It was a featured added under 3.0 specifications, which allows declaring variable by using a var
Keyword. The type of the variable will be considered depending upon the value by assign to a
variable.

Example:
1. var x = 100---------------x as integer
2. var x= true----------------x as bool
3. var x; ---------------------Invalid.

Note Must Read:


To declare a variable using var keyword it is mandatory to assign a value to, it at the time of
declaration only.

Boxing and UnBoxing:

If a value type is stored on managed Heap in the form of a Reference, type is called as BOXING.
If at all, the Reference type is again being converted into value type as referred as UnBoxing.

Example:

Int x =100;

Object obj= x; ---------Boxing

int y = obj; ----------UnBoxing

Loops:

Foreach:
It was a special Loop designed for Processing of Array and Collections.

1. Arrays is a set of similar type values


2. Collection is a set of dissimilar type values.

Jump Statements:

MailId:ashvin.kumar01@gmail.com 4
Aprash Technologies
+91-9953904262
C-Sharp provides a number of statements that allow jumping immediately to another line in a
program;
1. Go to
2. Break
3. Continue
4. Return
Example:

using System;
class GoText
{
static void Main()
{
goto xx
Console.WriteLine (“hello “);
xx;
Console.WriteLine (“Go to statement called”);
}
}

Output:
Go to statement called.

Arrays:
1. Single Dimension
2. Two Dimension
3. Jagged Array

It is a set of similar type values, which were stored in a sequential order,


In C-Sharp – Arrays can be declared as a fixed length and Dynamic. Fixed
Length can store a pre-defined number of items while size of dynamic array increases as u added
new items to the Array.

Note:
1. Memory allocation to an array gets performed either with the use of new operator of
assigning of values to the Array.
2. Array were Reference type because they are not in fixed size, as we have a chance of
declaring and initializing later it gets the memory allocated on Managed Heap

Array Class:

It was a class under System Namespace, which provides a set of methods a set of methods, and
Properties (variables).

Which can be applied in an Array?


1. Sort
2. Copy(source, destination)
3. Reverse(arrayname)
4. Length

MailId:ashvin.kumar01@gmail.com 5
Aprash Technologies
+91-9953904262
Example:
using System:
class Arraycalss
{
static void Main(string[] args)
{
int[] arr ={ 5, 6, 8, 8, 3 };
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}

Console.WriteLine();

Array.Sort(arr);

foreach (int k in arr)


{
Console.WriteLine(k);
}
Console.WriteLine();

Array.Reverse(arr);

foreach (int k in arr)


{
Console.WriteLine(k);
}
Console.WriteLine();

int[] brr = new int[5];


brr = arr;

foreach (int k in brr)


{
Console.WriteLine(k);
}
Console.WriteLine();

int[] crr = new int[10];

Array.Copy(arr, crr, 5);

foreach (int k in crr)


{
Console.WriteLine(k);
}
Console.WriteLine();
}
}

MailId:ashvin.kumar01@gmail.com 6
Aprash Technologies
+91-9953904262

Jagged Array:

It is same as Two-D array but in Two-D array , the number of columns to each row should be fixed,
whereas In case of Jagged Array each row can have varying number of columns , it is also as Array
of Arrays because Multiple single dimensional array were combined together to form a New Array
i.e. Jagged Array.
Pointing to each row of the array we need to specify the number of columns to row.

Syntax:
dataType [][] arrayname=new dataType [no of rows] [ ];

using System;
class Program
{
static void Main(string[] args)
{
int[][] array = new int[3][];
array[0] = new int[4];
array[1] = new int[5];
array[2] = new int[2];

//Input From User


for (int i = 0; i < 3; i++)
{
for (int j = 0; j < array[i].Length; j++)
{
array[i][j] = int.Parse(Console.ReadLine());
}
}

//display by for loop

for (int i = 0; i < 3; i++)


{
foreach (int k in array[i])
{
Console.Write(k + " ");
}
Console.WriteLine();
}
}
}

Static values assigned to a Jagged Array:


int [] [] array = {
new int [4] {2, 3, 4,5},
new int [4] {4, 5},
new int [4] {6.9, 6},
};

MailId:ashvin.kumar01@gmail.com 7
Aprash Technologies
+91-9953904262
Supplying Command inputs to a Program

We can supply input to a program, which can be captured into the program in two ways:
1. using Redline () of Console Class.
2. using Command line Parameters.

In case of second way while executing the program from command prompt we can supplied a list of
values separated with a white space.

Note:
To captured the values supplied to the Program we can makes use of string array Parameter in main
method, i.e. all the values provided will directly sit

Under the string array of Main ().

Example: File Name: example.cs

using System;

class Program
{
static void Main(string[] args)
{
Console.ReadLine();
foreach (string str in args)
{

Console.WriteLine(str);
}
}
}

Compile : csc example.cs


Run : example 67 78 90 Aprash [press Enter]

Output:
67
78
90
Aprash

MailId:ashvin.kumar01@gmail.com 8
Aprash Technologies
+91-9953904262
Object Oriented Programming

Traditionally we were using procedural programming, which lacks of features like security and
Reusability.
To provide the security and Reusability a new approached in programming has been introduced
known as OOPs.

Object oriented programming is a set of rules that has to be satisfied by languages to be called as
Object Oriented those are:
1. Encapsulation
2. Abstraction
3. Polymorphism
4. Inheritance

Encapsulation:
It prescribes the code under object oriented under an Object Oriented Programming has to be
enclosed under a wrapper or container known as class. Which provides basic securities for your
code?

Abstraction:
A talks about Hiding of complexity and provide with a set of Interfaces to consume the
Functionality.

Polymorphism:
Entity is behaving in different ways depending upon the input, the receive is known as
Polymorphism.
this. Load += new Evanthandler (Test);

Inheritance:
It talks about acquiring the properties of a class into another class by establishing the Parent – Child
relationships that provides Reusability of the Code.

Method: A method or a Sub Program was a block of code, which can be Reuse by calling it.

Syntax :[< Modifiers> void/ type Name ([Parameters])


{ <Statements> }

1. In C, language “void” is Type like data Type.


2. In C Sharp “void” is Keyword.
3. Modifiers were optional which can be like public private etc.
4. “Void” or type tells whether the method is returning a value or not.
5. Parameters definitions were the parameters wants to pass to the method(Optional), which
can be done as following
[Ref]<Type><variable> […………n];

1. After defining a method in a class, they need to be called explicitly for execution.
2. To call method defined under a class should be explicitly create the object of class.

MailId:ashvin.kumar01@gmail.com 9
Aprash Technologies
+91-9953904262
Syntax : <class> <object>=new <class> ([<list of values>])
Example: Class1 c1=new Class1 ();

Object of the class is created only with the use of new operator under Java and .Net Languages.
We can create the object of a class anywhere under a class as well as can be created in other classes
also, but generally it is created under Main () method of the class because it was the entry point of
the class.

Abstract Class:
An abstract class is not useful to itself because its object cannot be created, its child classes can only
consume it after implementing the abstract methods of Parent class.

Example:
using System;
abstract class Program
{
public void Add(int x, int y)
{
Console.WriteLine("Result is "+x+y);
}
public abstract void Multiply(int x, int y);

}
class child :Program
{
public override void Multiply(int x, int y)
{
Console.WriteLine("Multiplication " + (x * y));
}

static void Main(string[] args)


{
child ch1 = new child();
ch1.Add(10, 90);
ch1.Multiply(10, 80);

Console.ReadLine();
}
}
Note: Under the child Class, we can create the reference of parent class by using child class object.
Using the Reference u can call all the abstract and Non-abstract members of parent. To check this
rewrite the following code under the Main () method of child class.

static void Main(string[] args)


{ child ch1 = new child();
Program prg = ch1;
prg.Add(10, 40);
prg.Multiply(10, 90);

MailId:ashvin.kumar01@gmail.com 10
Aprash Technologies
+91-9953904262
}
Figure Class

Public double height, width,


radius;
Public abstract void Get Area ()

Public override Public override Public override


double Get Area () double Get Area () double Get Area ()
{ { {
return height * return 0.5*radius return ½ *height *
width *radius width
} } }

Rectangle class Circle Class Triangle Class

In the above case the abstract class Figure provide the attributes that are common for all the and
imposes restrictions on the child classes to implement the abstract methods as per there requirements
without changing their signatures.

Example:-Under Same Project


1. Figure.cs

abstract class Figure


{

public double width,height,radius;

public abstract double GetArea();

2.Add New Class naming as Rectangle.cs


class Rectangle:Figure
{
public Rectangle(double height, double width)
{
this.height = height;
this.width = width;
}

public override double GetArea()


{
return height * width;

MailId:ashvin.kumar01@gmail.com 11
Aprash Technologies
+91-9953904262

}
}

3.Add new Class naming as Circle.cs

class Circle:Figure
{
public Circle(double radius)
{
this.radius = radius;

}
public override double GetArea()
{
return 3.14 * radius * radius;
}
}

4.Add new Class naming as Test.cs

class Test
{
static void Main()
{
Rectangle rect = new Rectangle(10, 20);
Circle cir = new Circle(20);
Console.WriteLine("Rectangle : "+rect.GetArea());
Console.WriteLine("Circle : "+cir.GetArea());
Console.ReadLine();
}
}

Note :
1. Run The Test.cs Class .
2. Right click on project name from solution explorer
3. Select properties option
4. Select the test class from startup object dropdown
5. Press F5 or ctrl +f5.

Note:

Non-Abstract Class : Only Non-Abstract Members [Assets]


Abstract Class : Abstract + Non - Abstract Members [Assets + Liabilities]
Interfaces : Only Abstract members [Liabilities]

MailId:ashvin.kumar01@gmail.com 12
Aprash Technologies
+91-9953904262

Interfaces:
It is type or container in Object Oriented Programming, which can be defined only with Abstract
Members. Advantage of these Interfaces i.e. they supports Multiple Inheritance. A class can have
more than one Interface as its immediate parent.

Inheritance can be categorized as Implementation Inheritance and Interface Inheritance

The Inheritance what we get through Classes is known as Implementation Inheritance this is always
Single. Where as Inheritance what we are using through Interface is known as Interface Inheritance
that was Multiple.

Class Set of Interfaces

Single Multiple

Class

Syntax:

[<Modifiers>] interface <name>


{
Abstract members Declaration
}

1. An Interface cannot be declared with variables in its.


2. Every members of an Interface by default public but incase of class it was private.
3. Every member of an Interface by default abstract.

As a class can inherit from another class and interface can inherit from an Interface.
Note:

Class Interface Interface Class

Class Class Interface Interface

1 2 3 4

MailId:ashvin.kumar01@gmail.com 13
Aprash Technologies
+91-9953904262
Above one, two and three case is possible but four case is not possible because u cannot define class
members in an Interface. Interface contains only member declarations.

Example:
1. Add an interface in Project from Project Menu  Add new item select Interface naming
as Inter1.cs and write the cod following

interface Inter1
{
void Add(int x, int y);
void Test();
}
2. Add another interface in Project from Project Menu  Add new item select Interface
naming as Inter2.cs and write the cod following

interface Inter2
{
void Sub(int x, int y);
void Test();
}

If a class was made parent of another class we call it as inheriting from a class where as if
an Interface is made as Parent to a class we call it as implementing as Interface because all
the abstract methods of the interface should be implemented under the class. The implement
method of both the Interfaces in Interclass.cs

3. Add a New Class in Project from Project Menu  Add new item select class naming as
Interclass’s and write the cod following

class InterClass:Inter1,Inter2
{
public void Add(int x, int y)
{
Console.WriteLine("Result of Add " + (x + y));
}

void Inter1.Test()
{
Console.WriteLine("Inte1 Method");

void Inter2.Test()
{
Console.WriteLine("Inte2 Method");

MailId:ashvin.kumar01@gmail.com 14
Aprash Technologies
+91-9953904262
}
public void Sub(int x, int y)
{
Console.WriteLine("Result of Subtract " + (x - y));
}
static void Main(string[] args)
{

InterClass obj = new InterClass();


obj.Add(40,50);
obj.Sub(100,70);
Inter1 int1 = obj;
Inter2 int2 = obj;
int1.Test();
int2.Test();
}
}

Note:
When a Class was implementing multiple interfaces and if these interfaces defines the same method
while implementing that method under the class we can follow two approaches.

1. Implement the method only once under the class so that both interfaces assume that the method of
itself implemented.

Example:

public void Test()


{
Console.WriteLine("Test Method of Interfaces Implemented");
}

Note: In this case, the Method can be called by using the object of the class directly.

2. Implement the method for multiple times under the class prefixing with the interface name before
the method name.

Example:
InterClass obj = new InterClass();
Inter1 int1 = obj;
int1.Test();

Note: In this case, the methods can be called only by using the Reference of Interface in which the
method was declared.

Important Questions:

MailId:ashvin.kumar01@gmail.com 15
Aprash Technologies
+91-9953904262
1. Can we consume a class of a project from a class of same project?

Ans: “Yes”, we can consume them directly as both those classes were under the same project
was considered as Family.

2. Can we consume a class of a project from a class of another project?

Ans: “Yes”, we can consume but not directly, as they were under different projects first we
need to add the reference of assembly in which the class was present to the project who
wants to consume it.

 How to add the Reference of an assembly in a project?

Ans:
Right click on Project from Solution Explorer

Select Add Reference

Click on Browse Tab

Select Assembly from project folder/bin/debug/assembly file without any extension

Click Ok.

Note: Now we can consume classes of the assembly by referring with Namespace.

MailId:ashvin.kumar01@gmail.com 16
Aprash Technologies
+91-9953904262
Access Specifiers:

These are used to define the scope of type (class or interfaces or structures) or its members i.e. who
can access them and who cannot.

C- Sharp provides five types of Specifiers.

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

Note: Members defined under a class with any specifier or scopes were always accessible within a
class, restrictions appear only when we tried to access them outside of the class.

1. Private: - Members declared as private under a type (class) are not accessible outside of
the type (class).Default scope for members of the class are private only.
A type (Class) under a Namespace cannot be declared as private.

 How to restrict a class not to be accessible to any other class?


Ans: This can be done by declaring a constructor of a class as Private.

 How to restrict a class not to be inherited by any other class?


Ans: This can be done by declaring a Class as SEALED.

2. Protected: - Members declared as protected under a class can be accessed only from a
child Class, A Non-Child class cannot consume them.
A type (Class) under a Namespace cannot be declared as protected.

 Q2: How to restrict a class not to be accessible for any other class to consume by creating its
object?

Ans: This can be done by declaring the constructor of the Class as protected.

MailId:ashvin.kumar01@gmail.com 17
Aprash Technologies
+91-9953904262

3. Internal: - Members declared as internal under a type (Class) or accessible only within the
project from a child or Non-Child class. Default scope of a class is internal only.

4. Protected Internal: - Members declared as protected internal enjoying dual scope i.e. within
the project they behave as internal and provide access to all other classes outside the project
and still provide access to their child classes.

5. Public: - A type (Class) or members of type (class) are declared as public is Global and can
be accessed from anywhere.

Example:

Note: Make the Default Program class as public and write the following.

First Step:
using System;
namespace TestAccess
{
public class Program
{
private void Test1()
{
Console.WriteLine("Private Method Invoked");
}

internal void Test2()


{
Console.WriteLine("Internal Method Invoked");
}
protected void Test3()
{
Console.WriteLine("Protected Method Invoked");
}
protected internal void Test4()
{
Console.WriteLine("ProtectedInternal Method Invoked");
}

public void Test5()


{
Console.WriteLine("Public Method Invoked");
}

MailId:ashvin.kumar01@gmail.com 18
Aprash Technologies
+91-9953904262

static void Main(string[] args)


{
Program prg = new Program();
prg.Test1();
prg.Test2();
prg.Test3();
prg.Test4();
prg.Test5();
}
}
}

Second Step:

Add a new class naming as Two.cs

using System;
namespace TestAccess
{
class Two:Program
{
static void Main()
{
Two t1 = new Two();
t1.Test2();
t1.Test3();
t1.Test4();
t1.Test5();
}

}
}

Note: Run the Two.cs, by following below steps:

Right click on project Name from solution explorer

Select Properties

Select startup project then select TestAccess.two

Press ctrl+f5

MailId:ashvin.kumar01@gmail.com 19
Aprash Technologies
+91-9953904262

Step3:

Add a new class naming as Three.cs

using System;
namespace TestAccess
{
class Three:Program
{
static void Main()
{
Three T2 = new Three ();
T2.Test2();
T2.Test4();
T2.Test5();
}
}
}

Note: Now check it out Run the Three.cs,

Step 4:
1. Add new project naming TestAccess2 than Add a New class Four.cs
2. Adding Assembly of TestAccess Project In TestAccess2 project.

Right click on TestAccess2 Project from Solution Explorer

Select Add Reference

Click on Browse Tab

Select Assembly from project folder/bin/debug/assembly file without any extension

Click Ok.
using System;
namespace TestAccess2
{
class Four : TestAccess.Program
{
Four f1 = new Four();
f1.Test2();
f1.Test4();

MailId:ashvin.kumar01@gmail.com 20
Aprash Technologies
+91-9953904262
f1.Test5();
}
}
Step5:
Add New Class in TestAccess2 naming as Five.cs

using System;
namespace TestAccess2
{
class Five : TestAccess.Program
{
Program f5 = new Program ();
F5.Test5();
}
}

Language Iteroperability

As we were aware that .net languages could interoperate with each other i.e. code of one language
can we consume other languages.

1. Add new Project under a solution by choosing the language as VB and template as class
Library by naming it as VBLibProject.

Note: Class Library is a collection of classes, which cannot be executed but only, consume.

2. By default under VBLibProject, there is a class name i.e. Class1.cs writes the code
under as:

Public Class Class1

Public Function Fun1(ByVal str As String) As String

Return "Welcome " + str


End Function

End Class

Note:Compile the Project (press f6)

3.To consume the VBLibProject Class in any Other language like C Sharp by adding the
reference Of VBLibProject in CSharpProject.

Right click on CSharpProject from Solution Explorer

MailId:ashvin.kumar01@gmail.com 21
Aprash Technologies
+91-9953904262

Select Add Reference

Click on Browse Tab

Select VBLibProject .dll from project folder/bin/debug/.dll file.

Click Ok.

using System;
namespace CsharpProject
{
class Test
{
static void Main()
{
VBLibProject.Class1 c1 = new VBLibProject.Class1();
Console.WriteLine(c1.Fun1());
Console.ReadLine();

}
}
}

Note: run The Test.cs File of CSharpProject


Members of a Class

1. Fields (variables)
2. Methods
3. Constructors
4. Properties
5. Delegates
6. Events
7. Enumerations

Properties: Some times, we have a value under a class, which should be accessible outside of the
class. Access to the value outside of a class can be provided in two ways.

1. Public 2.properties

Note:

MailId:ashvin.kumar01@gmail.com 22
Aprash Technologies
+91-9953904262
1. If a variable is declared as public i.e. accessible to everyone either to get the value or set the value.
2. If the access to the same value and if provided with property we can use in three ways.

Read Write Property: Where the User can get or set the value
Read Only Property: Where the User can get the value but not set the value.
Write Only Property: Where the User can set the value but not get the value.
Syntax:
[<Modifiers>] <Type> <name>
{
[
get
{ Statements; }
set
{ Statements; }
]
}
1. If the property is defined with both get and set blocks i.e. Read write property.
2. If the property is defined with get and set block only i.e. Read only property.
3. If the property is defined with block only i.e. write property.

Enumerations: - It is also a type, which is a collection of values. (It is Value Type)


Syntax:
[<modifiers>] enum <name> {<List of Values>}

public enum Days {Monday, Tuesday, Wednesday};

Enum type can be declared under either a namespace as well as a class also.
Advised to declare under a namespace. As enum is a type to consume it, we required to create a copy
of the type as well as initialized with a value.

Example:
Days d=0;
Or
Days d= Days. Monday;

Example of Property and enum:

using System;
namespace PropClass
{

public enum Days { Sunday, Monday, Tuesday, Wednesday,


Thursday };
class Propert
{
Days _weekday=Days.Monday;

int _cid = 101,_age=15;

MailId:ashvin.kumar01@gmail.com 23
Aprash Technologies
+91-9953904262
string _cname = "Amit", _city = "Delhi";
//Read Only Property
public int Custid
{
get
{ return _cid; }

}
//ReadWrite property with condition
public int Age
{
get
{
return _age;
}
set
{
if (value > 18)
_age = value;
}
}
//ReadWrite Property

public string Cname


{
get
{
return _cname;
}
set
{
_cname = value;
}
}

//scope of property accessor set independently (2.0


version)
public string City
{
get
{
return _city;
}
protected set
{
_city = value;
}
}

//Automatic property(3.0 version)

MailId:ashvin.kumar01@gmail.com 24
Aprash Technologies
+91-9953904262
//Doesnt requre a variable cannot write the code inside
the block
public string State
{
get;
set;

public Days Weekday


{
get
{
return _weekday;
}
set
{
_weekday = value;
}
}
}
}

To Consume all the above properties add a new Class Program.cs


Example:
using System;
namespace PropClass
{
class Program
{
static void Main(string[] args)
{
Propert p1 = new Propert();
Console.WriteLine("Cust prev Id "+p1.Custid);
//p1.Custid = 102; Invalid because it is read only
property
Console.WriteLine("After Changed Id "+p1.Custid);

p1.Age = 12;
Console.WriteLine("Age "+p1.Age);

Console.WriteLine(p1.Cname);
p1.Cname = "ankit";
Console.WriteLine(p1.Cname);
Console.WriteLine(p1.City);
//p1.City = "Haryana"; it will set on only child
classes u cannot set the value
//p1.State = "Uttar Pradesh";
//Console.WriteLine("state" = p1.State);

MailId:ashvin.kumar01@gmail.com 25
Aprash Technologies
+91-9953904262
Console.WriteLine("default weekday " + p1.Weekday);
p1.Weekday = Days.Tuesday;
Console.WriteLine("Changed weekday " +p1.Weekday);
//Cannot access have as this was not a child class
p1.State = "Haryana";
Console.WriteLine(p1. State);

}
}
}

Note:
1. Under 2.0 specifications, we were given the feature of setting the property accessor that
scope or accessibility.
2. under 3.0 specifications we have been provided with automatic properties , where u can
define a property without under code get & set blocks, but the restrictions here was both get
& set blocks were mandatory

Delegate: - A delegate is a pointer to a method, which is similar to the concept of function pointers
under c and c++ languages. Whenever a function is called to execute that, it creates a stack and
destroys after execution. The creation and destruction of stack each time is a time consuming
process. This can be overcome with the help of function pointers or delegates.

After defining the delegate for a method, we never call the method directly for execution.
It is only a delegate, which is called for execution of the method, which uses the same stack even if
method requires executing for multiple times.

Syntax:

[<Modifiers>] delegate <void | type> Name ([<parameters>])

How to use delegate follow 3 steps give below:

Step1:-Declare the Delegate


Note: the Input Output parameters of a delegate should be same as the Input Output parameters of
the method, which the delegate has to call.

Example:

public delegate void AddDelagate(int x, int y);

public static void Add(int x, int y)


{
Console.WriteLine(x + y);
}

MailId:ashvin.kumar01@gmail.com 26
Aprash Technologies
+91-9953904262
Step2:- As a delegate is also Reference type to consume it we need to create object of it by
passing the target method name, it has to call as parameter.

Example:

AddDelegate Ad = new AddDelegate(Add);

Step3: Call the delegate for execution, which will execute the method internally.

Example:
Ad (100, 90);
Ad (80, 90);

Types of Delegate

1. Single cast Delegate


2. Multi cast Delegate

If a delegate invokes a single method of the class, it is a single “Single cast Delegate”
Where as if a delegates invokes multiple methods of a class that was “Multi cast Delegate”.
Using a single delegate, we want to call multiple methods the input and output parameters of all
these methods should be same.

Example of Delegate.

using System;
namespace MultiCast
{
class Program
{

public delegate void Arithemetic(int x, int y);


public void Add(int x, int y)
{
Console.WriteLine("Add "+ (x+y));
}
public void Sub(int x, int y)
{
Console.WriteLine("Subtract "+ (x-y));
}
public void Mult(int x, int y)
{
Console.WriteLine("Multiply "+ (x*y));
}
static void Main(string[] args)
{

Program obj = new Program();


Arithemetic arth = new Arithemetic(obj.Add);

MailId:ashvin.kumar01@gmail.com 27
Aprash Technologies
+91-9953904262
arth += obj.Sub;
arth(10, 20);
Console.WriteLine();
Console.WriteLine("Removing Add method from Delegate
and Adding New Mult method");
Console.WriteLine();
arth -= obj.Add;
arth += obj.Mult;
arth(20, 90);

}
}
}

Structures:
It was also a user-defined type similar to a class, which can be defined with every member that can
be defined under a class.

Difference between Class and Structures?

S.No Class Structures

1 It was a reference type. It was a value type.

2 It gets the memory allocated on Managed Heap Memory. It gets memory allocated on
This has support of Garbage Collector for allocation and stack memory where we do not
destruction. have memory management
with Garbage Collector.

3 Not Faster in access than Structure. Faster in Access.

4 Required to use new operator for creating a object. Using new operator to create
object was optional.

5 Can contain variable declaration and initialization. Can contain variable


declaration but cannot
initialization, It can be
initializing either by referring
with object of structure or
under a Constructor.

MailId:ashvin.kumar01@gmail.com 28
Aprash Technologies
+91-9953904262

6 May or May not contain a default constructor in it. It was must, it should contain a
default constructor, which will
be always defined implicitly,
where a programmer cannot
define it.

7 If Class defined with n number of constructors, contains n If Defined with n constructor


number of constructors or else one Constructor. contains n+1 constructors or
else only one constructor.

8 It supports inheritance. It does not support


Inheritance.(Not oops)

Note:
All the pre-defined types, which come under value type category, were implemented as a structure
where as a type, which comes under reference type (object and string) were implemented as a class.

Example:
using System;
namespace Structures
{
struct Mystruct
{
int x;

public Mystruct(int x)
{
this.x = x;
}

public void display()


{
Console.WriteLine("Result is " + x);
}

static void Main(string[] args)


{
Mystruct My;//Invokes Default constructor
My.x = 1000;
My.display();

Mystruct My2 = new Mystruct(100);


My2.display();
}
}
}

MailId:ashvin.kumar01@gmail.com 29
Aprash Technologies
+91-9953904262
If u want to consume a structure under a class or structure it is still possible by creating its object.

Add a new MyStruct2.cs File.

using System;
namespace Structures
{
class MyStruct2
{
static void Main()
{
Mystruct My3 = new Mystruct(2000);
My3.display();
}

}
}

Exception and Exception Handling

In the development of an Application, we may be coming across a set of errors, which can be of two
different types.
1. Compile Time Errors

2. Run Time Errors

 Compile Time Errors:-These are the errors, which come into picture due to the
syntactical mistakes within a language these are considered as a big problem.

 Run Time Errors:-These are the errors, which may come into picture while the
execution of the program, which may be due to some reasons like wrong
implementation of logic, wrong input supplies to the program etc.

These Run time errors were also know as exceptions, these were a big problem because Whenever
the exception occurs program terminated automatically on the same line by displaying an error
Message without executing the next line of the code.

Exception Handling:-

As a program is terminating abnormally when an exception occurs without executing the code i.e.
not related with exception also. To stop the abnormal termination and execute all the code, which
was not related with an exception, is known as Exception handling.

There were number of exceptions in applications where all these exceptions were internally
implemented in the form of classes mostly comes under in System. Threading namespace.

Exception Class

MailId:ashvin.kumar01@gmail.com 30
Aprash Technologies
+91-9953904262

Abnormal Termination

Return an Error Msg with Return an Error Msg with Return an Error Msg
Exception Exception with Exception

DivideByZero IndexOutofRange Format Exception


NullRefObject FileNotFound

Process Of Execution while Exception Occurs.


Whenever an exception scenario comes into picture within a program execution, then Exception
Manager Gets invoked which identifies the type of exception that creates the object of related
Exception class and throws it. This will terminate the program abnormally and displays the related
error message.

To handle this we can use the try catch block.


Syntax:

try
{
Statements, which will cause an exception
Statements related with Exception, which should not execute when exception occurs
}
catch (<exception> variable)
{

Statements that has to execute only when exception occurs

[<Multiple catch blocks if required>]


.
Example: Exception Handling

using System;
namespace ExceptionDemo
{
class Program

MailId:ashvin.kumar01@gmail.com 31
Aprash Technologies
+91-9953904262
{
static void Main(string[] args)
{ int x, y, z;
try
{
Console.WriteLine("Enter X value ");
x = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Y value ");
y = int.Parse(Console.ReadLine());
z = x / y;
Console.WriteLine("Result is " + z);

}
catch (DivideByZeroException e1)
{
Console.WriteLine("Division cannot be zero"+e1);
}
catch (FormatException e2)
{
Console.WriteLine("Input value is not in correct
format"+e2);
}
catch (Exception e3)
{
Console.WriteLine("Exception caught"+e3);
}
Console.WriteLine("End of the Program");
}
}
}

Finally:

It is a block of code, which can be paired with try the code written under this block will be executed
at any coast. I.e. Exception occurred or not.

Example:

using System;
namespace ExceptionDemo
{
class FinallyDemo
{
static void Main()
{
int x, y,z;
try
{
Console.WriteLine("Enter X value ");
x = int.Parse(Console.ReadLine());

MailId:ashvin.kumar01@gmail.com 32
Aprash Technologies
+91-9953904262
Console.WriteLine("Enter Y value ");
y = int.Parse(Console.ReadLine());

if (y == 1)
return;
z = x / y;
Console.WriteLine("Result is " + z);

}
catch (Exception ex1)
{
Console.WriteLine(ex1.Message);
}
finally
{
Console.WriteLine("Finally Block Executed");
}
Console.WriteLine("End of the Program");
Console.ReadLine();

}
}
}
Note:

In the above program, if the value to a divisor is one (1) the execution of the program suspends
because of the return statement, but only after executing the finally block .because once the control
enters into try block we can not stop the execution without executing Finally block.

Message is a property of exception class, which returns the Error message that is associated with the
exception that has occurred.

Try catch and finally blocks can be used in three different combinations.

1. try and catch


2. try, catch and finally
3. try and finally

Exceptions are of two types:-

1. System Exception: - An exception that is raised internally on some predefined error or


conditions is known as System Exception.

2. Application Exception:-programmer within a program on their own conditions can also raise
Exceptions.

If a Programmer wants to raise its own exception under a program, we need to do following steps.

MailId:ashvin.kumar01@gmail.com 33
Aprash Technologies
+91-9953904262
 Create the object of any Exception class
 Throw the object by using throw statement.

Question:-Can we throw the object of any exception class to raise an exception?

Ans:-“Yes”, we can throw the object of any exception class for raising an exception but the error
message will be the same error message associated with that exception.

Note: Programmer can also create its own exception by inheriting the Application Exception Class.

Example:

using System;
namespace ExceptionDemo
{
class ThrowDemo
{
static void Main()
{
int x, y, z;
Console.WriteLine("Enter X value ");
x = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Y value ");
y = int.Parse(Console.ReadLine());
z = x / y;

if(y %2>0)
throw new ApplicationException("Attended
exceptionto odd number");
Console.WriteLine("Result is "+z);
Console.ReadLine();
}
}
}

In the above program if the value to the divisor is an odd number, then exception is raised.

Threading:

Thread:-A thread can considered as a unit of execution responsible for executing the code. By
default, every program has one thread for execution i.e. thread.

Multitasking:-if more than one program can be executed at a given point of time, we call it as
Multitasking. This is generally supported in the Operating System.

 Dos -------------------Single tasking O/S


 Windows, UNIX ---Multi tasking O/S

MailId:ashvin.kumar01@gmail.com 34
Aprash Technologies
+91-9953904262
Multithreading: - A single Application performing multiple activities simultaneously is known as
multithreading, which the languages with the help of O/S generally support.

In a Single thread model, if multiple a method has to be executed, they are executed in queue based
i.e. one method after the other, which may be poor in performance.
The other way of executing multiple methods in an execution is using Multithreading i.e. a separate
thread for each method to execute where the execution takes place as following

1. 1.Time Sharing:-In this, the O/S allocates some time period for each method to execute and
keeps on transferring the control between each thread giving equal importance to all
methods.

2. Maximum Utilization of CPU Resources:-This comes into the picture when the first
principal violate i.e. if a thread could not execute within its given time without wasting the
time then, the control gets transferred to the other thread in execution.

Creating Thread:-

To create a thread we need to create the object of thread class by passing the method name, it has to
call as an argument. Thread class available under the namespace i.e.System.Threading.

Example:-
Thread (Method name)
Thread th1=new Thread (method)
Methods of thread Class

1. Start ():-It is used for starting the execution of thread.

2. Sleep (int milliseconds):-It was a static method, which makes the current executing thread to
sleep up to the specified time, was elapsed.

3. Join ():-By default the execution of a program starts from Main () because it was the entry
point as well as the controller of a program, the execution should also end with Main () only
because it controls the complete program. In Multithreading, we have a problem i.e. the
thread, which completes its work, first will exit from the program First. If Main () complete
its work it will leave the program as well as leaving the control to other threads in execution
which should not be happens a point of time. In this scenario if we want the Main () thread
to wait until all the other threads exiting the program and then exit we need to call the
method Join () on all the other thread in execution.

4. Abort ():-It is used for terminating the execution of a thread.

5. Suspend ():-Causes the thread to suspending its execution until resume was called.

6. Resume ():-It is used to resume the thread that has been suspended.

MailId:ashvin.kumar01@gmail.com 35
Aprash Technologies
+91-9953904262
Example:-
using System;
using System.Threading;
namespace ExceptionDemo
{
class ThreadDemo
{
Thread t1, t2;
public ThreadDemo()
{
t1 = new Thread(Check1);
t2 = new Thread(Check2);
t1.Start();
t2.Start();
}
public void Check1()
{
for (int i = 1; i <= 100; i++)
{
Console.WriteLine("Check1 " + i);
if (i == 5)
{
Thread.Sleep(10000);
}
}
Console.WriteLine("Thread1 Exit");
}
public void Check2()
{
for (int i = 1; i <= 100; i++)
{
Console.WriteLine("Check2 " + i);

}
Console.WriteLine("Thread2 Exit");
}
static void Main()
{
ThreadDemo obj = new ThreadDemo();
obj.t1.Join();
obj.t2.Join();
Console.WriteLine("MainThread Exit");
}
}
}

Thread Synchronization: - A multithreading we use a separate thread for calling an each method as
in our previous example ,Whereas in some cases multiple threads may access the same resource, in
this situation we may be getting some un expected result results as following.

MailId:ashvin.kumar01@gmail.com 36
Aprash Technologies
+91-9953904262
using System;
using System.Threading;
namespace ThreadSynExample
{
class ThreadSyn
{
Thread t1, t2;
public ThreadSyn()
{
t1 = new Thread(Display);
t2 = new Thread(Display);
t1.Start();
t2.Start();
}
public void Display()
{
Console.Write(".Net is Product of :-");
Thread.Sleep(5000);
Console.WriteLine("Microsoft ");
}
static void Main(string[] args)
{
ThreadSyn SynThr = new ThreadSyn();
SynThr.t1.Join();
SynThr.t2.Join();
}
}
}
Note: In the above case, two threads were calling the same method Display () where as get some
unexpected result:
Output of above Program like-

.Net is a: - .Net is a: - Microsoft Microsoft

To overcome the above problem we can use the thread Synchronization or thread locking
mechanism, which allows only one thread to access the method at a time.

Example:
using System;
using System.Threading;

namespace ThreadSynExample
{
class ThreadSyn
{
Thread t1, t2;

public ThreadSyn()
{

MailId:ashvin.kumar01@gmail.com 37
Aprash Technologies
+91-9953904262
t1 = new Thread(Display);
t2 = new Thread(Display);
t1.Start();
t2.Start();
}
public void Display()
{
lock (this)
{
Console.Write(".Net is Product of :-");
Thread.Sleep(5000);
Console.WriteLine("Microsoft ");
}
}
static void Main(string[] args)
{
ThreadSyn SynThr = new ThreadSyn();
SynThr.t1.Join();
SynThr.t2.Join();
}
}
}
Result:
.Net is product of Microsoft
.Net is product of Microsoft

When the method is locked ,a monitor gets created around the class which allows only one thread
can enter into it at a time when one thread under the monitor even if the other thread start their
execution ,they can’t enter inside the monitor until the thread inside the monitor out.
Thread Priorities:-By default when there were multiple threads in execution. The operating system
allocates some time to each thread in execution and transfers the control between each thread. By
default, the operating system gives same priority for all the threads in execution, which was the
Normal.

If u wants to give any additional priority to a thread for execution, we can make a request to the
operating system for allocating more time to consume the CPU resources by setting priorities.

Priority to a thread can be set with 5 different values.

1. Lower
2. Below Normal
3. Normal (default)
4. Above Normal
5. Highest

Example:

using System;
using System.Threading;

MailId:ashvin.kumar01@gmail.com 38
Aprash Technologies
+91-9953904262
namespace ThreadSynExample
{
class ThreadPrior
{
Thread t1, t2;
long cnt1, cnt2;
public ThreadPrior()
{
t1 = new Thread(IncCount1);
t2 = new Thread(IncCount2);
t1.Priority = ThreadPriority.Highest;
t2.Priority = ThreadPriority.Lowest;
t1.Start();
t2.Start();
}
public void IncCount1()
{
while (true)
cnt1 += 1;
}
public void IncCount2()
{
while (true)
cnt2 += 1;
}
static void Main()
{
ThreadPrior obj = new ThreadPrior();
Console.WriteLine("Please Wait Thread is in Process");

Thread.Sleep(4000);
obj.t1.Abort();
obj.t2.Abort();

Console.WriteLine("Count 1 " + obj.cnt1);


Console.WriteLine("Count 2 " + obj.cnt2);
obj.t1.Join();
obj.t2.Join();

}
}
}

Windows Application

Traditionally we were using various type of application like Console as known as CUI.

Examples are-Dos, UNIX operating System.

CUI has Many Disadvantages’ like-

MailId:ashvin.kumar01@gmail.com 39
Aprash Technologies
+91-9953904262

1. There was not user friendly.


2. Do not allow to navigate from one field to another.

GUI is Graphical User Interface, which solves the above disadvantages. To develop Windows
Application Microsoft has introduced in 90’s Visual Basic language.
Later when .Net introduced, the support for developing windows Applications has given in all .Net
languages along with Visual Basics.

We can work on windows application by using some components called Controls which are in under
the namespace of System.Windows.Forms.

Controls categorize in two ways:-

1. Container Controls: - Panel, Split Container and Tab Control.


2. Non-Container Controls:-Button, Label Textbox, Treeview etc.

Every control has three things in common

1. Properties:-Attributes of control.
2. Method:-Perform an Action.
3. Events:-It is a period, which is specifying u to perform an action or method like Click,
Key Press.

Example of Developing Application through Notepad.

using System;
using System.Windows.Form;

public class MyForm: Form


{

static void Main ()


{
MyForm obj=new MyForm ();
Application. Run (obj);
}
}

Note: Save the File App.cs and execute it through command prompt.

Partial Class:
It is an approach, which allows defining a class in more than one file, it was introduced under 2.0
specifications the advantages of this approach will be

MailId:ashvin.kumar01@gmail.com 40
Aprash Technologies
+91-9953904262
1. Multiple programmers’ works on a class at a time.
2. Splitting of huge volume of code into multiple files that make managing easier.

Q1:-What is the method under which we were writing the code corresponding to an event?

Ans:-The method under which we write the code has a special name known as Event Procedure.
An Event Procedure is a block of code i.e. bound with an event of a control and is executed
whenever the Event raises.
The code Written under event procedure will be internally executed by the event with the help of
delegate.

Bounds
Control Event
Procedure

Delegate

Description:-In the above case whenever the event raises it will call the delegate, which takes the
responsibility of executing code under the Event Procedure.

Q2: How does the Event and Delegate & Event Procedure is linked with each other?
Ans: Events and Delegate were predefined under the base class Library, what we define here only an
event procedure under the form to link the delegate and event procedure .Visual studio writes a
mapping statement as following.

Syntax:
<Control>.<event> +=new <delegate> (<event procedure>)

Ex:
this. Load +=new EventHandler (form1_Load);
this. Click +=new EventHandler (button1_Click);

Q3: Can we define Event Procedure manually?


Ans: Yes, we can define event procedure manually as follow

[<Modifiers>] void <name> (object sender, Eventargs e)


{
<Statements>

MailId:ashvin.kumar01@gmail.com 41
Aprash Technologies
+91-9953904262

Note:
 Event Procedure is Non Returning value method, so they were always void.
 We can specify any name to an Event procedure but Visual studio

Follows a convention while naming them.

Examples are - Form1_Load, button1_Click

Every Event Procedure should have two mandatory parameters

 Object sender
 EventArgs e

Example in Notepad: App.cs


using System;
using System.Windows.Form;

public class MyForm1: Form


{

public MyForm1 ()
{
IntializeComponent ();
}

Private void IntializeComponent ()


{
this. Text=”My Form”;
this. Width=400;
this. Height=400;
this. Load += new EvantHandler (Test);
this. Click += new EvantHandler (Test);
}

Private void Test (object sender, EventArgs e)


{
MessageBox.Show (“Event raised”);
}

static void Main ()


{
Application. Run (new MyForm1 ());
}

MailId:ashvin.kumar01@gmail.com 42
Aprash Technologies
+91-9953904262
Note: Run the App.cs file through Command prompt.

ADO.NET

In Windows Applications, code is categorized in two ways:-

1. Designer Code
2. Business Logic

1. Designer Code:-This code is generated by Visual studio Under the Initialize Component
(), method and Business programmers in the form of event procedure define logic.

2. Business Code: which is responsible for execution of the form, is known as Business
Logic?

Before .Net2.0, Designer code and Business Logic were defined under a class present under
a file.

From .Net2.0 with introduction of partial classes’ designer code and business logic code were
separated into two different files but on the same class only.

Data Source:-

1. A data source (or) data store is a place where we stored the information.
2. Examples: Files, Databases, Indexing Servers.

A language cannot communicate directly because each data adopts a different protocol for
communication.
To facilitate the process of communication’s.Ms has provided a solution in the form of drivers and
providers.

Applications------> Drivers and Providers------> Data Sources

Drivers: - These were the initial solution provided by the Microsoft to communicate with Databases
.They were again Two Types.
1. JET (Joint Engine Technology) Drivers.
2. ODBC (Open Database Connectivity).

1. Jet Drivers: - These are used for communication with local Databases.

2.Odbc Drivers:-These are used for Communicate with Remote Databases.

Drawbacks’ of Drivers

 They were initially designed only to communicate with Databases.

MailId:ashvin.kumar01@gmail.com 43
Aprash Technologies
+91-9953904262
 The Driver installed and configured on each and every machine where the Application in
Executing.

Providers:

OLEB Providers: These were provided, as a next solution after drivers, which can communicate with
data sources, and in case of providers we do not required any installations and configurations on each
client machine.
OLEBDB:-Object Linking Embedded Database.

Both the Driver and providers suffers from a common problem i.e. as they were designed by using
Native Code Languages they were purely Platform Dependent.

The classical Visual basic language could not communicate directly with this drivers and providers
because of the Native Code support in them.

To overcome the problem MS has designed few Intermediate components for VB language to
communicate with drivers and providers, which will intern communicate with data servers as
follows:-

Visual Basic

Data Access Remote Data Active-X data


Object Object Object

JET ODBC OLEDB


Drivers Drivers Drivers

Remote Data
Local Databases Database Sources

MailId:ashvin.kumar01@gmail.com 44
Aprash Technologies
+91-9953904262

ADO.Net:- It was the collection of managed providers used for communication with any data source
from .Net languages.When .Net introduced to communicate with data sources from.Net applications,
the best of traditional 3 technologies ADO’S has been redesigned as ADO.Net.

ADO.Net provides various classes, which can be used for data source communication under the
following Namespaces.

1. System.Data
2. System.Data.Oledb
3. System.Data.SqlClient
4. System.Data.OracleClient
5. System.Data.Odbc

System.Data: It is a collection of classes used for holding and managing the data on Client machine.
Classes under these were DataSet, DataTable, DataColumn, DataView, and DataRelation.

System.Data.Oledb: Collection of classes used for communicate with any database.

System.Data.SqlClient: Collection of classes and communicate only with Sqlserver.

System.Data.OracleClient: Collection of classes used for communicate with Oracle.

System.Data.Odbc: Collection of classes used for communicate with traditional ODBC drivers,
which will intern communicate with data sources.

Note:
All the above four namespaces contains some set of classes as following.

1. Connection
2. Command
3. DataReader
4. DataAdapter
5. CommandBuilder
6. Parameter etc.

Every Operations we perform on a data source involves three steps

 Establishing a Connection
 Applying a SqlStatement
 Expecting the result

1. Establishing a Connection: - In this process, we open a class for communication with target
machine to perform our operations. To open the channel for communication we use
Connection Classes

MailId:ashvin.kumar01@gmail.com 45
Aprash Technologies
+91-9953904262

 Connection ()
 Connection (string ConnectionString)

ConnectString is a collection of attributes that is used for connecting with target machine. Those are

1. Provider
2. Data Source
3. User Id and Password
4. Database or Initial Catalog
5. Trusted Connection
6. DSN

Provider: - As we were aware that a provider is required for communicating with data sources, we
use a different provider for each Data Source.

A. Oracle Msdaora
B.SqlServer SqlOledb
C.MsAccess/Excel Microsoft.Jet.Oledb.4.0
D.Indexing Server MsIdx

Data Source: - It was the name of the target machine where a data source or database is present, does
not required to be specified, if it was on Local machine.

User Id and Password: - As databases were secured places for storing data to connect with them, we
required valid username and password.
A. Oracle Scott/Tiger
B.SqlServer SA/<Blank>

Initial catalog or Database and Trusted Connection: -These attributes will be used only while
connecting with SqlServer.

DSN: -This attribute is used in case of ODBC classes.

Connection String for Oracle

“Provider=Msdaora; User Id=Scott; Password =Tiger [; Data Source=<server>]”

Connection String for SqlServer

“Provider=SqlOledb; User Id=SA; Password=<pwd> Database=<dbName> [; Data


Source=<server>]”

Methods and Properties of Connection Class

1. Open(): -Method to Open a Connection


2. Close (): -Method to Close a Connection.
3. State: -Property to find current state of Connection.
4. ConnectionString-Property to get or set the Connection String.

MailId:ashvin.kumar01@gmail.com 46
Aprash Technologies
+91-9953904262

The object of the connection class can be created in any of the following ways.

Connection con= new Connection ();


Con.ConnectionString=” ”;

Or
Connection con= new Connection (“<ConString> “);

Example:
1.Create a new Windows Application Project.

2. Place two Buttons Inside the form.

3. Double Click on First Button and write the code as following

OleDbConnection con = new


OleDbConnection("Provider=Msdaora;User
Id=Scott;Password=tiger");
con.Open();
MessageBox.Show(con.State.ToString());
con.Close();

4. Double Click on Second Button and write the code as


following

SqlConnection con = new SqlConnection();


con.ConnectionString= "provider=Sqloledb;User
Id=sa;Password=123;database=Master";
con.Open();
MessageBox.Show(con.State.ToString());
con.Close();

Verify The Result.

MailId:ashvin.kumar01@gmail.com 47
Aprash Technologies
+91-9953904262
Applying a Statement

In this process, we send an instruction to the data source specifying the type of activity that has to be
performed using a SqlStatement like Insert, Update, Delete, and Select. We Use Commend Class for
applying a statement.

1. Command ()
2. Command (string sqlstmt, Connection con);

Properties of Command class

1. Connection:-To set or get the Current Connection Object associated with Command.

2. Command Text:-To set or get the Current sqlStatemant associated with Command.

Object of the Command Class created as below

Command cmd= new Command ();


cmd.Connection=<con>;
cmd.CommandText=”<sqlStmt”>;

Or

Command cmd=new Command (“<sqlstmt”>, con);

Methods Of Command Class.

1. ExecuteReader() -------> Data Reader (Return)


2. ExecuteScalar() --------> Object (Return)
3. ExecuteNonQuery()--- > Integer (Return)

Note:-

After Creating the Object of Command class, we need to call any of these three methods to execute
the Statement.

1. ExecuteReader ():- Whenever we want to execute a select statement that returns values in the
form of Rows and Columns. This captures the data under DataReader, which was a class,
modeled on table.

2. ExecuteScalar ():-Whenever we want to execute a select statement that returns single value
result, which captures the data under an object variable.

3. ExecuteNoneQuery ():-Whenever we want to execute Non-Query Statements(DML)like


Insert , Update , Delete .so that number of Rows being affected is returned as a integer value.

MailId:ashvin.kumar01@gmail.com 48
Aprash Technologies
+91-9953904262
Accessing data from DataReader.

DataReader is a class, which is modeled on Table. To access the data from DataReader it provides
Methods.

1. Read ():- Returns Boolean value. used for moving the record pointer from current location to
next row , after moving the pointer it will return the specifying values were present in the
row to which , it moves that will be true if present and false if not present.

2. GetValue (int index):- Returns an object. Used for picking the field value from the row to
which pointer was pointing by specifying the column index position.

Note: - We can also access data pointer by pointer in the form of single dimensional array
also by either specifying column index position or name.

<dr> [index] --------> object


<dr> [name] --------> object

3. GetName (index): -Returns an string. Used getting the name of column for specifying
index.

Excersise1:

Steps:

1. Include Namespace using System.Data.OleDb;

Declaration under class globally.

MailId:ashvin.kumar01@gmail.com 49
Aprash Technologies
+91-9953904262
OleDbConnection con;
OleDbCommand cmd;
OleDbDataReader dr;

1. Write the Code under the Form_Load Event

con = new OleDbConnection("Provider=Msdaora;User Id=Scott;


Password=tiger");
cmd = new OleDbCommand("select * from Emp", con);
con.Open();
dr = cmd.ExecuteReader();
label1.Text = dr.GetName(0);
label2.Text = dr.GetName(1);
label3.Text = dr.GetName(2);
ShowData();

2. Create A function in a class


private void ShowData()
{
if (dr.Read())
{
//Fetching EmpId ,Name and City from emp table
textBox1.Text = dr.GetValue(0).ToString();
textBox2.Text = dr[1].ToString();
textBox3.Text = dr["City"].ToString();
}
else
{
MessageBox.Show("Last Record");
}
}

3. Code under Next Button

ShowData();

4. Code under Close Button

if (con.State == ConnectionState.Open)
{
con.Close();
this.Close();
}

5. Execute the Application.

MailId:ashvin.kumar01@gmail.com 50
Aprash Technologies
+91-9953904262
Excersie2:

Steps:

1. Include Namespace using System.Data.OleDb;

2. Declaration under class globally.

OleDbConnection con;
OleDbCommand cmd;
OleDbDataReader dr;
string SqlStr;

3. Code under form_Load Event

con = new OleDbConnection("Provider=Msdaora;User


Id=Scott;Password=tiger");
cmd = new OleDbCommand();
cmd.Connection = con;
LoadData();

2. Create functions
private void SetStmnt()
{
if (con.State == ConnectionState.Closed)
{

MailId:ashvin.kumar01@gmail.com 51
Aprash Technologies
+91-9953904262
con.Open();
}
cmd.CommandText = SqlStr;
con.Open();
}

private void ShowData()


{
if (dr.Read())
{
//Fetching EmpId ,Name and City from emp table
textBox1.Text = dr[0].ToString();
textBox1.Text = dr[1].ToString();
textBox1.Text = dr[2].ToString();
}
else
{
MessageBox.Show("Last Record");
}
}
private void ExecuteDML()
{
DialogResult drs=MessageBox.Show("Do You want to Execute
?","n\n\Confirm
SqlQuery",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
if(drs==DialogResult.Yes)
{
SetStmnt();
int count=cmd.ExecuteNonQuery();
if(count>0)
{
MessageBox.Show("Stmt Executed");
}
else
{
MessageBox.Show("Stmt Failed");
}
LoadData();
}
}

3. Code under Next Button

LoadData ();

4. Code under New Button

textBox1.Text = textBox2.Text = textBox3.Text = "";


SqlStr = "select max(Eid) from Emp";
SetStmnt();

MailId:ashvin.kumar01@gmail.com 52
Aprash Technologies
+91-9953904262
textBox1.Text = cmd.ExecuteScalar().ToString();
textBox2.Focus();

5. Code under Insert Button

{
SqlStr="insert into Emp(EId,Ename,City)values("+textBox1.Text+",
'"+textBox2.Text+" ','"+textBox3.Text+"')";
ExecuteDML();
}

6. under Update Button

SqlStr="update Emp set EName='"+textBox2.Text+" ',City='


"+textBox3.Text+ "' where EId="+textBox1.Text;
ExecuteDML();

7. under Delete Button

SqlStr="Delete from Emp where Eid="+textBox1.Text;


ExecuteDML();

8. under Close Button

if (con.State == ConnectionState.Open)
{
con.Close();
this.Close();
}

9. Execute Application

Working with SQl Server

Create the table in SQL Server with following fields. In addition, set status field as default value is
one (1).

MailId:ashvin.kumar01@gmail.com 53
Aprash Technologies
+91-9953904262
Add some values in it.

Now comes to Windows Application and design the Form as well.

1. Include namespace-using System.Data.SqlClient;

2. Declarations at class level

SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
string SqlStr;

3. Create the Show Data Function

private void ShowData()


{
if (dr.Read())
{
//Fetching EmpId ,Name and City from emp table
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
textBox3.Text = dr[2].ToString();
textBox4.Text = dr[3].ToString();

MailId:ashvin.kumar01@gmail.com 54
Aprash Technologies
+91-9953904262
}
else
{
MessageBox.Show("Last Record");
}
}
4. under form_load Event

con = new SqlConnection(@"Data


Source=localhost;InitialCatalog=Abc;Integrated Security=True");
cmd = new SqlCommand("select Sno,SName,Class,Fee from students",
con);
con.Open();
dr = cmd.ExecuteReader();
label1.Text = dr.GetName(0);
label2.Text = dr.GetName(1);
label3.Text = dr.GetName(2);
label4.Text = dr.GetName(3);
ShowData();

5. under Next Button

ShowData();

6. under Close Button


if (con.State == ConnectionState.Open)
{
con.Close();
this.Close();
}

7. Rest of buttons code are similar to previous Excersice.


8. Execute the Application.

DataReader: - It is a class modeled on table that can be used for holding data on Client machine.

Features of DataReader.

1. Faster Access to data from Data Source as it was Connection oriented.

2. It can hold multiple tables’ in it at a time to load multiple tables we need to pass multiple
select statements as arguments to Command Class Separated by semicolon.

Example:

SqlCommand cmd= new SqlCommand ("select * from Emp ; select * from Dept ");

DataReader dr=cmd.ExecuteReader ();

MailId:ashvin.kumar01@gmail.com 55
Aprash Technologies
+91-9953904262

Note:-Use the NextResult () Method on DataReader object to navigate from current table to next
Table.

Example: - dr.NextResult ();

Drawbacks of DataReader

1. It is designed as connection oriented which requires a permanent connection with data


source to access the data, if the connection is closed we cannot access data, which will be a
burden on database server when multiple clients were accessing data from in it.

2. It provides only forward Navigation i.e. allow to go either to Next Record or Table but not to
previous record or table.

3. It was a Read Only Object. Which will not to allow any changes to data present in it?

DataSet

It was a class used for holding and managing the data on a client machines apart from DataReader.It
was present under namespace. using System. Data.

Features of DataSet

1. It was also capable of holding multiple tables.

2. It was designed on Disconnected Architecture, which does not require any permanent
connection with Data Source for holding the Data.

3. It provides Scrollable Navigation that allows moving any direction.

4. It was Updatable; changes can be performed on Data present in it.

Using DataSet

The class, which is responsible for loading of Data into DataReader from DataSet, is Command in it
in the same way; DataAdapter is used for communication between Data Source and DataSet.

DataReader <--------Command <------DataSource

DataSet <------ DataAdapter <---- DataSource

Constructors of DataAdapter

DataAdapter (string SqlStmnt, Connection con)

DataAdapter (Command cmd)

MailId:ashvin.kumar01@gmail.com 56
Aprash Technologies
+91-9953904262
Example:-

DataAdpter da= new DataAdapter (“<SqlStmnt”, con);

Methods of DataAdapter

1. Fill ( ):-Used for loading data from data source to dataset.


2. Update ( ):- Used to transfer changes made on data from data source to DataSet.

DataAdapter was internally collection of four Commands

1. Select Command
2. Insert Command
3. Update Command
4. Delete Command

When we call Fill, method on adapter following things takes place.

1. Opens a connection with the DataSource.


2. Executes the Select Command under it and loads data from table to Dataset.
3. Closes the Connection.

If any changes made on DataSet, if we want to send those changes back to data source, we need to
call Update method

Accessing Data from DataSet.

DataSet is a collection of tables where each table is represented


as a class i.e. DebaTable and identified by its index position or
Name.

DataSet – Collection of Tables (Data Tables)

Syntax:-
<Dataset>.Tables [Index] or Tables [“table name”]
Ds.Tables [0] or Ds.Tables [“student”]

Every Data Table is again collection of Rows and Columns where each row is represented as a
class i.e. DataRow. Moreover, identified by its index position. Each column is represented as a class
i.e. DataColumn and identified by its index position or name.

DataTable.

1. collection of Rows [Data Row]


2. <DataTable>.Rows [index]
3. Collection of Columns [Data Columns]
4. <DataTable>.Columns [index] or [Column Name]
5. ds.Tables [0].Columns [0]
Or

MailId:ashvin.kumar01@gmail.com 57
Aprash Technologies
+91-9953904262
6. ds.Tables [0].Columns [“Sno”].

Referring to cell under a DataTable

<DataTable>.Rows [row] [column]

ds.Tables [0].Rows [0] [0]


Or
ds.Tables [0].Rows [0] [“Sno”]

Exercise 3:

Steps:
1. Add reference of Microsoft.VisualBasics assembly from.Net tab of add Reference window
Moreover, write the code under the form.

2. using System.Data.SqlClient; using Microsoft.VisualBasic;

3. Declarations:
SqlConnection con;
SqlDataAdapter ad;
SqlCommandBuilder cmb;
DataSet dst;
int rwno=0;

MailId:ashvin.kumar01@gmail.com 58
Aprash Technologies
+91-9953904262
4. Code under Form_Load
con = new SqlConnection("Data Source=localhost;Initial
Catalog=Data;Integrated Security=True;Pooling=False");
ad = new SqlDataAdapter("Select Sno,SName,Class,Fee from
students", con);
dst = new DataSet();
ad.MissingSchemaAction = MissingSchemaAction.AddWithKey;
cmb = new SqlCommandBuilder(ad);
ad.Fill(dst, "Students");
ShowData();

5. Code under FirstBtn


rwno = 0;
ShowData();

6. Code under Nextbtn

if (rwno < dst.Tables[0].Rows.Count - 1)


{
rwno += 1;
ShowData();
}
else
{
MessageBox.Show("Last Record");
}
7. Code under Previousbtn
if (rwno > 0)
{
rwno -= 1;
ShowData();
}
else
{
MessageBox.Show("First Record");
}

8. Code under Next

rwno = dst.Tables[0].Rows.Count - 1;
ShowData();

9. Code under InsertBtn

DataRow dr = dst.Tables[0].NewRow();
dr[0] = textBox1.Text; dr[1] = textBox2.Text;
dr[2] = textBox3.Text; dr[3] = textBox4.Text;
dst.Tables[0].Rows.Add(dr);
textBox1.ReadOnly = true;

MailId:ashvin.kumar01@gmail.com 59
Aprash Technologies
+91-9953904262
FirstBtn.PerformClick();//exectes the code under click of
first button

10. Code under UpdateBtn

dst.Tables[0].Rows[rwno][1]=textBox2.Text;
dst.Tables[0].Rows[rwno][2] = textBox3.Text;
dst.Tables[0].Rows[rwno][3] = textBox4.Text;
MessageBox.Show("Record Updated");

11. Code under DeleteBtn

dst.Tables[0].Rows[rwno].Delete();
MessageBox.Show("Deleted SuccessFully");
FirstBtn.PerformClick();

12. Code under SaveBtn

ad.Update(dst, "Students");
MessageBox.Show("Data Saved");

13. Code under FindBtn

int row =int.Parse( Interaction.InputBox("Enter Student


Number", "Information", "", 200, 200));
DataRow dr = dst.Tables[0].Rows.Find(row);
if (dr != null)
{
textBox1.Text = dr[0].ToString(); textBox2.Text =
dr[1].ToString();
textBox3.Text = dr[2].ToString(); textBox4.Text =
dr[3].ToString();
}
else
{
MessageBox.Show("Invalid Student Number");
}

14. Create a Function at class level

private void ShowData()


{
textBox1.Text = dst.Tables[0].Rows[rwno][0].ToString();
textBox2.Text = dst.Tables[0].Rows[rwno][1].ToString();
textBox3.Text = dst.Tables[0].Rows[rwno][2].ToString();
textBox4.Text = dst.Tables[0].Rows[rwno][3].ToString();
}
15. Execute the applicaton

MailId:ashvin.kumar01@gmail.com 60
Aprash Technologies
+91-9953904262

DataGridView:-It is a control used for displaying the data in the form of table i.e. Rows and
Columns.

1. We can bind the table directly to the control making use of the DataSource property.
<Control>.DataSource=<data Table>;
e.g. dataGridview1.DataSource=ds.Tables [0].ToString ();

2. DataGridview Control is updatable which will allow adding, modifying or delete Command,
the escepeciallty of this control was any changes performed on data of the controls reflects
directly into the datatable to which it was bound.

DataControl DataSet Database

GridView Datatable Database Tables

Exercise: DataGridview

1. Declaration of classes at class level


SqlConnection con;

SqlDataAdapter ad;
SqlCommandBuilder cmb;
DataSet ds;
2. Code under Form_Laod

MailId:ashvin.kumar01@gmail.com 61
Aprash Technologies
+91-9953904262
con = new SqlConnection("Data Source=localhost;Initial
Catalog=Data;Integrated Security=True;Pooling=False");
ad = new SqlDataAdapter("select SNo,Sname,Class,Fee From
Students", con);
ds = new DataSet();
cmb = new SqlCommandBuilder(ad);
ad.Fill(ds, "Students");//any name u can give as temp table bt
pref as table name
dataGridView1.DataSource = ds.Tables[0];

3. Code under SaveButton


ad.Update(ds, "Students");
MessageBox.Show("Transacion Succeed");
4. Code under CloseButton

this.Close();
Loading Multiple tables in Dataset

If we want to load multiple tables into a Dataset, we have two different approaches using Single
DataAdapter we can load any number of tables into a dataset by changing the select command after
calling the Fill method & load tables.

Note:-In this approach, we cannot perform changes on data on all the tables and send back to
Databases, because an adapter can hold all the four commands only for single command.

Example:-

da = new DataAdapter (“Select * from Emp “, con);


da.Fill (ds,”Emp”);
da.SelectCommand.CommandText=”Select * from Dept”;
da.Fill (ds,”Dept”);

Using separate dataadapter for each table, we can load any no of tables into the dataset in this case
we can perform changes on the data & send back to database.

Note:-In this approach, each table can be loaded from different sources.
_______________________________________________________________________________

Filtering Data Under Datasets

If we want to filter the data present under the Datasets, we have two approaches
 using Find ()
 using DataView class.

Find ():- This method can be used for filtering the data based on primary Key column of the table,
which can retrieve only single Record.

MailId:ashvin.kumar01@gmail.com 62
Aprash Technologies
+91-9953904262
DataView Class: -
This class can be used for filtering the data based on any column of the table and can retrieve
multiple rows of Data. It was a class, which was modeled on the concept of View under Databases.

A view under database was a logical table used for filtering the data, which will act as mediator
between the Data provider and Consumer.

DataView also provides similar behavior like a View, which can be used for filtering the data under
DataTable & present it to the consumer.

Using a DataView

To use a DataView we follow the below process.

1. Create a View by making use of default view property of DataTable class.

Syntax:-
DataTable  DefaultView  DataView

Example:-

DataView dv=ds.Tables [0].DefaultView;

2. Specify the condition to filter using the RowFilter property of the DataView
dv.RowFilter=<condition>
dv.RowFilter=”job =’Manager’;

Exercise:

MailId:ashvin.kumar01@gmail.com 63
Aprash Technologies
+91-9953904262
Declarations:

SqlConnection con;
SqlDataAdapter ad;
DataView dv;
DataSet dst;
bool flag = false;

Code underForm_Load

con = new SqlConnection("Data Source=localhost;Initial


Catalog=Data;Integrated Security=True;Pooling=False");
ad = new SqlDataAdapter("Select * from Dept",con);
dst = new DataSet();
ad.Fill(dst, "Dept");
ad.SelectCommand.CommandText = "Select * from Emp";
ad.Fill(dst, "Emp");
comboBox1.DataSource = dst.Tables["Dept"];
comboBox1.DisplayMember = "DName";
comboBox1.ValueMember = "DeptNo";
dataGridView1.DataSource = dst.Tables["Emp"];
flag = true;

code under comboBox1.SelectedIndex

if (flag)
{
dv = dst.Tables["Emp"].DefaultView;
dv.RowFilter = "DeptNo=" +
comboBox1.SelectedValue.ToString();
}

Note:

Using DisplayMember & ValueMember properties of ComboBox,ListBox controls,we can bind


multiple columns to the controls but only display member column will be visible to end users, we
can access either display or ValueMember in our code using SelectedItem and SeclectedValue
properties.

1. Dock Property: It was a property a property available to all controls on the container,
which can be set with six different values.
 None
 Left
 Right
 Top
 Bottom

MailId:ashvin.kumar01@gmail.com 64
Aprash Technologies
+91-9953904262
 Fill

Split: It was a container control, which comes with two panels left side and right. The benefit of this
control is the size of two panels can be adjusted at runtime .It is by default Fill

DataRelations

It was a class used for establishing parent-child relationships between tables under dataset.

DataRelation(string relName, DataColumn refKeyColumn, DataColumn pkColumn)

After creating object of DataRelaton it has to be added explicitly to the DataSet under which tables
were present using

<Dataset>.Relations.Add(DataRelation dr);

Now for deleting or updating reference key values in parent table there were some rules which
comes into the picture separately for Delete and Update known as DeleteRules $ Updaterules.These
are the Properties--

i. None -Cannot delete or update reference key value of parent table when
corresponding child records exists in child table.

ii. Cascade –we can delete or update reference key values in parent table ,but
the corresponding child records in child table will also be deleted &
updated,this is by Default applied in the case of DataSet.

iii. SetNull –We can delete or update Reference key value of parent table but
the corresponding child recordsforeign key values changes to Null.

iv. SetDefault –Same to SetNull,but in this case the corresponding chil records,
foreign key value changes to default value of the column.

Adding Rules Syntax

<DataRelation>.childKeyConstraint.DeleteRule=Rule.<rule>.

Excercise:

MailId:ashvin.kumar01@gmail.com 65
Aprash Technologies
+91-9953904262

1. Place the Split container on it.


2. Place DataGridView on each panel and set the Dock Property as Fill.
3. Declarations

SqlConnection con;
SqlDataAdapter ad1,ad2;
DataSet dst;
DataRelation dr;

4. Code under Form_Load

con = new SqlConnection("Data Source=localhost;Initial


Catalog=Data;Integrated Security=True;Pooling=False");
ad1 = new SqlDataAdapter("Select * from Emp", con);
ad2 = new SqlDataAdapter("Select * from Dept", con);
dst = new DataSet();
ad1.Fill(dst, "Emp");
ad2.Fill(dst, "Dept");

dr = new DataRelation("Dept_Emp",
dst.Tables["Dept"].Columns["DeptNo"],
dst.Tables["Emp"].Columns["DeptNo"]);
dst.Relations.Add(dr);

//Setting Default Value;


//dst.Tables["Emp"].Columns["DeptNo"].DefaultValue = 50;
dr.ChildKeyConstraint.DeleteRule = Rule.None;
//dr.ChildKeyConstraint.DeleteRule = Rule.Cascade;
//dr.ChildKeyConstraint.DeleteRule = Rule.SetNull;

dr.ChildKeyConstraint.UpdateRule = Rule.None;
//dr.ChildKeyConstraint.UpdateRule = Rule.SetDefault;
//dr.ChildKeyConstraint.UpdateRule = Rule.SetNull;

dataGridView1.DataSource = dst.Tables["Dept"];

MailId:ashvin.kumar01@gmail.com 66
Aprash Technologies
+91-9953904262
dataGridView2.DataSource = dst.Tables["Emp"];

_________________________________________________________________________________

Drawback of Datasets

A Dataset is a local copy of data which allows changes, but modifications on a local copy may lead
to Concurrency problems i.e. change performed at allocation may not be reflecting to others
immediately.
Note:-Dataset only for retrieving data but not for performing manipulations, as local copy changes
are not advised in Application Environments.

Stored Procedure

If we want to interact with databases, we write the SQl Statements in our application whenever we
run an Application the statement will compile and execute in multiple times, it will increase the
workload on database servers and may kill the performance of our application.

To overcome the above drawback we can write stmnts under Database directly with an Object
known as “Stored Procedure “& then call for Execution.

SQl Stmnts Parse + Execute

Call Sp Only Execution Sp (SQl Stmnts)

Stored procedure is Pre-Compiled block of code, which is ready for Execution will directly execute
the Stmnts without parsing (compiling) each time, so that we can improve the performance of
Database servers.

Examples:-
In Oracle:
Create procedure Add (x number, y number)

In SQl Server
Create procedure Add (@x int, @ y int)

A sp (stored procedure) can return values, to return a value we use the clause out in oracle and output
in SQL server.

Q: How to create SP in Database through Visual Studio.


Steps:

1. View Server Explorer


2. Right click on stored procedure select add new stored Procedure

MailId:ashvin.kumar01@gmail.com 67
Aprash Technologies
+91-9953904262

3.Write the Stored procedure

Example:
CREATE PROCEDURE Select_Students
AS
Begin
Select SNo,SName,Class,Fee from Students
End

Calling a stored procedure from .Net Application.

1. Command class is responsible for calling SP, so create an object of Command class by
passing the SP name as argument.

E.g. Command cmd =new Command (“Select_Students”, Con);

2. Set the Command Type property of Command as SP because by default it can execute
SqlStmnts only, after setting the property SP’s can be called.

cmd.CommandType = CommandType.StoredProcedure.

Note:-

If the SP contains DML Stmnts in it, call the ExecuteNonQuery() method on command to Execute
SP.If it contains SELECT statement int it and if we want to load the data into dataset then, create the
object of Command as argument and then call the Fill() method , so that Commands Executes the SP

MailId:ashvin.kumar01@gmail.com 68
Aprash Technologies
+91-9953904262
and Adapter loads the Data into

Exercise:

1. Declarations:

SqlConnection con;
SqlDataAdapter ad;
SqlCommand cmd;
DataSet dst;

2. Drag gridview on the form

3. Code under Form_Load

con = new SqlConnection("Data Source=localhost;Initial


Catalog=Data;Integrated Security=True;Pooling=False");
cmd = new SqlCommand("Select_Students",con);
cmd.CommandType = CommandType.StoredProcedure;
ad = new SqlDataAdapter(cmd);
dst = new DataSet();
ad.Fill(dst, "Dept");

MailId:ashvin.kumar01@gmail.com 69
Aprash Technologies
+91-9953904262
dataGridView1.DataSource = dst.Tables[0];
_____________________________________________________________

Storing an Image on Database.

1. We can store images, audio or video data also on database but only in binary Format.
2. To store an image first it should be converted into Binary Data (Byte Array) and then store
in database.
3. In this database, we use image/varbinary data type in SQLserver (max 2GB) and BLOB data
type in Oracle (max 4 GB) Binary Large Object.

Exercise:

Picture Box

Create Procedures
_______________________________________________________________
Alter PROCEDURE Select_Students(@Sno int=null)
AS
Begin
if @Sno is null
Select SNo,SName,Class,Fee from Students where status=1
Else
Select SName,Class,Fee,Picture from Students Where SNo=@Sno
and Status=1
End

create procedure Ins_Upd_Studsents(@SNo int,@SName


varchar(20),@Class int,@Fee Money,@Photo Image)
As

MailId:ashvin.kumar01@gmail.com 70
Aprash Technologies
+91-9953904262
Begin
If Not Exists (Select SNo From Students Where SNo=@Sno and
Status=1)
Insert into Students (
SNo,SName,Class,Fee,Picture)Values(@SNo,@Sname,@Class,@Fee,@Photo)
Else
Update Students Set
SName=@Sname,Class=@Class,Fee=@Fee,Picture=@Photo Where SNo=@Sno
End

Namespaces
using System.IO;
using System.Data.SqlClient;
using System.Drawing.Imaging;

Declarations
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter ad;
DataSet dst;
MemoryStream ms;

Under Form_Load

con = new SqlConnection("Data Source=localhost;Initial


Catalog=Data;Integrated Security=True;Pooling=False");
cmd = new SqlCommand();

cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;

Under InserBtn
try
{
cmd.CommandText = "Ins_Upd_Studsents";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@SNo", textBox1.Text);
cmd.Parameters.AddWithValue("@SName", textBox2.Text);
cmd.Parameters.AddWithValue("@Class", textBox3.Text);
cmd.Parameters.AddWithValue("@Fee", textBox4.Text);

//Converting Image To Byte[]

ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] data = new byte[ms.Length];
ms.Position = 0; ms.Read(data, 0, Convert.ToInt32(ms.Length));
cmd.Parameters.AddWithValue("Photo", data);
con.Open();

MailId:ashvin.kumar01@gmail.com 71
Aprash Technologies
+91-9953904262
cmd.ExecuteNonQuery();
MessageBox.Show("Executed");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}

under DeleteBtn
try
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@SNo", textBox1.Text);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Executed");
button2.PerformClick();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}

MailId:ashvin.kumar01@gmail.com 72

You might also like