1 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#
May 10, 2015
1
1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types5. Operator Overloading6. Event driven programming7. .NET Framework Class Library8. A GUI in C#9. A web service in C#
2
C# and .NET
1. Introduction • History• C# features• .NET framework
2. C# versus Java : highlights3. C# data types4. Defining custom data types5. ...
3
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 towardscomponent based design
4
Historyprocedural/structured design/programming
object oriented design/programming
component based design/programming
C/PASCAL
C++
JAVA
C#/.NET
component support possibleBUT NOT built into the language- templates- deployment descriptors
COM/COM+CORBA component model
5
C# features : component orientedModern large-scale systems are component based
Properties
get/set
event based communication
support to annotate component for- deployment- configuration at design and/or runtime- component versioning- documentation
6
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
7
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
8
.NET framework
“.NET framework”
CLR
FCL Framework Class Library
Application Code
Version 1.0 released January 15, 2002
9
.NET execution model
Platform AND language portabilityCLR can exploit processor/platform specific optimizationsSupported languages :
C#, J#, VB.NET, JScript, Microsoft IL, Managed Extensions for C++Supplied by 3rd parties :
COBOL, Eiffel, Haskell, Forth, Scheme, Smalltalk, Pascal, ...
CLR
CompilerApplication Code in “A Language”
CIL
10
.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 languageAll types eventually mapped to CTS-types
e.g. cross language inheritanceJ# 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
11
.NET : FCL categoriescomprises
- > 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
12
Hellonamespace 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); }}
C#
Java
13
C# and .NET
1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types
14
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
15
PropertiesC# : special support for getters/settersJava : 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 Min {
get {return min;}set {min=value;}
}// value : implicit variable used when// calling setter method
- getter/setter grouped together- encourages to think in terms of properties
16
IndexerMeans to index underlying datastructureJava 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”);
17
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 eventif(!cancel) temp=value;
}
}}
18
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.");
}
}
}
19
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);
}}
20
Enummerations
Standard Java approachpublic class Period {
public final static int DAILY=1;public final static int WEEKLY=2;public final static int MONTHLY=3;public final static int YEARLY=4;
}
// ...int publicationPeriod=Period.DAILY;// PROBLEM : does not prevent int publicationPeriod=12; ???
C# approachpublic enum Period{DAILY=1,WEEKLY=2,MONTHLY=3,YEARLY=4};Period publicationPeriod = Period.WEEKLY;
21
Enummerations
Java 5 approachenum PeriodE{DAILY,WEEKLY,MONTHLY,YEARLY}//... int publicationPeriod=Period.DAILY;
System.out.println(publicationPeriod); PeriodE pubPeriod=PeriodE.DAILY; System.out.println(pubPeriod);
// OUTPUT : // 1 // DAILY
22
Iterating over a CollectionStandard 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# approachforeach(object o in collection) {
// do something with o}foreach(int i in array) {
// do something with i}
Java 5 approachfor(Object o : collection) {
// do something with o}for(int i : array) { // do something with i}
23
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 + ")"; }
24
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());}
25
Operator OverloadingAllows to program type specific operator semanticsMore 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); // TRUEConsole.WriteLine((object)p == (object)q); // FALSE non-virtual !
26
PolymorphismJava : all methods virtual (late binding) by defaultC# (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
27
AssembliesType 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
28
Visibilityprivate
same as Java = default for interface and enum members
publicsame 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 protectedvisible 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
29
Parameter modifiersPassing referencesref
pass reference to method requires parameter is assigned definite value before method entry
outrequires definite parameter assignment before returning frommethod call
Variable number of argumentsparams
can be applied to last argument of method
Parameter modifiers are part of method signature
30
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
31
AttributesAllow 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
32
Field modifiersconst
- 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 ...”)
33
Pointer arithmetic
allowed in sections marked as unsafepointer type : <type>* dereferencing : *<pointer expression>address calculation : &<variable>
Garbage collector should NOT move around objectsused in unsafe regions
MUST be declared fixed
34
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 4AdditionOne(k);foreach (int a in k) Console.WriteLine("{0}", a); // 2 3 4 5
35
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;
...
36
Constructors - DestructorsVery similar to Java constructors – finalizersConstructor :
can contain explicit constructor callspecified outside constructor body
- call to other constructor of same type : this(...)- call to base class constructor : base(...)
DestructorNOT for value typeNO explicit calls to destructorC++-like syntax (actually expands to calling Finalize)
class A {
public A():this(1){}public A(int i):base(i){}~A() {/* Destructor */}
}
37
C# and .NET
1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types
38
C# type systemValue 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 + ")"; }}
39
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 + ")"; }}
40
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)
41
Type unification
all struct and class types derive from object(pointer types do not ...)
“simple” (“primitive”) types are actually structsint : alias for System.Int32long : alias for System.Int64... boxing – unboxing- value type -> reference type : copy made (automatic)- reference type -> value type : explicit cast necessaryint x=12;object o=x; // box int y=(int)o; // unbox through downcast
42
Available types
Value typessigned integer : sbyte, short, int, longunsigned integer : byte, ushort, uint, ulongfloating point : float, decimal, doublelogical : boolcharacters : char
Reference typesobjectstring
standard notations for constants apply (U : unsigned, L : long)standard rules for conversions apply
43
Checked Arithmetic
checked(<expression>)checked {/* block */}
checks for integral overflowsgenerates runtime exception OverflowException
unchecked(<expression>)unchecked{/* block */}
turns off compile time bounds checking
44
Control flow statementsSame as in Java, BUTswitch :
no “fall through” behavioureach case must end with jump (break, goto, ...)
foreach
goto label;
// ...int x=0;loop :
x++;if(x<5) goto loop;
45
Namespaces
Similar to java packages w.r.t. avoiding name clashesBUT : no boundary for accessibilityCan be nestednamespace 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
46
C# and .NET
1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types
47
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)
48
ModifiersAccessibility (visibility) : private, internal, protected, publicInheritable
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 abstractParameter modifiers : ref,out,paramsClass member/instance member : staticLate binding/static binding : virtual, override, newDangerous ? : unsafe
- unsafe class- unsafe method- unsafe property
49
Inheritanceclass A {}class B : A {}class C : B {}class D : A {}
Runtime type checking (RTTI)operator isif(a is A) {/* ... */}if(b is A) {/* ... */} // true if b is A or B
Conversions :- widening conversions (upcast) : automatic
B b = new B();C c = new C();D d = new D();A ab = b;A ac = c;B bc = c;B bd = d; // compile time errorA ad = d;
- narrowing (cntd.)
50
Inheritance
- narrowing conversions : cast necessary- simple downcast :
B ba=(B)ab; // OKC ca=(C)ac; // OKD da=(D)ad; //OKD dc=(D)ac; // 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
51
PolymorphismKey idea : late binding, based on dynamic object typeC# : 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()");}}
52
Polymorphism
A a = new A();B b = new B();C c = new C();D d = new D();a.f(); // A.f()b.f(); // B.f()c.f(); // C.f()d.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()
53
PolymorphismSealingclass 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
54
PolymorphismHiding base class member : newclass A{public virtual void f() {Console.WriteLine("A.f()");}}class B : A{public override void f() {Console.WriteLine("B.f()");}}class C : B
{public new void f() { Console.WriteLine("C.f()"); }}class D : A{public override void f() {Console.WriteLine("D.f()");}}
A aa = new A(); aa.f(); // A.f() B bb = new B(); bb.f(); // B.f() C cc = new C(); cc.f(); // C.f() D dd = new D(); dd.f(); // D.f() A ab = new B(); ab.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()
55
PolymorphismHiding base class member : newclass A{public virtual void f() {Console.WriteLine("A.f()");}}class B : A{public override void f() {Console.WriteLine("B.f()");}}class C : B
{public new void f() { Console.WriteLine("C.f()"); }}class D : A
{public new void f() {Console.WriteLine("D.f()");}} A aa = new A(); aa.f(); // A.f() B bb = new B(); bb.f(); // B.f() C cc = new C(); cc.f(); // C.f() D dd = new D(); dd.f(); // D.f() A ab = new B(); ab.f(); // B.f()
A ac = new C(); ac.f(); // B.f() A ad = new D(); ad.f(); // A.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() A.f()
56
Polymorphismnew
- 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; public new int I {set{i = value;} get{return i;} } public new void f() {Console.WriteLine(“B.f()");}}
57
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}
58
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
59
Interfacesinterface 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()"); }}
60
InterfacesIP[] p = new IP[] { new A(), new B(), new C(), new D(), new E() };IQ[] q = new IQ[] { new B(), new C(), new E() };foreach (IP pp in p) pp.f();foreach (IQ qq in q) qq.g();
// A.f()// B.f()// C.f()// D.f()// E.f()// B.g()// C.g()// E.g()
Extending an interfaceinterface IPP : IP {
void ff();}
61
Explicit interface implementationPROBLEM : 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()
62
Explicit interface implementation
LIMITATIONS (compared to implicit implementations)• NO late binding
no polymorphism related modifiers(no abstract, virtual, override, new)
• NO access modifierusage requires cast to interfaceaccess modifier mentioned there is used implicitely
Same rules (as with classes) to• convert between types• to convert to structs
63
C# and .NET1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types5. Operator Overloading6. Event driven programming7. .NET Framework Class Library8. A GUI in C#9. A web service in C#
64
Operator overloadingIdea
• 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 ...)
65
C# Operator overloadingOperators to overload
+ - ! ~ ++ -- (unary)
(binary)+ - * / % arithmetic& | ^ bit logic<< >> bit shift== != > < >= <= relational
CAN NOT BE OVERLOADED :- address related operators (unary *, &)- assignment ! (cf. C++ ...)
ONLY static operators allowedLOGIC pairs (MUST be overloaded together)
== and !=< and ><= and >=
66
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
67
Value equality
Operators == and != default to reference equalityIf other behavior is needed :
- override Equals method (cf. Java)- redirect Equals to “==“ and “!=“ -> allows compatibility with .NET languages
NOT supporting operator overloading -> allows polymorphism
68
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); } }
69
Value equalityProblem 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 != ...
70
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>
71
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
72
Value equality : polymorphismPoint[] 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) { return !(a == b); }
// False True False False// False False False True
73
Overloading arithmetic operatorsOperator + Point p: translate over pOperator + 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); //<30,50>Console.WriteLine(a + 100); //<110,120>Console.WriteLine(100 + a + b); //<130,150>
74
Type Conversion
Two versionsimplicit
not dangerous, can be invoked by compiler whenever neededexplicit
dangerous, only done if explicitely asked
e.g. conversion to and from intPoint-to-int : max value of x and y (looses info !)int-to-Point : Point on diagonal (no info lost !)
75
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; }
76
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
77
C# and .NET
1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types5. Operator Overloading6. Event driven programming
• delegates• events
7. .NET Framework Class Library8. A GUI in C#9. A web service in C
78
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); } //... }
79
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 Ladya beautiful mindEnding with z :hye buzzthe zzz
80
Multicast DelegatesUse operators += and -= to add/remove delegates to other delegateif 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 ..."); } }
81
Multicast Delegates // public delegate void M(int i); class Multi { // ... public static void Main() { M m = null; Console.WriteLine("----------------------------"); m += new M(Print); m += new M(Sqrt); m += new M(EndMessage); m(12); Console.WriteLine("----------------------------"); m += new M(Print); m(16); Console.WriteLine("----------------------------"); m -= new M(Sqrt); m(25); Console.WriteLine("----------------------------"); m -= new M(Print); m(36); Console.WriteLine("----------------------------"); } }
-----------------i = 123,46410161513775Ending ...-----------------i = 164Ending ...i = 16-----------------i = 25Ending ...i = 25-----------------i = 36Ending ...-----------------
82
Multicast DelegatesFrom 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();}
83
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>
84
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”
85
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'; } }
86
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 Ladya beautiful mind for zEnding with z :the king and a za beautiful mind for zthe zzz
87
Events
A
B
events- notification from A -> B- WITHOUT calling directly method on B
use of intermediary- event listeners + event handlers- in C# : implemented through delegates
event
88
EventsA
B
event
Event Source
Event Sink
- 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
d
Delegate
delegate
delegate
delegate
89
Events : ExampleCustomer 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
90
Events : ExampleDelegate signaturedelegate 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 { get { return d; } } public Priority Urgency { get {return p;} } public CustomerArgs() { d = DateTime.Now; p=(Priority)(r.Next(3)); }}
Preliminaries• Delegate declaration• Definition of event handler argument type
91
Events : Example public class Customer { private string name; public event CustomerHandler CustomerArrival; public string Name { get { return name; } } public Customer(string n){name = n;} public void arrive() { if (CustomerArrival != null) { CustomerArgs args = new CustomerArgs(); CustomerArrival(this, args); // fire the event; } } public override string ToString(){return "<Customer : "+name+">";} }
Event source class : Customer• Declares event • Listeners will register to event• FIRES event when needed
92
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() { return "Hotel service : "+n; } } class HotelPersonnel {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; } }
Event sink classes :• HotelService• HotelPersonnel• declare a method conforming to delegate signature
93
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
94
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("---------------------"); } } }
95
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)---------------------
96
C# and .NET
1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types5. Operator Overloading6. Event driven programming7. .NET Framework Class Library8. A GUI in C#9. A web service in C#
97
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, Convert, Exception)- core interfaces (ICloneable, IComparable, ...)- time related classes (DateTime, TimeSpan)- support for
- delegates- mathematical operations- custom attributes (Attribute)- exception handling- strings (String)
98
FCLSystem.Text
- immutable string (System.String)- mutable string (StringBuilder)- regular expressions (System.Text.RegularExpressions)
C# string is alias for System.Stringoverloaded “==“ 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”)
99
FCLSystem.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 IEnumerablepublic interface IEnumerable {
IEnumerator GetEnumerator();}
- iterator implements IEnumeratorpublic interface IEnumerator {
bool MoveNext();object Current {get;}void Reset();
}
- also : foreach idiom can be used
100
FCLiterator 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 countingconverting to array
indexed collection
101
FCLclass Array : ICollection, IEnumerable, IList
fixed size indexed arrayclass ArrayList : IList
dynamically sized arrayclass Hashtable : IDictionary
standard dictionary key/value pairshash computed using GetHashCode() method
-> should be overridden class Queue
FIFO data structuremethods to queue and dequeue
class StackLIFO data structurekey methods : push and pop
102
FCL
class Bitarraycompressed form of bool[] (one bit per boolean)
class SortedList : IDictionarysorted to increase lookup efficiency(binary search instead of linear search)
class StringCollection : ICollectionspecial purpose collection for storing strings
class StringDictionary : IEnumerableidem for storing string maps
103
FCL : Examplespublic 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 -> Wim1 -> Ann2 -> Bram3 -> Bart4 -> Greet--------------------0 -> Ann1 -> Bart2 -> Bram3 -> Greet4 -> Wim--------------------Bart0 -> Ann1 -> BART2 -> Bram3 -> Greet4 -> Wim--------------------
104
FCL : ExamplesHashtable 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);
1230 -> 11 -> 22 -> 33 -> 4--------------------0 -> 41 -> 32 -> 23 -> 1--------------------140 -> 21 -> 32 -> 4--------------------0 -> 31 -> 22 -> 1--------------------
105
FCL : SortingTwo options :
- object ordering implemented in the class itselfpublic interface IComparable {
int CompareTo(object o);}
- delegate ordering to special objectpublic interface IComparer {
int Compare(object o1,object o2);}
comparing must follow special contract1. if a comes before b -> a.CompareTo(b)<02. if a is equal to b -> a.CompareTo(b) == 03. if a comes after b -> a.CompareTo(b)>04. null first -> a.CompareTo(null)>05. a.CompareTo(b) -> a.GetType() == b.GetType()
106
FCLSystem.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
107
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
108
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
109
FCLSystem.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
110
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
111
FCLSystem.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, ... - part of ASP.NET
112
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
113
C# and .NET
1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types5. Operator Overloading6. Event driven programming7. .NET Framework Class Library8. A GUI in C#9. A web service in C#
114
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
115
Example : incrementor
System.Windows.Forms.Buttondeclares properties : Name, Textfires events :
System.EventHandler Click
System.Windows.Forms.TextBox declares properties : Name, Text
System.Windows.Forms.Formdeclares properties :
Name, Text Controls (container)
fires events :System.EventHandler Load
116
Example : incrementorMain()-methodusing System;using System.Collections.Generic;using System.Windows.Forms;
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()); } }}
IDE-generated[Program.cs]
117
Example : incrementorForm1-classnamespace WindowsApplication1{
partial class Form1 { /// <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); }
IDE-generated(edited)[Form1.Designer.cs]
118
Example : incrementor#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; this.button1.Click += new System.EventHandler(this.button1_Click);
IDE-generated(edited)[Form1.Designer.cs]
Form1-class
119
Example : incrementorForm1-class
// // 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);
IDE-generated(edited)[Form1.Designer.cs]
120
Example : incrementor // // Form1 // 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
private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox1; }}
IDE-generated(edited)[Form1.Designer.cs]
Form1-class
121
Example : incrementornamespace WindowsApplication1
{ 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) { } }}
template IDE-generatedhandler code to add ![Form1.cs]
Form1-class
122
C# and .NET
1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types5. Operator Overloading6. Event driven programming7. .NET Framework Class Library8. A GUI in C#9. A web service in C#
123
.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- MessageName : default = method name
124
.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
125
Hello Service
Server side
Create ASP.NET Web Service projectFile -> New -> Web SiteASP.NET Web Service template
Edit [WebService] attribute (if necessary)Add class logic, give any WS method [WebMethod] attributeBuild projectRun ProjectCheck if service is running (WSDL-file)
http://localhost:1665/WebSite1/?.asmx ? WSDLInvoke method from browser to check proper functioning
126
Hello Service
Service.asmx
<%@ WebService Language="C#" CodeBehind="~/App_Code/Service.cs" Class="Service" %>
127
Hello ServiceService.csusing System;using System.Web;using System.Web.Services;using 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; } }
128
Hello ServiceWSDL (http://localhost:1655/WebSite1/Service.asmx?WSDL)
129
Hello ServiceService invocation from browser
(http://localhost:1655/WebSite1/Service.asmx?op=HelloWorld)
Answer :<string>Hello World there, MyName</string>
130
Hello ServiceClient side
Create Windows Console project (or GUI project ...)Open WS project and add to current solutionAdd Web Reference
-> Browse local host-> Select Web Reference (= namespace for proxy)
(Here : HelloService)Add client code
-> instantiate proxy object-> call WS methods on proxy
131
Hello Serviceusing 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, GeorgiePress any key to continue . . .