You are on page 1of 231

DCIT 318

PROGRAMMING II

Session 1 – Introduction to C# and .NET


framework
Lecturer: Mr. Paul Ammah, CSD
Contact Information: pammah@ug.edu.gh

Department of Computer Science


School of Physical and Mathematical Sciences
2022/2023
Introduction to .NET
• The .NET Framework is one of the most popular widely used
integrated software development environments today.
• .NET Framework allows the integration of codes written in
different programming languages.
• Earlier each language required different execution
environments.
• But with the introduction of .NET framework this problem was
solved.
• .NET Framework provides programmers a single platform to
develop Windows and Web applications in various
programming languages, such as Visual Basic(VB) and Visual
C#
Slide 2
Generations of .NET Framework
• .NET Framework 1.0
• .NET Framework 1.1
• .NET Framework 2.0
• .NET Framework 3.0
• .NET Framework 3.5
• .NET Framework 4.0(release year-2010)
• .NET Framework 4.5(release year-2012)
• .NET Framework 4.6(release year-2015)
• .NET Framework 4.7(release year-2017)
• ….
• .NET Framework 6.0
• .NET Framework 7.0
Slide 3
Benefits of .NET Framework
• Consistent Programming Model: By using this model different tasks such
as Database Connectivity, Reading from and Writing to files is performed.
• Language Interoperability: Piece of code written in one language can be
used in another language.
• Automatic Management of Resources: Garbage Collection(Part of CLR)
performs the allocation and de allocation of all the resources such as files,
memory and database connections. Programmer does not need to provide
code for memory management tasks.
• Ease of Deployment: Applications coded under .NET Framework can be
easily deployed(installed on computer) because deployment is done in the
form of assemblies which are the single , logical deployment unit and
hence registries does not need to store information about components and
applications.

Slide 4
Core Components of .NET Framework

• Common Language Runtime


• Common Type System
• Common Language Specification
• .NET Framework Class Library(Base Class Library)
• Windows Forms
• ASP.NET and ASP.NET Ajax
• ADO.NET
• WPF and WCF

Slide 5
.NET Architecture

Slide 6
.NET Framework
ASP.NET Windows Forms

Web Services Web Forms Controls Drawing

ASP.NET Application Services Windows Application Services

Framework Class Library

ADO.NET XML Threading IO

Network Security Diagnostics Etc.

Common Language Runtime

Memory Management Common Type System Lifecycle Monitoring

Slide 7
Common Language Runtime
• A Common Language Runtime (CLR) provides essential runtime
services such as automatic memory management and exception
handling.
• The CLR is at the core of the .NET platform - the execution
engine. A unifying framework for designing, developing,
deploying, and executing distributed components and
applications.
• Loads and runs code written in any runtime-aware programming
language
• Manages memory, thread execution, type safety verification and
garbage collection.
• Performs compilation (Just In-time Compiler)
• Makes use of a new common type system capable of expressing
the semantics of most modern programming languages.
• The common type system defines a standard set of types and
rules for creating new types.
Slide 8
MSIL and JIT Compilation
• Source code is compiled into MSIL (Microsoft Intermediate Language).
Similar to Java bytecode.
• MSIL allows for runtime type-safety and security, as well as portable
execution platforms (all Windows).
• MSIL code cannot play tricks with pointers or illegal type conversions.
• The MSIL architecture results in apps that run in one address space - thus
much less OS overhead.
• Compilers also produce “metadata”:
– Definitions of each type in your code.
– Signatures of each type’s members.
– Members that your code references.
– Other runtime data for the CLR.
• Metadata along with the MSIL enables code to be self-describing - no need
for separate type libraries, IDL, or registry entries.
• When code is executed by the CLR, a JIT compilation step occurs.
• Code is compiled method-by-method to native machine code.
Slide 9
Packaging: Modules, Types,
Assemblies, and the Manifest

Assembly

Manifest

Module

Metadata

MSIL

Type Type Type

Slide 10
Packaging: Modules, Types,
Assemblies, and the Manifest
• A module refers to a binary, such as an EXE or DLL.
• Modules contain definitions of types, such as classes, interfaces,
structures, and enumerations.
• An assembly contains a manifest, which is a catalog of
component metadata containing:
– Assembly name.
– Version (major, minor, revision, build).
– Assembly file list - all files contained in the assembly.
– Type references - mapping the managed types included in the assembly
with the files that contain them.
– Scope - private or shared.
– Referenced assemblies.
• No MSIL code can be executed unless there is a manifest
associated with it.

Slide 11
.NET Tools
Microsoft Visual Studio .NET and Microsoft .NET
Framework supplies complete solution for
developers to build, deploy and run XML services

Visual Studio .NET is the next generation of


Microsoft’s popular multi-language development
tool built especially for .NET

Enhances existing languages like Visual Basic


with new OO features

Introduces C#
Slide 12
Microsoft C#
• A modern, object-oriented programming language
built from the ground up to exploit the power of
XML-based Web services on the .NET platform.
• The main design goal of C# was simplicity rather than
pure power.
• Features of C#
Simplicity Type Safety
Consistency Version Control
Modernity Compatibility
Object Orientation Flexibility

Slide 13
C# Language
• C# is type-safe object-oriented language
• Enables developers to build a variety of secure and
robust applications
• Very similar in syntax to C, C++, and Java.
• Syntax is highly expressive.
• Key features: nullable value type, enumerations,
delegates, lambda expressions, and direct memory
access

Slide 14
Compile-time and Run-time
Relationships of C#

Slide 15
C# Program Structure
• Namespaces
– Contain types and other namespaces
• Type declarations
– Classes, structs, interfaces, enums,
and delegates
• Members
– Constants, fields, methods, properties, indexers, events,
operators, constructors, destructors
• Organization
– No header files, code written “in-line”
– No declaration order dependence

Slide 16
Type System
• Value types
– Directly contain data
– Cannot be null
• Reference types
– Contain references to objects
– May be null
int i = 123;
string s = "Hello world";

Slide 17
Type System
• Value types
– Primitives int i;
– Enums enum State { Off, On }
– Structs struct Point { int x, y; }
• Reference types
– Classes class Foo: Bar, IFoo {...}
– Interfaces interface IFoo: IBar
{...}
– Arrays string[] a = new string[10];
– Delegates delegate void Empty();
Slide 18
Predefined Types
• C# predefined types
– Reference object, string
– Signed sbyte, short, int, long
– Unsigned byte, ushort, uint, ulong
– Character char
– Floating-point float, double, decimal
– Logical bool
• Predefined types are simply aliases for system-
provided types
– For example, int == System.Int32

Slide 19
Classes
• Single inheritance
• Multiple interface implementation
• Class members
– Constants, fields, methods, properties, indexers, events,
operators, constructors, destructors
– Static and instance members
– Nested types
• Member access
– public, protected, internal, private

Slide 20
Structs
• Like classes, except
– Stored in-line, not heap allocated
– Assignment copies data, not reference
– No inheritance
• Ideal for light weight objects
– Complex, point, rectangle, color
– int, float, double, etc., are all structs
• Benefits
– No heap allocation, less GC pressure
– More efficient use of memory

Slide 21
Decision Statements
• If..else if..else
• Tenary Operators (?:)
• Switch Statements

Slide 22
The if statement
void DisplayCharacter(char ch)
{
if (char.IsUpper(ch))
{
Console.WriteLine($"An uppercase letter: {ch}");
}
else if (char.IsLower(ch))
{
Console.WriteLine($"A lowercase letter: {ch}");
}
else if (char.IsDigit(ch))
{
Console.WriteLine($"A digit: {ch}");
}
else
{
Console.WriteLine($"Not alphanumeric character: {ch}");
}
}

Slide 23
Switch Statements
void DisplayMeasurement(double measurement)
{
switch (measurement)
{
case < 0.0:
Console.WriteLine($"Measured value is {measurement}; too low.");
break;

case > 15.0:


Console.WriteLine($"Measured value is {measurement}; too high.");
break;

case double.NaN:
Console.WriteLine("Failed measurement.");
break;

default:
Console.WriteLine($"Measured value is {measurement}.");
break;
}
}

Slide 24
Tenary Operator
• The conditional operator ?:, also known as the
ternary conditional operator, evaluates a Boolean
expression and returns the result of one of the two
expressions, depending on whether the Boolean
expression evaluates to true or false

string weatherDisplayString = tempInCelsius < 20.0 ? "Cold."


: "Perfect!";

Slide 25
Iteration statements
• while loop
• For loop
• Foreach loop
• Do loop

Slide 26
The for statement
• The for statement executes a statement or a block of
statements while a specified Boolean expression
evaluates to true

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


{
Console.Write(i);
}

Slide 27
The foreach statement
• The foreach statement executes a statement or a block of statements for
each element in an instance of the type that implements the
System.Collections.IEnumerable or
System.Collections.Generic.IEnumerable<T> interface

var fibNumbers = new List<int> { 0, 1, 1, 2, 3, 5};


foreach (int element in fibNumbers)
{
Console.Write($"{element} ");
}

Slide 28
The while statement
• The while statement executes a statement or a block
of statements while a specified Boolean expression
evaluates to true
int n = 0;
while (n < 5)
{
Console.Write(n);
n++;
}
Slide 29
The do statement
• The do statement executes a statement or a block of statements while a
specified Boolean expression evaluates to true.
• Because that expression is evaluated after each execution of the loop, a do
loop executes one or more times.
int n = 0;
do
{
Console.Write(n);
n++;
} while (n < 5);

Slide 30
C# Special Characters
• Special characters are predefined, contextual
characters that modify the program element (a literal
string, an identifier, or an attribute name) to which
they are prepended.
• C# supports the following special characters:
– @, the verbatim identifier character.
– $, the interpolated string character.

Slide 31
Verbatim text - @ in variables, attributes, and string
literals
• The @ special character serves as a verbatim
identifier.
• You use it in the following ways:
– To indicate that a string literal is to be interpreted verbatim
– To use C# keywords as identifiers
– To enable the compiler to distinguish between attributes in
cases of a naming conflict

Slide 32
Verbatim String Literal
string filename1 = @"c:\documents\files\u0066.txt";
string filename2 = "c:\\documents\\files\\u0066.txt";

Console.WriteLine(filename1);
Console.WriteLine(filename2);

// The example displays the following output:

-> c:\documents\files\u0066.txt
-> c:\documents\files\u0066.txt

Slide 33
C# keywords as identifiers
• The @ character prefixes a code element that the compiler is to interpret as
an identifier rather than a C# keyword
string[] @for = { "John", "James", "Joan", "Jamie" };
for (int ctr = 0; ctr < @for.Length; ctr++)
{
Console.WriteLine($"Here is your gift, {@for[ctr]}!");
}
// The example displays the following output:
// Here is your gift, John!
// Here is your gift, James!
// Here is your gift, Joan!
// Here is your gift, Jamie!

Slide 34
String interpolation using $
• The $ special character identifies a string literal as an
interpolated string.
• An interpolated string is a string literal that might
contain interpolation expressions
• When an interpolated string is resolved to a result
string, items with interpolation expressions are
replaced by the string representations of the
expression results.
• String interpolation provides a more readable,
convenient syntax to format strings.

Slide 35
String interpolation using $
string name = "Mark";
var date = DateTime.Now;

// Composite formatting:
Console.WriteLine("Hello, {0}! Today is {1}, it's
{2:HH:mm} now.", name, date.DayOfWeek, date);

// String interpolation:
Console.WriteLine(
$"Hello, {name}! Today is {date.DayOfWeek}, it’s
{date:HH:mm} now.”
);

Slide 36
Raw string literal text - """
• A raw string literal starts and ends with a minimum of three
double quote (") characters
• Raw string literals can span multiple lines
var xml = """
<element attr="content">
<body>
</body>
</element>
""";

Slide 37
DCIT 318
PROGRAMMING II

Session 2 – OOP using C#

Lecturer: Mr. Paul Ammah, CSD


Contact Information: pammah@ug.edu.gh

Department of Computer Science


School of Physical and Mathematical Sciences
2022/2023
Defining a class
using System;
namespace Lecture2
{
public class Person
{
}
}

Slide 2
Access Modifiers

Slide 3
Class Members
• Classes and structs have members that represent
their data and behavior.
• A class's members include all the members declared
in the class, along with all members (except
constructors and finalizers) declared in all classes in
its inheritance hierarchy

Slide 4
Class Members contd.
• Fields are variables declared at class scope. A field may be a built-in
numeric type or an instance of another class
• Constants are fields whose value is set at compile time and cannot
be changed.
• Properties are methods on a class that are accessed as if they were
fields on that class
• Methods define the actions that a class can perform.
• Constructors are methods that are called when the object is first
created.
• Indexers enable an object to be indexed in a manner similar to
arrays.
• Operators: Overloaded operators are considered type members
• Events provide notifications about occurrences, such as button
clicks or the successful completion of a method, to other objects

Slide 5
Fields
• A class or struct may have instance fields, static
fields, or both.
• Generally, you should declare fields as private or
protected accessibility
• Fields typically store the data that must be accessible
to more than one type method and must be stored
for longer than the lifetime of any single method

Slide 6
Fields
public class CalendarEntry
{

// private field (Located near wrapping "Date" property).


private DateTime _date;

// Public property exposes _date field safely.


public DateTime Date
{
get
{
return _date;
}
set
{
// Set some reasonable boundaries for likely birth dates.
if (value.Year > 1900 && value.Year <= DateTime.Today.Year)
{
_date = value;
}
else
{
throw new ArgumentOutOfRangeException("Date");
}
}
}
Slide 7
}
Constants
• Constants are immutable values which are known at
compile time and do not change for the life of the
program.
• Constants can be marked as public, private, protected,
internal, protected internal or private protected.
class Calendar1
{
public const int Months = 12;
public const int Weeks = 52, Days = 365;
}

Slide 8
Properties
• A property is a member that provides a flexible
mechanism to read, write, or compute the value of a
private field.
• Properties can be used as if they're public data members,
but they're special methods called accessors
• A get property accessor is used to return the property
value, and a set property accessor is used to assign a new
value
• Properties can be
– read-write (they have both a get and a set accessor),
– read-only (they have a get accessor but no set accessor),
– or write-only (they have a set accessor, but no get accessor)

Slide 9
Auto-Implemented Properties
• Auto-implemented properties make property-
declaration more concise when no additional logic is
required in the property accessors

public class Customer {


//Auto-implemented properties for trivial get and set

public double TotalPurchases { get; set; }


public string Name { get; set; } = "Jane";
public int CustomerId { get; set; }

Slide 10
Properties with backing fields
public class TimePeriod
{
private double _seconds;

public double Hours


{
get { return _seconds / 3600; }
set
{
if (value < 0 || value > 24)
throw new ArgumentOutOfRangeException(nameof(value),
"The valid range is between 0 and 24.");

_seconds = value * 3600;


}
}
}

Slide 11
Required Properties
• Beginning with C# 11, you can add the required member to
force client code to initialize any property or field:
public class SaleItem
{
public required string Name
{ get; set; }

public required decimal Price


{ get; set; }
}

Slide 12
Required Properties contd.
• To create a SaleItem, you must set both the Name
and Price properties using object initializers

var item = new SaleItem { Name = "Shoes",


Price = 19.95m };

Slide 13
Methods
• A method is a code block that contains a series of statements.

class SimpleMath
{
public int AddTwoNumbers(int num1, int num2)
{
return num1 + num2;
}

public int SquareANumber(int number)


{
return number * number;
}
}

Slide 14
Method Overloading
• Two or more methods in a class with the same name but different
numbers, types, and order of parameters, it is called method overloading
namespace MethodOverload {

class Program {

// method with one parameter


void display(int a) {
Console.WriteLine("Arguments: " + a);
}

// method with two parameters


void display(int a, int b) {
Console.WriteLine("Arguments: " + a + " and " + b);
}
}
}

Slide 15
Constructors
• Whenever an instance of a class or a struct is created, its constructor is called.
• A class or struct may have multiple constructors that take different arguments.
public class Person
{
private string last;
private string first;

public Person(string lastName, string firstName)


{
last = lastName;
first = firstName;
}

// Remaining implementation of Person class.


}

Slide 16
Constructors contd
class Coords
{
public Coords()
: this(0, 0)
{ }

public Coords(int x, int y)


{
X = x;
Y = y;
}

public int X { get; set; }


public int Y { get; set; }

Slide 17
Private Constructors
• A private constructor is a special instance
constructor.
• It is generally used in classes that contain static
members only.
• If a class has one or more private constructors and
no public constructors, other classes (except nested
classes) cannot create instances of this class

Slide 18
Private Constructors
class NLog
{
// Private Constructor:
private NLog() { }

public static double e = Math.E;


}

Slide 19
Object Initializers
• Object initializers let you assign values to any
accessible fields or properties of an object at
creation time without having to invoke a constructor
followed by lines of assignment statements
• The object initializer syntax enables you to specify
arguments for a constructor or omit the arguments
(and parentheses syntax)

Slide 20
Object Initializers
public class Cat
{
public int Age { get; set; }
public string? Name {get; set;}

public Cat()
{
}

public Cat(string name)


{
this.Name = name;
}
}

Cat cat = new Cat { Age = 10, Name = "Fluffy" };


Cat sameCat = new Cat("Fluffy"){ Age = 10 };

Slide 21
Collection initializers
• Collection initializers let you specify one or more
element initializers when you initialize a collection
type that implements IEnumerable

List<Cat> cats = new List<Cat>


{
new Cat{ Name = "Sylvester", Age=8 },
new Cat{ Name = "Whiskers", Age=2 },
new Cat{ Name = "Sasha", Age=14 }
};

Slide 22
DCIT 318
PROGRAMMING II

Session 3 – OOP using C# Part II

Lecturer: Mr. Paul Ammah, CSD


Contact Information: pammah@ug.edu.gh

Department of Computer Science


School of Physical and Mathematical Sciences
2022/2023
Inheritance in C# and .NET
• Inheritance is one of the fundamental attributes of
object-oriented programming.
• It allows you to define a child class that reuses (inherits),
extends, or modifies the behavior of a parent class.
• Not all members of a base class are inherited by derived
classes.
• The following members are not inherited:
• Static constructors, which initialize the static data of a class.
• Instance constructors, which you call to create a new instance
of the class. Each class must define its own constructors.
• Finalizers, which are called by the runtime's garbage collector to
destroy instances of a class.

Slide 2
Inheritance in C# and .NET
• A member's accessibility affects its visibility for
derived classes as follows:
– Private members are visible only in derived classes that
are nested in their base class.
– Protected members are visible only in derived classes.
– Internal members are visible only in derived classes that
are located in the same assembly as the base class.
• They are not visible in derived classes located in a different
assembly from the base class.
– Public members are visible in derived classes and are part
of the derived class' public interface.

Slide 3
Inheritance in Action
public class A
{ public class Example
public void Method1() {
{ public static void Main(){
// Method implementation. B b = new ();
} b.Method1();
} }
}
public class B : A { }

Slide 4
Inheritance in Action
public class A
{
private int _value = 10; public class AccessExample
{
public class B : A public static void Main(string[] args)
{
public int GetValue()
{
{ var b = new A.B();
return _value; Console.WriteLine(b.GetValue());
}
}
}
} }

public class C : A
{
// public int GetValue()
// {
// return _value;
// }
}

Note: Accessing GetValue() from class C is not


possible from class B

Slide 5
Overriding Inherited Members
• Derived classes can also override inherited members
by providing an alternate implementation
• In order to be able to override a member, the
member in the base class must be marked with the
virtual keyword
• By default, base class members are not marked as
virtual and cannot be overridden

Slide 6
Overriding Inherited Members
public class A
{
public virtual void Method1()
{
// Do something.
}
}

public class B : A
{
public override void Method1() {
// Do something else.
}
}

Slide 7
Implicit inheritance
• Besides any types that they may inherit from through
single inheritance, all types in the .NET type system
implicitly inherit from Object or a type derived from
it.

• Inheritance applies only to classes and interfaces.


– Other type categories (structs, delegates, and enums) do
not support inheritance.

Slide 8
Abstract Classes and Class Members
• The abstract keyword enables you to create classes
and class members that are incomplete and must be
implemented in a derived class.

public abstract class A


{
public abstract void DoWork(int i);
}

Slide 9
Interfaces
• An interface defines a contract.
• A class or struct that implements an interface shall
adhere to its contract.
• An interface may inherit from multiple base
interfaces, and a class or struct may implement
multiple interfaces.

Slide 10
Interfaces
interface ISampleInterface
{
void SampleMethod();
}

class ImplementationClass : ISampleInterface


{
// Explicit interface member implementation:
void ISampleInterface.SampleMethod()
{
// Method implementation.
}

Slide 11
Interfaces
public interface INamed
{
public string Name {get; set;}
}
• An interface may include
– Constants
– Static fields, methods, properties, indexers, and events
– Operators
– Nested Types
– Explicit access modifiers (default is public)

Slide 12
Interfaces
interface ISampleInterface
{
void SampleMethod();
}

class ImplementationClass : ISampleInterface


{
// Explicit interface member implementation:
void ISampleInterface.SampleMethod()
{
// Method implementation.
}

Slide 13
Interface Inheritance
public interface IControl
{
void Paint();
}
public interface ISurface
{
void Draw();
}
public class SampleClass : IControl, ISurface
{
public void Paint()
{
Console.WriteLine("Paint method in SampleClass");
}

public void Draw()


{
Console.WriteLine(”Draw method in SampleClass");
}
}

Slide 14
Interface Inheritance
public interface IControl
{
void Paint();
}
public interface ISurface
{
void Paint();
}
public class SampleClass : IControl, ISurface
{
public void IControl.Paint()
{
Console.WriteLine("Paint method from IControl");
}

public void ISurface.Paint()


{
Console.WriteLine(”Paint method from ISurface");
}
}

Slide 15
Operator Overloading
• A user-defined type can overload a predefined C#
operator
• Use the operator keyword to declare an operator.
• An operator declaration must satisfy the following
rules:
– It includes both a public and a static modifier.
– A unary operator has one input parameter.
– A binary operator has two input parameters.
• In each case, at least one parameter must have type T or T?
where T is the type that contains the operator declaration.

Slide 16
Overloadable Operators

Slide 17
Operator Overloading
public class Fraction
{
private readonly int num;
private readonly int den;

public Fraction(int numerator, int denominator)


{
if (denominator == 0)
{
throw new ArgumentException("Denominator cannot be zero.", nameof(denominator));
}
num = numerator;
den = denominator;
}

public static Fraction operator +(Fraction a) => a;

public static Fraction operator -(Fraction a) => new Fraction(-a.num, a.den);

public static Fraction operator +(Fraction a, Fraction b)


=> new Fraction(a.num * b.den + b.num * a.den, a.den * b.den);

Slide 18
Structs
• Structs are similar to classes in that they represent
data structures that can contain data members and
function members.
• A structure type (or struct type) is a value type that
can encapsulate data and related functionality.
• Structs are particularly useful for small data
structures that have value semantics.
– Complex numbers, points in a coordinate system, or key-
value pairs in a dictionary are all good examples of structs.

Slide 19
Structs
public struct Coords
{
public Coords(double x, double y)
{
X = x;
Y = y;
}

public double X { get; }


public double Y { get; }

public override string ToString() => $"({X},


{Y})";
}

Slide 20
readonly Struct
• You use the readonly modifier to declare that a
structure type is immutable.
• All data members of a readonly struct must be read-
only as follows:
• Any field declaration must have the readonly
modifier
• Any property, including auto-implemented ones,
must be read-only

Slide 21
readonly Struct
public readonly struct Coords
{
public Coords(double x, double y)
{
X = x;
Y = y;
}

public double X { get;} //or declare readonly


public double Y { get;}

public override string ToString() => $"({X}, {Y})";


}

Slide 22
Records
• Beginning with C# 9, you use the record modifier to
define a reference type that provides built-in
functionality for encapsulating data
• C# 10 allows the record class syntax as a synonym to
clarify a reference type, and record struct to define a
value type with similar functionality
• When you declare a primary constructor on a record, the
compiler generates public properties for the primary
constructor parameters
– The primary constructor parameters to a record are referred to
as positional parameters.

Slide 23
Records and Record Class
//Record
public record Person(string FirstName, string
LastName);

//Record Class
public record Person
{
public required string FirstName { get; init; }
public required string LastName { get; init; }
};

Slide 24
Record Struct Types
public readonly record struct Point(double X, double
Y, double Z);

public record struct Point


{
public double X { get; init; }
public double Y { get; init; }
public double Z { get; init; }
}

Slide 25
Sealed Modifier
When applied to a class, the sealed modifier prevents
other classes from inheriting from it.
In the following example, class B inherits from class A,
but no class can inherit from class B.

class A {}
sealed class B : A {}

Slide 26
override Modifier
• The override modifier is required to extend or
modify the abstract or virtual implementation of an
inherited method, property, indexer, or event.

Slide 27
override Modifier
abstract class Shape
{
public abstract int GetArea();
}

class Square : Shape


{
private int _side;

public Square(int n) => _side = n;

public override int GetArea() => _side * _side;


}

Slide 28
Override Example
public class Employee
{
public string Name { get; }

protected decimal _basepay;

public Employee(string name, decimal basepay)


{
Name = name;
_basepay = basepay;
}

// Declared virtual so it can be overridden.


public virtual decimal CalculatePay()
{
return _basepay;
}
}

Slide 29
Override Example contd.
public class SalesEmployee : Employee
{
private decimal _salesbonus;

public SalesEmployee(string name, decimal basepay,


decimal salesbonus)
: base(name, basepay)
{
_salesbonus = salesbonus;
}

// Override the CalculatePay method


public override decimal CalculatePay()
{
return _basepay + _salesbonus;
}
}

Slide 30
DCIT 318
PROGRAMMING II

Session 4 – Collections & Generics

Lecturer: Mr. Paul Ammah, CSD


Contact Information: pammah@ug.edu.gh

Department of Computer Science


School of Physical and Mathematical Sciences
2022/2023
Collections
• For many applications, you want to create and manage
groups of related objects. There are two ways to group
objects:
– by creating arrays of objects,
– and by creating collections of objects.
• Arrays are most useful for creating and working with a
fixed number of strongly typed objects
• Collections provide a more flexible way to work with
groups of objects.
• Unlike arrays, the group of objects you work with can
grow and shrink dynamically as the needs of the
application change.

Slide 2
Collections cont’d
• For some collections, you can assign a key to any
object that you put into the collection so that you
can quickly retrieve the object by using the key
• A collection is a class, so you must declare an
instance of the class before you can add elements to
that collection.
• If your collection contains elements of only one data
type, you can use one of the classes in the
System.Collections.Generic namespace

Slide 3
Kinds of Collections
• Many common collections are provided by .NET.
• Each type of collection is designed for a specific
purpose.
• The kinds are:
– System.Collections.Generic classes
– System.Collections.Concurrent classes
– System.Collections classes
• We focus on only System.Collections.Generic and
System.Collections classes

Slide 4
System.Collections Classes
• The classes in the System.Collections namespace do
not store elements as specifically typed objects, but
as objects of type Object.
• The following table lists some of the frequently used
classes in the System.Collections namespace:

Slide 5
ArrayList Class
• Implements the IList interface using an array whose
size is dynamically increased as required.
• The ArrayList is not guaranteed to be sorted. You
must sort the ArrayList by calling its Sort method
prior to performing operations (such as
BinarySearch) that require the ArrayList to be sorted
• Not recommended that you use the ArrayList class
for new development, it does not always offer the
best performance, use the generic List<T> class.

Slide 6
ArrayList Example
ArrayList myAL = new ArrayList();
myAL.Add("Hello");
myAL.Add("World");
myAL.Add("!");

Console.WriteLine( " Count: {0}",


myAL.Count );

Slide 7
Hashtable Class
• Represents a collection of key/value pairs that are
organized based on the hash code of the key.
• Each element is a key/value pair stored in a
DictionaryEntry object
• When an element is added to the Hashtable, the element
is placed into a bucket based on the hash code of the key.
• Subsequent lookups of the key use the hash code of the
key to search in only one particular bucket, reducing the
number of key comparisons required to find an element.
• Hashtable class not recommended for new development,
use the generic Dictionary<TKey,TValue> class.

Slide 8
Hashtable Example
Hashtable myhashTable = new Hashtable();
myhashTable.Add("txt", "notepad.exe");
myhashTable.Add("bmp", "paint.exe");

foreach( DictionaryEntry de in myhashTable ) {


Console.WriteLine("Key = {0}, Value = {1}",
de.Key, de.Value);
}

Slide 9
Queue Class
• Represents a first-in, first-out collection of objects.
• This class implements a queue as a circular array. Objects
stored in a Queue are inserted at one end and removed
from the other.
• Three main operations can be performed on a Queue and
its elements:
• Enqueue adds an element to the end of the Queue.
• Dequeue removes the oldest element from the start of the
Queue.
• Peek peek returns the oldest element that is at the start of the
Queue but does not remove it from the Queue
• Queue not recommended for new development, use
Queue<T>
Slide 10
Stack Class
• Represents a simple last-in-first-out (LIFO) non-
generic collection of objects.
• Three main operations can be performed on a Stack
and its elements:
• Push inserts an element at the top of the Stack.
• Pop removes an element from the top of the Stack.
• Peek returns an element that is at the top of the
Stack but does not remove it from the Stack.
• Not recommended for new development, use
Stack<T>

Slide 11
Stack Example
Stack myStack = new Stack();
myStack.Push("Hello");
myStack.Push("World");
myStack.Push("!");
Console.WriteLine( "\tCount: {0}",
myStack.Count );

Slide 12
Why Non-generic Collections should
be Avoided
• Error prone: since non-generic collections are
untyped, it requires frequent casting between object
and the actual type you're expecting.
– Since the compiler can't check that your types are
consistent, it's easier to put the wrong type in the wrong
collection.
• Less performant: generic collections have the
advantage that value types don't have to be boxed as
object.

Slide 13
Non-Generic Collection Types
Replacement

Slide 14
Generics
• Generics let you tailor a method, class, structure, or
interface to the precise data type it acts upon
• Among the benefits of generics are increased code
reusability and type safety.
• Generics are classes, structures, interfaces, and
methods that have placeholders (type parameters)
for one or more of the types that they store or use.
• A generic collection class might use a type parameter
as a placeholder for the type of objects that it stores.

Slide 15
Generics cont’d
• The type parameters appear as the types of its fields and the
parameter types of its methods
• A generic method might use its type parameter as the type of
its return value or as the type of one of its formal parameters.
• When you create an instance of a generic class, you specify
the actual types to substitute for the type parameters.

public class SimpleGenericClass<T>


{
public T Field;
}
SimpleGenericClass<string> g = new
SimpleGenericClass<string>();
Slide 16
Generic Methods
• A generic method definition is a method with two
parameter lists: a list of generic type parameters and
a list of formal parameters.
• Type parameters can appear as the return type or as
the types of the formal parameters

Slide 17
Generic Method
T GenMethod<T>(T arg) T NonGenMethod(T arg) {
{ T temp = arg;
T temp = arg; //...
//... return temp;
return temp; }
}

Non Generic Method even


Valid Generic Method though it uses the Generic
Type of the class

Slide 18
Advantages
• Type safety. Generics shift the burden of type safety
from you to the compiler.
– There is no need to write code to test for the correct data
type because it is enforced at compile time.
– The need for type casting and the possibility of run-time
errors are reduced.
• Less code and code is more easily reused.
• Better performance.
– Generic collection types generally perform better for
storing and manipulating value types because there is no
need to box the value types.

Slide 19
Limitations
• Enumerations cannot have generic type parameters.
• Lightweight dynamic methods cannot be generic.
• A nested type that is enclosed in a generic type
cannot be instantiated unless types have been
assigned to the type parameters of all enclosing
types

Slide 20
System.Collections.Generic Classes
• A generic collection is useful when every item in the collection has the
same data type.
• A generic collection enforces strong typing by allowing only the desired
data type to be added.
• Below is a list of frequently used classes.

Slide 21
Dictionary<TKey,TValue> Class
• Represents a collection of keys and values.
• Tkey: The type of the keys in the dictionary.
• Tvalue: The type of the values in the dictionary
• There also exists assorted version of Dictionary
(SortedDictionary<Tkey,TValue>)

Dictionary<string, string> myDict =


new Dictionary<string, string>();

myDict.Add(”name", ”Peter"); // Add Key-value pair


myDict.Remove(“name”); // Remove Key-value pair

//Looping through Dictionary


foreach( KeyValuePair<string, string> kvp in myDict )
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key,kvp.Value);
}

Slide 22
List<T> Class
• Represents a strongly typed list of objects that can be
accessed by index.
• Provides methods to search, sort, and manipulate lists.
• Not sorted by default.
List<string> names = new List<string>();
names.Add(”Peter");
names.Add(”Paul");
names.Sort();
names.Reverse();
Names.BinarySearch(“Peter”);
names.Remove(”Peter");
names.Clear();

Slide 23
Queue<T> Class
• This class implements a generic queue as a circular
array.
• Objects stored in a Queue<T> are inserted at one
end and removed from the other.
• Queues and stacks are useful when you need
temporary storage for information; that is, when you
might want to discard an element after retrieving its
value.
• Use Queue<T> if you need to access the information
in the same order that it is stored in the collection

Slide 24
Queue<T> Class
• Three main operations can be performed on a
Queue<T> and its elements:
• Enqueue adds an element to the end of the Queue<T>.
• Dequeue removes the oldest element from the start of the
Queue<T>.
• Peek peek returns the oldest element that is at the start of
the Queue<T> but does not remove it from the Queue<T>

Slide 25
Queue<T> Class
Queue<string> nums = new Queue<string>();
nums.Enqueue("one");
nums.Enqueue("two");
nums.Enqueue("three");
Console.WriteLine(
"\nDequeuing '{0}’”, nums.Dequeue()
);
Console.WriteLine(
"Peek at next item to dequeue: {0}", nums.Peek()
);
Console.WriteLine("Dequeuing '{0}'", nums.Dequeue());
Console.WriteLine(”Count '{0}'", nums.Count);
nums.Clear();
Console.WriteLine(”Count '{0}'", nums.Count);

Slide 26
SortedList<TKey,TValue> Class
• Represents a collection of key/value pairs that are
sorted by key based on the associated IComparer<T>
implementation.
• SortedList<TKey,TValue> is implemented as an array
of key/value pairs, sorted by the key. Each element
can be retrieved as a KeyValuePair<TKey,TValue>
object.
• SortedList<TKey,TValue> requires a comparer
implementation to sort and to perform comparisons.

Slide 27
SortedList<TKey,TValue> Class
SortedList<string, string> myList =
new SortedList <string, string>();

myList.Add(”name", ”Peter"); // Add Key-value pair


myList.Remove(“name”); // Remove Key-value pair

//Looping through SortedList


foreach( KeyValuePair<string, string> kvp in myList )
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key,kvp.Value);
}

Slide 28
Stack<T> Class
• Represents a variable size last-in-first-out (LIFO)
collection of instances of the same specified type.
• Stack<T> is implemented as an array.
• Stacks and queues are useful when you need
temporary storage for information; that is, when you
might want to discard an element after retrieving its
value.
• Use Stack<T> if you need to access the information
in reverse order.

Slide 29
Stack<T> Class cont’d
• Three main operations can be performed on a
Stack<T> and its elements:
• Push inserts an element at the top of the Stack<T>.
• Pop removes an element from the top of the
Stack<T>.
• Peek returns an element that is at the top of the
Stack<T> but does not remove it from the Stack<T>.

Slide 30
Stack<T> Class cont’d
Stack<string> numbers = new Stack<string>();
numbers.Push("one");
numbers.Push("two");
numbers.Push("three");

Console.WriteLine("\nPopping '{0}'", numbers.Pop());


Console.WriteLine(
"Peek at next item to destack: {0}", numbers.Peek()
);
Console.WriteLine("Popping '{0}'", numbers.Pop());

numbers.Clear();

Console.WriteLine("\nCount = {0}", numbers.Count);

Slide 31
THE END

Slide 32
DCIT 318
PROGRAMMING II

Session 5 – Exceptions & Exception


Handling
Lecturer: Mr. Paul Ammah, CSD
Contact Information: pammah@ug.edu.gh

Department of Computer Science


School of Physical and Mathematical Sciences
2022/2023
Exceptions
• Exceptions in C# provide a structured, uniform, and type-safe
way of handling both system level and application-level error
conditions.
• Exceptions have the following properties:
– Exceptions are types that all ultimately derive from System.Exception.
– Use a try block around the statements that might throw exceptions.
– If no exception handler for a given exception is present, the program
stops executing with an error message.
– If a catch block defines an exception variable, you can use it to obtain
more information about the type of exception that occurred.
– Exceptions can be explicitly generated by a program by using the
throw keyword.

Slide 2
Causes of Exceptions
• A throw statement throws an exception immediately
and unconditionally.
• Control never reaches the statement immediately
following the throw.
• Certain exceptional conditions that arise during the
processing of C# statements and expression cause an
exception in certain circumstances when the
operation cannot be completed normally
– Example: An integer division operation

Slide 3
The System.Exception class
• The System.Exception class is the base type of all
exceptions.
• This class has a few notable properties that all
exceptions share:
– Message is a read-only property of type string that
contains a human-readable description of the reason for
the exception.
– InnerException is a read-only property of type Exception.
If its value is non-null, it refers to the exception that
caused the current exception

Slide 4
Common Exceptions

Slide 5
Exception Handling
• A try block is used to partition code that might be
affected by an exception.
• Associated catch blocks are used to handle any
resulting exceptions.
• A finally block contains code that is run whether or
not an exception is thrown in the try block

Slide 6
Exception Handling cont’d
try
{
// Code to try goes here.
}
catch (SomeSpecificException ex)
{
// Code to handle the exception goes here.
// Only catch exceptions that you know how to handle.
// Never catch base class System.Exception without
// rethrowing it at the end of the catch block.
}

Slide 7
Exception Handling cont’d
try
{
// Code to try goes here.
}
finally
{
// Code to execute after the try block goes here.
}

Slide 8
Exception Handling cont’d
try
{
// Code to try goes here.
}
catch (SomeSpecificException ex)
{
// Code to handle the exception goes here.
}
finally
{
// Code to execute after the try (and possibly catch)
// blocks goes here.
}

Slide 9
Examples
int GetInt(int[] array, int index)
{
try
{
return array[index];
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine(
"Parameter index is out of range.");
}
}

Slide 10
Creating and Throwing Exceptions
• You create your own exception classes by deriving from
Exception
• The derived classes should define at least three
constructors:
– one parameterless constructor,
– one that sets the message property,
– and one that sets both the Message and InnerException
properties.
• Add new properties to the exception class when the data
they provide is useful to resolving the exception.
– ToString() should be overridden to return the added
information.

Slide 11
Example: Defining Exception Classes
[Serializable]
public class InvalidDepartmentException : Exception
{
public InvalidDepartmentException() : base() { }

public InvalidDepartmentException(string message) :


base(message) { }

public InvalidDepartmentException
(string message, Exception inner) :
base(message, inner) { }
}

Slide 12
Throwing Exceptions
• Exception objects that describe an error are created and then thrown with
the throw statement or expression.
public class ProgramLog
{
FileStream logFile = null!;
public void OpenLog(FileInfo fileName, FileMode mode) { }

public void WriteLog()


{
if (!logFile.CanWrite)
{
throw new InvalidOperationException("Logfile cannot be
read-only");
}
// Else write data to the log and return.
}
}

Slide 13
Things to Avoid When Throwing
Exceptions
• Do not use exceptions to change the flow of a
program as part of ordinary execution.
– Use exceptions to report and handle error conditions.
• Exceptions should not be returned as a return value
or parameter instead of being thrown.
• Do not throw System.Exception,
System.SystemException,
System.NullReferenceException, or
System.IndexOutOfRangeException intentionally
from your own source code.

Slide 14
THE END

Slide 15
DCIT 318
PROGRAMMING II

Session 6 – Developing GUI Applications

Lecturer: Mr. Paul Ammah, CSD


Contact Information: pammah@ug.edu.gh

Department of Computer Science


School of Physical and Mathematical Sciences
2022/2023
Windows Forms app in Visual Studio
with C#
• Windows Forms is a UI framework for .NET that
creates rich desktop client apps for Windows.
• The Windows Forms development platform supports
a broad set of app development features, including
controls, graphics, data binding, and user input.
• Windows Forms features a drag-and-drop visual
designer in Visual Studio to easily create Windows
Forms apps.

Slide 2
Windows Forms app in Visual Studio
with C#
• To create a Windows Form App, Open Visual Studio
and then click on Create a new project window,
select the Windows Forms App (.NET Framework)
template for C#.
• In the Configure your new project window, type in
the Project name and then, select Create.

Slide 3
Example Window Form Application

Slide 4
Toolbox

Slide 5
Add a New Form
• Add a new form with Visual Studio.
1. In Visual Studio, find the Project Explorer pane. Right-click
on the project and choose Add > Form (Windows Forms).
2. In the Name box, type a name for your form, such as
MyNewForm. Visual Studio will provide a default and
unique name that you may use.

• Once the form has been added, Visual Studio opens


the form designer for the form.

Slide 6
Adding a New Form

Slide 7
Adding a New Form

Slide 8
Resize a Form
• Approach 1 • Approach 2

Slide 9
Partial Classes and Methods
• It is possible to split the definition of a class, a struct,
an interface or a method over two or more source
files.
• Each source file contains a section of the type or
method definition, and all parts are combined when
the application is compiled.

Slide 10
Partial Classes
• There are several situations when splitting a class
definition is desirable:
• Spreading a class over separate files enables multiple
programmers to work on it at the same time.
• When working with automatically generated source, code
can be added to the class without having to recreate the
source file.
• Visual Studio uses this approach when it creates Windows
Forms, Web service wrapper code, and so on.
• When using source generators to generate additional
functionality in a class.
Slide 11
Partial Classes
public partial class Employee
{
public void DoWork()
{
}
}

public partial class Employee


{
public void GoToLunch()
{
}
}

Slide 12
Partial Classes
partial class Earth : Planet, IRotate { }
partial class Earth : IRevolve { }

• They are equivalent to the following declarations:

class Earth : Planet, IRotate, IRevolve { }

Slide 13
Restrictions
• All partial-type definitions meant to be parts of the
same type must be modified with partial.
• The partial modifier can only appear immediately
before the keywords class, struct, or interface.
• All partial-type definitions meant to be parts of the
same type must be defined in the same assembly
and the same module
• The class name and generic-type parameters must
match on all partial-type definitions

Slide 14
Partial Methods
• A partial class or struct may contain a partial method.
• One part of the class contains the signature of the
method.
• An implementation can be defined in the same part or
another part.
• If the implementation is not supplied, then the method
and all calls to the method are removed at compile time.
• Implementation may be required depending on method
signature.

Slide 15
Partial Methods
// Definition in file1.cs
partial void OnNameChanged();

// Implementation in file2.cs
partial void OnNameChanged()
{
// method body
}

Slide 16
Windows Forms: Controls
• Windows Forms controls are reusable components that
encapsulate user interface functionality.
• You can combine existing controls, extend existing controls,
or author your own custom controls.
• The position a control appears on a parent is determined by
the value of the Location property relative to the top-left of
the parent surface.
• The top-left position coordinate in the parent is (x0,y0).
– The size of the control is determined by the Size property and
represents the width and height of the control.
• Besides manual positioning and sizing, various container
controls are provided that help with automatic placement
of controls.
Slide 17
Automatic Placement and Size
• There are two properties on a control that help
automatic placement and size within a parent: Dock
and Anchor.

Slide 18
Dock
• The Dock property sets which border of the control is
aligned to the corresponding side of the parent, and
how the control is resized within the parent.

Slide 19
Anchor
• Anchoring a control allows you to tie the control to
one or more sides of the parent container.
• As the container changes in size, any child control
will maintain its distance to the anchored side.

Slide 20
Anchor

Slide 21
Control Layout Options
• Control placement in Windows Forms is determined
not only by the control, but also by the parent of the
control.
• Fixed position and size: The position a control
appears on a parent is determined by the value of
the Location property relative to the top-left of the
parent surface.
• Margin and Padding: The Margin property defines
the space around the control, The Padding property
defines the space in the interior of a control

Slide 22
Controls
• Button, CheckBox, ComboBox, RadioButton
• TextBox, RichTextBox, ListBox, MaskedTextBox, and
CheckedListBox controls
• ListView , TreeView control
etc

Slide 23
Label Class
• Labels are one of the most frequently used C#
control.
• We can use the Label control to display text in a set
location on the page.
• In addition to displaying text, the Label control can
also display an image using the Image property, or a
combination of the ImageIndex and ImageList
properties.

Slide 24
Label
Label label1 = new Label();
label1.Text = "This is my first Label";
label1.BorderStyle = BorderStyle.FixedSingle;
label1.TextAlign = ContentAlignment.MiddleCenter;

Slide 25
Button Class
• Represents a Windows button control.
private void InitializeMyButton()
{
// Create and initialize a Button.
Button button1 = new Button();

// Set the button to return a value of OK when clicked.


button1.DialogResult = DialogResult.OK;

// Add the button to the form.


Controls.Add(button1);
}

Slide 26
Button

Slide 27
CheckBox
• Use a CheckBox to give the user an option, such as true/false or yes/no.
– The CheckBox control can display an image or text or both.

public void InstantiateMyCheckBox()


{
// Create and initialize a CheckBox.
CheckBox checkBox1 = new CheckBox();

// Make the check box control appear as a toggle button.


checkBox1.Appearance = Appearance.Button;

// Turn off the update of the display on the click of the control.
checkBox1.AutoCheck = false;

// Add the check box control to the form.


Controls.Add(checkBox1);
}

Slide 28
CheckBox

Slide 29
ComboBox Class
• A ComboBox displays a text box combined with a
ListBox, which enables the user to select items from
the list or enter a new value.
• You can use these properties to manage the
currently selected item in the list,
– the Text property to specify the string displayed in the
editing field,
– the SelectedIndex property to get or set the current item,
and
– the SelectedItem property to get or set a reference to the
object.

Slide 30
ComboBox
ComboBox comboBox1 = new ComboBox();
comboBox1.Items.AddRange(
new object[] {
"Item 1", "Item 2", "Item 3", "Item 4",
"Item 5”
}
);

Slide 31
ComboBox

Slide 32
RadioButton Class
• Enables the user to select a single option from a group of
choices when paired with other RadioButton controls
• When the user selects one option button (also known as
a radio button) within a group, the others clear
automatically.
• All RadioButton controls in a given container, such as a
Form, constitute a group.
• To create multiple groups on one form, place each group
in its own container, such as a GroupBox or Panel
control.

Slide 33
RadioButton
private GroupBox groupBox1 = new GroupBox();
private RadioButton radioButton2 = new RadioButton();
private RadioButton radioButton1 = new RadioButton();

groupBox1.Controls.Add(this.radioButton2);
groupBox1.Controls.Add(this.radioButton1);
groupBox1.Text = "Radio Buttons";
radioButton1.Text = "Choice 1";
radioButton1.CheckedChanged += new EventHandler(radioButton_CheckedChanged);
radioButton2.Text = "Choice 2";
radioButton1.CheckedChanged += new EventHandler(radioButton_CheckedChanged);

void radioButton_CheckedChanged(object sender, EventArgs e) {


RadioButton rb = sender as RadioButton;
if (rb == null) {
MessageBox.Show("Sender is not a RadioButton");
return;
} // Ensure that the RadioButton.Checked property // changed to true.
if (rb.Checked) {
// Keep track of the selected RadioButton by saving a reference // to it.
selectedrb = rb;
}
}

Slide 34
RadioButton

Slide 35
Panel Class
• Used to group collections of controls.
• A Panel is a control that contains other controls.
• You can use a Panel to group collections of controls
such as a group of RadioButton controls.
• As with other container controls such as the
GroupBox control, if the Panel control's Enabled
property is set to false, the controls contained within
the Panel will also be disabled.

Slide 36
Panel
Panel dynamicPanel = newPanel();

dynamicPanel.Location = new System.Drawing.Point(26, 12);

dynamicPanel.Name = "Panel1";

dynamicPanel.Size = new System.Drawing.Size(228, 200);

dynamicPanel.TabIndex = 0;

Controls.Add(dynamicPanel);

dynamicPanel.Visible = false;

Slide 37
Panel

Slide 38
TextBox Class
• With the TextBox control, the user can enter text in
an application
• Typically, a TextBox control is used to display, or
accept as input, a single line of text.
• You can use the Multiline and ScrollBars properties
to enable multiple lines of text to be displayed or
entered.

Slide 39
TextBox
private TextBox textBox1;
textBox1 = new System.Windows.Forms.TextBox();
textBox1.AcceptsReturn = true;
textBox1.AcceptsTab = true;
textBox1.Dock = DockStyle.Fill;
textBox1.Multiline = true;
textBox1.ScrollBars = ScrollBars.Vertical;

Slide 40
TextBox

Slide 41
ListBox Class
• The ListBox control enables you to display a list of
items to the user that the user can select by clicking.
• A ListBox control can provide single or multiple
selections using the SelectionMode property.
• The MultiColumn property to enable the display of
items in columns instead of a straight vertical list of
items.
– With this, the control can display more visible items and
the user no longer needs to scroll to an item.

Slide 42
ListBox
// Create an instance of the
ListBox. ListBox listBox1 = new ListBox();

// Set the ListBox to display items in multiple columns.


listBox1.MultiColumn = true;

// Set the selection mode to multiple and extended.


listBox1.SelectionMode = SelectionMode.MultiExtended;

// Shutdown the painting of the ListBox as items are added.


listBox1.BeginUpdate();

// Loop through and add 50 items to the ListBox.


for (int x = 1; x <= 50; x++) {
listBox1.Items.Add("Item " + x.ToString());
}

// Allow the ListBox to repaint and display the new items.


listBox1.EndUpdate();

Slide 43
ListBox

Slide 44
ListView Class
• Represents a Windows list view control, which
displays a collection of items that can be displayed
using one of four different views.

Slide 45
ListView
// Create two items and three sets of subitems.
// Create a new ListView control. ListViewItem item1 = new ListViewItem("item1",0);
ListView listView1 = new ListView();
listView1.Bounds = new Rectangle(
// Place a check mark next to the item.
new Point(10,10), new Size(300,200)
item1.Checked = true; item1.SubItems.Add("1");
);
item1.SubItems.Add("2");
// Set the view to show details. item1.SubItems.Add("3");
listView1.View = View.Details;
ListViewItem item2 = new ListViewItem("item2",1);
// Allow the user to edit item text. item2.SubItems.Add("4");
listView1.LabelEdit = true; item2.SubItems.Add("5");
item2.SubItems.Add("6");
// Allow the user to rearrange columns.
listView1.AllowColumnReorder = true;
// Create columns for the items and subitems.
// Width of -2 indicates auto-size.
// Display check boxes.
listView1.CheckBoxes = true; listView1.Columns.Add("Item Column", -2,
HorizontalAlignment.Left);
// Select the item and subitems listView1.Columns.Add("Column 2", -2,
listView1.FullRowSelect = true; HorizontalAlignment.Left);
listView1.Columns.Add("Column 3", -2,
// Display grid lines. HorizontalAlignment.Left);
listView1.GridLines = true;
//Add the items to the ListView.
// Sort the items in ascending order. listView1.Items.AddRange(new
listView1.Sorting = SortOrder.Ascending; ListViewItem[]{item1,item2,item3});
Slide 46
ListView

Slide 47
Windows Forms: Control Events
• Controls provide a set of common events through
the base class: Control.
• Not every control responds to every event.
• Most shared events fall under these categories:
• Mouse events
• Keyboard events
• Property changed events
• Other events

Slide 48
Events
• An event is an action that you can respond to, or
"handle," in code.
• Events can be generated by a user action, such as clicking
the mouse or pressing a key, by program code, or by the
system.
• To define an event, you use the event keyword in the
signature of your event class, and specify the type of
delegate for the event.
• To raise an event, you add a method that is marked as
protected and virtual and name method OnEventName
– The method should take one parameter that specifies an event
data object, which is an object of type EventArgs or a derived
type

Slide 49
Event Example
class Counter
{
public event EventHandler ThresholdReached;

protected virtual void OnThresholdReached(EventArgs e)


{
ThresholdReached?.Invoke(this, e);
}

// provide remaining implementation for the class


}

Slide 50
Delegates
• Delegates are classes commonly used within .NET to
build event-handling mechanisms.
• The event model uses delegates to bind events to
the methods that are used to handle them.
• The delegate enables other classes to register for
event notification by specifying a handler method

Slide 51
EventHandler Delegates
• .NET provides the EventHandler and
EventHandler<TEventArgs> delegates to support
most event scenarios.
• Use the EventHandler delegate for all events that
don't include event data.
• Use the EventHandler<TEventArgs> delegate for
events that include data about the event.
• These delegates have no return type value and take
two parameters (an object for the source of the
event and an object for event data)

Slide 52
Delegate Example
public delegate void ThresholdReachedEventHandler
(
object sender,
ThresholdReachedEventArgs e
);

public class ThresholdReachedEventArgs : EventArgs


{
public int Threshold { get; set; }
public DateTime TimeReached { get; set; }
}

Slide 53
Common Events
• Controls provide a set of common events through
the base class: Control
• Not every control responds to every event
• Most shared events fall under these categories:
• Mouse events
• Keyboard events
• Property changed events
• Other events

Slide 54
Mouse Events
• All controls provide basic mouse-related events:
• MouseClick
• MouseDoubleClick
• MouseDown
• MouseEnter
• MouseHover
• MouseLeave
• MouseMove
• MouseUp
• MouseWheel
• Click
Slide 55
Control.MouseClick Event
• Occurs when the control is clicked by the mouse.
//event
public event MouseEventHandler? MouseClick;

//handler
private void Control1_MouseClick(
Object sender, MouseEventArgs e
) {
MessageBox.Show(
messageBoxCS.ToString(),
"MouseClick Event"
);
}

Slide 56
Keyboard Event
• If the control responds to user input, such as a
TextBox or Button control, the appropriate input
event is raised for the control.
• The control must be focused to receive keyboard
events.
• The following is a list of keyboard events:
• KeyDown
• KeyPress
• KeyUp

Slide 57
Control.KeyPress Event
• Occurs when a character, space or backspace key is pressed while the control has
focus.

public event KeyPressEventHandler? KeyPress;

// This event occurs after the KeyDown event

private void textBox1_KeyPress


( object sender, KeyPressEventArgs e)
{

if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9) {


MessageBox.Show(“Number Entered”);
}
}

Slide 58
DCIT 318
PROGRAMMING II

Session 7 – Database Programming


Using ADO.NET
Lecturer: Mr. Paul Ammah, CSD
Contact Information: pammah@ug.edu.gh

Department of Computer Science


School of Physical and Mathematical Sciences
2022/2023
ADO.NET
• ADO.NET is a set of classes for database access.
• It is a specification that unifies access to relational
databases, XML files, and other application data.
• The ADO.NET classes are found in System.Data
namespace.
• The full form of ADO.Net is ActiveX® Data Objects
• ADO.Net can be used by any .Net Language

Slide 2
ADO.NET Architecture
• The two main components of ADO.NET for accessing and
manipulating data are
– the .NET Framework data providers
– the DataSet
• A .NET Framework data provider is used for connecting to
a database, executing commands, and retrieving result
• Those results are either:
– processed directly
– placed in a DataSet in order to be exposed to the user as needed
– combined with data from multiple sources
– remoted between tiers.

Slide 3
Data Providers

OLE DB - Object Linking and Embedding Database


ODBC - Open Database Connectivity
Slide 4
Core Objects of .NET Framework Data
Providers

• In addition to the core classes .NET Framework data provider also contains these
classes:
• Transaction, CommandBuilder, ConnectionStrngBuilder,
• Parameter, Exception, Error and ClientPErmission

Slide 5
ADO.NET DataSets
• The DataSet is a memory-resident representation of
data that provides a consistent relational
programming model regardless of the data source.
• The methods and objects in a DataSet are consistent
with those in the relational database model.
• DataSet contains a collection of zero or more tables
represented by DataTable objects.

Slide 6
DataSet Object Model

Slide 7
DataSet Object Model cont’d
• The DataTableCollection contains all the DataTable objects in
a DataSet.
• A DataTable is defined in the System.Data namespace and
represents a single table of memory-resident data.
• A collection of rows (DataRow) represented by the
DataRowCollection
• A collection of columns (DataColumn) in a DataTable is
represented by a DataColumnCollection
• A collection of constraints on a DataTable is represented by a
ConstraintCollection
• A DataView enables you to create different views of the data
stored in a DataTable
Slide 8
Retrieving and Modifying Data in
ADO.NET
• .NET Framework data providers of ADO.NET allow
you to execute commands as well as to retrieve data
by using a
– DataReader
– DataAdapter

• Updating data involves using


– DataAdapter and DataSet, and Command objects; and it
may also involve using transactions.

Slide 9
Connecting to a Data Source
• Each .NET Framework data provider included with
the .NET Framework has a DbConnection object
– Data Provider for OLE DB includes an OleDbConnection
object
– Data Provider for SQL Server includes a SqlConnection
object
– Data Provider for ODBC includes an OdbcConnection
object
– Data Provider for Oracle includes an OracleConnection
object

Slide 10
Connecting to SQL Server
• The using block in C# automatically disposes of the connection
when the code exits the block, even in the case of an unhandled
exception
• A connection string contains initialization information that is
passed as a parameter from a data provider to a data source. E.g.
“Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword; “

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();
// Do work here.
}

Slide 11
Connecting to an OLE DB Data Source
// Assumes connectionString is a valid connection string.

using (
OleDbConnection connection = new OleDbConnection(connectionString)
)
{
connection.Open();
// Do work here.
}

Slide 12
Connecting to an ODBC Data Source
// Assumes connectionString is a valid connection string.

using (
OdbcConnection connection = new OdbcConnection(connectionString)
)
{
connection.Open();
// Do work here.
}

Slide 13
Connecting to an Oracle Data Source
// Assumes connectionString is a valid connection string.

using (
OracleConnection connection =
new OracleConnection(connectionString)
)
{
connection.Open();
// Do work here.
}

Slide 14
Commands and Parameters
• After establishing a connection to a data source, you
can execute commands and return results from the
data source using a DbCommand object.
• Create a command for a particular connection using
the CreateCommand method of a DbConnection
object.
• The SQL statement being executed by the command
can be configured using the CommandText property

Slide 15
Executing a Command
• Each .NET Framework data provider has its own
command object that inherits from DbCommand
– Data Provider for OLE DB includes an OleDbCommand
object
– Data Provider for SQL Server includes a SqlCommand
object
– Data Provider for ODBC includes an OdbcCommand object
– Data Provider for Oracle includes an OracleCommand
object

Slide 16
Command Execution Methods &
Command Types
Command Objects expose methods for executing commands based on the type of command
and desired return value as described below:

Command object also supports a CommandType enumeration that specifies how a


command string is interpreted

Slide 17
ExecuteReader Example
public void ReadMyData(string connectionString)
{ //Executes commands that return rows.
string queryString = "SELECT OrderID, CustomerID FROM Orders";
using (
OleDbConnection connection = new OleDbConnection(connectionString)
)
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();

while (reader.Read())
{
Console.WriteLine(reader.GetInt32(0) + ", " +
reader.GetString(1));
}
// always call Close when done reading.
reader.Close();
}
Slide 18
}
ExecuteNonQuery Example
public void InsertRow(string connectionString, string insertSQL)
{
using (OdbcConnection connection =
new OdbcConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
OdbcCommand command = new OdbcCommand(insertSQL, connection);

// Open the connection and execute the insert command.


try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
Executes commands such as SQL INSERT, DELETE, UPDATE, and SET statements.
Slide 19
ExecuteScalar Example
static public int GetTotalNumberOfRegions(string connString)
{
Int32 count = 0;
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
count = (Int32) cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int) count;
}

Slide 20
Using Parameters
• Command objects use parameters to pass values to
SQL statements or stored procedures, providing type
checking and validation
• Unlike command text, parameter input is treated as a
literal value, not as executable code.
– This behavior helps guard against "SQL injection" attack
• When adding parameters, you must supply a
ParameterDirection property for parameters other
than input parameters.

Slide 21
ParameterDirection

Slide 22
Parameter Placeholders and Data
Types
• The syntax for parameter placeholders depends on the data
source.
• The SqlCommand data provider uses named parameters in
the format @parametername
• With an OleDbCommand or OdbcCommand, parameters
must be added to the Parameters collection in the order
defined
• You specify the type of a Parameter in a generic manner by
setting the DbType property of the Parameter object to a
particular DbType.
• E.g. DbType:
– Boolean, Binary, DateTime, Date, Decimal, Double, Int16, Int32, Int64,
String, VarNumeric, UInt16, UInt32, UInt64

Slide 23
Parameter Placeholders

Slide 24
Adding Parameters
• Each .NET Framework data provider has its own
command object that inherits from DbParameter
– Data Provider for OLE DB includes an OleDbParameter
object
– Data Provider for SQL Server includes a SqlParameter
object
– Data Provider for ODBC includes an OdbcParameter object
– Data Provider for Oracle includes an OracleParameter
object

Slide 25
Parameter Example
sql = SELECT * FROM Customers WHERE CustomerID = ?

OdbcCommand command = new OdbcCommand(sql,


connection);

OdbcParameter parameter =
new OdbcParameter(“@p1”,OdbcType.Int);

parameter.Value = 20;
parameter.Direction = ParameterDirection.Input;
command.Add(parameter);

OdbcDataReader reader = command.ExecuteReader();

Slide 26
DataReaders
• You can use ADO.NET DataReader to retrieve a read-
only, forward-only stream of data from a database.
• Results are returned as the query executes
• Results are stored in the network buffer on the client
until they are requested using the Read method of
the DataReader.
• Using the DataReader can increase application
performance both by
– retrieving data as soon as it is available,
– and (by default) storing only one row at a time in memory

Slide 27
DbDataReaders
• Each .NET Framework data provider has its own
DbDataReaders
– Data Provider for OLE DB includes an OleDbDataReader
object
– Data Provider for SQL Server includes a SqlDataReader
object
– Data Provider for ODBC includes an OdbcDataReader
object
– Data Provider for Oracle includes an OracleDataReader
object

Slide 28
DbDataReader Example
static void HasRows(SqlConnection connection)
{
using (connection)
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM Categories;",
connection);
connection.Open();

SqlDataReader reader = command.ExecuteReader();

if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}

Slide 29
DataAdapters
• A DataAdapter is used to retrieve data from a data
source and populate tables within a DataSet.
• Each .NET Framework data provider has a
DbDataAdapter object
– Data Provider for OLE DB -> OleDbDataAdapter
– Data Provider for SQL Server -> SqlDataAdapter
– Data Provider for ODBC -> OdbcDataAdapter
– Data Provider for Oracle -> OracleDataAdapter

Slide 30
DataAdapter Example
using (connection)
{
// Define the query.
string queryString = "SELECT CategoryName FROM Categories";

// Assumes that connection is a valid OdbcConnection object.


OdbcDataAdapter adapter = new OdbcDataAdapter();

OdbcCommand selectCMD = new OdbcCommand(selectSQL, connection);

adapter.SelectCommand = selectCMD;

DataSet customers = new DataSet();


adapter.Fill(customers, "Customers");
}

A DataAdapter has SelectCommand, InsertCommand, UpdateCommand, DeleteCommand


Properties that can be used to set the commands appropriately
Slide 31
Accessing DataRow From DataTable
OdbcDataAdapter odbcDataAdapter = new OdbcDataAdapter( sqlString, conn );
DataSet studentDataSet = new DataSet();
odbcDataAdapter.Fill(studentDataSet,”students”);

foreach(
DataRow studentRow in studentDataSet.Tables[”students"].Rows
) {
Console.WriteLine($"ID: {studentRow["id"].ToString()}");
Console.WriteLine($"NAME: {studentRow["name"].ToString()}");
Console.WriteLine($"GENDER: {studentRow["gender"].ToString()}");
Console.WriteLine(
$"INDEX NUMBER: {studentRow["index_number"].ToString()}”
);

}
}

Slide 32
Combining Multiple DataAdapters
• Any number of DataAdapter objects can be used
with a DataSet
• DataRelation and Constraint objects can be added to
the DataSet locally, which enables you to relate data
from dissimilar data sources.

Slide 33
Populating a DataSet from Multiple
DataAdapters
SqlDataAdapter custAdapter = new SqlDataAdapter(
"SELECT * FROM dbo.Customers", customerConnection);

OleDbDataAdapter ordAdapter = new OleDbDataAdapter(


"SELECT * FROM Orders", orderConnection);

DataSet customerOrders = new DataSet();

custAdapter.Fill(customerOrders, "Customers");
ordAdapter.Fill(customerOrders, "Orders");

DataRelation relation = customerOrders.Relations.Add("CustOrders",


customerOrders.Tables["Customers"].Columns["CustomerID"],
customerOrders.Tables["Orders"].Columns["CustomerID"]);

foreach (DataRow pRow in customerOrders.Tables["Customers"].Rows)


{
Console.WriteLine(pRow["CustomerID"]);
foreach (DataRow cRow in pRow.GetChildRows(relation))
Console.WriteLine("\t" + cRow["OrderID"]);
}

Slide 34
Generating Commands with
CommandBuilders
• If your DataTable maps to a single database table,
you can use DbCommandBuilder to build
commands.
• DbCommandBuilder object can automatically
generate the DeleteCommand, InsertCommand, and
UpdateCommand of the DbDataAdapter.
– As a minimum requirement for automatic command
generation, set the SelectCommand property
– The SelectCommand must also return at least one primary
key or unique column

Slide 35
CommandBuilder Objects
• Each .NET Framework data provider has a
DbCommandBuilder object
– Data Provider for OLE DB -> OleDbCommandBuilder
– Data Provider for SQL Server -> SqlCommandBuilder
– Data Provider for ODBC -> OdbcCommandBuilder
– Data Provider for Oracle -> OracleCommandBuilder

Slide 36
Generating Commands with
DbCommandBuilder
OdbcDataAdapter adapter = new OdbcDataAdapter(
"SELECT * FROM dbo.Customers", connection
);

OdbcCommandBuilder builder = new OdbcCommandBuilder(adapter);

Console.WriteLine(builder.GetInsertCommand().CommandText);

Console.WriteLine(builder.GetDeleteCommand().CommandText);

Console.WriteLine(builder.GetUpdateCommand().CommandText);

Slide 37

You might also like