CS411 Final Term Lec 19 To 45
CS411 Final Term Lec 19 To 45
Lecture #19:
Dock panel allows easy docking of elements to an entire side. Dock attached property has left,
right, top, bottom values. Last child fills space unless lastchildfill=false.
<dockpanel>
<Button dockpanel.Dock="Top" Background="Red">1(Top)</Button>
<Button dockpanel.Dock="Left" Background="Orange">2 (Left)</Button>
<Button dockpanel.Dock="Right" Background="Yellow">3 (Right)</Button>
<Button dockpanel.Dock="Bottom" Background="Lime">4 (Bottom)</Button>
<Button Background="Aqua">5</Button>
</dockpanel >
Grid is the most versatile. Its the default panel in VS and expression blend. You arrange things
in multirow multicolumn, like a table in html. Also a Table class which is a
frameworkcontentelement not a uielement.
<Grid Background="lightblue">
<!-- Define four rows: -->
<Grid.rowdefinitions>
<rowdefinition/>
<rowdefinition/>
<rowdefinition/>
<rowdefinition/>
</Grid.rowdefinitions >
<!-- Define two columns: -->
<Grid.columndefinitions>
<columndefinition/>
<columndefinition/>
</Grid.columndefinitions >
We can make spanning rows and cols. Rowspan and columnspan 1 by default. By default
height n width are same. Height and Width = “Auto” for sizing to content. Showgridlines
= “True” to show grid lines.
Here is how gridlength is used in procedural code.
Gridlength length = new gridlength(100);
Gridlength length = new gridlength(0, gridunittype.Auto);
Gridlength length = new gridlength(100, gridunittype.Pixel);
Gridlength length = new gridlength(2, gridunittype.Star);
Lecture #20:
Sharedsizegroup enables multiple row cols to remain the same width height when length
changed via gridsplitter.
Content overflow can be dealt with Clipping, Scrolling, Scaling, Wrapping and Trimming.
1
CS411 Final term preparation | Lecture 19 to 45
Lecture #21:
Handlers for routed events have a System.Object parameter (sender to which handler was
attached), and System.eventargs, and source which is the logical tree element that originally
raised the event and originalsource which is the element in visual tree that raised the event.
There are many keyboard, mouse, multi-touch, and stylus events. Most are bubbling events but
many have a tunneling counterpart. By convention tunneling event names are prefixed with
Preview and come just before the bubbling event comes. Previewmousemove comes before
mousemove. By convention, actions are only taken on bubbling event so tunneling gives a
chance to cancel or modify the event.
Lecture #22:
Note that we never receive an event on listbox item. Button has no border element so setting
border has no effect. Handling a halted event can only be done from procedural code.
Attached events can bubble and tunnel through elements who have not defined the event. Like
prop value inheritance and attach properties.
discuss keyboard events keydown, keyup, and preview versions of them. Keyeventargs
contains Key, imepro-cessedkey, deadcharprosessedkey, systemkey, isup, isdown, istoggled,
keystates, isrepeat, and keyboarddevice.System.Windows.Input.Keyboard and its
primarydevice property are accessible everywhere.
e.g: protected override void OnKeyDown(KeyEventArgs e).
if ((e.KeyboardDevice.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt && (e.Key
==Key.A || e.SystemKey == Key.A)){
// Alt+A has been pressed, potentially also with Ctrl, Shift, and/or Windows
if (e.KeyboardDevice.Modifiers == ModifierKeys.Alt && (e.Key == Key.A || e.SystemKey
==Key.A)){
// Alt+A and only Alt+A has been pressed
You can use keyboarddevice.iskeydown to even check if left or right alt is down etc. What is
keyboard focus. Uiele-ment Focusable property (true by default). Focusablechanged event,
2
CS411 Final term preparation | Lecture 19 to 45
Lecture #23:
Manipulation events are manipulationstarting and manipulationstarted, manipulationdelta,
3
CS411 Final term preparation | Lecture 19 to 45
Lecture #24:
Commands are a more abstract and loosely coupled version of events e.g. Cut copy paste
commands. WPF defines a number of built-in commands. Commands have automatic support
for input gestures (such as keyboard shortcuts). Some of wpfs controls have built-in behavior
tied to various commands.
Following are pre-defined builtin commands. Applicationcommands e..g Close, Copy, Cut,
Delete, Find, Help, New, Open, Paste, Print, printpreview, Properties, Redo, Replace, Save,
saveas, selectall, Stop, Undo, and more. Componentcommands e.g. Movedown, moveleft,
moveright, moveup, scrollbyline, scrollpagedown, scrollpageleft, scrollpageright, scrollpageup,
selecttoend, selecttohome, selecttopagedown, selecttopageup, and more. Mediacommands
e.g. Channeldown, channelup, decreasevolume, fastforward, increasevolume,
mutevolume, nexttrack, Pause, Play, previoustrack, Record, Rewind, Select, Stop, and more.
Navigationcommands e.g. Browseback, browseforward, browsehome, browsestop, Favorites,
firstpage, gotopage, lastpage, nextpage, previouspage, Refresh, Search, Zoom, and more.
Editingcommands e.g. Aligncenter, alignjustify, alignleft, alignright, correctspellingerror,
decreasefontsize, decreaseindentation, enterlinebreak, enterparagraphbreak,
ignorespellingerror, increasefontsize, increaseindentation, movedownbyline,
movedownbypage, movedownbyparagraph, moveleftbycharacter, moveleftbyword,
moverightbycharacter, moverightbyword, and more.
All instances of routeduicommand implement icommand and support bubbling.
Helpbutton.Command= applicationcommands.Help;
4
CS411 Final term preparation | Lecture 19 to 45
Button and textbox have no direct knowledge of each other. Through commands we have a
rich interaction. The more the standardization on builtin commands, the more seamless and
declarative the interaction can be between controls.
wpf input events make possible rich interactive content. We focused on uielement but
the same events can be used with contentelement.
Lecture #25:
A standard windows app or partial trust web app or loose xaml.
WPF Window is a win32 window, same chrome (non-client area) same taskbar behavior
etc.
Another windows Owner property after parent shown, ownedwindows property. There
are Activated & Deactivated events. Activate method (like setforegroundwindow).
Showactivated=false, initially not shown.
App code-behind can be omitted altogether. But where is main. App.xaml is assigned
applicationdefinition which causes App.g.cs to be generated and can be seen in Solution
Explorer if you Show all files. System.Environment.getcommandlinea or set build action to Page
and write Main. Startup, Exit,Activated, Deactivated (any window), sessionending (can-cellable
logoff shutdown). A read-only Windows collection, mainwindow property (read-write).
Shutdownmode (when to end the app). Properties dictionary for sharing between windows.
Application.Current from any window.
Modal dialogs include common dialogs which are actually provided by win32. Instantiate, call
showdialog and process result.
Windows installer benefits include showing custom setup UI like a EULA, control over where
files installed, arbitrary code at setup time, install shared assemblies in global assembly
cache, register COM components and file associations, install for all users, o✏ine installation
from cd. Clickonce benefits include builtin support for automatic updates and rollback to prev
versions, a web-like “go-away” experience or start menu and control panel program list, all files
in isolated area, so no effect on other apps, clean uninstallation, but full trust apps can do
things while they run, .net code access security, partial trust.
Lecture #26:
Navigation based apps like windows explorer, media player, photo gallery.
Navigationwindow more like a top-level window whereas Frame more like an HTML frame or
iframe By default navwind has a bar on top with back/fwd, frame doesnt but can be shown.
<navigationwindow
Xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
5
CS411 Final term preparation | Lecture 19 to 45
Mc:Ignorable="d" x:Class="photogallery.Container"
Title="Photo Gallery" Source="mainpage.xaml"
D:designwidth="1320" d:designheight="919"
/>
ou can set a title that is used in the drop-down menu associated with the Back and
Forward buttons as follows:
This.navigationservice.Title = Main Photo Gallery Page;
Or you can refresh the current Page as follows:
This.navigationservice.Refresh();
You can perform navigation in three main ways: Calling the Navigate method, Using Hyperlinks,
Using the journal.
Hyperlink element is used to link to xaml. Or handle its Click event and call navigate yourself to
link from html towpf. Handle Navigating event and look for a sentinel HREF value can also set
targetname to update a frame or use# and any named element in a page.
E.g: <textblock>
Click
<Hyperlink navigateuri="photopage.xaml">here</Hyperlink> to view the photo.
</textblock >
Journal provides logic behind back and fwd. Internally two stacks. Back / fwd moves pages
between stacks. Any other action empties the fwd stack. Back fwd can also nav. Containers
goback and goforward and cangoback/fwd to avoid exception. Nav. Wnd. Always has journal
but frame may depending on its journalownership=ownsjournal, usesparentjournal, Automatic
(parent when hosted in wnd or frame).
Other purposes of journal e.g. Application specific undo redo scheme. Nav. Container
addbackentry and pass customcontentstate abstract class with a replay method that must be
defined. Optionally journalentryname can be set.
Navigationstopped is an event called instead of loadcompleted if an error occurs or nav. Is
cancelled. These events also defined in “Application” to handle for any nav. Cont. Html to html
nav. Not in journal, no event raised. To send data to pages, Navigate overloads with an extra
“object” param. Target page receives it in loadcompleted.
Lecture #27:
Silverlight more popular to deliver partial-trust wpf content in a browser. Differences are that
not all features available by default, nav is integrated into the browser, deployment different.
In VS, create WPF browser application. Create UI in Page and compile and run. Really just
online-only clickonce applications, with some special wpf handling for browser-integrated
experience.
Use rich text and media, isolated storage upto 512kb.
6
CS411 Final term preparation | Lecture 19 to 45
There are also full-trust browser apps. In the project file you change
<targetzone>Internet</targetzone>
To this:
<targetzone>Custom</targetzone>
Additional events can be used for fine grained progress. Loose xaml is powerful sometimes
instead of html.
Lecture #28:
Apply Uid directive to any element needing localization.
Logical resources are introduced by wpf. Arbitrary .net object stored and named in an elements
Resources prop. Typically meant to be shared by multiple child objects. Frameworkelement and
framework content element both have a Resources prop.
Dynamicresource reapplied every time it changes nothing special about the resources. Only if
you want to see updates or not. Dynamic more overhead but demand loaded. Dynamic can
only be used to set dep. Prop. Values. Static can even abstract whole controls.
Lecture #29:
Data means an arbitrary .net obj. Data binding, data templates, data triggers are related
concepts. Data can be collection obj, xml file, web service, db table, custom obj, even wpf
element eg button. So data binding is typing together arbitrary objects. Classic scenario is a
visual rep. (e.g. Listbox or datagrid) of items in an xml file, db, or in-memory collection.
Binding binds two properties together and keeps a communication channel open. Setup
Binding once and let it handle all the sync.
When an item with no header selected, then a default value ( in this case) returned. No
exception is raised. Binding has a source prop and a target prop. Source is an object and a prop.
Path. Can also use bindingoperations.setbinding. Bindingoperations.clearbinding.
Bindingoperations.clearallbindings. Or set the target prop to a new val. (but clear would allow
receiving values from lower prop. Sources).
Implicit data source is provided by a Data Context. We set datacontext of a parent and then
dont specify Source or elementname or set parent.datacontext = photos;. It is useful when
plugging in resources: usage context or decl.context.
Control rendering is easy without binding but there are benefits of data binding. WPF gives
three ways. String formatting which only works if the target prop is a string. {} to escape. Can
add 1000 seperator etc.
String formatting can be used even without data binding.
Lecture #30:
7
CS411 Final term preparation | Lecture 19 to 45
Sortdescriptions prop. Is a collection of sortdescription which chooses a field and order, sort by
datetime, then by name. A clear method to return to unsorted. Eg. Three buttons to sort and
toggle.
Sortdescription sort = new sortdescription("Name", listsortdirection.Ascending);
View.sortdescriptions.Add(new sortdescription("datetime", listsortdirection.Descending);
View.sortdescriptions.Add(new sortdescription("Name", listsortdirection.Ascending);
There is no explicit relationship with listbox. If additional controls bound, they would sort with
it. Now groupdescriptions prop. Containing propertygroupdescription obj. But it has no effect
without the groupstyle.
Sorting is applied before grouping. First sorting criteria should be same as grouping otherwise
output doesnt make much sense. Can pass null to get total custom control in the value
converter.
Navigation means managing the current item, not the other kind of nav. Icollectionview has
currentitem currentposition and also methods for changing them.
Prop. Paths in Bindings are useful for master/detail interfaces. Sorting, grouping, filtering
automatic. But navigation only when issynchronizedwithcurrentitem=true.
Collectionviewsource can be used to create new views and applied to targets.
Collectionviewsource has its own sortdescriptions and groupdescriptions properties and a Filter
event to be used from xaml.
You could bind to db, registry, excel spreadsheet etc.
We use xdata to avoid compiler errors. Namespace pollution avoided with xmlns=. Bindings
xpath prop used rather than Path. If external file, even easier. “gamestat/@Type” would fill list
with each gamestats Type attribute.
Lecture #31:
Hierarchicaldatatemplate for every node and datatemplate for a leaf node.
Hierarchicaldatatmplate allow specifyingchildren using itemsource prop. =all children. Datatype
means effect all instances within the scope. Datatype corresponds to xmlnode name. No key.
Internally datatype value used as key.
.net object as a data source.
Binding.Mode can be oneway i.e. The target is updated whenever the source changes. Twoway
i.e. a change to either the target or source updates the othe
Updatesourcetrigger. Do you want the two way source to be updated on every key stroke.
Propertychanged. Changed when target prop value changes. Lostfocus. Changed when focus
lost.
Explicit. Call bindingexpres sion.updatesource which you can get from any
frameworkelement.getbindingexpression.
Binding has validationrules prop that can be set to one or more validationrule derived objects.
8
CS411 Final term preparation | Lecture 19 to 45
Lecture #32:
Concurrency is More than one thing happening at the same time.
Thread: execution path that can proceed independently of others. Normal processes (programs
in exec.) Have one thread. Multithreaded programs have more and can share data.
Let’s create one.
Class threadtest
{
Static void Main()
{
Thread t = new Thread(writey);
T.Start();
For (int i = 0; i < 1000; i++) Console.Write("x");
}
Static void writey()
{
For (int i = 0; i < 1000; i++) Console.Write("y");
}
}
A thread is pre-empted because of time slicing. A threads isalive=true once starts and until
ends. Name property, Thread.currentthread is the currently executing thread.
Lambda expressions and captured vars
Lecture #33:
Long rnning operations make application unresponsive. Because main thread used for
rendering UI and responding to events.
Threadpool save time of thread creation.
Threadpool.queueuserworkitem (notused => Console.writeline ("Hello"));
Task.Run (() => Console.writeline ("Hello from the thread pool"));
Lecture #34:
Synchronous vs. Asynchronous. Async typically return quickly. Called non-blocking.
Thread.start, task.run, at-taching continuations. For io bound we can usually work without
thread. For cpu bound we can start and return task. Cpu bound async tasks.
How to make async. Course grained.
Task.Run (() => displayprimecounts());
Async can be applied to methods returning void or Task or Task¡tresult¿.
Task<int> getprimescountasync(int start, int count).
Async doesnt change method so no need to list in interface.
9
CS411 Final term preparation | Lecture 19 to 45
Lecture #35:
We can return a Task from void function without explicitly return it. Enables async call chains.
Compiler indirectly uses taskcompletionsource to implement methods returning Tasks.
Async call graph exec. Brief sync exec on thread calling Go. Everyone await and returns.
Parallelism. how to run two tasks in parallel and then await them.
Cancellation. Cancel is on cancellationtokensource. Most have builtin cancellation support.
Class cancellationtoken
{….};
Task-based Async Pattern (TAP): A TAP method Returns a “hot” (running) Taskor Task¡tresult¿.
Has an “Async” suffix (except for special cases such as task combinators). Is overloaded to
accept a cancellation token and/or iprogress¡T¿if it supports cancellation and/or progress
reporting.
Lecture #36:
Task Parallel Library exploit multicore for real parallel tasks. 3 steps partition into small chunks,
process, collate the results in thread-safe manner.
Data parallelism vs. Task parallelism. Data parallelism easier and scales well. It also structured.
Same place in code where parallelism starts and ends.
Concurrent collections also useful when you want a thread-safe collection three static methods
in the Parallel class Parallel.Invoke is not a shortcut for creating many threads. Actually batches
to use processors efficiently.
Concurrent collections include concurrent stack, concurrent queue, concurrent bag, concurrent
dictionary. They are optimized for concurrent. But also useful for thread-safe.
Thread-safe collection doesnt guarantee thread safe code.
Concurrentbag is an unordered collection. Its kind of linked list for each thread. Add has almost
no contention.
Lecture #37:
Static web sites were there initially. Html. Hypertext markup language. Display information and
thats it.Today websites reach interactivity of desktop applications. Because of javascript.
Animation, interactivity, dynamic visual effects.
Javascript was introduced in 95 by netscape. About as old as web.
JQuery solves JS complexity and browser incompatibilities. Can do things in single LOC that
would take hundreds. Many advanced features come as jquery plugins. Used on millions of
websites.
HTML: structural layer and CSS: presentation layer and JS: behavioral layer.
HTML has simple commands called tags.
Originally there was only HTML. CSS is a formatting language. Html only to structure, so ¡h1¿
¡h2¿ are both headings with diff imp ¡ul¿ is an unordered list. CSS adds design. CSS style is a rule
telling web browser how to display an element.
10
CS411 Final term preparation | Lecture 19 to 45
Client side vs. Server side. Prog lang for the web browser. Alternate is a server prog lang. Php,
.net, asp, cold fusion, ruby on rails, etc. They run on web server. Log of intelligence by accessing
DB, process CC, send emails. Visitors wait until response comes. Client side lang can re-act
immediately. client side technologies are applet’s, silverlight, flash.
Compiled vs scripted languages (interpreted). JS interpreter is in web browser. Let’s write a
prog to askvisitor name, get response, and print a welcome msg. Web browser has layout or
rendering engine (understanding HTML and CSS) and a JS interpreter.
Dynamically changing webpage is key idea. Mouse over, click, detail info. E.g. Date picker is run
by JS but itself is made of HTML / CSS. JS just makes presentation interactive.
Lecture #38:
HTML DOM is much like an XML DOM. JS provides ways to select e.g. Some browsers allow
selecting by CSS sometimes not cross browser.
Jquery filters are :even :odd $(’.striped tr:even’) :first :last :not $(’a:not(.navbutton)’);
:has $(’li:has(a)’).
Jquery selection. Dont end up with DOM lists. Rather jquery equivalents automatic
loops.$(’#slideshowimg’).hide();
Attributes can be manipulated with addclass removeclass toggleclass.
Lecture #39:
Lecture #40:
JS, server-side programming, and web browser, all work together. Web browser:
xmlhttprequest object.
Web server: receives request and responds as HTML, plain text, XML, JSON.
Server returns a string formatted like a JSON obj literal. Jquery getjson method. Callback will be
a JSON object.
Lecture #41:
Objective-C introduces smalltalk style messaging in C. Early 1980s. Used for next computer. It is
simple extension of C. To create an object, send it an alloc message. Nsmutablearray
*arrayinstance = [nsmutablearray alloc];. Initialize it. [arrayinstance init];.
Subclassing. Root class of entire hierarchy. Nsobject. Objective-C keywords start with @.
Instance variables.
#import <uikit/uikit.h>
@interface Possession: nsobject
Lecture #42:
11
CS411 Final term preparation | Lecture 19 to 45
Lecture #43:
Delegation is a design pattern. An OO approach to callbacks. Allows callback methods to share
data. A delegatecan only be sent messages specified in its protocol. For every object that can
have a delegate, there is a corresponding protocol.
Protocols are like interfaces in other langs i.e. No implementation. Protocols for delegations
delegate protocols.
Lecture #44:
xxxxxxxxx
12