Object Oriented Programming
Object Oriented Programming
Object Oriented Programming
+91-9953904262
.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.
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
MailId:[email protected] 1
Aprash Technologies
+91-9953904262
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.
1. LINQ
2. Object Initializes and collections
3. Implicit Type Array
4. Lambda Expressions
5. Automatic properties
6. Partial methods
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:[email protected] 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.
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.
Decimal or Float:
Boolean type:
MailId:[email protected] 3
Aprash Technologies
+91-9953904262
Character Type:
Char--------------------------2 byte
String------------------------variable length (depend on input text, dynamic)
Root type:
Object type: It was a type, which can store anytype of value in it.its length, is also variable.
Example:
1. var x = 100---------------x as integer
2. var x= true----------------x as bool
3. var x; ---------------------Invalid.
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;
Loops:
Foreach:
It was a special Loop designed for Processing of Array and Collections.
Jump Statements:
MailId:[email protected] 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
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).
MailId:[email protected] 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);
Array.Reverse(arr);
MailId:[email protected] 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];
MailId:[email protected] 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
using System;
class Program
{
static void Main(string[] args)
{
Console.ReadLine();
foreach (string str in args)
{
Console.WriteLine(str);
}
}
}
Output:
67
78
90
Aprash
MailId:[email protected] 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.
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:[email protected] 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));
}
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.
MailId:[email protected] 10
Aprash Technologies
+91-9953904262
}
Figure 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.
MailId:[email protected] 11
Aprash Technologies
+91-9953904262
}
}
class Circle:Figure
{
public Circle(double radius)
{
this.radius = radius;
}
public override double GetArea()
{
return 3.14 * radius * radius;
}
}
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:
MailId:[email protected] 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.
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.
Single Multiple
Class
Syntax:
As a class can inherit from another class and interface can inherit from an Interface.
Note:
1 2 3 4
MailId:[email protected] 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:[email protected] 14
Aprash Technologies
+91-9953904262
}
public void Sub(int x, int y)
{
Console.WriteLine("Result of Subtract " + (x - y));
}
static void Main(string[] args)
{
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:
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:[email protected] 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.
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.
Ans:
Right click on Project from Solution Explorer
Click Ok.
Note: Now we can consume classes of the assembly by referring with Namespace.
MailId:[email protected] 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.
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.
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:[email protected] 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");
}
MailId:[email protected] 18
Aprash Technologies
+91-9953904262
Second Step:
using System;
namespace TestAccess
{
class Two:Program
{
static void Main()
{
Two t1 = new Two();
t1.Test2();
t1.Test3();
t1.Test4();
t1.Test5();
}
}
}
Select Properties
Press ctrl+f5
MailId:[email protected] 19
Aprash Technologies
+91-9953904262
Step3:
using System;
namespace TestAccess
{
class Three:Program
{
static void Main()
{
Three T2 = new Three ();
T2.Test2();
T2.Test4();
T2.Test5();
}
}
}
Step 4:
1. Add new project naming TestAccess2 than Add a New class Four.cs
2. Adding Assembly of TestAccess Project In TestAccess2 project.
Click Ok.
using System;
namespace TestAccess2
{
class Four : TestAccess.Program
{
Four f1 = new Four();
f1.Test2();
f1.Test4();
MailId:[email protected] 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:
End Class
3.To consume the VBLibProject Class in any Other language like C Sharp by adding the
reference Of VBLibProject in CSharpProject.
MailId:[email protected] 21
Aprash Technologies
+91-9953904262
Click Ok.
using System;
namespace CsharpProject
{
class Test
{
static void Main()
{
VBLibProject.Class1 c1 = new VBLibProject.Class1();
Console.WriteLine(c1.Fun1());
Console.ReadLine();
}
}
}
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:[email protected] 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.
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;
using System;
namespace PropClass
{
MailId:[email protected] 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
MailId:[email protected] 24
Aprash Technologies
+91-9953904262
//Doesnt requre a variable cannot write the code inside
the block
public string State
{
get;
set;
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:[email protected] 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:
Example:
MailId:[email protected] 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:
Step3: Call the delegate for execution, which will execute the method internally.
Example:
Ad (100, 90);
Ad (80, 90);
Types of 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
{
MailId:[email protected] 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.
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.
4 Required to use new operator for creating a object. Using new operator to create
object was optional.
MailId:[email protected] 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.
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;
}
MailId:[email protected] 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.
using System;
namespace Structures
{
class MyStruct2
{
static void Main()
{
Mystruct My3 = new Mystruct(2000);
My3.display();
}
}
}
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
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:[email protected] 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
try
{
Statements, which will cause an exception
Statements related with Exception, which should not execute when exception occurs
}
catch (<exception> variable)
{
using System;
namespace ExceptionDemo
{
class Program
MailId:[email protected] 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:[email protected] 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.
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:[email protected] 33
Aprash Technologies
+91-9953904262
Create the object of any Exception class
Throw the object by using throw statement.
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.
MailId:[email protected] 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
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.
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:[email protected] 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:[email protected] 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-
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:[email protected] 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.
1. Lower
2. Below Normal
3. Normal (default)
4. Above Normal
5. Highest
Example:
using System;
using System.Threading;
MailId:[email protected] 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();
}
}
}
Windows Application
Traditionally we were using various type of application like Console as known as CUI.
MailId:[email protected] 39
Aprash Technologies
+91-9953904262
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.
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.
using System;
using System.Windows.Form;
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:[email protected] 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);
MailId:[email protected] 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
Object sender
EventArgs e
public MyForm1 ()
{
IntializeComponent ();
}
MailId:[email protected] 42
Aprash Technologies
+91-9953904262
Note: Run the App.cs file through Command prompt.
ADO.NET
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.
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.
Drawbacks’ of Drivers
MailId:[email protected] 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
Remote Data
Local Databases Database Sources
MailId:[email protected] 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.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.
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:[email protected] 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.
MailId:[email protected] 46
Aprash Technologies
+91-9953904262
The object of the connection class can be created in any of the following ways.
Or
Connection con= new Connection (“<ConString> “);
Example:
1.Create a new Windows Application Project.
MailId:[email protected] 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);
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.
Or
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.
MailId:[email protected] 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.
3. GetName (index): -Returns an string. Used getting the name of column for specifying
index.
Excersise1:
Steps:
MailId:[email protected] 49
Aprash Technologies
+91-9953904262
OleDbConnection con;
OleDbCommand cmd;
OleDbDataReader dr;
ShowData();
if (con.State == ConnectionState.Open)
{
con.Close();
this.Close();
}
MailId:[email protected] 50
Aprash Technologies
+91-9953904262
Excersie2:
Steps:
OleDbConnection con;
OleDbCommand cmd;
OleDbDataReader dr;
string SqlStr;
2. Create functions
private void SetStmnt()
{
if (con.State == ConnectionState.Closed)
{
MailId:[email protected] 51
Aprash Technologies
+91-9953904262
con.Open();
}
cmd.CommandText = SqlStr;
con.Open();
}
LoadData ();
MailId:[email protected] 52
Aprash Technologies
+91-9953904262
textBox1.Text = cmd.ExecuteScalar().ToString();
textBox2.Focus();
{
SqlStr="insert into Emp(EId,Ename,City)values("+textBox1.Text+",
'"+textBox2.Text+" ','"+textBox3.Text+"')";
ExecuteDML();
}
if (con.State == ConnectionState.Open)
{
con.Close();
this.Close();
}
9. Execute Application
Create the table in SQL Server with following fields. In addition, set status field as default value is
one (1).
MailId:[email protected] 53
Aprash Technologies
+91-9953904262
Add some values in it.
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
string SqlStr;
MailId:[email protected] 54
Aprash Technologies
+91-9953904262
}
else
{
MessageBox.Show("Last Record");
}
}
4. under form_load Event
ShowData();
DataReader: - It is a class modeled on table that can be used for holding data on Client machine.
Features of DataReader.
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 ");
MailId:[email protected] 55
Aprash Technologies
+91-9953904262
Note:-Use the NextResult () Method on DataReader object to navigate from current table to next
Table.
Drawbacks of DataReader
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
2. It was designed on Disconnected Architecture, which does not require any permanent
connection with Data Source for holding the Data.
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.
Constructors of DataAdapter
MailId:[email protected] 56
Aprash Technologies
+91-9953904262
Example:-
Methods of DataAdapter
1. Select Command
2. Insert Command
3. Update Command
4. Delete Command
If any changes made on DataSet, if we want to send those changes back to data source, we need to
call Update method
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.
MailId:[email protected] 57
Aprash Technologies
+91-9953904262
6. ds.Tables [0].Columns [“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.
3. Declarations:
SqlConnection con;
SqlDataAdapter ad;
SqlCommandBuilder cmb;
DataSet dst;
int rwno=0;
MailId:[email protected] 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();
rwno = dst.Tables[0].Rows.Count - 1;
ShowData();
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:[email protected] 59
Aprash Technologies
+91-9953904262
FirstBtn.PerformClick();//exectes the code under click of
first button
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");
dst.Tables[0].Rows[rwno].Delete();
MessageBox.Show("Deleted SuccessFully");
FirstBtn.PerformClick();
ad.Update(dst, "Students");
MessageBox.Show("Data Saved");
MailId:[email protected] 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.
Exercise: DataGridview
SqlDataAdapter ad;
SqlCommandBuilder cmb;
DataSet ds;
2. Code under Form_Laod
MailId:[email protected] 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];
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:-
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.
_______________________________________________________________________________
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:[email protected] 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
Syntax:-
DataTable DefaultView DataView
Example:-
2. Specify the condition to filter using the RowFilter property of the DataView
dv.RowFilter=<condition>
dv.RowFilter=”job =’Manager’;
Exercise:
MailId:[email protected] 63
Aprash Technologies
+91-9953904262
Declarations:
SqlConnection con;
SqlDataAdapter ad;
DataView dv;
DataSet dst;
bool flag = false;
Code underForm_Load
if (flag)
{
dv = dst.Tables["Emp"].DefaultView;
dv.RowFilter = "DeptNo=" +
comboBox1.SelectedValue.ToString();
}
Note:
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:[email protected] 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.
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.
<DataRelation>.childKeyConstraint.DeleteRule=Rule.<rule>.
Excercise:
MailId:[email protected] 65
Aprash Technologies
+91-9953904262
SqlConnection con;
SqlDataAdapter ad1,ad2;
DataSet dst;
DataRelation dr;
dr = new DataRelation("Dept_Emp",
dst.Tables["Dept"].Columns["DeptNo"],
dst.Tables["Emp"].Columns["DeptNo"]);
dst.Relations.Add(dr);
dr.ChildKeyConstraint.UpdateRule = Rule.None;
//dr.ChildKeyConstraint.UpdateRule = Rule.SetDefault;
//dr.ChildKeyConstraint.UpdateRule = Rule.SetNull;
dataGridView1.DataSource = dst.Tables["Dept"];
MailId:[email protected] 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.
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.
MailId:[email protected] 67
Aprash Technologies
+91-9953904262
Example:
CREATE PROCEDURE Select_Students
AS
Begin
Select SNo,SName,Class,Fee from Students
End
1. Command class is responsible for calling SP, so create an object of Command class by
passing the SP name as argument.
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:[email protected] 68
Aprash Technologies
+91-9953904262
and Adapter loads the Data into
Exercise:
1. Declarations:
SqlConnection con;
SqlDataAdapter ad;
SqlCommand cmd;
DataSet dst;
MailId:[email protected] 69
Aprash Technologies
+91-9953904262
dataGridView1.DataSource = dst.Tables[0];
_____________________________________________________________
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
MailId:[email protected] 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
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);
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:[email protected] 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:[email protected] 72