Advanced Language Concepts in C# David Figge [email protected] Extra Session Last Update:...
85
Advanced Language Concepts in C# David Figge [email protected]Extra Session Last Update: 3/09 Page 1 Copyright (C) 2009 by David Figge. All Rights Reserved.
Advanced Language Concepts in C# David Figge [email protected] Extra Session Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights
Advanced Language Concepts in C# David Figge
[email protected] Extra Session Last Update: 3/09Page
1Copyright (C) 2009 by David Figge. All Rights Reserved.
Slide 2
Advanced Language Concepts in C# WPF, Delegates and Events, and
Design Patterns Last Update: 3/09Page 2Copyright (C) 2009 by David
Figge. All Rights Reserved.
Slide 3
Introduction When Windows Vista was introduced, it included a
new graphical subsystem, code named Avalon Its purpose was to
Provide a new state-of- the-art graphics API Supported through the
DirectX module, which provides low-level graphics APIs for games,
etc Designed to use hardware acceleration at a low level (when
present) Windows 7 inherited this subsystem, too. Last Update:
2/11Copyright (C) 2011 by David Figge. All Rights Reserved.Page
3
Slide 4
What Is Windows Presentation Foundation? Windows Presentation
Foundation (WPF) is the.Net component designed to leverage these
new graphical capabilities. WPF is a graphical subsystem within.Net
Introduced in.Net 3.0 WPF was designed to provide a single
interface to support the flexibility and needs of todays modern
applications. It works on Vista/Win7 and XP Vista/Win 7 has it
automatically XP requires an update to have.Net 3.0 (minimum) Last
Update: 2/11Copyright (C) 2011 by David Figge. All Rights
Reserved.Page 4
Slide 5
WPF Provides Unified Support for Standard Windows elements
(dialog boxes, controls) Easy support for higher level graphics
(gradient fills, etc) The ability to defining complex data
representation at the presentation level The ability to easily
combine graphics, animation, video, and audio Support for 2D and 3D
graphics, including putting 2D graphics on a 3D surface This is a
good example of an application that can be put together using the
capabilities of WPF, including Last Update: 2/11Copyright (C) 2011
by David Figge. All Rights Reserved.Page 5
Slide 6
Introduction So WPF takes several, disjointed APIs within the
OS and put them under one presentation foundation Last Update:
2/11Copyright (C) 2011 by David Figge. All Rights Reserved.Page 6
Windows Forms PDFWindows Forms/ GDI+ Windows Media Player Direct3D
(DirectX) WPF Graphical interface (e.g. forms and controls)
On-screen documents Fixed-format documents Images Video and audio
Two-dimensional graphics Three-dimensional graphics Windows Forms
(WinForms) is the.Net 1.x and 2.x solution to UI design. It
basically provided layout capabilities for standard Windows
controls and ActiveX controls. Fixed Format Documents were
typically displayed using something like Adobes PDF File Format.
This allows documents to display on screen as they will on a
printer. Images and 2D graphics were displayed using WinForms,
sometimes with assistance from COM object technology. To use Video
and Audio, you were delving into the Media arena, which is
supported by Windows Media Player And if you wanted to get fancy 3D
graphics, you had to use the DirectX technology WPF combines all
these technologies into one presentation layer and allowing
improved development and integration between all these elements.
Questions so far? So lets see how this is integrated into.Net
Slide 7
.Net Architecture.Net Applications.Net Dev Tools.Net WCF
(Indigo) WPF (Avalon) CardSpace (InfoCard) WF (WorkFlow) Common
Language Runtime.Net 2.0 Base Class Libraries, ASP.Net 2.0, ADO.Net
2.0, WinForms 2.0 Windows OS (Windows Vista/7, XP, Server) PC
Hardware At the very base, of course, we have the PC Hardware. The
significant factor here is that for the first time the Windows
presentation layer will make use of hardware accelereration
provided by graphics cards The OS provides the ultimate interface
between the application programs and the hardware.Net sits on top
of the OS, and consists of a series of run-time and compile-time
elements. Well come back to this in a minute.Net applications run
on top of.Net. For developers, the.Net Development Tools are a key
element in this structure, providing support for creation and
debugging of.Net applications in many languages. One of the key
elements within the.Net structure is the Common Language Runtime
(CLR) providing just- in-time compiling, security, memory
management, and a host of other services..Net 3.0 introduced
Windows Communi- cations Foundation, providing support for server
level and peer-to- peer network communi- cations. CardSpace
provides identity verification technologies to.Net, tying together
everything from Web Logins to Active Directory. Windows WorkFlow
Foundation supports taking information through a series of steps
(the work flow) to its completion. WPF Sits beside these
technologies providing the UI support for.Net applications and
integrating these into.Net, the Operating System, and ultimately
the hardware. Lets look more closely at the WPF components. Last
Update: 2/11Copyright (C) 2011 by David Figge. All Rights
Reserved.Page 7
Slide 8
.Net Applications.Net Dev Tools.Net OS PC Hardware WPF
Components PresentationFramework PresentationCore Common Language
Runtime Milcore Media Integration Layer DirectX User32/GDI Kernel
WPF ComponentNon-WPF.Net OS Component Codecs From the beginning of
Windows, the presentation of a window and its components resided in
the OS, through functions in the User32 and GDI modules, working in
conjunction with the core OS kernel. As the need for more direct
graphic programming came about (mostly from game developers),
DirectX was developed as a fast, direct link to core level graphics
capabilities of the OS and the hardware. All WPF output to the
system occurs through DirectX. The Media Integration Layer,
Milcore, is the component that ties WPF into DirectX Milcore is the
one major component of WPF that is written in unmanaged code. This
was needed for performance reasons, especially around timing of
animations audio, video, and production of 2D and 3D graphics.
Video and audio Codecs are used by Milcore, and are also written in
unmanaged code. The Presentation Core layer provides the managed
code interface into milcore, and implements the core services for
WPF. The Presentation Foundation module implements the end user
presentation features, including layouts, storyboard animations,
and data binding. Last Update: 2/11Copyright (C) 2011 by David
Figge. All Rights Reserved.Page 8 Still doing okay?
Slide 9
Under the Covers Lets take a quick look under the covers at WPF
This will help us understand coding aspects as well UI Elements are
maintained as a group of Visual objects Visual objects are
maintained in a Composition Tree, managed by the MIL Each element
of WPF creates and adds one or more Composition Nodes to the tree
These nodes contain rendering instructions So the entire
applications visuals are represented as a collection of Composition
Nodes. Last Update: 2/11Copyright (C) 2011 by David Figge. All
Rights Reserved.Page 9
Slide 10
UI Rendering So the MIL maintains the visual tree for each
application Remember these dont contain visuals, they contain
instructions used to render the visuals This allows the MIL to
retain the visual tree for each application, so it becomes
responsible for updating the graphics rather than continually
calling into the application via a Paint method This also allows
the application to update the visuals incrementally, as individual
pieces change, rather than all at once like traditional Windows
apps Animations become simple incremental changes applied based on
a timer interval. Last Update: 2/11Copyright (C) 2011 by David
Figge. All Rights Reserved.Page 10
Slide 11
UI Rendering So the MIL maintains the visual tree for each
application The MIL has a dedicated thread that periodically
updates the visuals as changes occur The MIL uses a painters
algorithm that renders elements from back to front, allowing you to
skip areas that are covered and handle complex aspects like
transparency easily. The rendering of the UI is also assisted via
the Graphics Processing Unit on the video adapter (if present) Last
Update: 2/11Copyright (C) 2011 by David Figge. All Rights
Reserved.Page 11
Slide 12
Managing the UI: Properties WPF employs a data-driven system
for displaying user content After the initial rendering, visual
objects are updated via Properties These properties may represent
data changes (like a new record to display), or any other visual
aspect (like IsVisible) These properties can be set manually via
code, or bound to an element and updated automatically Last Update:
2/11Copyright (C) 2011 by David Figge. All Rights Reserved.Page
12
Slide 13
Managing the UI: Properties So, the visuals are largely
customized by a collection of Properties These properties, however,
also support an inheritance element Base level properties (like
FontSize) are inherited by child elements So, when base properties
are changed, child elements are notified as well This is also good,
because elements may have dozens (or hundreds) of properties
managing visuals, and this avoids each element retaining copies
Last Update: 2/11Copyright (C) 2011 by David Figge. All Rights
Reserved.Page 13
Slide 14
Managing the UI: Properties Finally, the Property system also
supports Attached Properties An example: A Grid Panel allows
elements to be laid out in a Grid format (columns and rows) Each
element on the grid has an attached property of the grid row and
column This is only because the grid is holding the element. This
isnt inheritance, because on a different layout, the properties may
change Last Update: 2/11Copyright (C) 2011 by David Figge. All
Rights Reserved.Page 14
Slide 15
Under the Covers So each application has two threads One for
rendering and repainting This one generally runs by itself without
developer help And one for managing the UI Input from the user,
changes you cause programmatically This is important, because any
processing you do in your program takes place in the UI thread,
effectively freezing the UI So any type of lengthy operations (that
might be felt by the UI) should be done in a background thread Last
Update: 2/11Copyright (C) 2011 by David Figge. All Rights
Reserved.Page 15
Slide 16
But Wait, Theres More! Some additional aspects worth discussing
(and we will over the next several slides): Graphical Services
Interoperability Media Services Animations Data Binding Annotations
Imaging Documents Last Update: 2/11Copyright (C) 2011 by David
Figge. All Rights Reserved.Page 16
Slide 17
Graphical Services All graphics (including windows) are through
Direct3D, providing A unified way to displaying from simple (Win32
level) graphics to complex 3D graphics The ability to offload
graphics tasks to the Graphics card GPU This can reduce the
workload on the computer's CPU. Use of vector-based graphics, which
allow lossless scaling. Supports 3D model rendering and interaction
in 2D applications. Allows interactive 2D content to be overlaid on
3D surfaces natively (cool stuff!). Last Update: 2/11Copyright (C)
2011 by David Figge. All Rights Reserved.Page 17
Slide 18
Interoperability WPF provides interoperability with the Windows
API Via hosting, one can use Windows Presentation Foundation inside
existing Win32 code Or one can use existing Win32 code inside
Windows Presentation Foundation. Interoperability with Windows
Forms is also possible through the use of the ElementHost and
WindowsFormsHost classes. Last Update: 2/11Copyright (C) 2011 by
David Figge. All Rights Reserved.Page 18
Slide 19
Media Services WPF provides shape primitives for 2D graphics
Also provides a built-in set of brushes, pens, geometries, and
transforms. It also supports 3D UI, 3D documents, and 3D media.
Supports most common image formats. Supports video formats WMV,
MPEG and some AVI files by default Because Windows Media Player is
running underneath, WPF can use all the codecs installed for it.
Last Update: 2/11Copyright (C) 2011 by David Figge. All Rights
Reserved.Page 19
Slide 20
Animations Time-based animation. Scene redraws are time
triggered. Isnt affected by CPU speed and load Presentation timers
are initialized and managed by WPF. Scene changes coordinated via
storyboards. This makes them easy to code Animations can be
triggered by other external events, including user action. Ships
with a set of predefined effects, such as fade out for all
controls. Last Update: 2/11Copyright (C) 2011 by David Figge. All
Rights Reserved.Page 20
Slide 21
Data binding WPF supports three types of data binding: One
time: where the element ignores updates One way: where the element
has read-only access to data. Two way: where the element can read
from and write data LINQ queries can act as data sources for data
binding. Binding of data has no bearing on its presentation. WPF
provides data templates to control presentation of data. Base
controls provided by WPF: buttons, menus, grids, list boxes, etc.
Last Update: 2/11Copyright (C) 2011 by David Figge. All Rights
Reserved.Page 21
Slide 22
Annotations Annotations can be applied on a per- object basis
via WPFs Document or FlowDocument element. WPF only provides the
capability for creating, storing and managing annotations Each
application must expose the UI on their own. Last Update:
2/11Copyright (C) 2011 by David Figge. All Rights Reserved.Page
22
Slide 23
Imaging WPF uses the native Windows Imaging Component (WIC)
code and APIs This means developers can write image codecs for
their specific image file formats. Last Update: 2/11Copyright (C)
2011 by David Figge. All Rights Reserved.Page 23
Slide 24
Effects WPF provides for bitmap effects Although.Net 3.5+ and
hardware support required Special effects such as drop shadows and
blurring are built in. Last Update: 2/11Copyright (C) 2011 by David
Figge. All Rights Reserved.Page 24
Slide 25
Documents WPF natively supports paginated documents. It
provides the DocumentReader class, which is for reading fixed
layout documents. The FlowDocumentReader class offers different
view modes such as per-page or scrollable It also reflows text if
the viewing area is re sized. Last Update: 2/11Copyright (C) 2011
by David Figge. All Rights Reserved.Page 25
Slide 26
UI Separation So, clearly, WPF is bringing a lot of power to
the UI and code development table. Another direction that WPF used
was to separate the design of the UI from the code to support that
UI This is a method that was introduced with ASP UI Design elements
are stored in one file Code to support the UI is stored in a Code
Behind page with the same name Visual Studio handles all the naming
and management details Last Update: 2/11Copyright (C) 2011 by David
Figge. All Rights Reserved.Page 26
Slide 27
In WPF, the design elements are defined in a file with a XAML
extension Rhymes with Camel Stands for eXtended Application Markup
Language This is an XML-based document that has definitions for all
the UI elements of a window Each window has its own xaml page The
Design Page
Slide 28
The Code Behind Page The Code Behind page contains code that
supports the UI Its usually best to keep this to code just required
to support the windows UI Avoid putting business logic in this file
This decouples the business logic from the UI elements
Slide 29
Why This Separation? The purpose behind this separation is to
allow the UI design and the support code to be done as separate
processes UI design is a specific skill from programming And,
typically, programmers are not good UI designers So this separation
really allows UI designers and programmers to have the ability to
work together, but not work in the same files Last Update:
2/11Copyright (C) 2011 by David Figge. All Rights Reserved.Page
29
Slide 30
Lets Give it a Try! At its simplest level, WPF can be very easy
to work with Visual Studio provides an easy form design mode that
allows for simple drag-and-drop functionality You dont need to work
with the Xaml code until you want something more advanced In this
example, well have a label, a text box, a button, and a message box
Well do this together as a class Last Update: 2/11Copyright (C)
2011 by David Figge. All Rights Reserved.Page 30
Slide 31
Our First WPF App Create a new WPF Windows app called Birthday
Drag the controls from the Toolbox and drop them onto the form as
shown Note how the xaml code changes as you add the controls Use
the Properties window to set The Content of the label to Your name:
The Content of the button to Todays My Birthday! Double-click on
the button to go to its handler in the code-behind page. Code:
MessageBox.Show(Happy Birthday, + textBox1.Text + !); Give it a
try! Last Update: 2/11Copyright (C) 2011 by David Figge. All Rights
Reserved.Page 31
Slide 32
Lets See What Weve Got Lets take a look at some of the elements
that make up this program First, looking at the code page
(Window1.xaml.cs) Last Update: 2/11Copyright (C) 2011 by David
Figge. All Rights Reserved.Page 32
Slide 33
Code Example Window1.xaml.cs using System;... namespace
Birthday { ///... public partial class Window1 : Window { public
Window1() { InitializeComponent(); } private void
button1_Click(object sender, RoutedEventArgs e) {
MessageBox.Show("Happy Birthday " + textBox1.Text + "!"); } Last
Update: 2/11Copyright (C) 2011 by David Figge. All Rights
Reserved.Page 33 The first thing we see is the definition of the
Window1 class. This is derived from the C# Window class, which
encapsulates the functionality of a Window Note the keyword
partial. This means that theres more class definition somewhere
else in the project. In this case, the rest of the class is in a
system generated at each build from the xaml code The primary
element in that system generated file is the InitializeComponent
function. The purpose of this function is to create the window
based on the instructions in the xaml code. So, although we cant
edit this function directly, we control whats in that function by
modifying the xaml code. Lets take a look at the xaml code
Slide 34 ... Last Update: 2/11Copyright (C) 2011 by David
Figge. All Rights Reserved.Page 34 As we discussed, xaml is
specific style of xml. Our root element is the Window tag, stating
that this xaml code describes a window (there are other options,
which well get to) This defines the class thats associated with the
window (the Window1 class in the Birthday namespace) Still in the
Window tag, were setting some properties of the Window its title
and size. We can add more if we need to. And heres the closing tag
of the root element Window. Inside the Window, we have a Grid
element. A grid is one of several layout elements, which are
responsible for positioning and supporting other elements (like
controls). Inside the Grid tags we find">
Code Example Window1.xaml ... Last Update: 2/11Copyright (C)
2011 by David Figge. All Rights Reserved.Page 34 As we discussed,
xaml is specific style of xml. Our root element is the Window tag,
stating that this xaml code describes a window (there are other
options, which well get to) This defines the class thats associated
with the window (the Window1 class in the Birthday namespace) Still
in the Window tag, were setting some properties of the Window its
title and size. We can add more if we need to. And heres the
closing tag of the root element Window. Inside the Window, we have
a Grid element. A grid is one of several layout elements, which are
responsible for positioning and supporting other elements (like
controls). Inside the Grid tags we find
Slide 35 Your Name: Today's My Birthday Last Update:
2/11Copyright (C) 2011 by David Figge. All Rights Reserved.Page 35
the controls for our app. So the grid owns the label, textbox, and
button. And the grid, in turn, is owned by the window
itself.">
Code Example Window1.xaml Your Name: Today's My Birthday Last
Update: 2/11Copyright (C) 2011 by David Figge. All Rights
Reserved.Page 35 the controls for our app. So the grid owns the
label, textbox, and button. And the grid, in turn, is owned by the
window itself.
Slide 36
This layered approach is important, and generally reflects the
way that a Window is created A Window consists of a 4 buttons
(System, Minimize, Maximize, and Close button) on top of a Title
window, all on top of that base window. Windows are ultimately
composites of many windows layered on top of one another. So the
xml-based xaml layout actually represents this layered window
approach well So, as you work your way through the xaml code, you
create a visual tree representing the visual elements of the
window. The Layered Approach Last Update: 2/11Copyright (C) 2011 by
David Figge. All Rights Reserved.Page 36
Slide 37
The Event Handler Before we leave our Birthday program, lets go
take a look at our Click handler. The handler is tied to the button
by associating it with the Click event of the button (in the xaml
code). Double-clicking on the element creates a handler for the
default event. In the case of the button, this is the Click event
You can also add other handlers by specifying the association in
the xaml code (well do that later). Note the Name element that
gives a unique identifier to this button, and is used in the
default handlers name Last Update: 2/11Copyright (C) 2011 by David
Figge. All Rights Reserved.Page 37...
Slide 38
The Event Handler Now lets look at the actual event handler
code All UI event handlers in WPF have two parameters Sender, which
refers to the triggering element In this case, it would be the
button Note that its passed as an Object, which means anything can
be passed in the first parameter If you need use sender to access
the button, youll need to cast it to a Button object Last Update:
2/11Copyright (C) 2011 by David Figge. All Rights Reserved.Page
38... private void button1_Click(object sender, RoutedEventArgs e)
{ MessageBox.Show("Happy Birthday " + textBox1.Text + "!");
}...
Slide 39
The Event Handler Now lets look at the actual event handler
code The other parameter is a type of EventArgs Derived from the
base class EventArgs Has information that might be of use to the
handler For example, MouseEventArgs, passed to MouseMove events,
has the current mouse coordinates In this case, theres little
useful information to the button click in RoutedEventArgs Last
Update: 2/11Copyright (C) 2011 by David Figge. All Rights
Reserved.Page 39... private void button1_Click(object sender,
RoutedEventArgs e) { MessageBox.Show("Happy Birthday " +
textBox1.Text + "!"); }...
Slide 40
More WPF Basics As you can see as we just scratch the surface,
there are many aspects to WPF There are too many to jump into
immediately, but lets hit some of the basics before we move on Last
Update: 2/11Copyright (C) 2011 by David Figge. All Rights
Reserved.Page 40
Slide 41
WPF Panels In the Birthday program, we used the Grid panel WPF
provides several different panels to suit various needs: PanelUse
GridAllows absolute placement CanvasUser defined contents
DockPanelAllows docking of panels (Left,Top,Right,Bottom)
StackPanelStacks elements (vertical or horizontally)
UniformGridPlaces elements into uniform sized columns, rows
WrapPanelAutomatically wraps elements as space fills up Last
Update: 2/11Copyright (C) 2011 by David Figge. All Rights
Reserved.Page 41
Slide 42
Primary Controls WPF provides standard controls, as well as
some more complex controls Alright. Enough talk. Lets take a look
at a Calculator program Ive got written in WPF CategoryElements Std
Window Controls Label, Textbox, Listbox, Combobox, Button,
Checkbox, GroupBox, RadioButton, Scrollbar Complex
ControlsListView, Border, Canvas, Image, ProgressBar, Tab,
TreeView, Slider, Rich Edit Box, Toolbar. Statusbar Basic
shapesEllipse, Rectangle Sub-ContainersScrollView, DocumentViewer
Last Update: 2/11Copyright (C) 2011 by David Figge. All Rights
Reserved.Page 42
Slide 43
Calculator Program Lets talk about This basic calculator was
made similar to how one would make it in WinForms Drag and drop
controls, etc. Adding Styles A style allows you to control the way
controls look and operate directly from the xaml Uncomment the
style Keep storyboard and its reference commented out WPF also
allows you to specify animations Either through code or from the
xaml itself Uncomment the storyboard and its reference Last Update:
3/09Copyright (C) 2009 by David Figge. All Rights Reserved.Page
43
Slide 44
WPF Summary So what you saw just scratched the surface, but as
you can see WPF gives Ability to customize control look and feel
(much more than WinForms) Ability to add 3D graphics,
multimedia,etc Ability to add animations easily Inclusion of
images, manipulations Built-in support for documents (pdf)
Questions on our brief introduction? Last Update: 3/09Copyright (C)
2009 by David Figge. All Rights Reserved.Page 44
Slide 45
Advanced Language Concepts in C# Delegates and Events Last
Update: 4/11Copyright (C) 2010 by David Figge. All Rights
Reserved.Page 45
Slide 46
Delegates Delegates are a software mechanism to allow function
call choices to be made at runtime. A reasonable analogy can be
drawn from politics... Last Update: 4/11Copyright (C) 2010 by David
Figge. All Rights Reserved.Page 46
Slide 47
Delegates The President is generally a pretty busy man. Often
when something unexpected arises, such as the death of a head of
state, the President is unable to attend, and must send his
representative The Vice President, Secretary of State, 1st Lady...
This person is a delegate, and represents our country for that
event The President defines in advance what responsibility will be
delegated (i.e. attend the funeral), and what parameters will be
passed (i.e. condolences, kind words) He then assigns a specific
person to act as that delegate at runtime, or as the situation
occurs. In the same way that the President defines and assigns a
delegate at runtime, C# delegates are used to make function call
decisions at runtime. Last Update: 4/11Copyright (C) 2010 by David
Figge. All Rights Reserved.Page 47
Slide 48
Delegates So delegates are used in situations where you need to
execute a particular action, but you dont know in advance what
method (or maybe even which object) youll use to call upon to
execute it. A delegate is a variable that points to a specific kind
of function in your code. For example, int function(double, double)
This is very similar to a function pointer in C/C++ Delegates have
many uses, but could probably be generalized into a couple of
categories Predefining a function to call Callback Functions Lets
talk about both of these a bit... Last Update: 4/11Copyright (C)
2010 by David Figge. All Rights Reserved.Page 48
Slide 49
Predefining a Function to Call Sometimes you need to selection
what function to call before youre actually ready to call the
function For example, perhaps a program has a customizable toolbar,
allowing the user to choose what tool (function) to call when the
button is pressed By storing the function to call in a delegate,
you can call it on demand easily without a complex switch or
if/then statements User wants button to be Print User presses
button Delegate = PrintDocument( ) Delegate executes PrintDocument
Lets diagram an example along a timeline... Sometime during the
running of the program, the user selects a button and assigns it to
the Print functionality. They arent printing, just defining the
button to print when pushed. At that point, the button for the
delegate is assigned to the PrintDocument function. Meanwhile, the
user continues to work with the document. When the user finally
presses the Print button, we simply execute the delegate and the
PrintDocument function is called. Last Update: 4/11Copyright (C)
2010 by David Figge. All Rights Reserved.Page 49 Does that make
sense?
Slide 50
Callbacks Functions A Callback is a term for a parameter to a
function that is the address of another function. For an example,
lets consider a sort function Sort functions have a challenge You
can make the function be very specific, and sort integers and
floats (and such), but that limits its usefulness You can make the
function be very general (like sorting user-defined arrays or
arrays of objects), but you dont have enough information about the
objects to compare them This is where the Callback function enters
Last Update: 4/11Copyright (C) 2010 by David Figge. All Rights
Reserved.Page 50
Slide 51
Callback Functions By including, as a parameter to Sort, the
function it should use to compare items (and therefore put them in
order), you can support any type of data the user wants to sort So
we use the term Callback because the generic sort code calls back
into your custom code to perform its task. Lets diagram this one,
too... User Code System Code So your program is humming along, and
it decides to call the Systems Sort method. You provide a callback
function (setting the delegate parameter) of a function that will
do the comparison of two objects. So as the system function is
sorting, it needs to know which of two objects is greater. So it
calls into your code (using the function you provided via the
delegate parameter), and your code compares the items, returning
the result to the sort function. During its processing, the sort
code may call into your compare routine many times. Of course, your
main program execution is halted waiting for the sort to be
finished. When the sort is done, your program continues on
normally, probably unaware of the calls to the compare routine.
Last Update: 4/11Copyright (C) 2010 by David Figge. All Rights
Reserved.Page 51 Have I lost anyone?
Slide 52
Callback Functions So Callback functions are used to add
runtime-based flexibility to otherwise pretty limited functions In
these cases, the delegate is a parameter in the function (e.g.
sort) These types of callbacks may be used synchronously (like our
sort example, simply waiting until its done before continuing the
main thread... Or asynchronously. where the called function starts
a separate thread at the start, then returning immediately. In
these cases, there may also be a callback to signify that the
thread has completed A good example of asynchronous processing is
connecting to an Internet site you dont want to hold up the main
program until this is complete. You can simply call a Callback
function when youre done, which signals the main program of the
status. So weve talked a lot about delegates, lets look at an
example... Last Update: 4/11Copyright (C) 2010 by David Figge. All
Rights Reserved.Page 52
Slide 53
Code Example Delegate Example delegate void GradeDelegate();
class Student { public void A() { Console.WriteLine(name + " got an
A"); } public void B() { Console.WriteLine(name + " got a B"); }
public void C() { Console.WriteLine(name + " got a C"); } public
GradeDelegate Grade; public string name; public Student(string n) {
name = n; }; } class TestClass { static void Main() { Student[]
stds = new Student[1]; stds[0] = new Student(Bob); stds[0].Grade =
stds[0].B; foreach (Student s in stds) s.Grade(); } } This is how
we define a delegate. It is of type delegate, and the delegate is a
void function with no parameters. These are functions well use in
the delegate. They have to match the delegate signature (void
functions with no parameters, in this case). Here I declare an
array of Students, and initialize the first one to Bob. This is the
syntax for initializing a delegate. You simply assign it the name
of the function you want to use (include the object if its an
instance method) Now, I can print out whatever grade is associated
with the student by the same function call for each Student object.
How are we doing? The next step is to define a variable to hold the
function, a variable of type GradeDelegate. Weve called this
variable Grade, and In this case each student will have a
GradeDelegate that well execute to find out what grade they got.
Last Update: 4/11Copyright (C) 2010 by David Figge. All Rights
Reserved.Page 53
Slide 54
Delegate Exercise Im going to go back to that WPF Calculator
program we used earlier. As you use the calculator, you will enter
the first operand, an operator (+,-,*,/), and then the second
operand (like 3 * 4). You then press the = key to get the total. As
it is now, when you press the +, -, *, or / key, the program
remembers the operation that you select. Were going to modify this
to use a delegate to hold the desired operation (Add, Subtract,
Multiply, or Divide) until the = key is pressed. When it is, well
simply call the delegate, passing in the two operands. Ready? Last
Update: 4/11Copyright (C) 2010 by David Figge. All Rights
Reserved.Page 54
Slide 55
Multiple Delegations One of the great features of delegates is
that you can use += with them So multiple functions can be
associated with the delegate When the delegate function is called,
each function associated with it will be called in turn You can
also remove an associated function with -= Delegates that use this
feature are called Multicast delegates All delegates are capable of
being multicast Lets see an example with our Student class we used
a while ago Last Update: 4/11Copyright (C) 2010 by David Figge. All
Rights Reserved.Page 55
Slide 56
Code Example Multiple Delgations Example delegate void
GradeDelegate(); class Student { public void A() {
Console.WriteLine(name + " got an A"); } public void B() {
Console.WriteLine(name + " got a B"); } public void C() {
Console.WriteLine(name + " got a C"); } static public GradeDelegate
Grade; public string name; public Student(string n) { name = n; } }
class TestClass { static void Main() { Student[] stds = new
Student[2]; stds[0] = new Student("Bob"); Student.Grade += new
GradeDelegate(stds[0].B); stds[1] = new Student("Mary");
Student.Grade += new GradeDelegate(stds[1].A); Student.Grade(); } }
Things have changed just a little. First, the Grade variable is now
static (shared for all Student objects). This makes more sense with
the += syntax. We now create 2 students. Note that I use += for
adding the student to the Grade delegate. Now, I simply call
Student.Grade() and it displays both students grade functions: Bob
got a B Mary got an A Pretty slick, huh? Any questions? Last
Update: 4/11Copyright (C) 2010 by David Figge. All Rights
Reserved.Page 56
Slide 57
Events So weve talked about delegates, now lets hit the
closely-related subject of events. Events are an implementation of
the Publisher/Subscriber design pattern (if that means anything to
you). The concept behind events is that there are two pieces: a
publisher (someone with information to share), and a subscriber
(someone interested in that information). Lets take a look at an
example to see if that clarifies things somewhat... Last Update:
4/11Copyright (C) 2010 by David Figge. All Rights Reserved.Page
57
Slide 58
Publishers and Subscribers Lets consider the situation where we
have a stock broker, Stock Broker Bill. Stock Broker Bill has
information his clients want his buy/sell recommendations for
stocks. Stock Broker Bill is the publisher of this information Some
of Stock Broker Bills clients are interested in getting
up-to-the-minute recommendations from him. The clients are the
subscribers So Bill sets up an event: StockNotify. He uses this to
send his buy/sell recommendations to his clients. Any client that
is interested can register with the StockNotify event, and receive
the buy/sell notifications. Lets see what this might look like...
Last Update: 4/11Copyright (C) 2010 by David Figge. All Rights
Reserved.Page 58
Slide 59
Code Example Event Declaration Example public class
StockBrokerBill { public delegate void dNotify(string ticker);
public static event dNotify StockNotify; public static void
Register(dNotify fcn) { StockNotify += fcn; } public static void
Main(string[] args) {... // At the right time... StockNotify(MSFT);
} } This class represents Stock Broker Bill. Events are based on
delegates (which define the format of the function). Here we
declare a delegate dNotify... And then the event
itself(StockNotify) At some point, the event will be triggered like
this (announcing that Microsoft stock is going up) Also in the
class is a function that registers a client with the StockNotify
event. Last Update: 4/11Copyright (C) 2010 by David Figge. All
Rights Reserved.Page 59
Slide 60
Code Example Event Subscription Example class Bob { public void
Notify(string ticker) { MessageBox.Show(Bob: Buy +ticker); } public
Bob() { StockBrokerBill.Register(Notify); } } So Bob is a client of
Stock Broker Bill, and wants to be notified of stock risings. He
has a method called Notify that displays a message to buy. In the
Bob class constructor, we register the Notify function with
StockBrokerBill.StockNotify (via Register). When the stock rises,
Bobs Notify function will be called, saying Bob: Buy MSFT Last
Update: 4/11Copyright (C) 2010 by David Figge. All Rights
Reserved.Page 60
Slide 61
Events vs. Delegates So, if the syntax looks very similar to
delegates, theres a reason Events, being based on delegates, use
the same registration and calling process So whats the difference
between Events and Delegates? Can you just use the delegate instead
of the event? Well, from a technical standpoint, theres not much
difference Events can only be called from the class that defined
them So theres a bit of a security benefit Delegates as data
elements cant be part of an interface, but events can be Last
Update: 4/11Copyright (C) 2010 by David Figge. All Rights
Reserved.Page 61
Slide 62
Events vs. Delegates So most of the difference between Events
and Delegates is conceptual, and by convention rather than
language-enforced rules Delegates are generally used for local
(within the same application) storage of a function Like the
calculator Events are typically for providing outside access to an
internal resource Like registering a function on a remote computer
to Stock Broker Bills StockNotify Or where you wish to have a level
of separation between classes in the same program Event (and
Delegate) Caveats: The calling order is not predictable, and
exceptions could potentially disrupt subsequent calls Last Update:
4/11Copyright (C) 2010 by David Figge. All Rights Reserved.Page
62
Slide 63
Windows Events C# Events is the mechanism used to support
Windows Events Windows programming like other GUI environments is
different from programming in a procedural environment (like the
DOS command prompt) In Windows programming, the system stays in
control of your program allowing windows to be selected and
manipulated and swapped between and the system notifies your
program when you need to get involved This removes significant
burden of Window management from the application developers job,
and gives a consistent look and feel to all of Windows Last Update:
4/11Copyright (C) 2010 by David Figge. All Rights Reserved.Page
63
Slide 64
Windows Events A good example of this is our WinCheckbook
program Windows handles the basic Windows mechanics moving a
window, resizing, swapping between applications. Windows handles
displaying of the pull-down menus, windows, buttons, etc., but when
the user clicks on a button, only your program knows what to do So
at that point, Windows contacts your program and tells it the user
clicked on the Export button. You can then respond to the message
and execute the export code In C#, the mechanism that Windows uses
to support this messaging scheme is Events Last Update:
4/11Copyright (C) 2010 by David Figge. All Rights Reserved.Page
64
Slide 65
Windows Events Windows defines hundreds of events that can
occur during the running of a program You can be notified when the
window is resized, moved, minimized, maximized, switched to,
switched from, clicked on, etc. The trick to Windows programming is
knowing what events occur and the order in which they happen So
Windows makes all these events available to you by creating C#
Events that you can register with If you want to know if a user
clicks on a menu item, you register a function with the Click event
of the menu item. That way, your code is called when the user
clicks on the menu Lets take a look at our WinCheckgook program and
see just where that code actually is for that Export button...
Questions on Events? Last Update: 4/11Copyright (C) 2010 by David
Figge. All Rights Reserved.Page 65
Slide 66
Advanced Language Concepts in C# Design Patterns Copyright (C)
2005 by David Figge. Unauthorized Use Prohibited.
Slide 67
Page 67 Design Patterns Design Patterns are a collection of
real-world solutions that have been proven in the industry over
time to solve common problems Recognize that were not talking about
a class or object. Were talking about repeating patterns of how
objects have been created, organized, and have interacted with each
other to solve common, repeating problems. These patterns are in
use all around us. No one person invented them. Theyre simply
common solutions to common problems. As these patterns become
recognizable to you, you will be better able to identify key
components, and potential issues to consider when solving these
common issues.
Slide 68
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 68 Design Patterns In the mid-90s Erich Gamma, Richard Helm,
Ralph Johnson, and John Vlissides also known as the gang of four
(or GoF) cataloged the basic patterns industry continued to use and
reinvent. The result is their book Design Patterns (our text). The
patterns they identified are generally considered the foundations
for all other patterns. The GoF categorized the patterns in 3
groups Creational Having to do with creating objects Structural
Having to do with program structure Behavioral Having to do with
object interactions There are too many patterns to look at in
depth, but lets take an overview look at these categories and look
in detail at some of the more common patterns...
Slide 69
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 69 Creational Patterns Creational design patterns abstract the
object instantiation process. Used correctly, they help make a
system independent of how its objects are created, composed, and
represented. Lets take a look at two common patterns: The Abstract
Factory, and The Singleton
Slide 70
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 70 The Abstract Factory The Abstract Factory pattern is when a
client rather than creating an object itself delegates that to an
intermediary object. By doing this, the intermediary takes
responsibility for determining what the best object is given the
current state of the system. A computer example might be making a
call to the OS to return a scrollbar object. If Im under Windows,
that scrollbar will look different than if Im under Mac OS. By
deferring the decision to the operating system, it was able to
create the appropriate one given the current system The client then
agrees to use the returned object according to the common public
interface for both scrollbars.
Slide 71
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 71 The Abstract Factory A real life example (although the book
focuses on object oriented software versions of these patterns, I
just wanted to show that these patterns dont only apply to
software, but to real life as well): When you call a travel agent,
you are delegating the creation of your tickets, hotel, car, etc to
them. The travel agent creates these items for you and returns them
to you after they have been created. You then use the tickets with
no further involvement from the travel agent. Get the idea?
Slide 72
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 72 Singleton A Singleton is a class where only one object of
that type is allowed to exist in the system. A good example of this
is a print queue. If multiple print queues were sending jobs to the
same printer, jobs would get intermixed and it would be a mess
Singletons are usually achieved by having a static creation
function (not a constructor) that a) if no objects exist creates
one, otherwise b) returns the existing one. At that point, all
interaction with that object type takes place through that single
global point of access.
Slide 73
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 73 Structural Patterns Structural Patterns deal with how
classes and objects are combined to create larger solutions. Lets
take a look at four common patterns: The Adapter The Bridge The
Facade The Proxy
Slide 74
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 74 The Adapter Also known as a wrapper, the adapters job is to
translate the interface of the target class into an interface that
the client wants. It fits in between the client and the target, and
simply translates method calls between the two. The queue template
and the stack template are simply adapters on top of a vector that
provide a queue and stack based interface to a client. Adapters are
typically derivations of the target class, but doesnt have to be.
Another example is the device that lets 3-prong plugs go into
2-prong electrical outlets (an adapter).
Slide 75
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 75 The Bridge Whereas the Abstract Factory isolated clients
from the creation of objects, the Bridge is used to isolate a
client completely from the details of an implementation...to
separate what you would like from how it is done. So where the
Abstract Factory simply created an object, the Bridge is used as an
intermediary for an entire process How about an example: I have a
car hands free phone system in my car, using Bluetooth wireless
technology With this technology, the hands free unit can work with
any bluetooth enabled cell phone that wants to use it The hands
free knows how to ask a bluetooth phone to make a call, and The
bluetooth phones lets the hands free interact with that phone call,
but isolates it from how the phone makes the call. This decoupling
of the request from the service provider allows me to use any
bluetooth phone with my hands free. Lets try to diagram this just a
little...
Slide 76
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 76 The Bridge Client InterfaceProvider So we start with a
client, and a provider. We also have an interface object, which
takes on the responsibility for the logical connection between the
client and the provider. In the case of my hands-free, thats the
bluetooth interface (half on the client, half on the provider were
dealing with concepts, not detailed implementation). The client
wants a service provided. In the case of my hands free, it wants to
place a phone call. So the client makes the request to the
interface object: place a call The interface calls to a provider
object which creates the requested connection, perhaps passing back
a connection object or identifier. This way the client can refer to
the process it started for subsequent calls. The interface then
returns this object or identifier to the client. The benefit comes
when we swap out the provider object with another one. (e.g. we
swap one phone for another) This can be done without shutting down
the system. The same request is make, but this time a different
provider serviced the request (a different phone) So the benefit of
the Bridge is that we have the ability to separate the provider
from the client. This allows us to create objects independent of
the code platform on the client side, and allows the client to
evolve separately from the objects it requests. Making sense?
Slide 77
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 77 The Facade Creating lots of powerful, focused objects is a
good thing, but systems can get large enough where dealing many
interfaces becomes difficult. The Facade inserts itself in between
the client(s) and all the objects, and provides a unified interface
into the subsystem. FacadeFacade Client Classes Subsystem
Classes
Slide 78
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 78 The Proxy A Proxy is any object that represents itself to
be another object. There are a variety of reasons to do this,
including security, load management, and remote representation. A
good example of a proxy is a firewall. To the Internet, the
firewall is your system. But the firewall handles flow control and
security issues so that your system doesnt have to and isnt exposed
to the dangers of the Internet. System Security Proxy
Slide 79
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 79 Behavioral Patterns Behavioral Patterns deal with
algorithms and the assignment of responsibilities between objects.
So its not just the structure of the class and object hierarchies,
but how they communicate and interact with one another. Lets take a
look at three common behavioral patterns: The Command The Iterator,
and The Observer
Slide 80
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 80 The Command The concept behind the Command pattern is to
pass a function to another object and have it called from there.
For example, when we created our Populate static method, we passed
a pointer to a function that added the Appt to the Storage object.
The command pattern is the object oriented version of that concept
Where the function pointer is encapsulated into an object and
passed around like other objects. By placing the command into an
object, you can store the object, like putting it into a queue of
commands that the system must address.
Slide 81
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 81 Undo Stack EMPTY The Command A good example of a Command
pattern is and undo operation When the user changes an element on
the display, you first save the state of the existing display
perhaps a series of commands to reset the current change to the way
it was into an object. This restore state command object is then
placed into an Undo stack. You may push perhaps 5 of these items
onto the stack. When the user decides to undo all five, each
element is taken in turn and executed, putting back the state where
the previous undo can restore from. Remove H _ H_HE_HEL_HELL_HELLO_
Display Controller Object Remove ERemove L Remove O Does it make
sense how Command works?
Slide 82
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 82 The Iterator The iterators job is to sequentially navigate
a container while hiding the underlying container implementation We
used iterators when we used Linq No matter whether the data came
from internal objects or a database, we accessed the data the same
way Iterators are very common in database systems, and are also
called cursors.
Slide 83
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 83 The Observer Also known as Publish-Subscribe, the Observer
pattern has two parties One who is interested about some event that
can or will occur (the subscriber), and One who notifies interested
parties that the event has occurred (the publisher) A simple
example is a calendars reminder option. You want to be reminded to
leave in time for this class, so you subscribe to the Notify list
when the appointments time comes up. When the time arrives, the
system advises you with a reminder window. We also discussed it
when we discussed eventsthe Broker Bill example Lets review that
from an Observer pattern viewpoint...
Slide 84
Copyright (C) 2005 by David Figge. Unauthorized Use Prohibited.
Page 84 The Observer A stock broker may (directly or indirectly)
allow you to subscribe to a notification service. This service
watches a particular stock, and when it rises beyond a certain
level, the system publishes that information by notifying
subscribers to pay attention to the stock This could be something
as simple as triggering an email to a mailing list, or be a remote
procedure executed over the Internet the implementation isnt
essential to the pattern. Does Observer make sense to everyone?
Questions on any of the patterns weve discussed?
Slide 85
Advanced Language Concepts in C# End of Session Last Update:
3/09Copyright (C) 2009 by David Figge. All Rights Reserved.Page
85