Title: C
1C - the language for the 2000s
- Judith Bishop
- University of Pretoria, South Africa
- jbishop_at_cs.up.ac.za
- Nigel Horspool
- University of Victoria, Canada
- nigelh_at_uvic.ca
2Thursday 27 May
- www.cs.up.ac.za
- Choose courses
- Go to bottom of list and choose IRA310
- Sign up for exam, and for tutorials
3Volunteers on a C course in Africa
Do it in C Naturally!
4Contents
- Introduction
- Basic C
- GUIs with Views
- Advanced OOPS
- Networking
- Technical considerations
5C Concisely
- First year programming text book due September
2003 - Addison Wesley, 2003
- Incorporates Views
- Reviewed by Microsoft
- Contents on the Views website
- http//www.cs.up.ac.za /rotor
6Microsoft Comments
- Many computer books are so heavy that lifting
them causes a hernia, yet they have less content
than your favorite tabloid. Many academic text
books are so boring that they turn your brains to
dust, yet they don't teach you anything that is
of use in the real world. - Not with this book!
- Erik Meijer, Technical Lead, MS Web Data Team
7Facts on C
- Designed at Microsoft by Anders Hejlsberg
(Delphi, Java Foundation classes). Scott
Wiltamuth and Peter Golde - Language of choice for programming in .NET
- Standardised by ECMA December 2002 and ISO April
2003 - It is expected there will be future revisions to
this standard, primarily to add new functionality.
8Goals
- general-purpose
- software engineering principles
- software components for distributed environments.
- source code portability
- internationalization
- embedded systems
- Is this Java or C?
9Why should I know about C?
- A good language, well supported
- Useful for teaching e.g. data structures,
compilers, operating systems, distributed
systems, first year - Inter-language operability via .NET (Java
doesn't) - Multi-platform via Rotor (like Java)
- Not tied to an IDE or rapid development (like VB
or Delphi) - Efficiency potential (scientific programming)
- Base for future development e.g. XEN
10Contents
- Introduction
- Basic C
- GUIs with Views
- Advanced OOPS
- Networking
- Technical considerations
11Syntactic niceties
- A slightly enhanced Hello World
- using System
- class Welcome
- static void Main()
- string name " Peter "
- Console.WriteLine("Welcome to C" name)
- Console.WriteLine("It is now "
DateTime.Now) -
-
- The libraries are the language
12Some terminology
13Structured types - structs
- Structs are lightweight - should be used often
- Structs can have fields, methods, properties,
constructors, operators, events, indexers,
implemented interfaces, nesting - Structs cannot have destructors, inheritance,
abstract
a
struct T int b, c void p ... T a
b c
p function
14Initialisation
- Struct initialisation rules
- instance fields may not be initialised
- static fields may be initialised
- if there is a constructor, then all fields must
be initialised there - if no constructor, values are unspecified
struct T static int a int b, c T
b 4 c 6
a 0 b 4 c 6
15The System.DateTime struct
// Constructors DateTime (int year, int month,
int day) DateTime (int year, int month, int
day, int hour, int min, int sec) //
Static Properties static DateTime Now
static DateTime Today static DateTime
UTCNow // Instance properties int Day
int Month int Year int Hour int DayOfYear
Plus more
16Example - Meetings
Console.WriteLine("London New York ") for
(int hour8 hourlt11 hour)
meeting new DateTime (now.Year, now.Month,
now.Day, hour, 0, 0)
offsetMeeting meeting.AddHours(offset)
Console.WriteLine("0t 1t", meeting,
offsetMeeting)
London New York 0800 AM 0300 AM 0900 AM
0400 AM 1000 AM 0500 AM 1100 AM 0600 AM
17Properties by example
- class TestTutorial
- public static void Main()
- City conference new City
- ("Klagenfurt",
- new DateTime(2003,8,24))
- conference.Meeting new
- DateTime(2003,8,
- tutorial.Meeting.Day-1)
- Console.WriteLine(
- "Speaking at "
- conference.Name
- " on "
- conference.Meeting)
-
-
- using System
- struct City
- string name
- DateTime meeting
- public City(string n,
- DateTime m)
- name n
- meeting m
-
- public DateTime Meeting
- get return meeting
- set meeting value
-
- public string Name
- get return name
-
18A struct vs a class
- struct complex
- double re, im
-
- complex c
- must define equality and comparison
- class complex
- double re, im
-
- complex d
- for values, must define equality and comparison
c
d
19Structured types - classes
- Classes are heavyweight
- Classes can have fields, methods, properties,
constructors, operators, events, indexers,
implemented interfaces, nesting - and destructors, inheritance, abstract
a
class T int b, c void p ... T a
b c VMT
p function
20Equality
- public override bool Equals(object d)
- Pet p (Pet) d
- return namep.name typep.type
-
- if (igt1 p.Equals(list))
- Console.WriteLine("Repeated data.")
- else
- Have to be careful because plist will compile,
but will compare references
21Value and reference semantics
22Type promotion
- The results of a mixed numerical expression are
promoted to the type with the greater range. - if either operand is double, the result is
double, - otherwise if either operand is long, the result
is long, - otherwise the result is int.
- For operations on bytes, the result is always
converted to an int. - Division applied to integers produces an integer
result. So for example we have - 7 / 3 2
- 3 / 4 0
23Explicit type conversion
- (typeid) expression or checked ((typeid)
expression) - The expression is evaluated and converted to the
type specified, with possible loss of
information. - Real numbers are rounded towards zero to make
integral values. - If the type cannot hold the resulting value and
checking is turned on, an error called an
OverflowException occurs. - Placing checked in front of the conversion forces
the exception to happen, even if the checking
option is off in the compiler. - int i 6 double z
- double x 3.14
- double y 5.003000000008E15
- z i // always valid - value is 6.0
- i x // compiler error - must explicitly
convert - i y // compiler error - must explicitly
convert - i (int) x // valid - value is 3
- i (int) y // execution error if checked is on,
- // unspecified value otherwise
24in, out and ref parameters
- in
- pass by value
- the default
- out
- value copied out only (not in as well)
- used to return multiple values from a method
- ref
- pass by reference
- changes are made to the actual object
- out and ref must be specified by caller and callee
void Rearrange(ref City a, ref City b)
DateTime temp a.MeetingTime a.MeetingTime
b.MeetingTime b.MeetingTime
temp.MeetingTime Rearrange(ref London, ref
NewYork)
25Visual Studio
- Ive done some overtime today, so the Visual
Studio .NET 2003 is available for our students
from today on at the download server I told them
today. The software is available in the English
and German (even Chinese) version. - For those who dont want to use the Visual
Studio, the .NET SDK will be available within the
next few days from the download server. - http//maniac.stud.uni-karlsruhe.de
- Andreas Heil
- Microsoft Student Consultant
- MAP - Microsoft Academic Program
- Email i-aheil_at_microsoft.com
- Web http//www.studentconsultant.org/unikarlsruhe
/ - Mobile 49 (0)174 9045832
26Output
- Printing is done using the System.Console class.
Three approaches - 1. Use concatenation
- Console.WriteLine(name " " descr " for G"
price) - 2. Use ToString
- public override string ToString()
- return name " " descr " for G" price
-
- Baskets grass, woven for G8.5
- cont ...
27Formatted output
- 3. Use a format string, where the justification
and field widths of each item can be controlled - Console.WriteLine("0 1 for G2,0f2"
- name, descr, price)
- Baskets grass, woven for G8.50
N,Ms
format code e.g. f or C or D
width - default is left, positive means right
item number
28Formatting other types
NumberFormatInfo f new NumberFormatInfo() f.Cur
rencyDecimalSeparator "," f.CurrencyGroupSepara
tor " " f.CurrencySymbol ""
- Less use of methods through format specifications
- double amount 10000.95
- Console.WriteLine(
- String.Format(f, "0C", amount))
- 10 000,95
29Control structures
- C has the standard C or Java control
structures, viz - for
- if-else and goto!
- while
- do-while
- switch-case
- Conditions must be explicitly converted to bool
- The switch has two very nice features
- case on strings
- Compulsory break after a case
if (s.Length 0) Not if (s.Length)
30Collections - Arrays
- Arrays are indexed by number e.g.
- int markCounts new markCounts101
- string monthNames new string13
- DateTime myExams new DateTimenoOfExams
- C follows the C/Java tradition of
- Once declared, their size is fixed.
- The indices are integers and start at zero.
- There is a property called Length.
- The elements in the array can be any objects.
- Bounds are always checked (ArrayOutOfBoundsExcepti
on)
31Array class
- Corresponding to the type array there is an
Array class with useful methods e.g. - Array.BinarySearch(a, v)
- Array.Clear(a, first, num)
- Array.IndexOf(a, v)
- Array.Sort(a)
- Example, including Split
24 8 2003
public Date(string s) string elements
s.Split(' ') day int.Parse(elements0)
month Array.IndexOf(monthNames,elements1)
32Indexers
- All of these have overloaded, so that they
can operate exactly like an array in a program - Cs rich collections include
- Hash tables
- Sorted lists
- Stacks
- Queues
- BitArrays
- ArrayLists
SL
A
0 1 2 3
Wed
A1 SL"Wed"
33Example of SortedLists
- COS110 350
- GEOL210 80
- ENG100 600
- class Enrollments
- string code
- int size
- public Enrollments(string c, int s)
- code c
- size s
-
- ... other methods here
34 continued
- Define a list
- SortedList year2003 new SortedList(100)
- Put an object in the list using the same
notation as for arrays - year2003"PHY215" new Enrollment("PHY215",
32) - Print out the enrollment for Physics
- Console.WriteLine("PHY215 has "
- (Enrollment)year2003"PHY215".size
"students") - PHY215 has 32 students
35Foreach loop
- Designed to loop easily through a collection
- foreach (type id in collection.Keys)
- ... body can refer to id
-
- Example
- foreach (string course in year2003.Keys)
- Enrollment e (Enrollment) year2003course
- Console.WriteLine(e.code " " e.size)
-
- Cant say foreach (string course in year2003)
Why?
36Demonstration 1 - Public Holidays
- The Public Holidays Program
- Illustrates
- switch on string
- sorted lists
- indexers
- Split
- file handling
- GUI specification described later
37Output from the demo
38Contents
- Introduction
- Basic C
- GUIs with Views
- Advanced OOPS
- Networking
- Technical considerations
39Views Vendor independent extensible windowing
system
- SSCLI (and Rotor) has no GUI capability
- General move to platform independent GUIs
- Views is a Rotor Project to provide GUI
specifications and a rendering engine using XML
and a toolkit such as Qt or Tcl/TK - Available on http//views.cs.up.ac.za
40GUI building today
41(No Transcript)
42Example in WinForms
show.Click new
EventHandler(ActionPerformed) hide.Click new
EventHandler(ActionPerformed) p
ublic void ActionPerformed(Object src,
EventArgs args) if (src
show) pic.Show() else if (src hide)
pic.Hide()
- Embedded in 115 lines of generated code labelled
do not touch - Unexplained classes and unused objects here
43A GUI using XML
44Example in Views
XML
Views.Form f new Views.Form(_at_"ltFormgt
ltverticalgt lthorizontalgt ltButton
NameShow/gt ltButton NameHide/gt
lt/horizontalgt ltPictureBox Namepic
Image'CJacarandas.jpg' Height175/gt
lt/verticalgt lt/Formgt" )
string c for () c f.GetControl()
PictureBox p (PictureBox) f"pic" if (c
null) break switch (c) case Show"
p.Show() break case Hide"
p.Hide() break
C
- No pixel positioning
- No generated code
- Separation of concerns
45Demo 2 - ShowHide
- Winforms
- Make some changes
- Views
- Make some changes
46The Views Notation
form ltformgt controlGroup lt/formgt controlGroup lt
verticalgt controlList lt/verticalgt
lthorizontalgt controlList lt/horizontalgt controlList
control textItemList ltitemgt text lt/itemgt
control controlGroup ltButton/gt
ltCheckBox/gt ltCheckedListBoxgt textItemList
lt/CheckedListBoxgt ltDomainUpDowngt textItemList
lt/DomainUpDowngt ltGroupBoxgt radioButtonList
lt/GroupBoxgt ltLabel/gt ltListBox/gt
ltOpenFileDialog/gt ltSaveFileDialog/gt
ltPictureBox/gt ltTextBox/gt ltProgressBar/gt
ltTrackBar/gt radioButtonList ltRadioButton/gt
47A typical control - Button
ON
- ltButton/gt NameS
- TextS
- ImageF
- WidthM
- HeightM
- ForeColorC
- BackColorC
- Creates a push button which is a variable given
by the Name S. - The button can be labelled with a Text string or
with an Image or both. - The size of the button defaults to something
large enough to hold the label, either text or an
image or can be set with Width and Height. - Clicking the button causes GetControl to return
with the name of the control.
ltButton NameonButton TextON /gt
Compulsory
48The Handler methods
Essentially five kinds of methods construct clo
se getControl get put PLUS direct access
Form(string spec,params) The constructor. void
CloseGUI( ) Terminates the execution thread
string GetControl( ) Waits for the user to
perform an action string GetText(string
name) Returns the value of the Text
attribute int GetValue(string name) Returns the
Value attribute from TrackBar, ProgressBar and
CheckBox int GetValue(string name, int index)
Returns the status of CheckBox at position
index void PutText(string name, string
s) Displays the string in a TextBox or ListBox
control. void PutValue(string name, int
v) Sets an integer value associated with a
ProgressBar or CheckBox
49Views.Form v new Form (_at_"ltform Text Luckygt
ltverticalgt ltTextBox name Number Text
'13'/gt ltButton name Start/gt
ltListBox name Day Width 270/gt
lt/verticalgt lt/formgt") int luckyNumber
int.Parse(v.GetText("Number")) Random r
new Random (luckyNumber) for( )
string s v.GetControl( ) if (snull)
break switch (s) case "Start"
DateTime luckyDate new
DateTime(DateTime.Now.Year, r.Next(3,12),
r.Next(1,30)) v.PutText("Day", "Your
lucky day will be "
luckyDate.DayOfWeek " " luckyDate.ToString("M"
)) break
50Multiple controls - arrays in XML?
- Arrays of product names and images
- Arrays of prices (in the background)
double unitCost new doublemaxNumProducts
string item new stringmaxNumProducts ltB
utton Name??? ImageApples.gif
Width72 Height72/gt
51XML Positional parameters
// Set up Form parameter itemcount
product formParameters2count product
formParameters2count1 product ".gif"
// Construct the form form new
Views.Form(v_specs, formParameters) // Part of
the Form specification ltverticalgt ltButton
Name0 Image1 Width72 Height72/gt
ltButton Name2 Image3 Width72 Height72/gt
ltButton Name4 Image5 Width72
Height72/gt lt/verticalgt // Handle a specific
product select Array.IndexOf(item,c)
52Demo 3 - Till Program
- Till Program
- Till Program amended
- Removing an product (see Run method)
- Adding controls (see ReadData method)
- Writing to a ListBox (see ReadDataFile method)
- Reacting to the Button (see ReadDataFile method)
- Emergence of scrollbars
53Acquiring more control
- Views.Form f new Views.Form( _at_"ltformgt
ltverticalgt - ltLabel Namelabel1 Text'Enter Your Name '/gt
- ltTextBox Namebox1 Width150/gt
- lt/verticalgt
- lt/formgt"
- creates in the Views engine a hash table of
controls with the keys being the strings of the
Name attributes - Access to an individual control may be obtained
by using the indexer operation, and that access
may be used to achieve run-time effects. - TextBox tb fbox1"
- tb.Font new Font(FontFamily.GenericMonospace,
10) - Label lab flabel1"
- lab.BackColor Color.Red
- f.Invalidate() // force form to be redrawn with
new colours
54Cross platform
- XWT-XUL Control Engine in Java and ActiveX
Rendering via XUL.CSS in Mozilla - SWT (not XML based) Rendering efforts for Win,
GTK, Mac Supported by IBM and Eclipse - Views Engine and rendering in Tcl/TK, using
Rotor for Unix, Win and MacOSX (Rajwinder)
55Cross Language
- XML-XUL Independent schema and specs
Handlers in JavaScript, in the XML - SWT For Java only, uses JNI to get to OS
- Views Schema is WinForms oriented but can be
used in Java with JNI wrapper to the engine
(Worrall and Lo)
56XUL example (for Tic-Tac-Toe)
lt!-- main.xwt --gt ltxwtgt lttemplate
thisbox"frame" width"220" height"260"
color"black"gt ltbox
orient"vertical"gt ltboxgt
ltcell id"northwest"gtlt/cellgt
ltcell id"north"gtlt/cellgt
ltcell id"northeast"gtlt/cellgt
lt/boxgt .. and two more of these
lt/boxgt lt/templategt lt/xwtgt lt!--
cell.xwt --gt ltxwtgt lttemplate hpad"5"
vpad"5"gt ltbox color"white"
width"44" height"44" id"inner"gt
lt/boxgt lt/templategt lt/xwtgt
Procedures
57XUL handlers
lt!-- cell.xwt --gt ltxwtgt lttemplate
hpad"5" vpad"5"gt _Press1
function() if (state
"empty") state "x"
_state
function(s) if (s "empty")
inner.image null
else if (s "x")
inner.image "x" else if
(s "o") inner.image
"o"
ltbox color"white" width"44" height"44"
id"inner"gt lt/boxgt
lt/templategt lt/xwtgt
JavaScript
58UIML from Harmonia
lt?xml version"1.0"gt lt!DOCTYPE uiml ...
"uiml2_0g.dtd"gt ltuimlgt ltinterfacegt
ltstructuregt ...lt/structuregt
ltstylegt ...lt/stylegt ltcontentgt
...lt/contentgt ltbehaviorgt
...lt/behaviorgt lt/interfacegt
ltpeersgt ltlogicgt ...lt/logicgt
ltpresentationgt...lt/presentationgt
lt/peersgt lt/uimlgt
ltstructuregt ltpart id"TopLevel"
class"JFrame"gt ltpart id"L"
class"JLabel"/gt ltpart id"Button"
class"JButton"/gt lt/partgt lt/structuregt
59UIML Handlers
ltbehaviorgt ltconditiongt ltevent
class"actionPerformed" part-name"Button"/gt
lt/conditiongt ltactiongt
ltproperty part-name"L" name"text"gt
ltcall name"Counter.increment"/gt
lt/propertygt lt/actiongt lt/behaviorgt
- Very Java-based
- Intended to map from UIML to Java, C, HTML, WML,
VoiceXML) - Our experiments in 2000 on mapping to applets,
WML and HTML showed this to be A bridge too
far (Bishop, Ellis, Roux and Steyn)
60Contents
- Introduction
- Basic C
- GUIs with Views
- Advanced OOPS
- Networking
- Technical considerations
61Extensibility
- Inheritance
- For classes and interfaces, not structs
- No multiple inheritance
- Used for closely coupled extensibility
- Interfaces
- Can have methods, properties, indexers and events
- Used for loosely coupled extensibility
- Abstract classes
- Used to force redefinition of methods
- All can have class modifiers
- For accessibility and versioning
62Modifiers etc
- this keyword refers to the current instance of a
type - Accessibility options
- public access everywhere default for enums and
interface members - protected access within a class and its
derivatives - internal access within a type default for
non-nested types - private access within a type default for
structs and classes - other
- readonly declarations that can be assigned
only once - sealed prevents inheritance
63Interfaces vs inheritance
INTERFACES
INHERITANCE
64Inheritance - virtual functions
- overridden
- base class specifies virtual, and derived class
may supply another version using override - overridden abstract
- base class specifies virtual abstract, and
derived class must supply another version using
override
virtual V
OR
virtual V
override V
virtual abstract V
65Virtual functions cont.
- hidden
- base class supplies a virtual function of the
same name as an existing derived class function.
Override is not assumed. Derived class should be
recompiled with function specified as new, to
make the separation explicit.
F
1 2 3
virtual F
F
virtual F
new F
66Demonstration 4 - StarLords
- Illustrates
- inheritance
- base constructor calling
- virtual and override
- ref parameters
67Program output
68Boxing and unboxing
- Value types are implicitly promoted to the object
type or an interface type implemented by the
value type - an object instance is created and and the value
copied in - object o
- int i 6
- o i
- The object type can be explicitly converted to a
value-type or from any interface type that
implements the value type - the object is checked to be a value of the value
type, then the value is copied out of the
instance. - i (int) o
69Using the IComparable Interface
- IComparable interface
- public int CompareTo(object obj)
- The meaning of the comparison is defined in the
method itself. - Returns negative, zero, or positive
- IComparable is used by the sorting and searching
methods already defined for the Array and other
collections. - It is already implemented for the basic types
such as int and string, and also for all the
types defined in the System namespace, such as
DateTime. - The comparison is not a bitwise one, but can be
intelligently defined to suit the type.
70Example - a small Staff class
- struct Staff
- string name
- int startDate
- public Staff(string n)
- name n
- startDate
- DateTime.Now.Year
-
- public string Name
- get return name
-
- public int StartDate
- get return startDate
-
- public override string
- ToString ()
- return "Staff "name
-
- Sort an array of Staff using Array.Sort
- The elements must implement IComparable
- public int CompareTo(object o)
- return (name.CompareTo
- (((Staff) o).name))
- Sort calls CompareTo, treating the elements of
the array as objects. We unbox to treat them as
Staff - Array.Sort(staffList,0,n)
Unboxing
71Alternative comparator methods
- IComparer interface
- public int Compare(object x, object y)
- We can force the Sort method to use a specific
Compare method - Array.Sort(staffList,0,n,compareByDate)
- A new compare method can check dates
- public class StaffByDate IComparer
- public int Compare(object x, object y)
- return (((Staff)x).startDate.
- CompareTo(((Staff) y).startDate))
-
- This class is declared inside the Staff class.
Then we can instantiate an object and pass it to
the extended version of Sort as follows - Array.Sort(staffList,0,count,new
Staff.StaffByDate())
72Class Conversions
- A class may be implicitly upcast to a class that
it derives from or that it implements. - It may be explicitly downcast to a class that
derives from it. This explicit downcast may fail.
- objectname is typename - returns true or false
- objectname as typename - converts or returns
null - (typename) objectname - converts or raises
exception - public int CompareTo(object o)
- if (o is Staff)
- return (name.CompareTo(((Staff) o).name))
- return -1
73Operator overloading
- DateTime struct
- public static DateTime operator
- (DateTime d, TimeSpan t)
- e.g. birth 18
- Not allowed for new ( )
- implicit can be used to make casting automatic
- public static implicit operator
- CheckBox(GenObject RHS)
- return (CheckBox)RHS.Control
-
- enables an object of type Control to be treated
as a CheckBox without a conversion - Indexer is not overloaded, but defined like a
property with get and set.
74Serialisation
- Persistence of objects on the net or on disks or
a server - All classes marked as Serializable can have
their objects send out with writeObject and
retrieved with readObject. - C offers
- CLR-centric serialization using soap and XML or
all graphs - CLR-centric binary serialisation
- And clean XSD schemas and XML for most graphs
- The XML serialising is done via SOAP
- SoapFormatter swrite new SoapFormatter ()
- Swrite.Serialize(output,st)
- SoapFormatter sread new SoapFormatter ()
- Fromdisk (theType) sread.Deserialize(input)
- Where output and input are the same stream
75Demonstration 5 Access control
- Card access control system
- Illustrates
- Interfaces
- Polymorphism
- Operator overloading
- Serialisation
76Delegates
- Delegates allow references to methods
- They separate methods from a specific name
- One step up from interfaces
C
Delegates
Interfaces
Inheritance
77Simple graphics
- Drawing is done in an OnPaint method
- protected override void OnPaint (PaintEventArgs
e) - or in a Handler connected to a Paint event
- public void whatever (Object source,
PaintEventArgs e) - this.Paint PaintEventHandler (whatever)
- Images can be displayed using drawimage
- E.Graphics.DrawImage(Image.FromFile(photo.jpg),0
,0) - Drawing can be integrated with Views
78Demonstration 6 Selecting images
- Illustrates
- Drawing
- Events
- Images
- Views
79Other C goodies
- Enumerations - System.Enum can write and read
them! - Param modifier allows variable number of
parameters - Assemblies for archiving compiled classes,
metadata, images etc - Reflection can make programming very powerful
- Extensive namespaces
- Proposals for
- Generics
- Anonymous methods
- Iterators
- Namespace alias qualifier
- Partial type declarations
80Generics
- Part of the Rotor Gyro download
- Defined in the OOPLSA paper by Kennedy and Syme
- Better approach than dynamic polymorphism (based
on object supertype) - safety, expressivity,
clarity, efficiency - Stack s new Stack()
- s.Push((int)s.Pop()(int)s.Pop())
- Stack ltintgt s new Stack ltintgt ()
- s.Push(s.Pop()s.Pop())
- Extension to the CLR giving exact runtime types,
dynamic linking, and shared code
81Contents
- Introduction
- Basic C
- GUIs with Views
- Advanced OOPS
- Networking
- Technical considerations
82Threads
- Threads are objects of the System.Threading class
- They are initiated by linking to a ThreadStart
delegate and supplying a callback method. - using System.Threading
- Thread t new Thread (
- new ThreadStart(object.RunMethodName)).Start
- public void RunMethodName()
- some loop
- statements
- possibly containing calls to
Thread.Sleep(n) -
83Demonstraion 7 Ticking Clock
- Ticking Clock
- Illustrates
- Threads
- Delegates and events
- Integrating it with Views
84Web requests
Support for Several protocols In a uniform way
85Socket communication
Standard socket Communication With
uniform streams
86Remoting
- Three kinds of remote objects
- Single call
- Singleton
- client-activated
- Leases created for objects transported outside
the application - Objects are hosted by
- A managed executable
- IIS (Internet Information Server)
- .NET component services
- Use serialization for transporting data
- Metadata and configuration files enable
cross-language programming
87Remoting scenarios
88Example - a Server
using System using System.Runtime.Remoting using
System.Runtime.Remoting.Channels using
System.Runtime.Remoting.Channels.Tcp namespace
Project public class RunServer public
static int Main(string args)
TcpChannel chan new TcpChannel(int.Parse(port))
ChannelServices.RegisterChannel(chan)
RemotingConfiguration.RegisterWellKnownServiceTy
pe (Type.GetType("Project.Server,
Server"), "Server", WellKnownObjectMode
.Singleton) Server server (Project.Server) //
customised Activator.GetObject(typeof(
Project.Server), "tcp//" "localhost"
"" "8085" "/Server")
server.Prepare()
89Demo 8 Currency Calculator
- Illustrates extensive client server with remoting
90Contents
- Introduction
- Basic C
- GUIs with Views
- Advanced OOPS
- Networking
- Technical considerations
91.NET offerings
Rotor - Microsofts Implementation of the CLI
(plus some)
Microsoft Windows Web service Framework
SSCLI
.NET
CE
92(No Transcript)
93RotorSSCLI- a Shared Source CLI
- Microsofts implementation of the CLI, Code name
Rotor - Free, modifiable and redistributable CLI
implementation - Platform independent Currently executes on MS
Windows, FreeBSD and Mac OS/X - Practically identical to .NET, but with retooled
JIT compiler and GC, and extensions such as
generics - Programmed in C an C
- Other implementations of CLI are Ximians Mono
and DotGNUs Portable.NET
94A compliant CLI Implementation
VS.NET
System.Web (ASP.NET)
System.WinForms
System.Drawing
C
System.Data (ADO.NET)
System.Xml
SDK Tools
System
Common Language Runtime
Windows Platform
95Rotor CLI Implementation
VS.NET
System.Web (ASP.NET)
System.WinForms
System.Drawing
System.Data (ADO.NET)
System.Xml
SDK Tools
System
Common Language Runtime
Platform Abstraction
96Runtime Architecture
- Three main tasks
- Loading and executing
- Memory management
- Security management
- The SSCLI makes the interactions easier to follow
- Class structure
- ClassLoader (in csload.h) manages the loading of
IL and metadata and when the JIT compiler will
run - FJit (in fjit.h) reads IL and produces machine
code - GCHeap (gc.h) handles memory management and
garbage collection
97Core classes in the runtime
98Hello World in IL
- Hello.Main in IL
- .method public hidebysig static void Main() cil
managed -
- .entrypoint
- Idstr "Hello, World!"
- call voidmscorlibSystem.ConsoleWriteLine(st
ring) - ret
-
- .NET provides a managed code environment for
handling IL and metadata, using the JIT compiler. - It is easy to understand the process on Rotor
99Hello.Main in x86 Native Code
- //Function Prologue
- push ebp
- mov ebp,esp
- push esi
- xor esi,esi
- push esi
- push ecx
- push edx
- //set stack frame to zero
- mov ecx,1
- addr_a
- push 0
- loop addr_a
- //load "Hello, World" and call Console.WriteLine
- mov eax, ltconstant string table entygt
- mov eax,dword ptr eax
- mov ecx,eax
- push ecx
- mov eax, Console.WriteLine
100The Size of Rotor
- Entire SSCLI package is big
- 16 MB download
- FastChecked binary build approx. 70MB, 1200
classes, 20 DLLs, 20 EXEs - 27MB of C and C, 8MB of C, some assembly code
- Source binary approx. 600MB, 6000 files
- Missing APIs
- Much needed WinForms GUI toolkit(see Views)
- Database connectivity
- Debugging
- Rotor not guaranteed to be bug-free
- Debugging tool similar to GDB/JDB
101Why use Rotor?
- Shared source
- Source code and binaries are free
- Useful for testing and experimentation
- Useful for CS education
- Provides for open platform development
- Platform independent
- PAL facilitates CLI deployment on many platforms
- Cross-platform
- Remoting provides convenient language independent
middleware - Standard
- ECMA and ISO
- Strong international academic community support
102Where to get C
- ECMA specs
- http//msdn.microsoft.com/net/ecma
- Microsoft commercial C and CLR SDK
- http//msdn.microsoft.com/downloads
- Shared source info (Rotor) for non-Windows
platforms - http//www.microsoft.com/sharedsource
- Microsoft Academic Alliance
- http//www.msdnaa.net/
103Further Reading
- Bishop Judith and Horspool Nigel, C Concisely,
Addison Wesley, due out September 2003 - Peter Drayton, Ben Albahari, Ted Neward, C in a
Nutshell, OReilly, 2002 - Troelsen, Andrew C and the .NET platform A!
press 2001 - Damien Watkins, Mark Hammond and Brad Abrams,
Programming in the .NET environment, Microsoft
.NET Development Series, Addison Wesley, 2002 - Visual Studio help files
- DevHood tutorials -- see http//www.devhood.com
- http//www.cs.up.ac.za/rotor -- for the Views
project