Module-3 With Content
Module-3 With Content
Module-3 With Content
Prepared by
Mrs. Suma M G
Assistant Professor
Department of MCA
RNSIT
Bengaluru – 98.
Programming using C# Module - 3 Chapter – 1: Delegates and Events
Chapter -1
1.1 Delegates:
A delegate is special type of object that contains the details of a method rather than data.
OR
A delegate is a class type object, which is used to invoke a method that has been encapsulated into it at the
time of its creation.
• A delegate is a reference type variable that holds the references to a method of any class.
• Delegates are especially used for implementing events and the call-back methods.
• All delegates are implicitly derived from the System.Delegate class.
Uses:
Suppose you need to create a program that requires data, such as student information, to display it on a website.
This data can be retrieved by calling a method without having to know to compiler time which method is to be
invoked. In this case, you need to create an object of delegate and encapsulate a reference to that method
inside the delegate object.
i. Declaring a delegate:
A delegate represents a class type, it can be declared at any place where a class can be defined – outside all
classes or inside a class.
Syntax: Access-modifier delegate <return-type>
delegate_name(arg1, arg2, … argn);
Where,
Access-modifier –that controls the accessibility of the delegate and can be public, private, protected or internal.
delegate – is a keyword indicates the declaration belongs to a delegate
return-type – return type of the delegate delegate-name – is the name of the delegate
Parameter-list – the list of parameter that the delegate takes.
Example: public delegate void Compute(int x, int y);
DelegatesDemo.cs
using System;
public delegate int Operation(int p, int q);
namespace Class_Demo{
class DelegatesDemo{
public static int AddNum(int p, int q){ return (p+q); }
public int MultNum(int p, int q){ return (p*q); }
static void Main(){
Operation op1 = new Operation(AddNum);
Console.WriteLine("Value of Num1: {0}", op1(10,20));
DelegatesDemo dd = new DelegatesDemo();
Operation op2 = new Operation(dd.MultNum);
Console.WriteLine("Value of Num2: {0}", op2(5,2));
Console.ReadKey();
} } }
Delegate object satisfy the following two conditions can be made as multicast delegates:
• The return type of the delegate is void
• None of the parameters of the delegate is an output parameter but a parameter declared using the out
keyword.
Example 1.2: using System;
namespace Class_Demos{
delegate void sample(int a,int b);
class MCDelegates{
void add(int n1, int n2){
Console.WriteLine(n1+ "+" +n2+ "=" + (n1 + n2));
}
void mul(int n1, int n2) {
Console.WriteLine(n1 + "*" + n2 + "=" + (n1 * n2));
}
void sub(int n1, int n2){
Console.WriteLine(n1 + "-" + n2 + "=" + (n1 - n2));
}
static void Main(){
MCDelegates m=new MCDelegates();
sample s1=new sample(m.add);
s1 += m.sub;
s1 += m.mul;
s1(10, 20);
Console.ReadKey();
}
}
}
1.4 Events:
An event is a delegate type class member that is used by an object or a class to provide a notification to other
objects that an event has occurred. The “event” keyword can be used to declare an event.
Where,
Access-Modifier – that determines the accessibility of the event
event – is a keyword
type – type of event, which should necessarily be a delegate type
event-name – valid c# identifier.
❖ You need to detach from a source of events, you can use −= operator as follows:
Class-object⚫event-name -= new class-object⚫delegate-name(method-name);
Example 1.3: This application, named EventHandlerDemo, where you find a simple event source object.
This object contains a given internal member variable that can be set using a member function. Each time this
member variable is changed, the event source fires an event to notify any listeners that changes are pending. If
no event handlers are defined, the event source notifies about that too.
EventsDemo.cs
using System;
namespace Class_Demos{
class EventTestClass{
int nvalue; //The value to track
public delegate void ValueChangedEventHandler();//Allow a handler for the event
public event ValueChangedEventHandler Changed; //This is the event itself
//This method is used to fire the event
protected virtual void onChanged(){
if (Changed != null)
Changed();
else
Console.WriteLine("Event fired. No handler");
}
public EventTestClass(int nvalue){
SetValue(nvalue);
}
public void SetValue(int nv){
if (nvalue != nv){
nvalue = nv;
onChanged(); //Fire the event
}
}
}
class EventsDemo{
static void Main() {
EventTestClass etc = new EventTestClass(3);
etc.SetValue(5);
etc.SetValue(5);
etc.SetValue(3);
Console.WriteLine("\nPress ENTER to quit...");
Console.ReadLine();
}
}
}
Event handler: receive event notifications. When an event source notifies that an event is called, all the event
handlers that have registered for the notification of that event start executing.
An event handler may be either a static or a non-static method of a class. In case of a static method, event
handlers simply respond to a given event source and take a course of action based on the information passed to
the handler.
Example 1.4:
EventHandlerDemo.cs static void Cat(){
Console.WriteLine("Cat");
using System; }
namespace Class_Demos{
public delegate void EventHandler(); static void Dog(){
class EventHandlerDemo{ Console.WriteLine("Dog");
public static event EventHandler _show; }
static void Main(){
// Add event handlers to Show event. static void Mouse(){
_show += new EventHandler(Dog); Console.WriteLine("Mouse");
_show += new EventHandler(Cat); }
_show += new EventHandler(Mouse); }
_show += new EventHandler(Mouse); }
public EventProgram(){
this.MyEvent −= new MyDel(this.Welcomeuser);
}
public string Welcomeuser(string username) {
return "Welcome" + username;
}
static void Main(string[] args) {
EventProgram obj1 = new EventProgram();
string result = obj1.MyEvent("C# Class");
Console.WriteLine(result);
Console.ReadLine();
}
}
}
Exception Handling
2.1 Introduction:
An exception is a problem that arises during the runtime (execution of a program) such as division of a number
by zero, passing a string to a variable that holds an integer value.
C# exception handling is built upon four keywords: try, catch, finally, and throw.
ExcepDemo.cs
using System;
namespace Class_Demos{
class ExcepDemo{
static void Main(string[] args){
int div=0, number=10;
try{
div = 100 / number;
}
catch (DivideByZeroException ex){
Console.WriteLine("Exception occured : " +ex.Message);
}
finally{
Console.WriteLine("Result is: {0}", div);
Console.WriteLine("\nPress ENTER to Quit...");
Console.ReadKey();
}
}
}
}
NOTE: According to the .NET framework documentation, SystemException is meant only for
those exceptions defined by the common language runtime whereas ApplicantionException is
intended to be used by user code.
using System;
namespace Chapter5_Examples {
class TestException : ApplicationException{
public override string Message{
get{
return "This exception means something bad happened";
}
}
}
class CusException {
static void Main(){
try{
throw new TestException();
}
catch(TestException ex){
Console.WriteLine(ex);
}
Console.ReadLine();
}
}
}
Here, you have defined overridden the Message property to return an exception message to the try block. Then
this message will be caught by the catch block.
2.4 System.Exception:
System.Exception class represents an error that occurs during runtime of an application. This class is the base
class for all exceptions.
When an error occurs, either the system or the currently executing application reports it by throwing an
exception containing information about the error. Once thrown, an exception is handled by the application or
by the default exception handler.
The Exception class has several properties that make understanding an exception easier. These properties
include:
Table 2.1: Property list of the System.Exception
System.Exception
Meaning
Property
is an IDictionary that can hold arbitrary data in key-value pairs. By default, this
Data
collection is empty.
HelpLink can hold a URL(or URN) to a help describing the error in full detail.
can be used to create and preserve a series of exceptions during exception handling.
InnerException
• use to create a new exception that contains previously caught exceptions.
• The original exception can be captured by the second exception in the
InnerException property, allowing code that handles the second exception to
examine the additional information.
returns the textual description of a given error. The error message itself is set as a
Message
constructor parameter.
Source returns the name of the assembly that threw the exception.
contains a stack trace that can be used to determine where an error occurred. The
StackTrace
stack trace includes the source file name and program line number if debugging
information is available.
returns a MethodBase type, which describes numerous details about the method that
TargetSite
threw the exception.
The following table provides some of the predefined exception classes derived from the Sytem.Exception class:
using System;
namespace Chapter5_Examples{
class MultCatch{
static void Main(){
int a = 1;
try{
int b = 77 / a;
int[] arr = {1,2};
arr[4]=100;
}
catch (DivideByZeroException ex){
Console.WriteLine("Cannot be divide: {0}", ex);
}
catch (IndexOutOfRangeException ex){
Console.WriteLine("Index out of Range:{0}",ex);
}
catch (Exception ex){
Console.WriteLine("Error: {0}", ex);
}
Console.ReadKey();
}
}
}
NOTE: When you are handling multiple catch blocks, you must be aware that when an exception
is own, it will be processed by the “first available” catch.
When you use multiple catch statements, it is important to remember that the exception subclass must come
before any of their super classes. This is because a catch statement that uses a super class will catch exceptions
of that type plus any of it subclasses.
To illustrate exactly what the “first available” catch means, assume you retrofitted the previous logic as
follows:
using System;
namespace Chapter5_Examples{
class MultCatch{
static void Main(){
int a = 1;
try{
int b = 77 / a;
int[] arr = { 1, 2 };
arr[4] = 100;
}
catch (Exception ex){
Console.WriteLine("Error: {0}", ex);
}
catch (DivideByZeroException ex){
Console.WriteLine("Cannot be divide: {0}", ex);
}
catch (IndexOutOfRangeException ex){
Console.WriteLine("Index out of Range:{0}",ex);
}
Console.ReadKey();
}
}
}
The “unchecked” keyword ignores the overflow-checking of the integral-type arithmetic operations
and conversions. Arithmetic overflow is ignored, and the program displays the truncated integers from
the result.
namespace Class_Demos{
class CheckUnDemo{
static void Main()
{
byte num1, num2, result;
num1 = 127;
num2 = 127;
try {
result=unchecked((byte)(num1 * num2));
Console.WriteLine("Unchecked result:" + result);
result=checked((byte)(num1 * num2));
Console.WriteLine("Checked result:" + result);
}
catch(OverflowException ex)
{
Console.WriteLine("Exception occured:" + ex.Message);
}
finally{
Console.WriteLine("Press Enter to Quit...");
Console.ReadLine();
}
}
}
}
Introduction:
ADO.NET stands for ActiveX Data Objects and is part of the .NET framework technology that allows to
access and modify data from different data sources. It supports many types of data sources such as Microsoft
SQL Server, MySQL, Oracle, and Microsoft Access.
The .NET Framework provides a number of data providers that you can use. These data providers are used to
connect to a data source, executes commands, and retrieve results.
Various Connection Architectures: There are the following two types of connection architectures:
• Connected architecture: the application remains connected with the database throughout the
processing.
• Disconnected architecture: the application automatically connects/disconnects during the processing.
The application uses temporary data on the application side called a DataSet.
DataSet provides a disconnected representation of result sets from the Data Source, and it is completely
independent from the Data Source.
Component of DataSets:
The various components that make up a DataSet are listed
as follow:
DataReader:
The DataReader object helps in retrieving the data from a database in a forward-only, read-only mode. The
base class for all the DataReader objects is the DbDataReader class.
The DataReader object is returned as a result of calling the ExecuteReader() method of the Command
object. The DataReader object enables faster retrieval of data from databases and enhances the performance
of .NET applications by providing rapid data access speed. However, it is less preferred as compared to the
DataAdapter object because the DataReader object needs an Open connection till it completes reading
all the rows of the specified table.
• EDM (Entity Data Model): EDM consists of three main parts - Conceptual model, Mapping and
Storage model.
➢ Conceptual Model: The conceptual model contains the model classes and their relationships.
This will be independent from your database table design.
➢ Storage Model: Storage model is the database design model which includes tables, views,
stored procedures, and their relationships and keys.
➢ Mapping: Mapping consists of information about how the conceptual model is mapped to the
storage model.
➢ LINQ to Entities: LINQ to Entities is a query language used to write queries against the object model.
It returns entities, which are defined in the conceptual model. You can use your LINQ skills here.
➢ Entity SQL: Entity SQL is another query language just like LINQ to Entities. However, it is a little
more difficult than L2E and the developer will have to learn it separately.
➢ Object Service: Object service is a main entry point for accessing data from the database and to return
it back. Object service is responsible for materialization, which is the process of converting data returned
from an entity client data provider (next layer) to an entity object structure.
➢ Entity Client Data Provider: The main responsibility of this layer is to convert L2E or Entity SQL
queries into a SQL query which is understood by the underlying database. It communicates with the
ADO.Net data provider which in turn sends or retrieves data from the database.
EDM
The Connection classes of the data providers provide a ConnectionString property that you can use to
specify the connection string for connecting to a database.
Syntax: connection string for connecting to a SQL Server Express data source:
Data Source=.\SQLEXPRESS;Initial Catalog=University; Integrated Security=SSPI;
The following table is the basic connection string parameters that can use when building connection string.
Note that not all parameters are the same for every data source.
Table 3.4: Lists of basic connection string parameters
Parameter Description
• Used only if you want to connect to an attachable database file.
AttachDBFileName
Example: an .mdf file that isn't registered with the database system.
/ InitialFileName
• The full version of SQL Server doesn't support this.
• The length of time (in seconds) to wait for a connection to the server
Connect Timeout / before terminating the attempt and generating an error.
Connection Timeout
• Defaults to 15 seconds and 0 seconds represent an infinite wait.
Data Source / • The server name or network address of the database product to
Server / Address / connect to.
Add / Network
Address • Use localhost for the current computer.
Initial Catalog /
The database the connection will initially use.
Database
Integrated Security / Defaults to false. When set to true or SSPI, the .NET provider attempts
Trusted_Connection to connect to the data source using Windows integrated security.
When set to false (the default), security-sensitive information such as
the password is removed from the ConnectionString property as soon as
Persist Security Info
the connection is opened. Thus, you can't retrieve this information in your
code.
User ID The database account user ID.
Property Description
Speicfies the Command object with the SQL command to be used for
DeleteCommand
deleting a record.
FillCommandBehavior Specifies the behavior of the command used to fill the data adapter.
Specifies the Command object with the SQL command used for
InsertCommand
inserting a record.
Specifies the Command object with the SQL command to be used for
SelectCommand
retrieving records.
UpdateBatchSize Specifies the number of commands that can be executed as a batch.
Specifies the Command object with the SQL command to be used for
UpdateCommand
updating a record.
Methods Description
AddToBatch Adds a Command object to a batch that will be executed.
The DbDataReader class contains properties and methods used for reading a row in a database table. Some
of this are presented in the following tables.
Table 3.8: List of properties in DataReader class
Property Description
FieldCount Specifies the number of columns of the current row or record.
HasRows Specifies whether the current row has at least 1 row.
IsClosed Specifies whether the DbDataReader is closed.
Specifies the number of rows that has been updated, inserted, or
RecordsAffected
deleted.