You are on page 1of 40

Event-Driven Programming

Tutorial – class
By: Dires B.
Outlines
⁃ Overview of Event-Driven Programming
⁃ Overview of .NET Framework
⁃ Object Oriented Programming
⁃ File Handling
⁃ ADO.NET (ActiveX Data Object)
What is Event-Driven Programming?
• Event-driven programming (EDP) is revolutionizing the
software development industry and is increasingly being used
in modern development.
• Its spread was stimulated by Windows and the dissemination
of visual RAD environments.
• As its name suggests, the programming approach focuses on
events. The latter may be user-initiated, systemic, and
program-generated.
• The most common areas of EDP application today include
the creation of GUIs, server apps, and multi-player game
development.
• Unlike old-style programs controlling the user’s options and
predetermining the flow of events, more adaptive and
innovative programming came up with a graphical user
interface (GUI).
Cont..
• The GUI changed the human-computer interaction by giving
users multiple options in the form of drop-down menus,
windows, buttons, checkboxes, etc. As a result, people gained
the ability to select one of the many possible instructions on
their own rather than having to follow the planned order of
activities set by the computer.
What is .NET Framework?
• .NET Framework is a software development platform
developed by Microsoft for building and running Windows
applications.
• The .NET framework consists of developer tools,
programming languages, and libraries to build desktop and
web applications. It is also used to build websites, web
services, and games.
• The Microsoft .NET framework can be used to create both –
Form-based and Web-based applications. Web services can
also be developed using the .NET framework.
.NET Framework Architecture
• .NET Framework Architecture is a programming model for
the .NET platform that provides an execution environment
and integration with various programming languages for
simple development and deployment of various Windows
and desktop applications.
Object Oriented Programming(OOP)
What is OOP?
• Procedural programming is about writing procedures or
methods that perform operations on the data, while OOP is
about creating objects that contain both data and methods.
• OOP has several advantages over procedural programming:
⁃ OOP is faster and easier to execute
⁃ OOP provides a clear structure for the programs
⁃ OOP helps to keep the C# code DRY "Don't Repeat Yourself", and
makes the code easier to maintain, modify and debug
⁃ OOP makes it possible to create full reusable applications with less
code and shorter development time
• The "Don't Repeat Yourself" (DRY) principle is about
reducing the repetition of code. You should extract out the
codes that are common for the application, and place them at
a single place and reuse them instead of repeating it.
Classes and Objects
• A Class is like an object constructor, or a "blueprint" for creating
objects.
• Everything in C# is associated with classes and objects, along with
its attributes and methods.
• For example: in real life, a car is an object. The car has attributes,
such as weight and color, and methods, such as drive and brake.
Example:
class Car
{
string color = "red";
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}
}
When a variable is declared directly in a class, it is often referred to
as a field (or attribute).
Note that we use the dot syntax (.) to access variables/fields inside a
class (myObj.color).
Class Members
• Fields and methods inside classes are often referred to as
"Class Members":
• Example Create a Car class with three class members:
two fields and one method.
Example:
class Car
{
string color = "red"; //field
int speed = 200; //field
public void displayInfo() //method
{
Console.Writeline(“The Car is going as fast as it can “);
}
}
Constructors
• A constructor is a special method that is used to initialize objects.
• The advantage of a constructor, is that it is called when an object
of a class is created. It can be used to set initial values for fields.
Example:
class Car
{
public string model; //field
int speed = 200; //field
public Car() //defining constructor
{
model = “Mustang”;
}
static void Main(string[] args)
{
Car Ford = new Car();// Creating of object of the Car and
// instantiate the object by the constructor
Console.WriteLine(Ford.model);//accessing of the field model
}
Access Modifiers
• C# has the following access modifiers:

Modifier Description
public The code is accessible for all classes
private The code is only accessible within the same class
The code is accessible within the same class, or in a class
protected
that is inherited from that class.
class Car
{
private string model = "Mustang";
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}
Note the field “model” didn’t accessible out of Car class.
Because the field is declared in the access modifier private.
Basic of OOP
Encapsulation: in object oriented programming
methodology, prevents access to implementation details.
Inheritance: It is useful for code reusability: reuse fields
and methods of an existing class when you create a new
class.
Polymorphism: can be static (Method overloading) or
dynamic (Method Overriding). In static polymorphism, the
response to a function is determined at the compile time. In
dynamic polymorphism, it is decided at run-time.
Abstraction : allows making relevant information visible and hide
detail implementation.
Interface : contain only the declaration of the members. It is
the responsibility of the deriving class to define the members.
Summery
• Object-Oriented Programming (OOP) is a programming
paradigm in computer science that relies on the concept of
classes and objects.
• It is used to structure a software program into simple,
reusable pieces of code blueprints (usually called classes),
which are used to create individual instances of objects.
• A class is an abstract blueprint that creates more specific,
concrete objects.
• An object can be defined as a data field that has unique
attributes and behavior of a class.
• Classes contain functions called methods that are available
only to objects of that type. These functions are defined
within the class and perform some action helpful to that
specific object type.
File Handling
Basics of File Handling
• The term File Handling refers to the various operations like
creating the file, reading from the file, writing to the file,
appending the file, etc.
• There are two basic operation which is mostly used in file
handling is reading and writing of the file.
• The file becomes stream when we open the file for writing
and reading. A stream is a sequence of bytes which is used
for communication.
• Two stream can be formed from file
• input stream which is used to read the file
• output stream is used to write in the file
• In C#, System.IO namespace contains classes which handle
input and output streams and provide information about file
and directory structure.
Basics of File Handling(cont..)
File-Handling-Class-Hierarchy
Basics of File Handling(cont..)
The System.IO Namespace has various classes and types that allow
reading of files and writing to files. Some of the classes in this
namespace are given as follows:
Classes Description
FileStream This class provides a Stream for a file, supporting both
synchronous and asynchronous read and write operations.
StreamReader This class implements a TextReader that reads characters
from a byte stream in a particular encoding.
StreamWriter This class implements a TextWriter for writing characters to a
stream in a particular encoding.
This class represents a reader that can read a sequential series
TextReader
of characters.
TextWriter This class represents a writer that can write a sequential
series of characters. This class is abstract.
FileStream Class
• FileStream class is used to read from and write to any location within a file.
• It supports both synchronous as well as asynchronous read and write operations.
‣ FileStream Class implementation source code
using System;
using System.IO;
namespace FileHandling
{
public class FileStreamExample
{
public static void Main(string[] args)
{
FileStream fi = new FileStream("e:\\file.txt", FileMode.OpenOrCreate);
fi.WriteByte(12);
fi.WriteByte(6);
fi.WriteByte(30);
fi.Close();
FileStream Class(cont..)
FileStream fo = new FileStream("e:\\file.txt", FileMode.OpenOrCreate);
int i = 0;
Console.WriteLine("The contents of the file are:");
while ((i = fo.ReadByte()) != -1)
{
Console.WriteLine(i);
}
fo.Close();
}
}
StreamWriter Class
• The StreamWriter class implements TextWriter for writing character
to stream in a particular format.
• Some of the methods used by StreamWriter class are:

Method Description

Closes the current StreamWriter object and stream associate


Close()
with it.

Clears all the data from the buffer and write it in the stream
Flush()
associate with it.

Write data to the stream. It has different overloads for


Write()
different data types to write in stream.

It is same as Write() but it adds the newline character at the


WriteLine()
end of the data.
StreamWriter Class(cont..)
• StreamWriter class implementation source code

using System;
using System.IO;
namespace FileHandling
{
public class StreamWriterExample
{
public static void Main(string[] args)
{
FileStream fs = new FileStream("e:\\file.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("File Handling in C#");
sw.Close();
fs.Close();
}
}
}
StreamReader Class
• The StreamReader class implements TextReader for reading
character from the stream in a particular format.
• The class contains the following method which are mostly used.
Method Description

Closes the current StreamReader object and stream associate


Close()
with it.

Peek() Returns the next available character but does not consume it.

Reads the next character in input stream and increment


Read()
characters position by one in the stream

ReadLin Reads a line from the input stream and return the data in form
e() of string

Seek() It is use to read/write at the specific location from a file


StreamReader Class(cont..)
• StreamReader class implementation source code
using System;
using System.IO;
namespace FileHandling
{
public class StreamReaderExample
{
public static void Main(string[] args)
{
FileStream fs = new FileStream("e:\\file.txt", FileMode.OpenOrCreate);
StreamReader sr = new StreamReader(fs);
string data = sr.ReadLine();
Console.WriteLine("The data in the file is as follows:");
Console.WriteLine(data);
sr.Close();
fs.Close();
}
}
}
TextReader Class and TextWriter Class
• The TextReader Class has a reader that reads the characters from the fil while
TextWriter Class has a writer that writes the characters into the file.
• TextReader and TextWriter Class implementation source code
using System;
using System.IO;
namespace FileHandlingDemo
{
class Example
{
static void Main(string[] args)
{
using (TextWriter tw = File.CreateText("e:\\file.txt"))
{
tw.WriteLine("C# File Handling");
tw.WriteLine("TextReader Class and TextWriter Class");
}
using (TextReader tr = File.OpenText("e:\\file.txt"))
{
Console.WriteLine(tr.ReadToEnd());
}
}
}
}
Summery
• A file is a collection of data stored on a disk with a specific name,
extension, and directory path. When you open File using C# for
reading and writing purposes it becomes Stream.
• A stream is a sequence of bytes traveling from a source to a
destination over a communication path. It has two main streams:
• Input stream: is used to read data from a file, which is known as a read
operation.
• Output stream: is used to write data into a file, which is known as a write
operation.
• The need to learn file handling is:
• As a programmer, several times you need to save information on a disk.
• You may not get a database everywhere to save the information
• Your project may require saving information in a text file, doc file, xls file,
pdf file, etc.
ADO.NET (Database Programming)
What Is ADO.NET?
• Database access technology developed by Microsoft as part
of the .NET framework known as ActiveX Data Object or
ADO.NET.
• ADO.NET is a module of .NET Framework which is used to
establish connection between application and data sources.
• Data sources can be such as:
• SQL Server (SqlClient)
• Oracle database (OracleClient)
• Microsoft Access (OleDb)
• XML.
• ADO.NET consists of classes that can be used to
connect, retrieve, insert, update and delete data.
• All the ADO.NET classes are located into
System.Data.dll and integrated with XML classes
located into System.Xml.dll.
Cont..
• ADO.NET has two main components that are used for
accessing and manipulating data .
1) .NET Framework Data Providers
2) The DataSet
1) .NET Farmwork Data Providers are designed for data
manipulation and fast access to data.
⁃ It provides various objects such as Connection, Command,
DataReader and DataAdapter that are used to perform database
operations.
2) The DataSet is used to access data independently from
any data resource.
⁃ It contains a collection of one or more DataTable objects
of data.
DataSet can work in disconnected connection, but DataReader
does not perform in disconnected mode.
ADO.NET Architecture
.NET Framework data provider
.NET Framework data provider Description
It provides data access for Microsoft SQL
.NET Framework Data Provider for SQL
Server. It requires the
Server
System.Data.SqlClient namespace.
It is used to connect with OLE DB. It requires
.NET Framework Data Provider for OLE DB
the System.Data.OleDb namespace.
It is used to connect to data sources by using
.NET Framework Data Provider for ODBC ODBC. It requires the System.Data.Odbc
namespace.
It is used for Oracle data sources. It uses the
.NET Framework Data Provider for Oracle
System.Data.OracleClient namespace.

It provides data access for Entity Data Model


EntityClient Provider applications. It requires the
System.Data.EntityClient namespace.

It provides data access for Microsoft SQL


.NET Framework Data Provider for SQL
Server Compact 4.0. It requires the
Server Compact 4.0.
System.Data.SqlServerCe namespace.
.NET Framework Data Providers Objects
Object Description
It is used to establish a connection to a
Connection
specific data source.
It is used to execute queries to perform
Command
database operations.
It is used to read data from data source.
DataReader The DbDataReader is a base class for all
DataReader objects.
It populates a DataSet and resolves
updates with the data source. The base
DataAdapter
class for all DataAdapter objects is the
DbDataAdapter class.
.NET Framework Data Providers for SQL Server
• Data provider for SQL Server is a lightweight component.
• It provides better performance because it directly access SQL Server
without any middle connectivity layer.
• The .NET Framework Data Provider for SQL Server classes is located in
the System.Data.SqlClient namespace.

• System.Data.SqlClient contains the following important classes:


• SqlConnection : It is used to create SQL Server connection.
• SqlCommand It is used to execute database queries.
• SqlDataAdapter: It represents a set of data commands and a database
connection that are used to fill the DataSet.
• SqlDataReader : It is used to read rows from a SQL Server database.
• SqlException: This class is used to throw SQL exceptions. It throws an
exception when an error is occurred.

• Note that all those classes are sealed class, so we cannot inherit
from it.
.NET Framework Data Provider for Oracle

• This data provider supports both local and distributed transactions.


• Oracle Data Provider classes are located into System.Data.OracleClient
namespace. We must use both System.Data.OracleClient and System.data
to connect our application with the Oracle database.

Data Provider Note


.NET Framework Data Provider It is good for middle-tier applications, single-
for SQL Server tier applications that use Microsoft SQL Server.
.NET Framework Data Provider It is good for single-tier applications that use
for OLE DB Microsoft Access databases.
.NET Framework Data Provider It is good for middle and single-tier applications
for ODBC that use ODBC data sources.
.NET Framework Data Provider It is good for middle and single-tier applications
for Oracle that use Oracle data sources.
ADO.NET SqlConnection Class

• SqlConnection class uses SqlDataAdapter and SqlCommand


classes together to increase performance when connecting to a
Microsoft SQL Server database.
• SqlConnection Signature
SqlConnection conn = new SqlConnection(("Data Source=localhost;Initial
Catalog=wdu_db;Integrated Security=True"));
• SqlConnection Constructors
Constructors Description
It is used to initializes a new instance of the
SqlConnection()
SqlConnection class.
It is used to initialize a new instance of the
SqlConnection(String)0 SqlConnection class and takes connection string
as an argument.
It is used to initialize a new instance of the
SqlConnection(String, SqlConnection class that takes two parameters.
SqlCredential) First is connection string and second is sql
credentials.
ADO.NET SqlCommand Class

• SqlCommand is used to store and execute SQL statement for SQL


Server database. It is a sealed class so that cannot be inherited.
• SqlCommand Signature
SqlCommand cm = new SqlCommand("select * from student", conn);
• SqlCommand Constructors
Constructor Description
It is used to initialize a new instance of the
SqlCommand()
SqlCommand class.
It is used to initialize a new instance of the
SqlCommand(String)
SqlCommand class with a string parameter.
It is used to initialize a new instance of the
SqlCommand(String,
SqlCommand class. It takes two parameters, first is
SqlConnection)
query string and second is connection string.
SqlCommand(String, It is used to initialize a new instance of the
SqlConnection, SqlCommand class. It takes three parameters query,
SqlTransaction) connection and transaction string respectively.
ADO.NET SqlDataReader Class
• SqlDataReader class is used to read data from SQL Server database. It reads data in
forward-only stream of rows from a SQL Server database.
Example
SqlConnection conn = new SqlConnection("Data
Source=localhost;Initial Catalog=wdu_db;Integrated Security=True”);
try{
SqlCommand cm = new SqlCommand("select * from student", conn);
conn.Open();
SqlDataReader sdr = cm.ExecuteReader();
while (sdr.Read())
{
Console.WriteLine(sdr["name"]+" "+ sdr["email"]);

}
}

catch (Exception e)
{
MessageBox.Show(ex.ToString());
}
finally
{
con.Close();
}
ADO.NET DataAdapter Class

• The DataAdapter works as a bridge between a DataSet and a data


source to retrieve data.
• DataAdapter is a class that represents a set of SQL commands and a
database connection. It can be used to fill the DataSet and update the
data source.
• DataAdapter class signature
using (SqlConnection con = new SqlConnection("Data
Source=localhost;Initial Catalog=wdu_db;Integrated
Security=True"))
{
SqlDataAdapter sde = new SqlDataAdapter("Select * from
student", con);
DataSet ds = new DataSet();
sde.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
Summery

• ADO.NET is a set of technologies that provides native access


to data in the Microsoft .NET Framework.
• It is designed to support an n-tier programming environment
and to handle a disconnected data architecture.
• ADO.NET is tightly integrated with XML and uses a common
data representation that can combine data from disparate
sources, including XML.
• One of the major components of ADO.NET is the .NET
Framework data provider, which connects to a database,
executes commands, and retrieve results.
• Generally ADO.NET is a bridge between the front end
controls and the back end database.
Thank you

You might also like