kelder.zeus.ugent.be

Download Report

Transcript kelder.zeus.ugent.be

1.
2.
3.
4.
5.
6.
7.
8.
9.
Introduction
C# versus Java : highlights
C# data types
Defining custom data types
Operator Overloading
Event driven programming
.NET Framework Class Library
A GUI in C#
A web service in C#
1
C# and .NET
1. Introduction
•
•
•
History
C# features
.NET framework
2. C# versus Java : highlights
3. C# data types
4. Defining custom data types
5. ...
2
History
Builds on legacy from
• C/C++ tradition -> new programming language C#
• Java tradition : many ideas borrowed
• runtime environment : virtual machine
• platform/language abstraction
• guarded execution environment
• garbage collection
• single rooted hierarchy
• ...
Takes software development one step further towards
component based design
3
History
procedural/structured
design/programming
object oriented
design/programming
C/PASCAL
C++
COM/COM+
CORBA component model
component based
design/programming
JAVA
C#/.NET
component support possible
BUT NOT built into the language
- templates
4
- deployment descriptors
C# features :
component oriented
Modern large-scale systems are component based
get/set
Properties
event based communication
support to annotate component for
- deployment
- configuration at design and/or runtime
- component versioning
- documentation
5
C# features : OO paradigm
supports all typical OO mechanisms
• encapsulation
• inheritance
• polymorphism
• interface based programming
C++ legacy (NOT supported in Java)
• support for operator overloading
• user defined type conversions
• rectangular arrays
• pass-by-reference
6
C# features :
Excution model
NO own runtime library
- uses .NET library (redesign of MS-library)
(implemented in C#)
Compiles to intermediary language
(CIL - Common Intermediate Language)
Executed by virtual machine
(CLR – Common Language Runtime)
- memory management through garbage collection
- guarded execution (e.g. array bounds guarding)
- JIT compilation
7
.NET framework
Application Code
FCL
Framework
Class Library
CLR
“.NET framework”
Version 1.0 released January 15, 2002
8
.NET execution model
Application Code in “A Language”
Compiler
CIL
CLR
Platform AND language portability
CLR can exploit processor/platform specific optimizations
Supported languages :
C#, J#, VB.NET, JScript, Microsoft IL, Managed Extensions for C++
Supplied by 3rd parties :
COBOL, Eiffel, Haskell, Forth, Scheme, Smalltalk, Pascal, ...
9
.NET :
Common Type System
Cross language type system, allowing
- type safety
- cross language integration
- execution services (garbage collection, JIT, exceptions, ...)
Defines rules to define types, irrespective of source language
All types eventually mapped to CTS-types
e.g. cross language inheritance
J# class inherits from C# class
Minimum subset for language to be supported by .NET :
CLS – Common Language Specification
- CLS-compliant language = “CLS consumer”
- if more than CLS : “CLS extender”
C#= both CLS consumer and extender
10
.NET : FCL categories
comprises
- > 3500 classes
- > 1 000 000 lines of code
• core functions
• basic datatypes, collections
• IO (network, console, file)
• calls to runtime services
• database interaction
• transactions
• consuming/producing XML
• manipulation of tables
• web-based applications (thin clients)
• desktop applications (thick clients)
• SOAP-based XML web services
11
Hello
C#
namespace Project1
{ using System;
class Class1
{
static void Main() {
Console.WriteLine("Hello there !");
for (int i = 0; i < 10; i++)
Console.WriteLine(i);
}
}
}
package project1;
import java.lang.*;
class Class1 {
public static void main(String[] args) {
System.out.println("Hello there !");
for (int i = 0; i < 10; i++)
System.out.println(i);
}
}
Java
12
C# and .NET
1. Introduction
2. C# versus Java : highlights
3. C# data types
4. Defining custom data types
13
C# - Java :
common approaches
Both intended as improvement to C++
• Compilation to machine independent language, managed execution
• Garbage Collection, no pointers
(C# allows pointer usage in special “unsafe” code sections)
• Reflection API
• No header files, no problems with circular (type) references
• Single rooted hierarchy, objects allocated on the heap
• Thread support by object-level lock
• Multiple extension of interfaces, single inheritance for classes
• Inner classes (closure instead of nested class)
• Simple inheritance rules (no inheritance modifiers)
• Everything is in a class (no global data, no global functions)
• Arrays, strings : bounds checked at execution time
• Systematic usage of “.” (instead of “->” and “::”)
• Keywords for null pointer (null) and boolean type (boolean/bool)
• Guaranteed initialization
• if-statement controlled by boolean (instead of integer)
• Finally-clause in try-catch blocks
14
Properties
C# : special support for getters/setters
Java : implied by coding convention (template or “design pattern”)
Property int min
Java style :
public int getMin() {return min;}
public void setMin(int m) {min=m;}
C# style :
public int
get
set
}
// value :
// calling
Min {
{return min;}
{min=value;}
implicit variable used when
setter method
- getter/setter grouped together
- encourages to think in terms of properties
15
Indexer
Means to index underlying datastructure
Java style :
public class Bookshop {
private Book[] books;
// ...
public void setBooks(int i,Book b) {
if(b!=null) books[i]=b;
}
public Book getBooks(int i) {return books[i];}
}
C# style :
public class Bookshop
{
private Book[] books;
// ...
public Book this[int i]{
get {return books[i];}
set {if(value!=null) books[i]=value;}
}
}
// ...
Bookshop standaard=new Bookshop();
standaard[10]=new Book(“Harry Potter”);
16
Event handling
Delegates used to handle events
- Java equivalent : inner class object
- C/C++ equivalent : function pointer
Direct support in C# for events
public delegate void TempChangeHandler(double t,ref bool cancel);
public class Thermometer {
public event TempChangeHandler TempChange;
double temp;
public double Temperature{
get{return temp;}
set{if(temp!=value) {
bool cancel=false;
TempChange(value,ref cancel); // fire event
if(!cancel) temp=value;
}
}
}
17
Event handling
public class TempController {
public TempController(Thermometer tm) {
tm.TempChange+=new TempChangeHandler(tm_TempChange);
}
private void tm_TempChange(double t,ref bool cancel) {
if(t>100) {
cancel=true;
System.Console.WriteLine(
"Way too hot : WRONG VALUE");
} else {
System.Console.WriteLine(
"New temperature registered.");
}
}
}
18
Event handling
public class Test {
public static void Main() {
Thermometer term=new Thermometer();
TempController tc=new TempController(term);
term.Temperature=30;
Console.WriteLine("Temp = {0}",term.Temperature);
term.Temperature=120;
Console.WriteLine("Temp = {0}",term.Temperature);
}
}
19
Enummerations
Standard Java approach
public class Period
public final
public final
public final
public final
{
static
static
static
static
int
int
int
int
DAILY=1;
WEEKLY=2;
MONTHLY=3;
YEARLY=4;
}
// ...
int publicationPeriod=Period.DAILY;
// PROBLEM : does not prevent int publicationPeriod=12; ???
C# approach
public enum Period{DAILY=1,WEEKLY=2,MONTHLY=3,YEARLY=4};
Period publicationPeriod = Period.WEEKLY;
20
Enummerations
Java 5 approach
enum PeriodE{DAILY,WEEKLY,MONTHLY,YEARLY}
//...
int publicationPeriod=Period.DAILY;
System.out.println(publicationPeriod);
PeriodE pubPeriod=PeriodE.DAILY;
System.out.println(pubPeriod);
// OUTPUT :
//
1
//
DAILY
21
Iterating over a Collection
Standard Java approach
for(Iterator i=collection.iterator();i.hasNext();) {
Object o=i.next();
// do something with o
}
for(int i=0;i<array.length;i++) {
// do something with array[i]
}
C# approach
foreach(object o in collection) {
// do something with o
}
foreach(int i in array) {
// do something with i
}
Java 5 approach
for(Object o : collection) {
// do something with o
}
for(int i : array) { // do something with i
}
22
Extension on
“primitive” types
C# struct datatype :
- very similar to class (defines attributes and methods)
- BUT : - allocated on the stack or in-line (instead of heap)
- value type -> pass by value by default
- efficient for small types
- usage similar to usage of primitive types in Java
struct CoupleV
{
private int x, y;
public int X
{
set { x = value; }
get { return x; }
}
public int Y
{
set { y = value; }
get { return y; }
}
public string ToString()
{
return "(" + x + "," + y + ")";
}
23
Extension on
“primitive” types
public static void Main()
{
CoupleV p = new CoupleV();
p.X = 10;
p.Y = 20;
CoupleV q=new CoupleV();
q.X = 20;
q.Y = 30;
Console.WriteLine(p.ToString());
Console.WriteLine(q.ToString());
CoupleV[] r = new CoupleV[4];
for (int i = 0; i < r.Length; i++)
r[i].X = r[i].Y=i;
foreach(CoupleV i in r)
Console.WriteLine(i.ToString());
}
24
Operator Overloading
Allows to program type specific operator semantics
More restrictive than C++ overloading mechanism
- always static
- NON virtual (static binding !) !
public static bool operator ==(CoupleV a, CoupleV b)
{
return ((a.x == b.x) && (a.y == b.y));
}
public static Boolean operator !=(CoupleV a, CoupleV b)
{
return !(a == b);
}
// ...
CoupleV p = new CoupleV();p.X = 10;p.Y = 20;
CoupleV q = new CoupleV();q.X = 10;q.Y = 20;
Console.WriteLine(p == q);
// TRUE
Console.WriteLine((object)p == (object)q); // FALSE non-virtual !
25
Polymorphism
Java : all methods virtual (late binding) by default
C# (like C++) : methods MUST be declared virtual if late binding applies
class A
{
public virtual void f() {Console.WriteLine("A.f()");}
}
class B : A
{
public override void f() {Console.WriteLine("B.f()");}
}
- shows intention of programmer
- more efficient
- can prevent later extensions ...
- explicit interface implementation
(solving name conflicts in case of multiple interface implementation)
- possibility to hide base class type/method in derived class
26
Assemblies
Type boundaries
- class
- namespace (equivalent to Java package)
- assembly (equivalent to Java archive)
Assemby = exe/dll to deploy
- meta-data (files contained, security settings, versioning info,
dependencies)
- modules (compiled source files)
- resources
Versioning
- contained in assemby info
- allows to run multiple versions of same types on same CLR
27
Visibility
private
same as Java
= default for interface and enum members
public
same as Java
=default for struct and class members
protected
visible in type itself or derived types
internal
visible in assembly
= default for non-nested types
internal protected
visible from type itself, in same assembly and in derived
types (= private or protected or internal)
Type can not be more accessible then types used for its declaration
28
Parameter modifiers
Passing references
ref
pass reference to method
requires parameter is assigned definite value before method entry
out
requires definite parameter assignment before returning from
method call
Variable number of arguments
params
can be applied to last argument of method
Parameter modifiers are part of method signature
29
Parameter modifiers
static void swap(ref int a, ref int b)
{
int t = a; a = b; b = t;
}
static void OneMore(int i, out int j)
{
j = i + 1;
}
static int sum(params int[] x)
{
int r = 0;
foreach (int i in x) r += i;
return r;
}
// ...
int x = 1, y = 2;
swap(ref x, ref y);
Console.WriteLine("{0} - {1}",x, y); // 2 - 1
OneMore(x, out y);
Console.WriteLine("{0} - {1}", x, y); // 2 - 3
Console.WriteLine(sum(1, 2, 3));
// 6
Console.WriteLine(sum(3, 4, 5, 6)); // 18
30
Attributes
Allow to extend language built-in declarative constructs
- Pre-defined attributes (e.g. Serialized)
- Custom attributes
Can be applied to
- class
- method
- field
- parameter
Attributes and values can be retrieved at runtime
31
Field modifiers
const
- value calculated at compile time
- equivalent to Java final
readonly
- value calculated at runtime
- can only be assigned once !
- allows to retrieve setting
(“a not so constant constant ...”)
32
Pointer arithmetic
allowed in sections marked as unsafe
pointer type : <type>*
dereferencing : *<pointer expression>
address calculation : &<variable>
Garbage collector should NOT move around objects
used in unsafe regions
MUST be declared fixed
33
Pointer arithmetic
unsafe static void AdditionOne(int[] b)
{
int l=b.Length;
fixed (int* a = b)
{
int* p = a;
for (int i = 0; i < l; i++,p++) *p = (*p) + 1;
}
}
//...
int[] k ={ 1, 2, 3, 4 };
foreach (int a in k) Console.WriteLine("{0}", a); // 1 2 3 4
AdditionOne(k);
foreach (int a in k) Console.WriteLine("{0}", a); // 2 3 4 5
34
Rectangular Arrays
int[,,] a=new int[3,4,5];
// rectangular array
// single reference variable
a[1,2,3]=20;
int[][][] b=new int[3][4][5]; // jagged array
b[1][2][3]=30;
...
35
Constructors - Destructors
Very similar to Java constructors – finalizers
Constructor :
can contain explicit constructor call
specified outside constructor body
- call to other constructor of same type : this(...)
- call to base class constructor : base(...)
Destructor
NOT for value type
NO explicit calls to destructor
C++-like syntax (actually expands to calling Finalize)
class A
{
public A():this(1){}
public A(int i):base(i){}
~A() {/* Destructor */}
}
36
C# and .NET
1. Introduction
2. C# versus Java : highlights
3. C# data types
4. Defining custom data types
37
C# type system
Value types (struct, enum)
Reference types (class, array, delegate, interface)
Pointer type
struct CoupleV
{
private int x, y;
public CoupleV(int xx, int yy) { x = xx; y = yy; }
public int X
{
set { x = value; }
get { return x; }
}
public int Y
{
set { y = value; }
get { return y; }
}
public override string ToString()
{
return "(" + x + "," + y + ")";
}
}
38
C# type system
class CoupleR
{
private int x=0, y=0;
public CoupleR(int xx, int yy) { x = xx; y = yy; }
public int X
{
set { x = value; }
get { return x; }
}
public int Y
{
set { y = value; }
get { return y; }
}
public override string ToString()
{
return "(" + x + "," + y + ")";
}
}
39
C# type system
// ...
CoupleR a = new CoupleR(1, 2);
CoupleR b = a;
CoupleV c = new CoupleV(3, 4);
CoupleV d = c;
a.X = 7;
c.X = 7;
Console.WriteLine(a); // (7,2)
Console.WriteLine(b); // (7,2)
Console.WriteLine(c); // (7,4)
Console.WriteLine(d); // (3,4)
40
Type unification
all struct and class types derive from object
(pointer types do not ...)
“simple” (“primitive”) types are actually structs
int : alias for System.Int32
long : alias for System.Int64
...
boxing – unboxing
- value type -> reference type : copy made (automatic)
- reference type -> value type : explicit cast necessary
int x=12;
object o=x;
// box
int y=(int)o; // unbox through downcast
41
Available types
Value types
signed integer : sbyte, short, int, long
unsigned integer : byte, ushort, uint, ulong
floating point : float, decimal, double
logical : bool
characters : char
Reference types
object
string
standard notations for constants apply (U : unsigned, L : long)
standard rules for conversions apply
42
Checked Arithmetic
checked(<expression>)
checked {/* block */}
checks for integral overflows
generates runtime exception OverflowException
unchecked(<expression>)
unchecked{/* block */}
turns off compile time bounds checking
43
Control flow statements
Same as in Java, BUT
switch :
no “fall through” behaviour
each case must end with jump (break, goto, ...)
foreach
goto label;
// ...
int x=0;
loop :
x++;
if(x<5) goto loop;
44
Namespaces
Similar to java packages w.r.t. avoiding name clashes
BUT : no boundary for accessibility
Can be nested
namespace A {
namespace B {
class CL {
}
}
}
// ...
A.B.CL x=new A.B.CL();
Alternative
using A.B;
CL x=new CL();
Global namespace = default surrounding namespace 45
C# and .NET
1. Introduction
2. C# versus Java : highlights
3. C# data types
4. Defining custom data types
46
Classes
[<attributes>][unsafe][<access modifier>][new]
[abstract | sealed] <class name>
[: <base class> |
: <interfaces> |
: <base class>,<interfaces> ] {
<class members>
}
Class members
• Fields
• Constants
• Properties
• Indexers
• Methods
• Events
• Nested type (like Java static inner class, no outer object)
47
Modifiers
Accessibility (visibility) : private, internal, protected, public
Inheritable
sealed : can not be overridden/inherited (Java equivalent : final)
- sealed class
- sealed method
abstract : MUST be overridden/inherited
- abstract class
- abstract method
class/method can not be sealed AND abstract
Parameter modifiers : ref,out,params
Class member/instance member : static
Late binding/static binding : virtual, override, new
Dangerous ? : unsafe
- unsafe class
- unsafe method
- unsafe property
48
Inheritance
class
class
class
class
A
B
C
D
{}
: A {}
: B {}
: A {}
Runtime type checking (RTTI)
operator is
if(a is A) {/* ... */}
if(b is A) {/* ... */} // true if b is A or B
Conversions :
- widening conversions (upcast) : automatic
B
C
D
A
A
B
B
A
b = new B();
c = new C();
d = new D();
ab = b;
ac = c;
bc = c;
bd = d;
// compile time error
ad = d;
- narrowing (cntd.)
49
Inheritance
- narrowing conversions : cast necessary
- simple downcast :
B
C
D
D
ba=(B)ab;
ca=(C)ac;
da=(D)ad;
dc=(D)ac;
// OK
// OK
//OK
// runtime error
- safe downcast (evaluates to null if unsuccesful)
B ba = ab as B;
C ca = ac as C;
D dc = ac as D; // null
50
Polymorphism
Key idea : late binding, based on dynamic object type
C# : use virtual methods, override in derived class
class A
{
public virtual void f() {Console.WriteLine("A.f()");}
}
class B : A
{
public override void f() {Console.WriteLine("B.f()");}
}
class C : B
{
public override void f() { Console.WriteLine("C.f()"); }
}
class D : A
{
public override void f() {Console.WriteLine("D.f()");}
}
51
Polymorphism
A a = new
B b = new
C c = new
D d = new
a.f(); //
b.f(); //
c.f(); //
d.f(); //
A();
B();
C();
D();
A.f()
B.f()
C.f()
D.f()
A[] a = new A[] { new A(), new B(), new C(), new D() };
foreach(A aa in a) aa.f();
// A.f()
// B.f()
// C.f()
// D.f()
52
Polymorphism
Sealing
class A
{
public virtual void f() {Console.WriteLine("A.f()");}
}
class B : A
{
public sealed override void f() {Console.WriteLine("B.f()");}
}
class C : B
{
public override void f() { Console.WriteLine("C.f()"); }
}
NOT allowed
53
Polymorphism
Hiding base class member : new
class A
{public
class B
{public
class C
virtual void f() {Console.WriteLine("A.f()");}}
: A
override void f() {Console.WriteLine("B.f()");}}
: B
{public new void f() { Console.WriteLine("C.f()"); }}
class D : A
{public override void f() {Console.WriteLine("D.f()");}}
A
B
C
D
A
aa
bb
cc
dd
ab
=
=
=
=
=
new
new
new
new
new
A();
B();
C();
D();
B();
aa.f();
bb.f();
cc.f();
dd.f();
ab.f();
//
//
//
//
//
A.f()
B.f()
C.f()
D.f()
B.f()
A ac = new C(); ac.f(); // B.f()
A ad = new D(); ad.f(); // D.f();
B bc = new C(); bc.f(); // B.f();
A[] a = new A[] { new A(), new B(), new C(), new D() };
foreach(A o in a) o.f(); // A.f() B.f()
B.f()
D.f()
54
Polymorphism
Hiding base class member : new
class A
{public
class B
{public
class C
virtual void f() {Console.WriteLine("A.f()");}}
: A
override void f() {Console.WriteLine("B.f()");}}
: B
{public new void f() { Console.WriteLine("C.f()"); }}
class D : A
{public
A
B
C
D
A
aa
bb
cc
dd
ab
new
=
=
=
=
=
new
new
new
new
new
void f() {Console.WriteLine("D.f()");}}
A();
B();
C();
D();
B();
aa.f();
bb.f();
cc.f();
dd.f();
ab.f();
//
//
//
//
//
A ac = new C(); ac.f(); //
A ad = new D(); ad.f(); //
A.f()
B.f()
C.f()
D.f()
B.f()
B.f()
A.f();
B.f();
B bc = new C(); bc.f(); //
A[] a = new A[] { new A(), new B(), new C(), new D() };
foreach(A o in a) o.f(); // A.f() B.f()
B.f() A.f()
55
Polymorphism
new
- define method as new (even if method with
same signature, possibly sealed, exists in base class)
- define new property
- define new field
class A
{protected double i;
public double I
{set{i = value;}
get{return i;}
}
public sealed void f() {Console.WriteLine("A.f()");}
}
class B : A
{private
new int i;
new int I
public
{set{i = value;}
get{return i;}
}
public new void f() {Console.WriteLine(“B.f()");}
}
56
Structs
Struct = class except for
• value type, allocated on the stack
• is implicitely sealed (inherit from single type, System.ValueType),
can implement several interfaces
• can NOT have destructor
• NO field initializers (initialization to 0)
• NO constructor that leaves fields uninitialized
struct CoupleV : A // not allowed unless A is interface
{
private int x=1, y=1; // NOT allowed : field initializer
public CoupleV(int xx) { x = xx; }
// NOT allowed : partial initialization
public CoupleV(int xx, int yy) { x = xx; y = yy; } // allowed
}
57
Interfaces
Interface = class except for
• no implementation, (pure abstract class)
• can be supertype of struct (class can not !)
Interface members :
- methods
- properties
- indexers
- events
always : implicitly public, abstract, virtual and non static
58
Interfaces
interface IP{void f();}
interface IQ{void g();}
class A : IP{
public virtual void f() {Console.WriteLine("A.f()");}
}
class B : A,IQ {
public override void f() {Console.WriteLine("B.f()");}
public virtual void g() {Console.WriteLine("B.g()");}
}
class C : B {
public override void f() { Console.WriteLine("C.f()"); }
public override void g() { Console.WriteLine("C.g()"); }
}
class D : A{
public override void f(){Console.WriteLine("D.f()");}
}
class E : D,IQ {
public override void f() { Console.WriteLine("E.f()"); }
public virtual void g() { Console.WriteLine("E.g()"); }
}
59
Interfaces
IP[] p = new IP[]
IQ[] q = new IQ[]
foreach (IP pp in
foreach (IQ qq in
//
//
//
//
//
//
//
//
{ new A(), new B(), new C(), new D(), new E() };
{ new B(), new C(), new E() };
p) pp.f();
q) qq.g();
A.f()
B.f()
C.f()
D.f()
E.f()
B.g()
C.g()
E.g()
Extending an interface
interface IPP : IP {
void ff();
}
60
Explicit interface
implementation
PROBLEM : implement two interfaces with name collision
-> explicit (instead of implicit) interface implementation
interface U
{
void a();
}
interface V
{
void a();
}
class O : U, V
{
void U.a() { Console.WriteLine("A.ua()"); }
void V.a() { Console.WriteLine("A.va()"); }
}
// ...
O o = new O();
// o.a();
// NOT allowed
((U)o).a();
// A.ua()
((V)o).a();
// A.va()
61
Explicit interface
implementation
LIMITATIONS (compared to implicit implementations)
• NO late binding
no polymorphism related modifiers
(no abstract, virtual, override, new)
• NO access modifier
usage requires cast to interface
access modifier mentioned there is used implicitely
Same rules (as with classes) to
• convert between types
• to convert to structs
62
C# and .NET
1. Introduction
2. C# versus Java : highlights
3. C# data types
4. Defining custom data types
5. Operator Overloading
6. Event driven programming
7. .NET Framework Class Library
8. A GUI in C#
9. A web service in C#
63
Operator overloading
Idea
• treat operators (+,-,*,/,%,...) as special functions
(keyword operator)
• give special meaning to operator according to class
semantics
• allows elegant programming for math-oriented
software
• important issue : what happens in case of mixed type
expressions ?
-> need to overload also type conversion
-> quite complex to keep consistent
-> not available in Java (but proposals are on the way ...)
64
C# Operator overloading
Operators to overload
+
!
~
++
--
+
*
/
%
&
|
^
<<
>>
==
!=
>
<
>=
<=
CAN NOT BE OVERLOADED :
- address related operators (unary *, &)
- assignment ! (cf. C++ ...)
ONLY static operators allowed
LOGIC pairs (MUST be overloaded together)
== and !=
< and >
<= and >=
(unary)
(binary)
arithmetic
bit logic
bit shift
relational
65
Indirect overloading
To keep things consistent
(developer might forget to overload ...)
- && and || are evaluated using & and |
- [] operator overloaded through indexers
- combined assignment operators (+=, -=, *=, /=, ...)
evaluated using non-combined counterparts
66
Value equality
Operators == and != default to reference equality
If other behavior is needed :
- override Equals method (cf. Java)
- redirect Equals to “==“ and “!=“
-> allows compatibility with .NET languages
NOT supporting operator overloading
-> allows polymorphism
67
Value equality
class Point
{
protected int x, y;
public Point(int xx, int yy) { x = xx; y = yy; }
public Point(int xx) : this(xx, xx) { }
public Point() : this(0) { }
public override string ToString()
{
return "<"+x+","+y+">";
}
public static bool operator ==(Point a, Point b)
{
return (a.x == b.x) && (a.y == b.y);
}
public static bool operator !=(Point a, Point b)
{
return !(a == b);
}
}
68
Value equality
Problem
Collections framework heavily uses Equals()-method
(implementation of no-duplicate collections such as Sets)
-> whenever == and != overloaded -> Equals() should be overridden
public override bool Equals(object o)
{
if (o is Point)
{
Point p = (Point)o;
return this == p;
}
else return false;
}
DO NOT call Equals() from within == and != ...
69
Value equality :
inheritance
class Point3D : Point
{
protected int z;
public Point3D(int xx,int yy,int zz):base(xx,yy){z=zz;}
public override string ToString()
{
return "<"+x+","+y+","+z+">";
}
}
// ...
Point a=new Point(1,1);
Point b=new Point(2,2);
Point c = new Point(2, 2);
Point3D d=new Point3D(3,3,3);
Point3D e = new Point3D(3, 3, 3);
Point3D f = new Point3D(3, 3, 4);
Console.WriteLine(a);
// <1,1>
Console.WriteLine(b);
// <2,2>
Console.WriteLine(e);
// <3,3,3>
Console.WriteLine(f);
// <3,3,4>
70
Value equality :
inheritance
Console.WriteLine(a == b); // False
Console.WriteLine(a == c); // False
Console.WriteLine(a == d); // False
Console.WriteLine(b == c); // True -> value !
Console.WriteLine(b == d); // False
Console.WriteLine(c == d); // False
Console.WriteLine(d == e); // True
Console.WriteLine(e == f); // True
Operators == and != should be overloaded in Point3D
public static bool operator ==(Point3D a, Point3D b)
{
return (a.x == b.x) && (a.y == b.y)&&(a.z==b.z);
}
public static bool operator !=(Point3D a, Point3D b)
{
return !(a == b);
}
// ...
Console.WriteLine(e == f);
// False
71
Value equality :
polymorphism
Point[] p ={ new Point(1, 1), new Point(2, 2),
new Point3D(1, 1, 1), new Point3D(2, 2, 2) };
Point s1 = new Point(2, 2)
Point s2 = new Point3D(2, 2, 2);
foreach (Point pp in p) Console.WriteLine(pp == s1);
foreach (Point pp in p) Console.WriteLine(pp == s2);
// False True False True
// False
True
False True
CHANGE operator in base class (!)
public static bool operator ==(Point a, Point b)
{
if(((a is Point3D)&&!(b is Point3D))||
(!(a is Point3D)&&(b is Point3D))) return false;
else return (a.x == b.x) && (a.y == b.y);
}
public static bool operator !=(Point a, Point b)
{
// False True False False
return !(a == b);
}
// False False False True
72
Overloading arithmetic
operators
Operator + Point p: translate over p
Operator + int i: translate over Point(i,i)
public static Point operator +(Point a, Point b){
return new Point(a.x + b.x,a.y + b.y);
}
public static Point operator +(Point a,int i){
return new Point(a.x + i, a.y + i);
}
public static Point operator +(int i, Point a){
return a + i;
}
//...
Point a = new Point(10, 20);
Point b = new Point(20, 30);
Console.WriteLine(a + b);
Console.WriteLine(a + 100);
Console.WriteLine(100 + a + b);
//<30,50>
//<110,120>
//<130,150>
73
Type Conversion
Two versions
implicit
not dangerous, can be invoked by compiler
whenever needed
explicit
dangerous, only done if explicitely asked
e.g. conversion to and from int
Point-to-int : max value of x and y (looses info !)
int-to-Point : Point on diagonal (no info lost !)
74
Type Conversion
public static Point operator +(Point a,int i)
{
Console.WriteLine("+(P,i)");
return new Point(a.x + i, a.y + i);
}
public static Point operator +(int i, Point a)
{
Console.WriteLine("+(i,P)");
return a + i;
}
public static implicit operator Point(int i)
{
Console.WriteLine("(P)i");
return new Point(i, i);
}
public static explicit operator int(Point p)
{
Console.WriteLine("(i)P");
return (p.x > p.y) ? p.x : p.y;
}
75
Type Conversion
Point a = new Point(10,20);
Console.WriteLine((Point)5); // (P)i <5,5>
Console.WriteLine(a + 5);
// +(P,i) <15,25>
Console.WriteLine((int)a + 5); //(i)P 25
In case NO +(Point,int) and +(int,Point) operators :
Console.WriteLine((Point)5); // (P)i <5,5>
Console.WriteLine(a + 5);
// (P)i <15,25>
Console.WriteLine((int)a + 5); // (i)P 25
76
C# and .NET
1.
2.
3.
4.
5.
6.
Introduction
C# versus Java : highlights
C# data types
Defining custom data types
Operator Overloading
Event driven programming
• delegates
• events
7. .NET Framework Class Library
8. A GUI in C#
9. A web service in C
77
Delegates
[<attributes>][unsafe][<access modifiers>]
[new]delegate <return type> <delegate name>
(<parameter list>);
= type defining method signature
- instance can hold (list of) method(s) with matching signature
public delegate bool Filter(string s);
class Del{
public static void Main(){
String[] r = new String[] { "a fair Lady",
"the king and I", "hye buzz", "a beautiful mind",
"the zzz" };
Filter f=new Filter(StartWithA);
ArrayList a=Show(r,f);
Console.WriteLine("Starting with a :");
foreach (String s in a) Console.WriteLine(s);
f=new Filter(EndWithZ);
ArrayList z = Show(r, f);
Console.WriteLine("Ending with z :");
foreach (String s in z) Console.WriteLine(s);
}
//...
78
}
Delegates
class Del
{
// ...
public static bool StartWithA(String s)
{
return s[0] == 'a';
}
public static bool EndWithZ(String s)
{
return s[s.Length-1] == 'z';
}
public static ArrayList Show(String[] s, Filter f)
{
ArrayList l = new ArrayList();
foreach(String i in s) if(f(i)) l.Add(i);
return l;
Starting with a :
}
a fair Lady
}
a beautiful mind
Ending with z :
hye buzz
the zzz
79
Multicast Delegates
Use operators += and -= to add/remove delegates to other delegate
if non-void : return value of last invocation is returned
public delegate void M(int i);
class Multi
{
// ...
public static void Print(int i)
{
Console.WriteLine("i = {0}",i);
}
public static void Sqrt(int i)
{
Console.WriteLine(Math.Sqrt(i));
}
public static void EndMessage(int i)
{
Console.WriteLine("Ending ...");
}
}
80
Multicast Delegates
// public delegate void M(int i);
class Multi
----------------{ // ...
public static void Main()
i = 12
{
3,46410161513775
M m = null;
Ending ...
Console.WriteLine("----------------------------");
----------------m += new M(Print);
i = 16
m += new M(Sqrt);
4
m += new M(EndMessage);
Ending ...
m(12);
i = 16
Console.WriteLine("----------------------------");
m += new M(Print);
----------------m(16);
i = 25
Console.WriteLine("----------------------------");
Ending ...
m -= new M(Sqrt);
i = 25
m(25);
----------------Console.WriteLine("----------------------------");
i = 36
m -= new M(Print);
Ending ...
m(36);
----------------Console.WriteLine("----------------------------");
}
81
}
Multicast Delegates
From within object -> invoked on this-object
public delegate void F();
public class A
{
public F f;
private int i = 0;
public A(int i) {
this.i = i;
f=null;
f+=new F(Print);
f+=new F(Inc);
f+=new F(Print);
f+=new F(Dec);
f+=new F(Dec);
f+=new F(Print);
}
public void Inc() { i++; }
public void Dec() { i--; }
public void Print() {Console.WriteLine(this);}
public override string ToString(){return "<"+i+">";}
public void IncAndDec() {f();}
82
Multicast Delegates
From within object -> invoked on this-object
// ...
public static void Test() {
A a=new A(10);
a.IncAndDec();
a.f();
}
}
class MultiObj
{
public static void Main()
{
A.Test();
A a = new A(20);
a.f();
}
}
<10>
<11>
<9>
<9>
<10>
<8>
<20>
<21>
<19>
83
Delegate versus ...
Delegate vs. C function pointer
- type safe (unless in unsafe regions ...)
- can hold multiple methods to invoke
- can hold instance to invoke method upon
Delegate vs. Interface
- multiple methods to invoke
(could be implemented through list of
interface objects)
- any problem solved with delegates can be
solved using interface types
- “more elegant”
84
Delegate versus Inteface
interface IF
{
bool Filter(string s);
}
class StartWithAFilter : IF
{
public bool Filter(string s)
{
return s[0] == 'a';
}
}
class EndWithZFilter : IF
{
public bool Filter(string s)
{
return s[s.Length - 1] == 'z';
}
}
85
Delegate versus Inteface
class Test {
public static void Main()
{
String[] r = new String[] { "a very fair Lady",
"the king and a z", "hye buzzy",
"a beautiful mind for z", "the zzz" };
ArrayList a = Show(r, new StartWithAFilter());
Console.WriteLine("Starting with a :");
foreach (String s in a) Console.WriteLine(s);
ArrayList z = Show(r, new EndWithZFilter());
Console.WriteLine("Ending with z :");
foreach (String s in z) Console.WriteLine(s);
}
public static ArrayList Show(String[] s, IF f)
{
ArrayList l = new ArrayList();
foreach (String i in s) if (f.Filter(i)) l.Add(i);
return l;
Starting with a :
}
a very fair Lady
}
a beautiful mind for z
Ending with z :
the king and a z
a beautiful mind for z
the zzz
86
Events
A
event
B
events
- notification from A -> B
- WITHOUT calling directly method on B
use of intermediary
- event listeners + event handlers
- in C# : implemented through delegates
87
Events
event
A
delegate
B
Event Source
d
Delegate
delegate
Event Sink
delegate
- delegate defined to fix handler signature
- source class declares ability to fire event
-> public (downcast) multicast delegate d
- delegates registered with d to get notified
- source class fires event by calling delegate d
88
Events : Example
Customer arrives in business centre
-> generates event
-> interested parties are notified
Delegate conventions for eventing
- first argument : identifies source of event
- second argument : additional info
subclass of EventArgs
Example
- ID = object reference
- additional info :
- time of event
- urgency
89
Events : Example
Delegate signature
delegate void CustomerHandler(object s, CustomerArgs e)
public delegate void CustomerHandler(object o,CustomerArgs e);
enum Priority {LOW=0,NORMAL=1,HIGH=2};
class CustomerArgs : EventArgs
{
private DateTime d;
public Priority p;
public static Random r = new Random();
public DateTime Time
{
Preliminaries
get { return d; }
• Delegate declaration
}
public Priority Urgency
• Definition of event handler argument type
{
get {return p;}
}
public CustomerArgs()
{
d = DateTime.Now;
p=(Priority)(r.Next(3));
}
90
}
Events : Example
public class Customer
{
private string name;
public event CustomerHandler CustomerArrival;
public string Name
{
Event source class : Customer
get { return name; }
• Declares event
}
• Listeners will register to event
public Customer(string n){name = n;}
• FIRES event when needed
public void arrive()
{
if (CustomerArrival != null)
{
CustomerArgs args = new CustomerArgs();
CustomerArrival(this, args); // fire the event;
}
}
public override string ToString(){return "<Customer : "+name+">";}
}
91
Events : Example
class HotelService
{private string n;
public HotelService(string n) {this.n=n;}
public string Name{get{return n;}}
public void CustomerArrivalNotification(object o,CustomerArgs a) {
Console.WriteLine(this + " : guest " + (Customer)o +
" arrived at " + (a.Time)+"(Priority : "+a.Urgency+")");
}
public override string ToString()
Event sink classes :
{ return "Hotel service : "+n;
• HotelService
}
• HotelPersonnel
}
• declare a method conforming
class HotelPersonnel
to delegate signature
{private string n;
public HotelPersonnel(string n) {this.n=n;}
public string Name{get{return n;}}
public void CustomerArrivalNotification(object o,CustomerArgs a) {
Console.WriteLine(this + " : guest " + (Customer)o +
" arrived at" + (a.Time) + "(Priority : " + a.Urgency + ")");
}
public override string ToString()
{ return "Hotel personnel : "+n;
}
92
}
Events : Example
class CustomerApp {
public static void Main() {
Customer[] c=new Customer[] {new Customer("Bart De Poorter"),
new Customer("George Bush"),
new Customer("Condaleeza Rice"),
new Customer("Mahatma Ghandi")};
HotelService[] hs = new HotelService[] {
new HotelService("House keeping"),
new HotelService("Accounting"),
new HotelService("Reception") };
HotelPersonnel[] hp = new HotelPersonnel[] {
new HotelPersonnel("Manager"),
new HotelPersonnel("Mr. BigBoss (owner)") };
foreach(HotelService h in hs)
{
foreach(Customer cu in c)
cu.CustomerArrival+=
new CustomerHandler(h.CustomerArrivalNotification);
}
// ...
Main method
• instantiates simulation objects
• binds sinks to sources
93
Events : Example
// ...
foreach (HotelPersonnel h in hp)
{
c[1].CustomerArrival +=
new CustomerHandler(h.CustomerArrivalNotification);
c[2].CustomerArrival +=
new CustomerHandler(h.CustomerArrivalNotification);
}
Console.WriteLine("Starting simulation ----------------");
foreach (Customer cc in c)
{
cc.arrive();
try
{
System.Threading.Thread.Sleep(1000);
}
catch (System.Threading.ThreadInterruptedException e) { }
Console.WriteLine("---------------------");
}
}
}
94
Events : Example
Starting simulation ---------------Hotel service : House keeping : guest <Customer : Bart De Poorter> arrived at 14/12/2005 9:57:06(Priority : NORMAL)
Hotel service : Accounting : guest <Customer : Bart De Poorter> arrived at 14/12/2005 9:57:06(Priority : NORMAL)
Hotel service : Reception : guest <Customer : Bart De Poorter> arrived at 14/12/2005 9:57:06(Priority : NORMAL)
--------------------Hotel service : House keeping : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW)
Hotel service : Accounting : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW)
Hotel service : Reception : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW)
Hotel personnel : Manager : guest <Customer : George Bush> arrived at14/12/2005 9:57:07(Priority : LOW)
Hotel personnel : Mr. BigBoss (owner) : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW)
--------------------Hotel service : House keeping : guest <Customer : Condaleeza Rice> arrived at 14/12/2005 9:57:08(Priority : NORMAL)
Hotel service : Accounting : guest <Customer : Condaleeza Rice> arrived at 14/12/2005 9:57:08(Priority : NORMAL)
Hotel service : Reception : guest <Customer : Condaleeza Rice> arrived at 14/12/2005 9:57:08(Priority : NORMAL)
Hotel personnel : Manager : guest <Customer : Condaleeza Rice> arrived at14/12/2005 9:57:08(Priority : NORMAL)
Hotel personnel : Mr. BigBoss (owner) : guest <Customer : Condaleeza Rice> arrived at14/12/2005 9:57:08(Priority : NORMAL)
--------------------Hotel service : House keeping : guest <Customer : Mahatma Ghandi> arrived at 14/12/2005 9:57:09(Priority : HIGH)
Hotel service : Accounting : guest <Customer : Mahatma Ghandi> arrived at 14/12/2005 9:57:09(Priority : HIGH)
Hotel service : Reception : guest <Customer : Mahatma Ghandi> arrived at 14/12/2005 9:57:09(Priority : HIGH)
---------------------
95
C# and .NET
1.
2.
3.
4.
5.
6.
7.
8.
9.
Introduction
C# versus Java : highlights
C# data types
Defining custom data types
Operator Overloading
Event driven programming
.NET Framework Class Library
A GUI in C#
A web service in C#
96
FCL
-CLS compliant set of managed type
- accessible from all .NET languages
- grouping (3542 types) :
- logically in namespaces (120)
- deployed as a set of assemblies (36) of .NET framework
System
- collection of core classes (Object, ValueType, Enum,
- core interfaces (ICloneable, IComparable, ...)
- time related classes (DateTime, TimeSpan)
- support for
- delegates
- mathematical operations
- custom attributes (Attribute)
- exception handling
- strings (String)
Convert, Exception)
97
FCL
System.Text
- immutable string (System.String)
- mutable string (StringBuilder)
- regular expressions (System.Text.RegularExpressions)
C# string is alias for System.String
overloaded “==“ operator for equality check (NOT in Java !)
indexing strings : use normal indexing mechanism ([])
string a=“abcde”;
char c=a[2];
formatting strings (Format()-method)
format specifier string :
{ParamIndex[,MinWidth][:FormatString]}
e.g. “Value of account {0} is {1:C}” (C -> “Currency”)
98
FCL
System.Collections
- Java-like set of interfaces and classes, implementing popular
data structures (ArrayList, Queue, Stack, BitArray, ...)
- System.Array is base type for all array types
- generics as of .NET v 2.0 (System.Collections.Generics)
to iterate over Collection :
- Collection implements IEnumerable
public interface IEnumerable {
IEnumerator GetEnumerator();
}
- iterator implements IEnumerator
public interface IEnumerator {
bool MoveNext();
object Current {get;}
void Reset();
}
- also : foreach idiom can be used
99
FCL
iterator for Dictionary (Java Map)
public interface IDectionaryEnumerator : IEnumerator {
DictionaryEntry Entry {get;}
object Key {get;}
object Value {get;}
}
IEnumerable
ICollection
IList
IDictionary
get iterator
support for counting
converting to array
indexed collection
100
FCL
class Array : ICollection, IEnumerable, IList
fixed size indexed array
class ArrayList : IList
dynamically sized array
class Hashtable : IDictionary
standard dictionary key/value pairs
hash computed using GetHashCode() method
-> should be overridden
class Queue
FIFO data structure
methods to queue and dequeue
class Stack
LIFO data structure
key methods : push and pop
101
FCL
class Bitarray
compressed form of bool[] (one bit per boolean)
class SortedList : IDictionary
sorted to increase lookup efficiency
(binary search instead of linear search)
class StringCollection : ICollection
special purpose collection for storing strings
class StringDictionary : IEnumerable
idem for storing string maps
102
FCL : Examples
public static void Print(ICollection c)
{
int j = 0;
foreach(object i in c)
Console.WriteLine("{0} -> {1}",j++,i);
Console.WriteLine("--------------------");
}
ArrayList al = new ArrayList();
al.Add("Wim");
al.Add("Ann");
al.Add("Bram");
al.Add("Bart");
al.Add("Greet");
Print(al);
al.Sort();
Print(al);
Console.WriteLine(al[1]);
al[1] = "BART";
Print(al);
0 -> Wim
1 -> Ann
2 -> Bram
3 -> Bart
4 -> Greet
-------------------0 -> Ann
1 -> Bart
2 -> Bram
3 -> Greet
4 -> Wim
-------------------Bart
0 -> Ann
1 -> BART
2 -> Bram
3 -> Greet
4 -> Wim
103
--------------------
FCL : Examples
Hashtable h = new Hashtable();
h["Wim"] = "onetwothree";
h["Bram"] = "123";
h["Greet"] = "Da Vinci";
h["Ann"] = "My fair lady";
Console.WriteLine(h["Bram"]); // 123
Queue q = new Queue();
Stack s = new Stack();
int[] a ={ 1, 2, 3, 4 };
foreach (int i in a) {q.Enqueue(i); s.Push(i);}
Print(q);
Print(s);
Console.WriteLine(q.Dequeue());
Console.WriteLine(s.Pop());
Print(q);
Print(s);
123
0 -> 1
1 -> 2
2 -> 3
3 -> 4
-------------------0 -> 4
1 -> 3
2 -> 2
3 -> 1
-------------------1
4
0 -> 2
1 -> 3
2 -> 4
-------------------0 -> 3
1 -> 2
2 -> 1
-------------------104
FCL : Sorting
Two options :
- object ordering implemented in the class itself
public interface IComparable {
int CompareTo(object o);
}
- delegate ordering to special object
public interface IComparer {
int Compare(object o1,object o2);
}
comparing must follow special contract
1. if a comes before b
->
2. if a is equal to b
->
3. if a comes after b
->
4. null first
->
5. a.CompareTo(b)
->
a.CompareTo(b)<0
a.CompareTo(b) == 0
a.CompareTo(b)>0
a.CompareTo(null)>0
a.GetType() == b.GetType()
105
FCL
System.IO
- standard in, out and error stream
- binary and text file I/O
- registering/notification of filesystem events
- access of user specific secure storage (“Isolated Storage”)
- System.Console
- System.IO.IsolatedStorage
System.Net
- classes for network communication
- raw socket access, TCP, UDP sockets
- HTTP support
- System.Net
- System.Net.Sockets
- System.IO.Stream
106
FCL
System.Security
- security policies, principals, permission sets, evidence
(authentication, key, ...)
- cryptographic library
System.Threading
- support for thread management and pool management
- synchronization mechanisms
- locks (monitor): serialized access
- pulse/wait : notify waiting threads
- System.Timers
- System.Thread
107
FCL
System.Reflection
- retrieve type information (methods, class names, signatures, ...)
at runtime
- retrieve (custom) attributes at runtime
-> for each custom attribute :
- CLR creates object
- retrieved using reflection interface
- retrieve metadata at runtime
- assembly info (version, target OS, ...)
- data to create custom attributes stored as metadata
108
FCL
System.Runtime.Serialization
- write object graph to/from stream (file or network)
- default serializers : XML and binary
- serializability : use non-custom attribute [Serializable]
- System.SerializableAttribute
- System.NonSerializableAttribute
System.Runtime.Remoting
- distributed object model of .NET
- calls can be : synchronous, asynchronous, one-way
- transport protocol : TCP, HTTP or SMTP
- format : binary or SOAP
- naming service, activation service, marshalling, messaging
109
FCL
System.Web.Services
- in fact part of ASP.NET (not part of CLR)
- describe, discover and publish web services
System.Data
- known as ADO.NET
- classes to support database access
System.Xml
- schemas, namespaces, parsing (DOM,SAX)
- implementation of XSLT, XPath, SOAP1.1
110
FCL
System.Drawing
- support for graphics
- known as GDI+
- brushes, fonts, bitmaps, rendering, drawing primitives, ...
System.Windows.Forms
- Rich client applications (“classic GUIs”)
- known as “Windows Forms”
- forms package, GUI components and RAD component model
System.Web
- Thin client applications
- known as “Web Forms”
- server side package creates HTML UI
- support for session management (state), security, deployment, ...
111
- part of ASP.NET
FCL
System.Globalization
- date/time conversions
- string adaptation to locale
- resource file to centralize locale data
System.Configuration
- per user, per application configuration management
System.EnterpriseServices
- advanced services
- distributed transaction, object pooling, queuing, event handling
- reliable asynchronous messaging
- access to directory service
112
C# and .NET
1.
2.
3.
4.
5.
6.
7.
8.
9.
Introduction
C# versus Java : highlights
C# data types
Defining custom data types
Operator Overloading
Event driven programming
.NET Framework Class Library
A GUI in C#
A web service in C#
113
GUIs in .NET
- heavily uses delegates
- event subscription
- event notification
- Visual Studio .NET contains IDE to assist GUI development
- choose New Project -> “Windows Application”
(instead of “Console Application”)
- Add WinForms as needed
- Drop components from ToolBox on each form
- Change component state in IDE generated code
- Code event handlers
114
Example : incrementor
System.Windows.Forms.Form
declares properties :
Name, Text
Controls
(container)
fires events :
System.EventHandler Load
System.Windows.Forms.TextBox
declares properties : Name, Text
System.Windows.Forms.Button
declares properties : Name, Text
fires events :
System.EventHandler Click
115
Example : incrementor
Main()-method
using System;
using System.Collections.Generic;
using System.Windows.Forms;
IDE-generated
[Program.cs]
namespace WindowsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
116
Example : incrementor
Form1-class
IDE-generated
namespace WindowsApplication1
(edited)
{
partial class Form1 {
[Form1.Designer.cs]
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources
/// should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
117
}
Example : incrementor
Form1-class
IDE-generated
(edited)
[Form1.Designer.cs]
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(92, 150);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Click here";
this.button1.UseVisualStyleBackColor = true;
118
this.button1.Click += new System.EventHandler(this.button1_Click);
Example : incrementor
Form1-class
IDE-generated
(edited)
[Form1.Designer.cs]
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(78, 103);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.TabIndex = 1;
this.textBox1.TextChanged +=
new System.EventHandler(this.textBox1_TextChanged);
119
Example : incrementor
IDE-generated
Form1-class
//
(edited)
// Form1
[Form1.Designer.cs]
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Incrementer";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
button1;
System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button
private
}
}
120
Example : incrementor
template IDE-generated
Form1-class
handler code to add !
namespace WindowsApplication1
[Form1.cs]
{
public partial class Form1 : Form
{
int i = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e){}
private void button1_Click(object sender, EventArgs e)
{
i++;
textBox1.Text = ""+i;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
121
C# and .NET
1.
2.
3.
4.
5.
6.
7.
8.
9.
Introduction
C# versus Java : highlights
C# data types
Defining custom data types
Operator Overloading
Event driven programming
.NET Framework Class Library
A GUI in C#
A web service in C#
122
.NET / C# web service
- actually part of ASP.NET
- uses .asmx file to bind server to code
- C# :
- web service derives from System.Web.Services.WebService
- class must be public, must have public constructor
- has [WebService] attribute
paramters :
- Description : info
- Name : default = class name
- Namespace : XML-namespace
- every exposed service method should have attribute
[WebMethod]
parameters include :
-Description : info
-EnableSession : default = false
123
- MessageName : default = method name
.NET / C# web service
web server
- runs .asmx -file
- locates class files referred
- loads, runs and manages code
client
- statically retrieves WSDL document
- generates and compiles proxy class
- instantiates service proxy
- call methods on the proxy
124
Hello Service
Server side
Create ASP.NET Web Service project
File -> New -> Web Site
ASP.NET Web Service template
Edit [WebService] attribute (if necessary)
Add class logic, give any WS method [WebMethod] attribute
Build project
Run Project
Check if service is running (WSDL-file)
http://localhost:1665/WebSite1/?.asmx ? WSDL
Invoke method from browser to check proper functioning
125
Hello Service
Service.asmx
<%@ WebService Language="C#"
CodeBehind="~/App_Code/Service.cs"
Class="Service" %>
126
Hello Service
Service.cs
using
using
using
using
System;
System.Web;
System.Web.Services;
System.Web.Services.Protocols;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld(string e) {
return "Hello World there, "+e;
}
}
127
Hello Service
WSDL (http://localhost:1655/WebSite1/Service.asmx?WSDL)
128
Hello
Service
Service invocation from browser
(http://localhost:1655/WebSite1/Service.asmx?op=HelloWorld)
Answer :
129
<string>Hello World there, MyName</string>
Hello Service
Client side
Create Windows Console project (or GUI project ...)
Open WS project and add to current solution
Add Web Reference
-> Browse local host
-> Select Web Reference (= namespace for proxy)
(Here : HelloService)
Add client code
-> instantiate proxy object
-> call WS methods on proxy
130
Hello Service
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
HelloService.Service s = new HelloService.Service();
Console.WriteLine(" -> " + s.HelloWorld("Georgie "));
}
}
}
-> Hello World there, Georgie
Press any key to continue . . .
131