Download as pdf or txt
Download as pdf or txt
You are on page 1of 327

GumNaaM_Helpers

Mega File for FinaL TerM


All Files in ONE FILE
‫۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔۔‬
(Handouts_waqar_moaz_junaid_vu toper_orange monkey)

‫الحمدہللا گمنام ہیلپرز ان تمام کتابوں میں مدد کرتے ہیں جن کے لنکس نیچے دیئے گئۓ ہیں‬
‫ل ٰیذا ہم سے صرف انہی کتابوں کی مدد کا سوال کیا جائے جن کے لنکس نیچے موجود ہیں‬
Groups Join Krty hi Description Read krna na bhoolyn

‫جزاک ہللا خیرا و احسن الجزاء‬

GumNaaM_Helpers All What’s App Group Links


💞Cs101🌹 https://chat.whatsapp.com/KCQ3jK6FcoYEvDYTF1gnBS 💞Eng101🌹 https://chat.whatsapp.com/Cwp4Ag9TG6ZKxyRqThqM6S
💞Cs201🌹 https://chat.whatsapp.com/DrYV1FAXmppImVZFwI6V2R 💞Eng201🌹 https://chat.whatsapp.com/EvvxcPtmrM22VTZhz5NCTw
💞Cs301🌹 https://chat.whatsapp.com/EPLvHztf8EB7aH8e1AtidV 💞Eco401🌹 https://chat.whatsapp.com/K3NLvyue6BdK0sVMqDFoU2
💞Cs302🌹 https://chat.whatsapp.com/BaYfW0P67vNIsl2n36otZM 💞Mcm301🌹 https://chat.whatsapp.com/GUyzfdHzu8r43TW16vhZWF
💞Cs304🌹 https://chat.whatsapp.com/C0mk0wdo0BU46dlhcd67IO 💞Mgt101🌹 https://chat.whatsapp.com/BmrYaQYuIBOKguHOiT6t2Y
💞Cs401🌹 https://chat.whatsapp.com/Jz9WDdHX84lKgkrMPAV0Mf 💞Mgt201🌹 https://chat.whatsapp.com/DZwztlUyxV50D6AshnvWCD
💞Cs402🌹 https://chat.whatsapp.com/DW9AZLb4i1P9la4XmcCsRz 💞Mgt211🌹 https://chat.whatsapp.com/EmX9xloZnbI12pX9m2DZwa
💞Cs403🌹 https://chat.whatsapp.com/HXV25Lc6MnLKZgrA7xOqjF 💞Mgt301🌹 https://chat.whatsapp.com/G62QTipycoXFrpOZxfDIBK
💞Cs408🌹 https://chat.whatsapp.com/EFy2mrYJodx5dB5W1jtlI7 💞Mgt501🌹 https://chat.whatsapp.com/H0dTUINbesw0GS4LLSt0W4
💞Cs411🌹 https://chat.whatsapp.com/IrOaF8Q3tkJKzeVTHapHR9 💞Mgt502🌹 https://chat.whatsapp.com/L3GSMFgwDl7DAsu9r0vAxl
💞Cs501🌹 https://chat.whatsapp.com/Eggxx3X0SH2LhOysM57SII 💞Mgt503🌹 https://chat.whatsapp.com/G7BNxqyLYwP48jfPTofkbJ
💞Cs502🌹 https://chat.whatsapp.com/FbLU96Xhmr2FI99fnbz5Yw 💞Mgt602🌹 https://chat.whatsapp.com/HXRpOrEL18vD7lb91nLHTB
💞Cs504🌹 https://chat.whatsapp.com/Gn7w0UzNCQ2FzRK7ZzY4Io 💞Mgt610🌹 https://chat.whatsapp.com/BxMcR1ouiao0wuqLlLj5dB
💞Cs506🌹 https://chat.whatsapp.com/BL4FFmDKf2S3WIoLsAD2JK 💞Mth101🌹 https://chat.whatsapp.com/LHsbl65FbwGH2SNFF9ipSb
💞Cs507🌹 https://chat.whatsapp.com/EINDZkV4e4zGLGqL8imozR 💞Mth202🌹 https://chat.whatsapp.com/GevRebusRaxFh6dgnzRJuM
💞Cs508🌹 https://chat.whatsapp.com/HTMAwnJ4Bic2ky8MbT3PuW 💞Mth301🌹 https://chat.whatsapp.com/EFm472nc2woDPrOEqnY1lj
💞Cs601🌹 https://chat.whatsapp.com/KYoaAutdXRlDNS0Mm5XfzP 💞Mth401🌹 https://chat.whatsapp.com/EP7tlcc17TzLtNaOgD4AcA
💞Cs602🌹 https://chat.whatsapp.com/FpJkLAFNQpZHRyi6vhl5n8 💞Mth501🌹 https://chat.whatsapp.com/Dy7XUVFqqD5LLw4i5X4Xzi
💞Cs604🌹 https://chat.whatsapp.com/KjDhHjxawtU43Veo9Eawa4 💞Mth601🌹 https://chat.whatsapp.com/BoD3akuXGK25MFB4UEZcRr
💞Cs605🌹 https://chat.whatsapp.com/BoF34LtMlYK1l4nQaEO2Ce 💞isL201🌹 https://chat.whatsapp.com/BtoqaMbbELW99MLLtQMGwC
💞Cs610🌹 https://chat.whatsapp.com/FcNcztKyYfd9szsJEJino2 💞Pak301🌹 https://chat.whatsapp.com/KuR9Y7YWeA32enRwKeZJaR
💞Cs615🌹 https://chat.whatsapp.com/HLVjBNcorFN9bwZhGEkFl3 💞Phy101🌹 https://chat.whatsapp.com/GjC6e47vF1zHwRs5iOc13J
💞Cs619🌹 https://chat.whatsapp.com/FEklYr700uj0ihxqnk55A6 💞Phy301🌹 https://chat.whatsapp.com/IBrOdznEHDi92fGa76Dqmr
💞Sta301🌹 https://chat.whatsapp.com/BchodAnjbydKXLuxFfKGxr

…Paid Service Available for LMS Activities…


Only for those students who are so busy in office or work or job that they can’t
watch their LMS due to their Busyness

For more INFo. CoNtaCt us oNly What’s app 0302-1400084


Visual Programming Lecture Notes

December 13, 2013


2
Contents

1 Lecture 1 5

2 Lecture 2 9

3 Lecture 3 13

4 Lecture 4 17

5 Lecture 5 21

6 Lecture 6 27

7 Lecture 7 35

8 Lecture 8 43

9 Lecture 9 47

10 Lecture 10 53

11 Lecture 11 61

12 Lecture 12 69

13 Lecture 13 71

14 Lecture 14 75

15 Lecture 15 77

16 Lecture 16 83

17 Lecture 17 89

18 Lecture 18 95

19 Lecture 19 101

20 Lecture 20 107

21 Lecture 21 111

22 Lecture 22 119

23 Lecture 23 123

3
4 CONTENTS

24 Lecture 24 129

25 Lecture 25 133

26 Lecture 26 137

27 Lecture 27 141

28 Lecture 28 145

29 Lecture 29 151

30 Lecture 30 157

31 Lecture 31 163

32 Lecture 32 169

33 Lecture 33 173

34 Lecture 34 177

35 Lecture 35 183

36 Lecture 36 189

37 Lecture 37 195

38 Lecture 38 201

39 Lecture 39 205

40 Lecture 40 211

41 Lecture 41 217

42 Lecture 42 223

43 Lecture 43 233

44 Lecture 44 241

45 Lecture 45 253
Chapter 23

Lecture 23

Lets see an example using touch events.


1 < Window x : Class =" TouchEvents . MainWindow "
2 xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
3 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml "
4 Title =" Touch Events " >
5 < Canvas Name =" canvas " >
6 < Canvas . Background >
7 < LinearGradientBrush >
8 < GradientStop Color =" Black "/ >
9 < GradientStop Color =" Red " Offset ="1"/ >
10 </ LinearGradientBrush >
11 </ Canvas . Background >
12 </ Canvas >
13 </ Window >

1 using System ;
2 using System . Collections . Generic ;
3 using System . Windows ;
4 using System . Windows . Controls ;
5 using System . Windows . Input ;
6 using System . Windows . Media ;
7 using System . Windows . Media . Imaging ;
8
9 namespace TouchEvents
10 {
11 public partial class MainWindow : Window
12 {
13 // Keep track of which images are used for which TouchDevices
14 Dictionary < TouchDevice , Image > fingerprints =
15 new Dictionary < TouchDevice , Image >();
16 public MainWindow ()
17 {
18 I n it i a li z eC o m po n e nt ();
19 }
20 protected override void OnTouchDown ( TouchEventArgs e )
21 {
22 base . OnTouchDown ( e );
23 // Capture this touch device
24 canvas . CaptureTouch ( e . TouchDevice );
25 // Create a new image for this new touch
26 Image fingerprint = new Image {
27 Source = new BitmapImage ( new Uri (" pack :// application : , , ,/ fingerprint . png "))

123
124 CHAPTER 23. LECTURE 23

28 };
29 // Move the image to the touch point
30 TouchPoint point = e . GetTouchPoint ( canvas );
31 fingerprint . RenderTransform = new T ra nsl at eT ra ns fo rm ( point . Position .X , point . Positio
32 // Keep track of the image and add it to the canvas
33 fingerprints [ e . TouchDevice ] = fingerprint ;
34 canvas . Children . Add ( fingerprint );
35 }
36 protected override void OnTouchMove ( TouchEventArgs e )
37 {
38 base . OnTouchMove ( e );
39 if ( e . TouchDevice . Captured == canvas )
40 {
41 // Retrieve the right image
42 Image fingerprint = fingerprints [ e . TouchDevice ];
43 TranslateTransform transform =
44 fingerprint . RenderTransform as T ra nsl at eT ra ns fo rm ;
45 // Move it to the new location
46 TouchPoint point = e . GetTouchPoint ( canvas );
47 transform . X = point . Position . X ;
48 transform . Y = point . Position . Y ;
49 }
50 }
51 protected override void OnTouchUp ( TouchEventArgs e )
52 {
53 base . OnTouchUp ( e );
54 // Release capture
55 canvas . Re l e as e T ou c h Cap t ur e ( e . TouchDevice );
56 // Remove the image from the canvas and the dictionary
57 canvas . Children . Remove ( fingerprints [ e . TouchDevice ]);
58 fingerprints . Remove ( e . TouchDevice );
59 }
60 }
61 }

Manipulation events are ManipulationStarting and ManipulationStarted, ManipulationDelta, ManipulationCom-


pleted. We combine information from multiple events. Manipulation events work if IsManipulationEnabled=true on
this or a parent and basic events not handled. Manipulation starting and started events at first finger touchdown, delta
at touchmove, and completed after touchup for all fingers. Starting and started events allow to customize or cancel or
disallow some manipulations. ManipulationDelta class has Translation, Scale, Rotation, Expansion (like Scale but dev
ind px instead of scale factor). ManipulationDeltaEventArgs has DeltaManipulation and CumulativeManipulation.
Lets see an example to move rotate zoom a photo.
1 < Window x : Class =" ManipulationEven ts . MainWindow "
2 xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
3 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml "
4 Title =" Manipulation Events " >
5 < Canvas Name =" canvas " Is Mani pu l a t i o n E n a b l e d =" True " >
6 < Image Name =" photo " Source =" photo . jpg " >
7 < Image . RenderTransform >
8 < MatrixTransform / >
9 </ Image . RenderTransform >
10 </ Image >
11 </ Canvas >
12 </ Window >

1 using System ;
2 using System . Windows ;
3 using System . Windows . Input ;
125

4 using System . Windows . Media ;


5 namespace Ma ni pu la ti on Ev en ts
6 {
7 public partial class MainWindow : Window
8 {
9 public MainWindow ()
10 {
11 I n it i al i z eC o m po n e nt ();
12 canvas . Man ipulat ionDel ta += C a n v a s _ M a n i p u l a t i o n D e l t a ;
13 }
14 void C a n v a s _ M a n i p u l a t i o n D el t a ( object sender , M a n i p u l a t i o n D e l t a E v e n t A r g s e )
15 {
16 MatrixTransform transform = photo . RenderTransform as MatrixTransform ;
17 if ( transform != null )
18 {
19 // Apply any deltas to the matrix ,
20 // then apply the new Matrix as the MatrixTransform data :
21 Matrix matrix = transform . Matrix ;
22 matrix . Translate ( e . Del taMani pulati on . Translation .X , e . Delt aManipulation . Translat
23 matrix . RotateAt ( e . Del taMani pulati on . Rotation , e . M an ip ul at io nOr igin .X , e . Manipula
24 matrix . ScaleAt ( e . Del taMani pulati on . Scale .X , e . Del taManip ulatio n . Scale .Y , e . Manip
25 transform . Matrix = matrix ;
26 e . Handled = true ;
27 }
28 }
29 }
30 }

Manipulations always done relative to a manipulation container. By default element with ismanipulationen-
abled=true or handle ManipulationStarting event and set ManipulationStartingEventArgs.ManipulationContainer.
Now what is Inertia. ManipulationInertiaStarting event when all fingers loose contact even before a completed
event. By default manipulationcompleted thrown right away but you can set ManipulationInertiaStartingEven-
tArgs.TranslationBehavior, RotationBehavior, and/or ExpansionBehavior which will cause deltas thrown and then
completed until inertia is completed. TranslationBehavior has DesiredDisplacement, DesiredDeceleration, and Ini-
tialVelocity. RotationBehavior has DesiredRotation, DesiredDeceleration, and InitialVelocity. ExpansionBehavior has
DesiredExpansion, DesiredDeceleration, InitialRadius, and InitialVelocity. Typically only set DesiredDeceleration or
the behavior-specific DesiredDisplacement, DesiredRotation, or DesiredExpansion. The latter properties are useful
for ensuring that the element doesnt go too far. By default, InitialVelocity and InitialRadius are initialized with the
current values. You can get the various velocities by checking ManipulationInertiaStartingEventArgs.InitialVelocities,
which has LinearVelocity, AngularVelocity, and ExpansionVelocity.
1 using System ;
2 using System . Windows ;
3 using System . Windows . Input ;
4 using System . Windows . Media ;
5 namespace Ma ni pu la ti on Ev en ts
6 {
7 public partial class MainWindow : Window
8 {
9 public MainWindow ()
10 {
11 I n it i al i z eC o m po n e nt ();
12 canvas . Man ipulat ionDel ta += C a n v a s _ M a n i p u l a t i o n D e l t a ;
13 canvas . M a n i p u l a t i o n I n e r t i a S t a r t i n g += C a n v a s _ M a n i p u l a t i o n I n e r t i a S t a r t i n g ;
14 }
15 void C a n v a s _ M a n i p u l a t i o n I n e r t i a S t a r t i n g ( object sender , M a n i p u l a t i o n I n e r t i a S t a r t i n g E v e n t A
16 {
17 e . TranslationBehavior . D e si r e dD e c el e r at i o n = 0.01;
18 e . RotationBehavior . De si r e dD e c el e r at i o n = 0.01;
126 CHAPTER 23. LECTURE 23

19 e . ExpansionBehavior . De si r e dD e c el e r at i o n = 0.01;
20 }
21 void C a n v a s _ M a n i p u l a t i o n D el t a ( object sender , M a n i p u l a t i o n D e l t a E v e n t A r g s e )
22 {
23 MatrixTransform transform = photo . RenderTransform as MatrixTransform ;
24 if ( transform != null )
25 {
26 // Apply any deltas to the matrix ,
27 // then apply the new Matrix as the MatrixTransform data :
28 Matrix matrix = transform . Matrix ;
29 matrix . Translate ( e . Del taMani pulati on . Translation .X , e . Delt aManipulation . Translat
30 matrix . RotateAt ( e . Del taMani pulati on . Rotation , e . M an ip ul at io nOr igin .X , e . Manipula
31 matrix . ScaleAt ( e . Del taMani pulati on . Scale .X , e . Del taManip ulatio n . Scale .Y , e . Manip
32 transform . Matrix = matrix ;
33 e . Handled = true ;
34 }
35 }
36 }
37 }

To be boundary aware ManipulationBoundaryFeedback event is used. Inside a ManipulationDelta event handler,


you can call the ReportBoundaryFeedback method on the passed-in ManipulationDeltaEventArgs instance to make
the window bounce similar to iphone bounce list behavior. Lets see a spin prize wheel example.

1 < Window x : Class =" SpinThePrizeWheel . MainWindow "


2 xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
3 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml "
4 Title =" Spin the Prize Wheel " >
5 < Window . Background >
6 < LinearGradientBrush >
7 < GradientStop Color =" White "/ >
8 < GradientStop Color =" Orange " Offset ="1"/ >
9 </ LinearGradientBrush >
10 </ Window . Background >
11 < Grid Name =" grid " Is Mani pulat i o n E n a b l e d =" True " >
12 < Image Name =" prizeWheel " Re nder Trans form Origi n ="0.5 ,0.5"
13 Source =" prizeWheel . png " Margin ="0 30 0 0" >
14 < Image . RenderTransform >
15 < RotateTransform / >
16 </ Image . RenderTransform >
17 </ Image >
18 < Image Source =" arrow . png " VerticalAlignment =" Top " Stretch =" None "/ >
19 </ Grid >
20 </ Window >
127

1 using System ;
2 using System . Windows ;
3 using System . Windows . Input ;
4 using System . Windows . Media ;
5 namespace SpinT hePrize Wheel
6 {
7 public partial class MainWindow : Window
8 {
9 public MainWindow ()
10 {
11 I n it i al i z eC o m po n e nt ();
12 grid . M a n i p u l a t i o n S t a rting += G r i d _ M a n i pu l a t i o n S t a r t i n g ;
13 grid . Man ipulat ionDel ta += G ri d_ Man ip ul ati on De lta ;
14 grid . M a n i p u l a t i o n I n e r t i a S t a r t i n g += G r i d _ M a n i p u l a t i o n I n e r t i a S t a r t i n g ;
15 grid . M a n i p u l a t i o n C o m plete d += G r i d _ M a n i p u l a t i o n C o m p l e t e d ;
16 }
17 void G r i d _ M a n i p u l a t i o n S t a r t i n g ( object sender , M a n i p u l a t i o n S t a r t i n g E v e n t A r g s e )
18 {
19 e . Mode = ManipulationModes . Rotate ; // Only allow rotation
20 }
21 void G r i d _ M a n i p u l a t i o n D e lta ( object sender , M a n i p u l a t i o n D e l t a E v e n t A r g s e )
22 {
23 ( prizeWheel . RenderTransform as RotateTransform ). Angle +=
24 e . DeltaManipulation . Rotation ;
25 }
26 void G r i d _ M a n i p u l a t i o n I n e r t i a S t a r t i n g ( object sender , M a n i p u l a t i o n I n e r t i a S t a r t i n g E v e n t A r g
27 {
28 e . RotationBehavior . De si r e dD e c el e r at i o n = 0.001;
29 }
128 CHAPTER 23. LECTURE 23

30 void G r i d _ M a n i p u l a t i o n C o m p l e t e d ( object sender , M a n i p u l a t i o n C o m p l e t e d E v e n t A r g s e )


31 {
32 // Now that the wheel has stopped , tell the user what s / he won !
33 }
34 }
35 }

You can take advantage of panning support built into ScrollViewer by setting its PanningMode property to Hori-
zontalOnly, VerticalOnly, HorizontalFirst, VerticalFirst, or Both. You can download the Surface Toolkit for Windows
Touch to get numerous slick Microsoft Surface WPF controls that are optimized for multi-touch. This includes “surface
versions” of most common controls (such as SurfaceButton and SurfaceCheckBox) and brand-new controls (such as
ScatterView and LibraryStack).
Chapter 24

Lecture 24

Commands are a more abstract and loosely coupled version of events e.g. cut copy paste commands. They are
exposed in various ways. They can be enabled disabled e.g. if there is nothing to paste. Two-way communication gets
cumbersome especially if you dont want the list of controls hard-coded.
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.
Any object implementing ICommand which defines Execute, CanExecute, CanExecuteChanged can work as a
Command. For Cut, Copy, and Paste, you could define and implement three classes implementing ICommand, find a
place to store them (perhaps as static fields of the main Window), call Execute from relevant event handlers (when
CanExecute returns true), and handle the CanExecuteChanged event to toggle the IsEnabled property on the relevant
pieces of user interface. Controls have logic to interface with commands through Command property. We can also do
it all in xaml.
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. Com-
ponentCommands e.g. MoveDown, MoveLeft, MoveRight, MoveUp, ScrollByLine, ScrollPageDown, ScrollPageLeft,
ScrollPageRight, ScrollPageUp, SelectToEnd, SelectToHome, SelectToPageDown, SelectToPageUp, and more. Me-
diaCommands e.g. ChannelDown, ChannelUp, DecreaseVolume, FastForward, IncreaseVolume, MuteVolume, Next-
Track, Pause, Play, PreviousTrack, Record, Rewind, Select, Stop, and more. NavigationCommands e.g. BrowseBack,
BrowseForward, BrowseHome, BrowseStop, Favorites, FirstPage, GoToPage, LastPage, NextPage, PreviousPage, Re-
fresh, Search, Zoom, and more. EditingCommands e.g. AlignCenter, AlignJustify, AlignLeft, AlignRight, Correct-
SpellingError, DecreaseFontSize, DecreaseIndentation, EnterLineBreak, EnterParagraphBreak, IgnoreSpellingError,
IncreaseFontSize, IncreaseIndentation, MoveDownByLine, MoveDownByPage, MoveDownByParagraph, MoveLeftBy-
Character, MoveLeftByWord, MoveRightByCharacter, MoveRightByWord, and more.
All instances of RoutedUICommand implement ICommand and support bubbling.
1 helpButton . Command = A p pl i c at i onCommands . Help ;

If you run it would be always disabled. We need to add CommandBinding to the element or a Parent (bubbling).
All UIElements have CommandBindings collection.
1 this . CommandBindings . Add ( new CommandBinding ( ApplicationCommands . Help , HelpExecuted , HelpCanExe
2 // Navigate to a page instance
3 PhotoPage nextPage = new PhotoPage ();
4 this . Navigati onServi ce . Navigate ( nextPage );
5 // Or navigate to a page via a URI
6 this . Navigati onServi ce . Navigate ( new Uri (" PhotoPage . xaml " , UriKind . Relative ));
7
8 this . CommandBindings . Add ( new CommandBinding ( ApplicationCommands . Help , HelpExecuted , HelpCanExec

1 < Window xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
2 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml "
3 x : Class =" AboutDialog "
4 Title =" About WPF Unleashed " SizeToContent =" WidthAndHeight "

129
130 CHAPTER 24. LECTURE 24

5 Background =" OrangeRed " >


6 < Window . CommandBindings >
7 < CommandBinding Command =" Help "
8 CanExecute =" HelpCanExecute " Executed =" HelpExecuted "/ >
9 </ Window . CommandBindings >
10 < StackPanel >
11 < Label FontWeight =" Bold " FontSize ="20" Foreground =" White " >
12 WPF 4 Unleashed
13 </ Label >
14 < Label > 2010 SAMS Publishing </ Label >
15 < Label > Installed Chapters : </ Label >
16 < ListBox >
17 < ListBoxItem > Chapter 1 </ ListBoxItem >
18 < ListBoxItem > Chapter 2 </ ListBoxItem >
19 </ ListBox >
20 < StackPanel Orientation =" Horizontal " HorizontalAlignment =" Center " >
21 < Button MinWidth ="75" Margin ="10" Command =" Help "
22 Content = "{
23 Binding RelativeSource ={ RelativeSource Self } , Path = Command . Text
24 }"/ >
25 < Button MinWidth ="75" Margin ="10" > OK </ Button >
26 </ StackPanel >
27 < StatusBar > You have successfully registered this product . </ StatusBar >
28 </ StackPanel >
29 </ Window >

1 using System . Windows ;


2 using System . Windows . Input ;
3 public partial class AboutDialog : Window
4 {
5 public AboutDialog ()
6 {
7 I ni t i al i z eC o m po n e nt ();
8 }
9 void HelpCanExecute ( object sender , C a n E x e c u t e Ro u t e d E v e n t A r g s e )
10 {
11 e . CanExecute = true ;
12 }
13 void HelpExecuted ( object sender , Ex ec u te d Ro ut e dE v en tA r gs e )
14 {
15 System . Diagnostics . Process . Start (" http :// www . adamnathan . net / wpf ");
16 }
17 }

There is a CommandConverter type converter.


x:Static ApplicationCommands.Help
Custom commands dont get this treatment. Now even F1 works, its an input gesture. You can also add KeyBindings
and MouseBindings yourself.
1 this . InputBindings . Add (
2 new KeyBinding ( ApplicationComm a n ds . Help , new KeyGesture ( Key . F2 )));

1 < Window . InputBindings >


2 < KeyBinding Command =" Help " Key =" F2 "/ >
3 < KeyBinding Command =" NotACommand " Key =" F1 "/ >
4 </ Window . InputBindings >

1 this . InputBindings . Add (


2 new KeyBinding ( ApplicationComm a n ds . NotACommand , new KeyGesture ( Key . F1 )));
131

Controls with builtin command bindings e.g. textbox that responds to ctrl-z etc.
1 < StackPanel xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
2 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml "
3 Orientation =" Horizontal " Height ="25" >
4 < Button Command =" Cut " CommandTarget ="{ Binding ElementName = textBox }"
5 Content ="{ Binding RelativeSource ={ RelativeSource Self } , Path = Command . Text }"/ >
6 < Button Command =" Copy " CommandTarget ="{ Binding ElementName = textBox }"
7 Content ="{ Binding RelativeSource ={ RelativeSource Self } , Path = Command . Text }"/ >
8 < Button Command =" Paste " CommandTarget ="{ Binding ElementName = textBox }"
9 Content ="{ Binding RelativeSource ={ RelativeSource Self } , Path = Command . Text }"/ >
10 < Button Command =" Undo " CommandTarget ="{ Binding ElementName = textBox }"
11 Content ="{ Binding RelativeSource ={ RelativeSource Self } , Path = Command . Text }"/ >
12 < Button Command =" Redo " CommandTarget ="{ Binding ElementName = textBox }"
13 Content ="{ Binding RelativeSource ={ RelativeSource Self } , Path = Command . Text }"/ >
14 < TextBox x : Name =" textBox " Width ="200"/ >
15 </ StackPanel >

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.
In summary, wpf input events make possible rich interactive content. We focused on UIElement but the same
events can be used with ContentElement.
132 CHAPTER 24. LECTURE 24
Chapter 25

Lecture 25

Lets discuss structuring and deploying an application. A standard windows app or partial trust web app or loose xaml.
We will discuss Photo Gallery example with the book. App.xaml and MainWindow.xaml and code-behind files on a new
wpf project. WPF Window is a win32 window, same chrome (non-client area) same taskbar behavior etc. Icon Title
WindowStyle TopMost ShowInTaskbar properties. Left and Top props or WindowStartupLocation=CenterScreen or
CenterOwner. Any number of child windows can be made by instantiating a Window dervied class and calling Show.
Child window like parent window but gets closed when parent and similarly minimized, also called modeless dialog.
Another windows Owner property after parent shown, OwnedWindows property. There are Activated & Deactivated
events. Activate method (like SetForegroundWindow). ShowActivated=false, initially not shown.
1 public partial class MainWindow : Window
2 {
3 public MainWindow ()
4 {
5 I ni t i al i z eC o m po n e nt ();
6 }
7 protected override void OnClosing ( CancelEventArgs e )
8 {
9 base . OnClosing ( e );
10 if ( MessageBox . Show (" Are you sure you want to close Photo Gallery ?" ,
11 " Annoying Prompt " , MessageBoxButton . YesNo , MessageBoxImage . Question )
12 == MessageBoxResult . No )
13 e . Cancel = true ;
14 }
15 protected override void OnClosed ( EventArgs e )
16 {
17 base . OnClosed ( e );
18 // Persist the list of favorites
19 //
20 }
21 protected override void OnInitialized ( EventArgs e )
22 {
23 base . OnInitialized ( e );
24 // Retrieve the persisted list of favorites
25 //
26 }
27 //
28 void exitMenu_Click ( object sender , RoutedEventArgs e )
29 {
30 this . Close ();
31 }
32 //
33 }
34 public static void Main ()

133
134 CHAPTER 25. LECTURE 25

35 {
36 MainWindow window = new MainWindow ();
37 window . Show ();
38 }
End result same whether you attach event handler or override this method. Technically a bit faster and more neat
when subclass wants to handle something base class throws. DispatcherObject cant be accessed from a di↵erent thread
which avoids many issues. App terminating, you need to add a message loop to process windows messages and pass
them to the correct window.
1 [ STAThread ]
2 Public static void Main ()
3 {
4 Application app = new Application ();
5 MainWindow window = new MainWindow ();
6 window . Show ();
7 app . Run ( window );
8 }
9 [ STAThread ]
10 Public static void Main ()
11 {
12 Application app = new Application ();
13 app . StartupUri = new Uri (" MainWindow . xaml " , UriKind . Relative );
14 app . Run ();
15 }

1 < Application x : Class =" PhotoGallery . App "


2 xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
3 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml "
4 StartupUri =" MainWindow . xaml "/ >

1 using System . Windows ;


2 namespace PhotoGallery
3 {
4 public partial class App : Application
5 {
6 public App ()
7 {
8 I n it i a li z eC o m po n e nt ();
9 }
10 }
11 }
12 Main ()
13 [ System . ST AThreadAttribute ()]
14 public static void Main ()
15 {
16 PhotoGallery . App app = new PhotoGallery . App ();
17 app . In itializeComponent ();
18 app . Run ();
19 }
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.GetCommandLineAr
or set build action to Page and write Main. Startup, Exit, Activated, Deactivated (any window), SessionEnding (can-
cellable logo↵ 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.
Lets discuss creating a single instance app. Can create app without Application using Dispatcher.Run or Win32
message loop but explicit termination and other issues. One UI Thread and one render thread. Can create more with
Dispatcher.Run which can improve responsiveness. Can schedule on UI thread with Dispatcher.Invoke and BeginInvoke
and priority from send (now) to systemidle.
135

1 bool mutexIsNew ;
2 using ( System . Threading . Mutex m =
3 new System . Threading . Mutex ( true , uniqueName , out mutexIsNew ))
4 {
5 if ( mutexIsNew )
6 // This is the first instance . Run the application .
7 else
8 // There is already an instance running . Exit !
9 }

You can also create a splash screen. Nothing fancy because wpf not loaded yet. In wpf project - add new item -
splash screen, adds an images with build action SplashScreen.
Modal dialogs include common dialogs which are actually provided by win32. Instantiate, call ShowDialog and
process result.
1 void printMenu_Click ( object sender , RoutedEventArgs e )
2 {
3 string filename = ( pictureBox . SelectedItem as ListBoxItem ). Tag as string ;
4 Image image = new Image ();
5 image . Source = new BitmapImage ( new Uri ( filename , UriKind . RelativeOrAbsolute ));
6 PrintDialog pd = new PrintDialog ();
7 if ( pd . ShowDialog () == true ) // Result could be true , false , or null
8 pd . PrintVisual ( image , Path . GetFileName ( filename ) + " from Photo Gallery ");
9 }

1 void renameMenu_Click ( object sender , RoutedEventArgs e )


2 {
3 string filename = ( pictureBox . SelectedItem as ListBoxItem ). Tag as string ;
4 RenameDialog dialog = new RenameDialog ( Path . G e t F i l e N a m e W i t h o u t E x t e n s i o n ( filename ));
5 if ( dialog . ShowDialog () == true ) // Result could be true , false , or null
6 {
7 // Attempt to rename the file
8 try
9 {
10 File . Move ( filename , Path . Combine ( Path . GetDirectoryName ( filename ) ,
11 dialog . NewFilename ) + Path . GetExtension ( filename ));
12 }
13 catch ( Exception ex )
14 {
15 MessageBox . Show ( ex . Message , C a n n o t Rename F i l e , MessageBoxButton . OK ,
16 MessageBoxImage . Error );
17 }
18 }
19 }

A window to be shown as a dialog sets its dialogResult to bool. Setting it closes window or set Button’s IsDefault
prop to true.
1 void okButton_Click ( object sender , RoutedEventArgs e )
2 {
3 this . DialogResult = true ;
4 }

1 [ STAThread ]
2 public static void Main ()
3 {
4 MainWindow window = new MainWindow ();
5 window . ShowDialog ();
6 }
136 CHAPTER 25. LECTURE 25

Lets discuss persisting and restoring. Can use registry or file system but lets use .net isolated storage. Physically
located in the users document folder in a hidden folder. VS generated Settings class provide an even easier and strongly
typed way but in a app. config file.
1 protected override void OnClosed ( EventArgs e )
2 {
3 base . OnClosed ( e );
4 // Write each favorites item when the application is about to close
5 I so l a te d S to r a ge F i le f = I so l atedStorageFile . Ge t Us er S to r eF or A ss e mb ly ();
6 using ( I s o l a t e d S t o r a g e F i l e S t r ea m stream =
7 new I s o l a t e d S t o r a g e F il e S t r e a m (" myFile " , FileMode . Create , f ))
8 using ( StreamWriter writer = new StreamWriter ( stream ))
9 {
10 foreach ( TreeViewItem item in favoritesItem . Items )
11 writer . WriteLine ( item . Tag as string );
12 }
13 }
14 protected override void OnInitialized ( EventArgs e )
15 {
16 base . OnInitialized ( e );
17 // Read each favorites item when the application is initialized
18 I so l a te d S to r a ge F i le f = I so l atedStorageFile . Ge t Us er S to r eF or A ss e mb ly ();
19 using ( I s o l a t e d S t o r a g e F i l e S t r ea m stream =
20 new I s o l a t e d S t o r a g e F i l eS t r e a m (" myFile " , FileMode . OpenOrCreate , f ))
21 using ( StreamReader reader = new StreamReader ( stream ))
22 {
23 string line = reader . ReadLine ();
24 while ( line != null )
25 {
26 AddFavorite ( line );
27 line = reader . ReadLine ();
28 }
29 }
30 //
31 }
Lets discuss clickonce vs. windows installer. VS setup and deployment projects or a simpler clickonce wizard from
build-¿publish menu. 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 e↵ect on other apps, clean
uninstallation, but full trust apps can do things while they run, .net code access security, partial trust.
Chapter 26

Lecture 26

Lets discuss navigation based apps like windows explorer, media player, photo gallery. Can use navigation support
for a wizard or organize the whole ui around navigation. With nav, content is usually in “Page” a simpler version of
Window. Then hosted in a NavigationWindow or a Frame. They provide support for navigating, a history journal,
and nav related events. 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.
1 < NavigationWindow
2 xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
3 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml "
4 xmlns : d =" http :// schemas . microsoft . com / expression / blend /2008"
5 xmlns : mc =" http :// schemas . openxmlformats . org / markup - compatibility /2006"
6 mc : Ignorable =" d " x : Class =" PhotoGallery . Container "
7 Title =" Photo Gallery " Source =" MainPage . xaml "
8 d : DesignWidth ="1320" d : DesignHeight ="919"
9 />
nav enabled version points startup uri to this and and mainpage.xaml referenced above has the content.
1 < Page x : Class =" PhotoGallery . MainPage "
2 xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
3 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml "
4 Title =" Photo Gallery " Loaded =" Page_Loaded " >
5 <! - - A p p l i c a t i o n - specific c o n t e n t -->
6 </ Page >
page does everything window does except onclosed and onclosing. with these changes, nothing much changes in
our app, just some disabled back/fwd buttons. navigation can also happen between html files.
A Page can interact with its navigation container by using the NavigationService class, which exposes relevant
functionality regardless of whether the container is a NavigationWindow or a Frame. You can get an instance of
NavigationService by calling the static NavigationService.GetNavigationService method and passing the instance of
the Page. But even more easily, you can simply use Pages NavigationService property. For example, you can set a
title that is used in the drop-down menu associated with the Back and Forward buttons as follows:
1 this . Navigati onServi ce . Title = Main Photo Gallery Page ;
Or you can refresh the current Page as follows:
1 this . Navigati onServi ce . Refresh ();
But Page also contains a few of its own properties that control the behavior of the parent container, such as
WindowHeight, WindowWidth, and WindowTitle. Can also set in xaml. You can perform navigation in three main
ways: Calling the Navigate method, Using Hyperlinks, Using the journal. Navigation containers support a Navigate
method.
1 // Navigate to a page instance
2 PhotoPage nextPage = new PhotoPage ();

137
138 CHAPTER 26. LECTURE 26

3 this . Navigatio nServi ce . Navigate ( nextPage );


4 // Or navigate to a page via a URI
5 this . Navigatio nServi ce . Navigate ( new Uri (" PhotoPage . xaml " , UriKind . Relative ));

root of xaml must be “Page”. or for html

1 this . Navigatio nServi ce . Navigate ( new Uri (" http :// www . adamnathan . net / wpf "));

can also use 2 properties. only useful from xaml.

1 this . Navigatio nServi ce . Content = nextPage ;


2 this . Navigatio nServi ce . Source = new Uri (" PhotoPage . xaml " , UriKind . Relative );

Hyperlink element is used to link to xaml. or handle its Click event and call navigate yourself to link from html to
wpf. 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.

1 < TextBlock >


2 Click
3 < Hyperlink NavigateUri =" PhotoPage . xaml " > here </ Hyperlink > to view the photo .
4 </ TextBlock >

Lets discuss using Journal. 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). When
frame has journal it has back/fwd buttons but can set NavigationUIVisibility=Hidden. when nav. with URI or
hyperlink, always new instance. can control when calling navigate with page so work to remember state. However,
JournalEntry.KeepAlive attached prop. can help for back fwd. RemoveFromJournal means a page is not in journal.
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. we use this in photo gallery for undoable image rotation.

1 [ Serializable ]
2 class RotateState : Cu st om Co nt en tState
3 {
4 FrameworkElement element ;
5 double rotation ;
6 public RotateState ( FrameworkElement element , double rotation )
7 {
8 this . element = element ;
9 this . rotation = rotation ;
10 }
11 public override string JournalEntryName
12 {
13 get { return " Rotate " + rotation + " "; }
14 }
15 public override void Replay ( Nav igatio nServi ce navigationService , NavigationMode mode )
16 {
17 // Rotate the element by the specified amount
18 element . LayoutTransform = new RotateTransform ( rotation );
19 }
20 }
139

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.
1 int photoId = 10;
2 // Navigate to a page instance
3 PhotoPage nextPage = new PhotoPage ();
4 this . Navigatio nServi ce . Navigate ( nextPage , photoId );
5 // Or navigate to a page via a URI
6 this . Navigatio nServi ce . Navigate ( new Uri (" PhotoPage . xam " , UriKind . Relative ) , photoId );

1 this . Navigatio nServi ce . LoadCompleted += new


2 L o a d C o m p l e t e d E v e n t H a n d l e r ( c o nt a in e r_ Lo a dC om p le t ed );
3 //
4 void c o n ta in e r _ L o a d C o m p l e t e d ( object sender , NavigationEventArgs e )
5 {
6 if ( e . ExtraData != null )
7 LoadPhoto (( int ) e . ExtraData );
8 }

1 int photoId = 10;


2 // Navigate to a page instance
3 PhotoPage nextPage = new PhotoPage ( photoId );
4 this . Navigati onServi ce . Navigate ( nextPage );
5
6 public PhotoPage ( int id )
7 {
8 LoadPhoto ( id );
9 }

1 // Navigate to a page by instance or URI


2 Application . Properties [" PhotoId "] = 10;
3 this . Navigati onServi ce . Navigate (/* */);
4
5 if ( Application . Properties [" PhotoId "] != null )
6 LoadPhoto (( Application . Properties [" PhotoId "]);

Lets see returning data with a pagefunction.

pagefunction acts likea function.


140 CHAPTER 26. LECTURE 26

1 < PageFunction
2 xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
3 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml "
4 xmlns : sys =" clr - namespace : System ; assembly = mscorlib "
5 x : Class =" MyProject . PageFunction1 "
6 x : TypeArguments =" sys : String "
7 Title =" PageFunction1 " >
8 < Grid >
9 </ Grid >
10 </ PageFunction >

1 PageFunction1 nextPage = new PageFunction1 < string >();


2 This . Navigatio nServi ce . Navigate ( nextPage );
3
4 nextPage . Return += new ReturnEventHandler < string >( nextPage_Return );
5 //
6 void nextPage_Return ( object sender , ReturnEventArgs < string > e )
7 {
8 string returnValue = e . Result ;
9 }
10 OnReturn ( new ReturnEventArgs < string >(" the data "));
Chapter 27

Lecture 27

Lets discuss XAML Browser apps (XBAPS). silverlight more popular to deliver partial-trust wpf content in a browser.
di↵erences are that not all features available by default, nav is integrated into the browser, deployment di↵erent.
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.
1 // Whoops ! Partially trusted code is not allowed to get this data !
2 AddFavorite ( Environment . GetFolderPath ( Environment . SpecialFolder . MyPictures ));
clickonce caching. VS increments. or you can clear cache. change some settings and its a xbap. but partial trust
restricts many api. e.g. above call exception. requires FileIOPermission which is not by default. hit n trial to find
what works. local registry and file system, new windows (popups ok), unmanaged, but others dependent on browser,
or on implementation details. BrowserInteropHelper.IsBrowserHosted property to check if its a XBAP.
1 string fileContents = null ;
2 OpenFileDialog ofd = new OpenFileDialog ();
3 if ( ofd . ShowDialog () == true ) // Result could be true , false , or null
4 {
5 using ( Stream s = ofd . OpenFile ())
6 using ( StreamReader sr = new StreamReader ( s ))
7 {
8 fileContents = sr . ReadToEnd ();
9 }
10 }
but u can still use rich text and media, isolated storage upto 512kb, arbitrary files on host web server, use browser
file open dialog for local files. how parameters passed in. either BrowserInteropHelper.Source to retrieve the complete
URL or browser cookie retrieved by Application.GetCookie method. any assembly marked with AllowPartiallyTrust-
edCallers and placed in GAC can be called by partial-trust code and it can be security loophole too.
There are also full-trust browser apps. In the project file you change
1 < TargetZone > Internet </ TargetZone >
to this:
1 < TargetZone > Custom </ TargetZone >
and in clickonce application manifest you add:
1 < PermissionSet class =" System . Security . PermissionSet " version ="1"
2 ID =" Custom " SameSite =" site " Unrestricted =" true "/ >
You get Integrated Navigation in XBAP. Many XBAP don’t take advantage of navigation. Such applications can
set ShowNavigationUI=false on Page. IE 7 and later merge the journal and provide a more streamlined interface.
However if it appears in an IFrame, there is still a separate nav. bar. To publish, use VS publishing wizard or mage
tool in SDK and copy files to webserver which must be configured to serve it. Users can install and run by just
navigating to a URL. No security prompt if you dont need non. Stdandard permissions.

141
142 CHAPTER 27. LECTURE 27

Lets discuss downloading files on demand. We will assign a set of loose files to a download group in VS. Under
publish-¿application files in proj. prop. Then use api in System.Deployment.Application to prompt download and be
notified e.g. progress bar while app loads. Page1 starts, loads MyGroup and shows page2.

1 using System ;
2 using System . Windows . Controls ;
3 using System . Windows . Threading ;
4 using System . Deployment . Application ;
5 public partial class Page1 : Page
6 {
7 public Page1 ()
8 {
9 I ni t i al i z eC o m po n e nt ();
10 }
11 protected override void OnInitialized ( EventArgs e )
12 {
13 base . OnInitialized ( e );
14 if ( Ap plic ation Depl oymen t . IsN etwork Deploy ed )
15 {
16 A p p l i c a t i o n D e p l o y m e n t . CurrentDeployment . D o w n l o a d F i l e G r o u p C o m p l e t e d +=
17 delegate {
18 Dispatcher . BeginInvoke ( DispatcherPriority . Send ,
19 new D i s p a t c h e r O p e r a t i o n C a l l b a c k ( GotoPage2 ) , null );
20 };
21 A p p l i c a t i o n D e p l o y m e n t . CurrentDeployment . D own lo ad Fil eG ro upA sy nc (" MyGroup ");
22 }
23 else
24 {
25 GotoPage2 ( null );
26 }
27 }
28 private object GotoPage2 ( object o )
29 {
30 return Na vigatio nServi ce . Navigate ( new Uri (" Page2 . xaml " , UriKind . Relative ));
31 }
32 }

Additional events can be used for fine grained progress. Loose xaml is powerful sometimes instead of html. In
summary, XBAP have similar impl. from desktop app to web app. Deployment just needs the right .net installed.
wpf 3.5 by default on win7, wpf4 now.

Lets discuss resources e.g. bitmap, fonts, string tables. Wpf builds on top, has binary resources and logical
resources. Binary resources are what rest of .net framework considers a resource. Even compiled xaml stored as a
resource. Can be embedded in assembly, loose file that may or may not be known at compile time. Can be localizable
or not.

To define a binary resource, add a file and set the build action resource or content (loose file).
143

Dont use embeddedresource. Its misleading name but wpf doesnt fully support. Adding as content and loading
directly are kind of equal but resource is neat. Should be embed if localizable or single binary file benefits.
Lets see how to assign binary resource whether embed or loose. Wont work if not added to proj. If not added be
explicit about the path.
1 < StackPanel Grid . Column ="1" Orientation =" Horizontal " HorizontalAlignment =" Center " >
2 < Button x : Name =" previousButton " ToolTip =" Previous ( Left Arrow )" >
3 < Image Height ="21" Source =" previous . gif "/ >
4 </ Button >
5 < Button x : Name =" slideshowButton " ToolTip =" Play Slide Show ( F11 )" >
6 < Image Height ="21" Source =" slideshow . gif "/ >
7 </ Button >
8 < Button x : Name =" nextButton " ToolTip =" Next ( Right Arrow )" >
9 < Image Height ="21" Source =" next . gif "/ >
10 </ Button >
11 </ StackPanel >
12
13 < Image Height ="21" Source =" pack :// siteOfOrigin : , , ,/ slideshow . gif "/ >
14
15 Image image = new Image ();
16 image . Source = new BitmapImage ( new Uri (" pack :// application : , , ,/ logo . jpg "));
Can use subfolders for embedded resources. From procedural code, cant use xaml spec. so there are shortcuts.
144 CHAPTER 27. LECTURE 27
Chapter 28

Lecture 28

Lets discuss localizing binary resources. can partition into satellite assembly and use LocBaml to manage string
localization. To spec. a default culture and auto. build a satellite assembly, you can to set UICulture. Need to
open project file in a text ed. add under debug, release etc. or where it e↵ects all prop. If you rebuild your project
with this setting in place, youll find an en-US folder alongside your assembly, containing the satellite assembly named
AssemblyName.resources.dll. Also mark assembly with the neutral resource language matching.
1 < Project >
2 < PropertyGroup >
3 < UICulture > en - US </ UICulture >
4 [ assembly : N e u t r a l R e s o u r c e s L a n g u a g e (" en - US " ,
5 U l t i m a t e R e s o u r c e F a l l b a c k L o c a t i o n . Satellite )]

next, apply Uid directive to any element needing localization. msbuild /t:updateuid ProjectName.csproj. LocBaml
/parse ProjectName.g.en-US.resources /out:en-US.csv. now edit and localize all strings. LocBaml /generate Project-
Name.resources.dll /trans:fr-CA.csv /cul:fr-CA. then copy the assembly with a name matching the locale. to test, Sys-
tem.Threading.Thread.CurrentThread.CurrentUICulture (and System.Threading.Thread.CurrentThread.CurrentCulture)
to an instance of the desired CultureInfo.
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 FrameworkContentElement both have
a Resources prop. often are style or data providers. first examples using simple brushes. much like css, share objects.
1 < Window xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
2 Title =" Simple Window " Background =" Yellow " >
3 < DockPanel >
4 < StackPanel DockPanel . Dock =" Bottom "
5 Orientation =" Horizontal "
6 H or i z on t a lA l ignment =" Center " >
7 < Button Background =" Yellow "
8 BorderBrush =" Red " Margin ="5" >
9 < Image Height ="21" Source =" zoom . gif "/ >
10 </ Button >
11 < Button Background =" Yellow "
12 BorderBrush =" Red "
13 Margin ="5" >
14 < Image Height ="21"
15 Source =" d e f a u l t T h u m b n a i l S i z e . gif "/ >
16 </ Button >
17 < Button Background =" Yellow "
18 BorderBrush =" Red "
19 Margin ="5" >
20 < Image Height ="21"
21 Source =" previous . gif "/ >
22 </ Button >

145
146 CHAPTER 28. LECTURE 28

23 < Button Background =" Yellow "


24 BorderBrush =" Red "
25 Margin ="5" >
26 < Image Height ="21"
27 Source =" slideshow . gif "/ >
28 </ Button >
29 < Button Background =" Yellow "
30 BorderBrush =" Red "
31 Margin ="5" >
32 < Image Height ="21"
33 Source =" next . gif "/ >
34 </ Button >
35 < Button Background =" Yellow "
36 BorderBrush =" Red "
37 Margin ="5" >
38 < Image Height ="21"
39 Source =" counterclockwise . gif "/ >
40 </ Button >
41 < Button Background =" Yellow "
42 BorderBrush =" Red "
43 Margin ="5" >
44 < Image Height ="21"
45 Source =" clockwise . gif "/ >
46 </ Button >
47 < Button Background =" Yellow "
48 BorderBrush =" Red "
49 Margin ="5" >
50 < Image Height ="21"
51 Source =" delete . gif "/ >
52 </ Button >
53 </ StackPanel >
54 < ListBox / >
55 </ DockPanel >
56 </ Window >
57
58 < Window xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
59 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml "
60 Title =" Simple Window " >
61 < Window . Resources >
62 < SolidColorBrush x : Key =" backgroundBrush " > Yellow </ SolidColorBrush >
63 < SolidColorBrush x : Key =" borderBrush " > Red </ SolidColorBrush >
64 </ Window . Resources >
65 < Window . Background >
66 < StaticResource ResourceKey =" backgroundBrush "/ >
67 </ Window . Background >
68 < DockPanel >
69 < StackPanel DockPanel . Dock =" Bottom "
70 Orientation =" Horizontal "
71 H o ri z o nt a l Al ignment =" Center " >
72 < Button Background ="{ StaticResource backgroundBrush }"
73 BorderBrush ="{ StaticResource borderBrush }" Margin ="5" >
74 < Image Height ="21" Source =" zoom . gif "/ >
75 </ Button >
76 < Button Background ="{ StaticResource backgroundBrush }"
77 BorderBrush ="{ StaticResource borderBrush }" Margin ="5" >
78 < Image Height ="21" Source =" defaultThumbnailSize . gif "/ >
79 </ Button >
80 < Button Background ="{ StaticResource backgroundBrush }"
81 BorderBrush ="{ StaticResource borderBrush }" Margin ="5" >
147

82 < Image Height ="21" Source =" previous . gif "/ >
83 </ Button >
84 < Button Background ="{ StaticResource backgroundBrush }"
85 BorderBrush ="{ StaticResource borderBrush }" Margin ="5" >
86 < Image Height ="21" Source =" slideshow . gif "/ >
87 </ Button >
88 < Button Background ="{ StaticResource backgroundBrush }"
89 BorderBrush ="{ StaticResource borderBrush }" Margin ="5" >
90 < Image Height ="21" Source =" next . gif "/ >
91 </ Button >
92 < Button Background ="{ StaticResource backgroundBrush }"
93 BorderBrush ="{ StaticResource borderBrush }" Margin ="5" >
94 < Image Height ="21" Source =" counterclockwise . gif "/ >
95 </ Button >
96 < Button Background ="{ StaticResource backgroundBrush }"
97 BorderBrush ="{ StaticResource borderBrush }" Margin ="5" >
98 < Image Height ="21" Source =" clockwise . gif "/ >
99 </ Button >
100 < Button Background ="{ StaticResource backgroundBrush }"
101 BorderBrush ="{ StaticResource borderBrush }" Margin ="5" >
102 < Image Height ="21" Source =" delete . gif "/ >
103 </ Button >
104 </ StackPanel >
105 < ListBox / >
106 </ DockPanel >
107 </ Window >
108 < Li ne arG radientBrush x : Key =" backgroundBrush " StartPoint ="0 ,0" EndPoint ="1 ,1" >
109 < GradientStop Color =" Blue " Offset ="0"/ >
110 < GradientStop Color =" White " Offset ="0.5"/ >
111 < GradientStop Color =" Red " Offset ="1"/ >
112 </ LinearGradientBrush >

now u can change brushes in one place and have di↵erent e↵ects. StaticResource markup extension walks the
logical tree or even application level or system resources. root level or app level resource dict for max sharing. closest
to element chosen. for multi-threaded either Frozen or x:Shared=false.
148 CHAPTER 28. LECTURE 28

Lets discuss static vs Dynamic Resources. 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.
1 < Window xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
2 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml " >
3
4 < Image Height ="21" Source =" zoom . gif "/ >
5
6 </ Window >
is equivalent to this Window :
1 < Window xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
2 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml " >
3 < Window . Resources >
4 < Image x : Key =" zoom " Height ="21" Source =" zoom . gif "/ >
5 </ Window . Resources >
6 < StackPanel >
7 < StaticResource ResourceKey =" zoom "/ >
8 </ StackPanel >
9 </ Window >
can be a way to factor but Image can only have one parent so cant share last, static doesnt support fwd. ref. with
dyn. the following is possible.
1 < Window xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
2 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml "
3 Title =" Simple Window " Background ="{ DynamicResource backgroundBrush }" >
4 < Window . Resources >
5 < SolidColorBrush x : Key =" backgroundBrush " > Yellow </ SolidColorBrush >
6 < SolidColorBrush x : Key =" borderBrush " > Red </ SolidColorBrush >
7 </ Window . Resources >
8
9 </ Window >
Without sharing, x:Shared=false e.g. new instance of image multiple times.
1 < Window xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
2 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml " >
3 < Window . Resources >
4 < Image x : Shared =" False " x : Key =" zoom " Height ="21" Source =" zoom . gif "/ >
5 </ Window . Resources >
6 < StackPanel >
7 <! - - Applying the resource multiple times works ! -->
8 < StaticResource ResourceKey =" zoom "/ >
9 < StaticResource ResourceKey =" zoom "/ >
10 < StaticResource ResourceKey =" zoom "/ >
11 </ StackPanel >
12 </ Window >
On in procedural code
1 window . Resources . Add (" backgroundBrush " , new SolidColorBrush ( Colors . Yellow ));
2 window . Resources . Add (" borderBrush " , new SolidColorBrush ( Colors . Red ));
3
4 Button button = new Button ();
5 // The Button must descend from the Window before looking up resources :
6 stackPanel . Children . Add ( button );
7 button . Background = ( Brush ) button . FindResource (" backgroundBrush ");
8 button . BorderBrush = ( Brush ) button . FindResource (" borderBrush ");
9
10 Button button = new Button ();
149

11 button . S e t Re s o u r c e R e f e r e n c e ( Button . BackgroundProperty , " backgroundBrush ");


12 button . S e t Re s o u r c e R e f e r e n c e ( Button . BorderBrushProperty , " borderBrush ");
13
14
15 Button button = new Button ();
16 button . Background = ( Brush ) window . Resources [" backgroundBrush "];
17 button . BorderBrush = ( Brush ) window . Resources [" borderBrush "];

Following are some XAML and equivalent C# examples.


1 XAML :
2 < Button Background =" SystemColors . WindowBrush "/ >
3 C \#:
4 button . Background = ( Brush ) new
5 BrushConverter (). ConvertFrom (" SystemColors . WindowBrush ");
6
7 XAML :
8 < Button Background =" { x : Static SystemColors . WindowBrush }"/ >
9 C \#:
10 button . Background = SystemColors . WindowBrush ;
11
12 XAML :
13 < Button Background =" { StaticResource SystemColors . WindowBrushKey }"/ >
14 C \#:
15 button . Background = ( Brush ) FindResource (" SystemColors . WindowBrushKey ");
16
17 XAML :
18 < Button Background =" { StaticResource { x : Static SystemColors . WindowBrush }}"/ >
19 C \#:
20 button . Background = ( Brush ) FindResource ( SystemColors . WindowBrush );
21
22 XAML :
23 < Button Background =" { StaticResource { x : Static SystemColors . WindowBrushKey }}"/ >
24 C \#:
25 button . Background = ( Brush ) FindResource ( SystemColors . WindowBrushKey );
26
27 XAML :
28 < Button Background =" { DynamicResource { x : Static SystemColors . WindowBrushKey }}"/ >
29 C \#:
30 button . S e t Re s o u r c e R e f e r e n c e (
31 Button . BackgroundProperty , SystemColors . WindowBrushKey );

In summary, resources really imp. in professional apps, enable localization, increase productivity as it consolidates
/ shares. Most interesting use is with styles and data binding.
150 CHAPTER 28. LECTURE 28
Chapter 29

Lecture 29

We will discuss data binding now. 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. Instead of iterating and adding items, tell listbox to get its data
from another source, keep them up to date, format them etc.
Binding binds two properties together and keeps a communication channel open. setup Binding once and let it
handle all the sync. eg. in proc. code.
1 < TextBlock x : Name =" currentFolder " DockPanel . Dock =" Top "
2 Background =" AliceBlue " FontSize ="16" / >
3
4 void t r e e V i e w _ S e l e c t e d I t e m C h a n g e d ( object sender ,
5 RoutedPropertyChangedEventArgs < object > e )
6 {
7 currentFolder . Text =
8 ( treeView . SelectedItem as TreeViewItem ). Header . ToString ();
9 Refresh ();
10 }
11 public MainWindow ()
12 {
13 I ni t i al i z eC o m po n e nt ();
14 Binding binding = new Binding ();
15 // Set source object
16 binding . Source = treeView ;
17 // Set source property
18 binding . Path = new PropertyPath (" SelectedItem . Header ");
19 // Attach to target property
20 currentFolder . SetBinding ( TextBlock . TextProperty , binding );
21 }

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).
There is a binding markup extension as well.
1 < TextBlock x : Name =" currentFolder " DockPanel . Dock =" Top "
2 Text ="{ Binding ElementName = treeView , Path = SelectedItem . Header }"
3 Background =" AliceBlue " FontSize ="16" / >
4 < TextBlock x : Name =" currentFolder " DockPanel . Dock =" Top "
5 Text ="{ Binding Source ={ x : Reference TreeView } , Path = SelectedItem . Header }"
6 Background =" AliceBlue " FontSize ="16" / >
7 < TextBlock Text ="{ Binding TargetNullValue = Nothing is selected .}" />

151
152 CHAPTER 29. LECTURE 29

8 < Label x : Name =" numItemsLabel "


9 Content ="{ Binding Source ={ StaticResource photos } , Path = Count }"
10 DockPanel . Dock =" Bottom "/ >
11 System . ComponentModel . I N o t i f y P r o p e r t y C h a n g e d
12 < Label x : Name =" numItemsLabel "
13 Content ="{ Binding Source ={ StaticResource photos }}"
14 DockPanel . Dock =" Bottom "/ >
could also set Source but using ElementName is easier. can also set value for nothing is selected.
We can also bind to plain .net properties. but the source obj should implement the System.ComponentModel.INotifyPropertyCh
interface, which has a single PropertyChanged event. (the right way) and Implement an XXXChanged event, where
XXX is the name of the property whose value changed. public class Photos : ObservableCollection¡Photo¿ target must
be a dep. prop. When binding to an object, Path is optional

1 < ListBox x : Name =" pictureBox "


2 ItemsSource ="{ Binding Source ={ StaticResource photos }}" >
3
4 </ ListBox >
We can also bind to a collection. how abt binding listbox in photo app to photo collection. when a new dir
selected, clear lisbox and created listboxitem for each item. when user del or rename, an event (because of filesys-
temwatcher) and manually refresh. raw binding i.e. Items is not dep. prop but ItemSource is. source prop must impl.
INotifyCollectionChanged (aka ObservableCollection). The simplest e

The DisplayMemberPath property can be used to improve display.


1 < ListBox x : Name =" pictureBox " Dis playMemberPath =" Name "
153

2 ItemsSource ="{ Binding Source ={ StaticResource photos }}" >


3
4 </ ListBox >

We cant mix Items and ItemSource. But we always retrieve from Items. We could add an Image property but
there are more flexible ways. 2 ways: data template and value converter. selected item can also be synchronized but
scrolling not synchronized, only first selection synchronized.
1 < ListBox I s S y n c h r o n i z e d W i t h C u r r e n t I t e m =" True " DisplayMemberPath =" Name "
2 ItemsSource ="{ Binding Source ={ StaticResource photos }}" > </ ListBox >
3 < ListBox I s S y n c h r o n i z e d W i t h C u r r e n t I t e m =" True " DisplayMemberPath =" DateTime "
4 ItemsSource ="{ Binding Source ={ StaticResource photos }}" > </ ListBox >
5 < ListBox I s S y n c h r o n i z e d W i t h C u r r e n t I t e m =" True " DisplayMemberPath =" Size "
6 ItemsSource ="{ Binding Source ={ StaticResource photos }}" > </ ListBox >

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.
1 < StackPanel DataContext ="{ StaticResource photos }" >
2 < Label x : Name =" numItemsLabel "
3 Content ="{ Binding Path = Count }" />
4
5 < ListBox x : Name =" pictureBox " DisplayMemberPath =" Name "
6 ItemsSource ="{ Binding }" >
7
8 </ ListBox >
9
10 </ StackPanel >

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.
1 < TextBlock x : Name =" numItemsLabel "
2 Text ="{ Binding StringFormat ={}{0} item ( s ) ,
3 Source ={ StaticResource photos } ,
4 Path = Count }"
5 DockPanel . Dock =" Bottom "/ >
6 < TextBlock x : Name =" numItemsLabel " DockPanel . Dock =" Bottom " >
7 < TextBlock . Text >
8 < Binding Source ="{ StaticResource photos }" Path =" Count " >
9 < Binding . StringFormat >{0} item ( s ) </ Binding . StringFormat >
10 </ Binding >
11 </ TextBlock . Text >
154 CHAPTER 29. LECTURE 29

12 </ TextBlock >

String formatting can be used even without data binding.

1 < ListBox ItemStringFormat ="{}{0: C }"


2 xmlns : sys =" clr - namespace : System ; assembly = mscorlib " >
3 < sys : Int32 > -9 </ sys : Int32 >
4 < sys : Int32 >9 </ sys : Int32 >
5 < sys : Int32 >1234 </ sys : Int32 >
6 < sys : Int32 >1234567 </ sys : Int32 >
7 </ ListBox >

With Data Template, UI auto-applied to arbitrary .net object when it is rendered. by setting these prop. you can
swap in a complete new visual tree easy in xaml, cumbersome in proc. code try with photo gallery

1 < ListBox x : Name =" pictureBox "


2 ItemsSource ="{ Binding Source ={ StaticResource photos }}" >
3 < ListBox . ItemTemplate >
4 < DataTemplate >
5 < Image Source =" placeholder . jpg " Height ="35"/ >
6 </ DataTemplate >
7 </ ListBox . ItemTemplate >
8
9 </ ListBox >
155

with a template there is implicit dataContext. template can be used on non-data bound but inside the element it
almost always make sense to use data binding. template can be shared as resources. template can even be auto-applied
to some type by setting its DataType prop. there is also HierarchicalDataTemplate that understands hierarchies. can
be used with Treeview or menu.
1 < ListBox x : Name =" pictureBox "
2 ItemsSource ="{ Binding Source ={ StaticResource photos }}" >
3 < ListBox . ItemTemplate >
4 < DataTemplate >
5 < Image Source ="{ Binding Path = FullPath }" Height ="35"/ >
6 </ DataTemplate >
7 </ ListBox . ItemTemplate >
8
9 </ ListBox >

Value Convertors morph source value into something else. introduce custom logic and can change type etc. e.g.
brush based on some enumeration. can be used to customize display.
1 < Window . Resources >
2 < local : C o u n t T o B a c k g r o u n d C o n v e r t e r x : Key =" myConverter "/ >
3 </ Window . Resources >
4
5 < Label Background ="{ Binding Path = Count , Converter ={ StaticResource myConverter } ,
6 Source ={ StaticResource photos }}" />
7 public class C o u n t T o B a c k g r o u n d C o n v e r t e r : IValueConverter
8 {
9 public object Convert ( object value , Type targetType ,
156 CHAPTER 29. LECTURE 29

10 object parameter , CultureInfo culture )


11 {
12 if ( targetType != typeof ( Brush ))
13 throw new I n v a l i d O p e r a t i o n E x c e p t io n (" The target must be a Brush !");
14 // Let Parse throw an exception if the input is bad
15 int num = int . Parse ( value . ToString ());
16 return ( num == 0 ? Brushes . Yellow : Brushes . Transparent );
17 }
18 public object ConvertBack ( object value , Type targetType ,
19 object parameter , CultureInfo culture )
20 {
21 return D ep en de nc yP ro pe rty . UnsetValue ;
22 }
23 }
Chapter 30

Lecture 30

In last lecture, we discused data binding, binding object, markup extension, bind to any prop with INotifyProperty-
Changed, target must be dependency property, bind to obj. so no property path, binding to collection, issynchronized
with current item, datacontext, displaymemberpath, stringformat, datatemplate, valueconverter.
Lets discuss customizing collection view. when isSynchronizedWithCurrentItem= true, where is the current item.
a default “view” inserted. object implementing ICollectionView. has also support for sorting, grouping, filtering, and
navigating. lets discuss these four and multiple views for the same source obj.
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.
1 SortDescription sort = new SortDescription (" Name " , ListSortDirection . Ascending );
2
3 view . SortDescriptions . Add ( new SortDescription (" DateTime " , ListSortDirection . Descending );
4 view . SortDescriptions . Add ( new SortDescription (" Name " , ListSortDirection . Ascending );
5
6 // Click event handlers for three different Buttons :
7 void sortByName_Click ( object sender , RoutedEventArgs e )
8 {
9 SortHelper (" Name ");
10 }
11 void s or tB yD a t e T i m e _ C l i c k ( object sender , RoutedEventArgs e )
12 {
13 SortHelper (" DateTime ");
14 }
15 void sortBySize_Click ( object sender , RoutedEventArgs e )
16 {
17 SortHelper (" Size ");
18 }
19 void SortHelper ( string propertyName )
20 {
21 // Get the default view
22 ICollectionView view = C o l l e ctionViewSource . GetDefaultView (
23 this . FindResource (" photos "));
24 // Check if the view is already sorted ascending by the current property
25 if ( view . SortDescriptions . Count > 0
26 && view . SortDescriptions [0]. PropertyName == propertyName
27 && view . SortDescriptions [0]. Direction == " , Lis tSortD irecti on . Ascending )
28 {
29 // Already sorted ascending , so toggle by sorting descending
30 view . SortDescriptions . Clear ();
31 view . SortDescriptions . Add ( new SortDescription (
32 propertyName , Lis tSortD irecti on . Descending ));
33 }
34 else

157
158 CHAPTER 30. LECTURE 30

35 {
36 // Sort ascending
37 view . SortDescriptions . Clear ();
38 view . SortDescriptions . Add ( new SortDescription (
39 propertyName , Lis tSortD irecti on . Ascending ));
40 }
41 }
42 // Get the default view
43 ICollectionView view = C o l l e c t i o nViewSource . GetDefaultView (
44 this . FindResource (" photos "));
45 // Do the grouping
46 view . GroupDesc riptio ns . Clear ();
47 view . GroupDesc riptio ns . Add ( new P ro p e r ty G r o up D e sc r i p ti o n (" DateTime "));
48 < ListBox x : Name =" pictureBox "
49 ItemsSource ="{ Binding Source ={ StaticResource photos }}" >
50 < ListBox . GroupStyle >
51 < GroupStyle >
52 < GroupStyle . HeaderTemplate >
53 < DataTemplate >
54 < Border BorderBrush =" Black " BorderThickness ="1" >
55 < TextBlock Text ="{ Binding Path = Name }" FontWeight =" Bold "/ >
56 </ Border >
57 </ DataTemplate >
58 </ GroupStyle . HeaderTemplate >
59 </ GroupStyle >
60 </ ListBox . GroupStyle >
61
62 </ ListBox >
There is no explicit relationship with ListBox. if additional controls bound, they would sort with it. Now a
GroupDescriptions prop. containing PropertyGroupDescription obj. but it has no e↵ect without the GroupStyle prop.
set with a HeaderTemplate.

1 < ListBox x : Name =" pictureBox "


2 ItemsSource ="{ Binding Source ={ StaticResource photos }}" >
3 < ListBox . GroupStyle >
4 <x : Static Member =" GroupStyle . Default "/ >
5 </ ListBox . GroupStyle >
6
7 </ ListBox >
8 // Get the default view
159

9 ICollectionView view = C o l l e c t i o nViewSource . GetDefaultView (


10 this . FindResource (" photos "));
11 // Do the grouping
12 view . GroupDesc riptio ns . Clear ();
13 view . GroupDesc riptio ns . Add (
14 new P r op e r t yG r o u pD e s c ri p t i on (" DateTime " , new D a t e T i m e T o D a t e C o n v e r t e r ()));
15
16 public class D a t e T i m e T o D a t e C o n v e r t e r : IValueConverter
17 {
18 public object Convert ( object value , Type targetType , object parameter ,
19 CultureInfo culture )
20 {
21 return (( DateTime ) value ). ToString (" MM / dd / yyyy ");
22 }
23 public object ConvertBack ( object value , Type targetType , object parameter ,
24 CultureInfo culture )
25 {
26 return D ep en de nc yP ro pe rty . UnsetValue ;
27 }
28 }

1 ICollectionView view = C o l l e c t i o nViewSource . GetDefaultView (


2 this . FindResource (" photos "));
3 view . Filter = delegate ( object o ) {
4 return (( o as Photo ). DateTime DateTime . Now ). Days <= 7;
5 };
6
7 ICollectionView view = C o l l e c t i o nViewSource . GetDefaultView (
8 this . FindResource (" photos "));
9 view . Filter = ( o ) = > { return (
10 ( o as Photo ). DateTime DateTime . Now ). Days <= 7;
11 };
12 void previous_Click ( object sender , RoutedEventArgs e )
13 {
14 // Get the default view
15 ICollectionView view = C ol l e ctionViewSource . GetDefaultView (
16 this . FindResource (" photos "));
17 // Move backward
18 view . Mo v e C u r r e n t T o P r e v i o u s ();
19 // Wrap around to the end
20 if ( view . IsCurrentBeforeFirst ) view . Mov eCurre ntToLa st ();
21 }
22 void next_Click ( object sender , RoutedEventArgs e )
160 CHAPTER 30. LECTURE 30

23 {
24 // Get the default view
25 ICollectionView view = C o l l e ctionViewSource . GetDefaultView (
26 this . FindResource (" photos "));
27 // Move forward
28 view . MoveCurr entToNe xt ();
29 // Wrap around to the beginning
30 if ( view . IsCurrentAfterLast ) view . M ov eC ur re nt ToF ir st ();
31 }
32 "{ Binding Path =/}"
33 "{ Binding Path =/ DateTime }"
34 "{ Binding Path = Photos /}"
35 "{ Binding Path = Photos / DateTime }"
36
37 C o l l e c t i o n Vi e w S o u r c e viewSource = new CollectionViewSource ();
38 viewSource . Source = photos ;
39
40
41 < Window . Resources >
42 < local : Photos x : Key =" photos "/ >
43 < C ol le ctionViewSource x : Key =" viewSource " Source ="{ StaticResource photos }"/ >
44 </ Window . Resources >
45 < ListBox x : Name =" pictureBox "
46 ItemsSource ="{ Binding Source ={ StaticResource photos viewSource }}" >
47
48 </ ListBox >
49
50 < C ol le ct io nViewSource x : Key =" viewSource "
51 Filter =" vi ewSourc e_Filt er "
52 Source ="{ StaticResource photos }" >
53 < C ol le ctionViewSource . SortDescriptions >
54 < componentModel : SortDescription PropertyName =" DateTime "
55 Direction =" Descending "/ >
56 </ Co ll e c t i o n V i e w S o u r c e . SortDescriptions >
57 < C ol le ctionViewSource . GroupDescriptions >
58 < P ro p e r t y G r o u p D e s c r i p t i o n PropertyName =" DateTime "/ >
59 </ Co ll e c t i o n V i e w S o u r c e . GroupDescriptions >
60 </ CollectionViewSource >
61
62 void viewSourc e_Filt er ( object sender , FilterEventArgs e )
63 {
64 e . Accepted = (( e . Item as Photo ). DateTime DateTime . Now ). Days <= 7;
65 }
66
67 < Window xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
68 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml "
69 Title =" XML Data Binding " >
70 < Window . Resources >
71 < XmlDataProvider x : Key =" dataProvider " XPath =" GameStats " >
72 <x : XData >
73 < GameStats xmlns ="" >
74 <! - - One stat per game type -->
75 < GameStat Type =" Beginner " >
76 < HighScore >1203 </ HighScore >
77 </ GameStat >
78 < GameStat Type =" Intermediate " >
79 < HighScore >1089 </ HighScore >
80 </ GameStat >
81 < GameStat Type =" Advanced " >
161

82 < HighScore >541 </ HighScore >


83 </ GameStat >
84 </ GameStats >
85 </ x : XData >
86 </ XmlDataProvider >
87 </ Window . Resources >
88 < Grid >
89 < ListBox ItemsSource ="{ Binding
90 Source ={ StaticResource dataProvider } ,
91 XPath = GameStat / HighScore }" / >
92 </ Grid >
93 </ Window >

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.
Filtering gives a property Filter of type Predicate¡Object¿. its null by default e.g. show only photos from last 7
days.
navigation means managing the current item, not the other kind of nav. ICollectionView has CurrentItem Cur-
rentPosition and also methods for changing them. e.g. prev/next photo buttons are handled like this view initializes
to 0 and first item listbox initializes to -1 and null (unselected).
prop. paths in Bindings are useful for master/detail interfaces. sorting, grouping, filtering automatic. but naviga-
tion only when IsSynchronizedWithCurrentItem=true. otherwise SelectedItem and CurrentItem are separate.
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. must include another
162 CHAPTER 30. LECTURE 30

namespace. IsSynchronizedWithCurrentItem=true by default for custom views. have to explicitly set false. kind of a
bit inconsistent. but we acknowledging view existance by custom view.
Lets discuss data providers. source obj can be arbitrary. you could bind to db, registry, excel spreadsheet etc.
with enough code. an obj. that exposes right props and notifications and handles messy details work involved
might overweight benefits if writing all logic yourself two generic data-binding-friendly way to expose common items.
XmlDataProvider and ObjectDataProvider. starting with wpf 3.5 sp1 data binding works with LINQ (language
independent query) you can set Source or DataContext to a LINQ and the enumerable result is used. Now with LINQ
to SQL and LINQ to XML, is an easy way than using wpf data providers.
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.
data provided in XmlNode etc. objects from System.Xml so you can use Path and XPath together. needs hierarchical
data template if you want to bind to xml tree.
1 < XmlDataProvider x : Key =" dataProvider " XPath =" GameStats " Source =" GameStats . xml "/ >
2 < Label Content ="{ Binding Source ={ StaticResource dataProvider } ,
3 XPath = GameStat / HighScore , Path = OuterXml }"/ >
Chapter 31

Lecture 31

In the last lecture, we discussed the view between binding source and target sorting, grouping, filtering, navigating.
creating additional views, data providers (xml and object), used xml data provider to fill a listbox, now use hierarchical
data template.
1 < Window xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
2 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml "
3 Title =" XML Data Binding " >
4 < Window . Resources >
5 < H ie r a r c h i c a l D a t a T e m p l a t e DataType =" GameStats "
6 ItemsSource ="{ Binding XPath =*}" >
7 < TextBlock FontStyle =" Italic "
8 Text =" All Game Stats "/ >
9 </ HierarchicalDataTemplate >
10 < H ie r a r c h i c a l D a t a T e m p l a t e DataType =" GameStat "
11 ItemsSource ="{ Binding XPath =*}" >
12 < TextBlock FontWeight =" Bold " FontSize ="20"
13 Text ="{ Binding XPath = @Type }"/ >
14 </ HierarchicalDataTemplate >
15 < DataTemplate DataType =" HighScore " >
16 < TextBlock Foreground =" Blue " Text ="{ Binding XPath =.}"/ >
17 </ DataTemplate >
18 < XmlDataProvider x : Key =" dataProvider " XPath =" GameStats " >
19 <x : XData >
20 < GameStats xmlns ="" >
21 <! - - One stat per game type -->
22 < GameStat Type =" Beginner " >
23 < HighScore >1203 </ HighScore >
24 </ GameStat >
25 < GameStat Type =" Intermediate " >
26 < HighScore >1089 </ HighScore >
27 </ GameStat >
28 < GameStat Type =" Advanced " >
29 < HighScore >541 </ HighScore >
30 </ GameStat >
31 </ GameStats >
32 </ x : XData >
33 </ XmlDataProvider >
34 </ Window . Resources >
35 < Grid >
36 < TreeView
37 ItemsSource ="{ Binding Source ={ StaticResource dataProvider } ,
38 XPath =.}" / >
39 </ Grid >

163
164 CHAPTER 31. LECTURE 31

40 </ Window >

hierarchicaldatatemplate for every node and datatemplate for a leaf node. hierarchicaldatatmplate allow specifying
children using ItemSource prop. =all children. datatype means e↵ect all instances within the scope. datatype
corresponds to xmlnode name. no key. internally datatype value used as key.
1 < rss version ="2.0" xmlns : atom =" http :// www . w3 . org /2005/ Atom "
2 xmlns : georss =" http :// www . georss . org / georss " >
3
4 </ rss >
5
6
7 < XmlDataProvider Source =" http :// twitter . com / statuses / user_timeline /24326956. rss "
8 X m lN a m es p ac e M an a ger ="{ StaticResource namespaceMapping }"
9 XPath =" rss / channel " x : Key =" dataProvider "/ >
10
11
12 < X m l N a m e s p a c e M a p p i n g C o l l e c t i o n x : Key =" namespaceMapping " >
13 < Xm lN amespaceMapping Uri =" http :// www . w3 . org /2005/ Atom " Prefix =" atom "/ >
14 < Xm lN amespaceMapping Uri =" http :// www . georss . org / georss " Prefix =" georss "/ >
15 </ XmlNamespaceMappingCollection >
16
17
18 "{ Binding XPath = atom : link }"

Now lets discuss ObjectDataProvider. .net object as a data source. so what does that add against binding directly
to a .net obj. Declaratively instantiate the source object with a parameterized constructor. Bind to a method on
the source object. Have more options for asynchronous data binding. When binding not quick, async so UI doesnt
stuck. wpf has two ways to mark async. IsAsync prop of Binding, XmlDataProvider and ObjectDataProvider have an
IsAsynchronous prop. false by default on objDP, true by default for XmlDP. create source obj on background thread.
when IsAsync ture (false by default), source prop invoked on background thread property getters supposed to be fast
so shouldn’t need.
first example wraps photos. its the same, even binding path because binding “unwraps”. it can also create the
object given its type.
1 < Window . Resources >
2 < local : Photos x : Key =" photos "/ >
3 < O bj ec tD at aP ro vi der x : Key =" dataProvider "
4 ObjectInstance ="{ StaticResource photos }"/ >
5 </ Window . Resources >
6 < Window . Resources >
7 <! - - The collection object is instantiated internally by ObjectDataProvider : -->
8 < O bj ec tD at aP ro vi der x : Key =" dataProvider " ObjectType ="{ x : Type local : Photos }"/ >
9 </ Window . Resources >

binding to a method is useful for classes that are not designed for data binding. imagine photos class had GetFold-
erName method. can use MethodParameters. if Path used. it would apply to the obj returned.
1 < O bj ec tD at aP ro vi der x : Key =" dataProvider " ObjectType ="{ x : Type local : Photos }" >
165

2 < O bj ec tD at aP ro vi der . ConstructorParameters >


3 < sys : Int32 >23 </ sys : Int32 >
4 </ Objec tD at aP ro vi der . ConstructorParameters >
5 </ ObjectDataProvider >

1 < O bj ec tD at aP ro vi der x : Key =" dataProvider "


2 ObjectType ="{ x : Type local : Photos }"
3 MethodName =" GetFolderName "/ >

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 other. OneWayToSource. This is the opposite of OneWay. The source is
updated whenever the target changes. OneTime. This works just like OneWay, except changes to the source are not
reflected at the target. The target retains a snapshot of the source at the time the Binding is initiated.
useful for editable datagrid and textbox (by default) thats why convertback method. only convertback on oneway-
tosource.
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
We can also have validation rules. want to validate as soon as possible for user feedback. without binding you
could insert custom logic but now the data is auto-pushed to target. lets say we want valid .jpg file. 2 ways. validation
rule or use source exceptions. Binding has ValidationRules prop that can be set to one or more ValidationRule derived
objects.
1 < TextBox >
2 < TextBox . Text >
3 < Binding >
4 < Binding . ValidationRules >
5 < local : JpgValidationRu le / >
6 </ Binding . ValidationRules >
7 </ Binding >
8 </ TextBox . Text >
9 </ TextBox >
10
11 public class Jpg Valida tionRu le : ValidationRule
12 {
13 public override ValidationResult Validate ( object value , CultureInfo cultureInfo )
14 {
15 string filename = value . ToString ();
16 if (! File . Exists ( filename ))
17 return new ValidationResult ( false , " Value is not a valid file .");
18 if (! filename . EndsWith (". jpg " , StringComparison . I n v a r i a n t C u l t u r e I g n o r e C a s e ))
19 return new ValidationResult ( false , " Value is not a . jpg file .");
20 return new ValidationResult ( true , null );
21 }
22 }

validation check whenever attempt to update target. in this case on LostFocus because it is default. when invalid,
an error adorner rendered on top of element. by default thin red border but can use Validation.ErrorTemplate attached
prop on target element to customize it, also other properties for custom control.
1 < TextBox >
2 < TextBox . Text >
3 < Binding >
4 < Binding . ValidationRules >
5 < ExceptionValidationRule />
6 </ Binding . ValidationRules >
7 </ Binding >
8 </ TextBox . Text >
9 </ TextBox >
166 CHAPTER 31. LECTURE 31

10 < TextBox >


11 < TextBox . Text >
12 < Binding >
13 < Binding . ValidationRules >
14 < ExceptionValidationRule />
15 < DataErrorValidationRule />
16 </ Binding . ValidationRules >
17 </ Binding >
18 </ TextBox . Text >
19 </ TextBox >
20 < TextBox >
21 < TextBox . Text >
22 < Binding V a l i d a t e s O n E x c e ption s =" True " Va lidat esOn DataE rror s =" True " />
23 </ TextBox . Text >
24 </ TextBox >

but what if already exceptions thrown by target. also the source can implement System.ComponentModel.IDataErrorInfo.
easier way in wpf 3.5 sp1.

Lets write an RSS reader without code. a two-way textbox so that user can change feed address. bindsdirect-
lytosource so path does not refer to the rss feed. UpdateSourceTrigger of PropertyChanged so update with every
keystroke. listbox/frame share the source. master detail.

1 < Window xmlns =" http :// schemas . microsoft . com / winfx /2006/ xaml / presentation "
2 xmlns : x =" http :// schemas . microsoft . com / winfx /2006/ xaml " Title =" RSS Reader " >
3 < Window . Resources >
4 < XmlDataProvider x : Key =" Feed "
5 Source =" http :// twitter . com / statuses / user_timeline /24326956. rss "/ >
6 </ Window . Resources >
7 < DockPanel
8 DataContext ="{ Binding Source ={ StaticResource Feed } ,
9 XPath =/ rss / channel / item }" >
10 < TextBox DockPanel . Dock =" Top "
11 Text ="{ Binding Source ={ StaticResource Feed } ,
12 B i n d s D i r ectl yToS ource = true , Path = Source ,
13 U pd a t eS o urceTrigger = PropertyChanged }"/ >
14 < Label DockPanel . Dock =" Top "
15 Content ="{ Binding XPath =/ rss / channel / title }"
16 FontSize ="14" FontWeight =" Bold "/ >
17 < Label DockPanel . Dock =" Top "
18 Content ="{ Binding XPath =/ rss / channel / description }"/ >
19 < ListBox DockPanel . Dock =" Left " DisplayMemberPath =" title "
20 ItemsSource ="{ Binding }"
21 I s S y n c h r o n i z e d W i t h C u r r e n t I t e m =" True " Width ="300"/ >
22 < Frame Source ="{ Binding XPath = link }"/ >
23 </ DockPanel >
24 </ Window >
167
168 CHAPTER 31. LECTURE 31
Chapter 32

Lecture 32

Concurrency is More than one thing happening at the same time. comparison with events. why still concurrency.
responsive user interface. simultaneous requests. parallel programming.
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. lets create one.
1 class ThreadTest
2 {
3 static void Main ()
4 {
5 Thread t = new Thread ( WriteY );
6 t . Start ();
7
8 for ( int i = 0; i < 1000; i ++) Console . Write (" x ");
9 }
10
11 static void WriteY ()
12 {
13 for ( int i = 0; i < 1000; i ++) Console . Write (" y ");
14 }
15 }
16 Typical Output :
17 Xxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxx

interleaved because of time slicing. real parallel on multicore but still repeated blocks cuz of the way Console
handles it. 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.
Join and Sleep. a thread is “blocked” when waiting. can use ThreadState property.
1 static void Main ()
2 {
3 Thread t = new Thread ( Go );
4 t . Start ();
5 t . Join ();

169
170 CHAPTER 32. LECTURE 32

6 Console . WriteLine (" Thread t has ended !");


7 }
8 static void Go () { for ( int i = 0; i < 1000; i ++) Console . Write (" y "); }
9
10 Thread . Sleep ( TimeSpan . FromHours (1));
11 Thread . Sleep (500);

Local vs Shared state.


1 static void Main ()
2 {
3 new Thread ( Go ). Start ();
4 Go ();
5 }
6 static void Go ()
7 {
8 for ( int cycles = 0; cycles < 5; cycles ++) Console . Write ( ’? ’);
9 }
10 class ThreadTest
11 {
12 bool _done ;
13 static void Main ()
14 {
15 ThreadTest tt = new ThreadTest ();
16 new Thread ( tt . Go ). Start ();
17 tt . Go ();
18 }
19 void Go ()
20 {
21 if (! _done ) { _done = true ; Console . WriteLine (" Done "); }
22 }
23 }
24
25 class ThreadTest
26 {
27 static bool _done ;
28 static void Main ()
29 {
30 new Thread ( tt . Go ). Start ();
31 Go ();
32 }
33 static void Go ()
34 {
35 if (! _done ) { _done = true ; Console . WriteLine (" Done "); }
36 }
37 }
38
39 class ThreadTest
40 {
41 static void Main ()
42 {
43 bool done = false ;
44 ThreadStart action = () = >
45 {
46 if (! done ) { done = true ; Console . WriteLine (" Done "); }
47 };
48 new Thread ( action ). Start ();
49 action ();
50 }
51 }
171

Lets discuss thread safety. In this code, we can output Done twice. and the odds increase if statements are reversed.
1 class ThreadSafe
2 {
3 static bool _done ;
4 static readonly object _locker = new object ();
5 static void Main ()
6 {
7 new Thread ( Go ). Start ();
8 Go ();
9 }
10 static void Go ()
11 {
12 lock ( _locker )
13 {
14 if (! _done ) { Console . WriteLine (" Done "); _done = true ; }
15 }
16 }
17 }
Passing Data to Threads. use lambda expression (easiest) or use object param.
1 static void Main ()
2 {
3 Thread t = new Thread (() = > Print (" Hello from t !"));
4 t . Start ();
5 }
6 static void Print ( string message ) { Console . WriteLine ( message ); }
7
8 new Thread (() = >
9 {
10 Console . WriteLine (" I ’ m running on another thread !");
11 Console . WriteLine (" This is so easy !");
12 }). Start ()
13
14 static void Main ()
15 {
16 Thread t = new Thread ( Print );
17 t . Start (" Hello from t !");
18 }
19 static void Print ( object messageObj )
20 {
21 string message = ( string ) messageObj ;
22 Console . WriteLine ( message );
23 }
24
25 public delegate void ThreadStart ();
26 public delegate void P a r a m e t e r i z ed T h r e a d S t a r t ( object obj );
Lambda expressions and captured vars
1 for ( int i = 0; i < 10; i ++)
2 new Thread (() = > Console . Write ( i )). Start ();
3
4 Typical Output :
5
6 0223557799
7 for ( int i = 0; i < 10; i ++)
8 {
9 int temp = i ;
10 new Thread (() = > Console . Write ( temp )). Start ();
11 }
172 CHAPTER 32. LECTURE 32

exceptions
1 public static void Main ()
2 {
3 try
4 {
5 new Thread ( Go ). Start ();
6 }
7 catch ( Exception ex )
8 {
9 Console . WriteLine (" Exception !");
10 }
11 }
12 static void Go () { throw null ; }
13
14 public static void Main ()
15 {
16 new Thread ( Go ). Start ();
17 }
18 static void Go ()
19 {
20 try
21 {
22 //...
23 throw null ;
24 //...
25 }
26 catch ( Exception ex )
27 {
28 //...
29 }
30 }

There are IsBackground and Priority properties. signaling between threads using a ManualResetEvent (simplest).
WaitOne and Set. ReSet closes the signal.
1 var signal = new ManualResetEvent ( false );
2 new Thread (() = >
3 {
4 Console . WriteLine (" Waiting for signal ...");
5 signal . WaitOne ();
6 signal . Dispose ();
7 Console . WriteLine (" Got signal !");
8 }). Start ();
9 Thread . Sleep (2000);
10 signal . Set ();
Chapter 33

Lecture 33

long running operations make application unresponsive. because main thread used for rendering UI and responding
to events. start up worker thread and update UI when finished. but UI updation usually possible only on UI thread.
so, forward the request to UI thread.(or marshal it). Low level way is to call BeginInvoke or Invoke on the elements
Dispatcher object. it takes a delegate and queues it on the UI thread. Invoke does same but then blocks until it is
done. so you can return a value. but if you dont need BeginInvoke is better.
1 partial class MyWindow : Window
2 {
3 public MyWindow ()
4 {
5 I ni t i al i z eC o m po n e nt ();
6 new Thread ( Work ). Start ();
7 }
8 void Work ()
9 {
10 Thread . Sleep (5000);
11 UpdateMessage (" The answer ");
12 }
13 void UpdateMessage ( string message )
14 {
15 Action action = () = > txtMessage . Text = message ;
16 Dispatcher . BeginInvoke ( action );
17 }
18 }

SynchronizationContext can be used for generalized thread marshaling.


1 partial class MyWindow : Window
2 {
3 S y n c h r on i z a t i o n C o n t e x t _uiSyncContext ;
4 public MyWindow ()
5 {
6 I ni t i al i z eC o m po n e nt ();
7 _uiSyncContext = S y n c h r o n iz at ion Co nt ext . Current ;
8 new Thread ( Work ). Start ();
9 }
10 void Work ()
11 {
12 Thread . Sleep (5000);
13 UpdateMessage (" The answer ");
14 }
15 void UpdateMessage ( string message )
16 {
17 _uiSyncContext . Post ( _ = > txtMessage . Text = message );

173
174 CHAPTER 33. LECTURE 33

18 }
19 }
ThreadPool save time of thread creation. cant name thread and difficult debugging. always background. blocking
can degrade performance. Thread.CurrentThread.IsThreadPoolThread property. threadpool creates or reduces real
threads using a hillclimbing algo to maximize cpu usage and reduce slicing.
1 ThreadPool . QueueU serWor kItem ( notUsed = > Console . WriteLine (" Hello "));
2
3 Task . Run (() = > Console . WriteLine (" Hello from the thread pool "));
Lets discuss Tasks. no easy way to get return value from a thread. we can join and use shared data. exceptions
difficult too. cant tell to start something else when finished. task: a higher level abstraction. tasks can be chained
using continuations. can use threadpool. with TaskCompletionSource callback approach.
starting a task is like creating a thread. except started right away (hot) and in a thread pool. task.wait is like
Join. Task has generic subclass Task¡TReturn¿. task.Result blocks.
1 Task . Run (() = > Console . WriteLine (" Foo "));
2 new Thread (() = > Console . WriteLine (" Foo ")). Start ();
3
4 Task task = Task . Run (() = >
5 {
6 Thread . Sleep (2000);
7 Console . WriteLine (" Foo ");
8 });
9 Console . WriteLine ( task . IsCompleted );
10 task . Wait ();
11
12 Task < int > task = Task . Run (() = > { Console . WriteLine (" Foo "); return 3; });
13 // ...
tasks propagate exception to whoever calls wait or accesses Result
1 int result = task . Result ;
2 Console . WriteLine ( result );
3 Task task = Task . Run (() = > { throw null ; });
4 try
5 {
6 task . Wait ();
7 }
8 catch ( Ag greg at eE xc ep tio n aex )
9 {
10 if ( aex . InnerException is N ul l R e f e r e n c e E x c e p t i o n )
11 Console . WriteLine (" Null !");
12 else
13 throw ;
14 }
Continuations says when finished continue with something else. two ways.
1 Task < int > primeNumberTask = Task . Run (() = >
2 Enumerable . Range (2 , 3000000). Count ( n = >
3 Enumerable . Range (2 , ( int ) Math . Sqrt ( n ) -1). All ( i = > n % i > 0)));
4
5 primeNumberTask . ContinueWith ( antecedent = >
6 {
7 int result = antecedent . Result ;
8 Console . WriteLine ( result );
9 });
10 var awaiter = primeNumberTask . GetAwaiter ();
11 awaiter . OnCompleted (() = >
12 {
175

13 int result = awaiter . GetResult ();


14 Console . WriteLine ( result );
15 });

if synchronization context present, run on UI thread


task completion source. any operation that start and finishes some time later. slave task you manually drive. mark
finish. ideal for i/o bound work. all benefits of tasks (returns, exceptions, continuations) without blocking thread.
create a task which you can wait and attach continuations. controlled by these operations.
1 public class TaskCompletionSource < TResult >
2 {
3 public void SetResult ( TResult result );
4 public void SetException ( Exception exception );
5 public void SetCanceled ();
6 public bool TrySetResult ( TResult result );
7 public bool TrySetException ( Exception exception );
8 public bool TrySetCanceled ();
9 //...
10 }

calling any function signals the task. call exactly once. following example prints 42 after 5s. calling this is equivalent
to creating long running task. lets do the same without a thread. then attaching continuation.
1 var tcs = new TaskCompletionSource < int >();
2 new Thread (() = > {
3 Thread . Sleep (5000); tcs . SetResult (42);
4 }). Start ();
5 Task < int > task = tcs . Task ;
6 Console . WriteLine ( task . Result )
7
8 Task < TResult > Run < TResult > ( Func < TResult > function )
9 {
10 var tcs = new TaskCompletionSo u r c e < TResult >();
11 new Thread (() = >
12 {
13 try { tcs . SetResult ( function ()); }
14 catch ( Exception ex ) { tcs . SetException ( ex );}
15 }). Start ();
16 return tcs . Task ;
17 }
18 //...
19 Task < int > task = Run (() = > { Thread . Sleep (5000); return 42; });
20
21 Task < int > GetAnswerToLife ()
22 {
23 var tcs = new TaskCompletionSource < int >();
24 var timer = new System . Timers . Timer (5000) { AutoReset = false };
25 timer . Elapsed += delegate { timer . Dispose (); tcs . SetResult (42); };
26 timer . Start ();
27 return tcs . Task ;
28 }

thread used only when continuation running. task.delay available.


1 var awaiter = GetAnswerToLife (). GetAwaiter ();
2 awaiter . OnCompleted (() = > Console . WriteLine ( awaiter . GetResult ()));
3
4 Task Delay ( int milliseconds )
5 {
6 var tcs = new TaskCompletionSource < object >();
7 var timer = new System . Timers . Timer ( milliseconds ) { AutoReset = false };
176 CHAPTER 33. LECTURE 33

8 timer . Elapsed += delegate { timer . Dispose (); tcs . SetResult ( null ); };


9 timer . Start ();
10 return tcs . Task ;
11 }
12
13 Delay (5000). GetAwaiter (). OnCompleted (() = > Console . WriteLine (42));
14 Delay (5000). ContinueWith ( ant = > Console . WriteLine (42));
15
16 Task . Delay (5000). GetAwaiter (). OnCompleted (() = > Console . WriteLine (42));
17 Task . Delay (5000). ContinueWith ( ant = > Console . WriteLine (42));
Chapter 34

Lecture 34

In last lecture we discussed Threadpool to avoid thread creation time. Task concept one thread many tasks. Contin-
uations / Exceptions / Returns. Task Completion Source. discussed Task.Delay.
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.
1 int GetPrimesCount ( int start , int count )
2 {
3 return
4 P ara ll el En um er ab le . Range ( start , count ). Count ( n = >
5 Enumerable . Range (2 , ( int ) Math . Sqrt ( n ) - 1). All ( i = > n % i > 0));
6 }
7
8 void Dis play Pr im eC ou nt s ()
9 {
10 for ( int i = 0; i < 10; i ++)
11 Console . WriteLine ( GetPrimesCount ( i * 1000000 + 2 , 1000000) +
12 " primes between " + ( i * 1000000) + " and " + (( i + 1) * 1000000 - 1));
13 Console . WriteLine (" Done !");
14 }
15 78498 primes between 0 and 999999
16 70435 primes between 1000000 and 1999999
17 67883 primes between 2000000 and 2999999
18 66330 primes between 3000000 and 3999999
19 65367 primes between 4000000 and 4999999
20 64336 primes between 5000000 and 5999999
21 63799 primes between 6000000 and 6999999
22 63129 primes between 7000000 and 7999999
23 62712 primes between 8000000 and 8999999
24 62090 primes between 9000000 and 9999999
how to make async. course grained.
1 Task . Run (() = > D is pl ay Pr im eC ou nts ());
2
3 Task < int > GetPrimesCountAsync ( int start , int count )
4 {
5 return Task . Run (() = >
6 P ara ll el En um er ab le . Range ( start , count ). Count ( n = >
7 Enumerable . Range (2 , ( int ) Math . Sqrt ( n ) - 1). All ( i = > n % i > 0)));
8 }
9 for ( int i = 0; i < 10; i ++)
10 {

177
178 CHAPTER 34. LECTURE 34

11 var awaiter = GetPrimesCountAs y nc ( i *1000000 + 2 , 1000000). GetAwaiter ();


12 awaiter . OnCompleted (() = >
13 Console . WriteLine ( awaiter . GetResult () + " primes between ... "));
14 }
15 Console . WriteLine (" Done ");

back to sequential. what if we want displayprimecounts async as well.


1 void Dis play Pr im eC ou nts ()
2 {
3 D i s p l a yP r i m e C o u n t s F r o m (0);
4 }
5 void D is pl ay P r i m e C o u n t s F r o m ( int i )
6 {
7 var awaiter = GetPrimesCountAs y nc ( i * 1000000 + 2 , 1000000). GetAwaiter ();
8 awaiter . OnCompleted (() = >
9 {
10 Console . WriteLine ( awaiter . GetResult () + " primes between ...");
11 if ( i ++ < 10) D is pl ayP ri m e C o u n t s F r o m ( i );
12 else Console . WriteLine (" Done ");
13 });
14 }

simple but lot of code.


1 Task D i s pl ay P r i m e C o u n t s A s y n c ()
2 {
3 var machine = new PrimesStateMa ch in e ();
4 machine . Dis pl ay Pri me Co unt sF ro m (0);
5 return machine . Task ;
6 }
7 class Prim es St at eM ac hin e
8 {
9 T a s k C o m p l e t i o n S o u r c e < object > _tcs = new TaskCompletionSource < object >();
10 public Task Task { get { return _tcs . Task ; } }
11 public void D i s p l a y P r i m e C o u n t s F r o m ( int i )
12 {
13 var awaiter = GetPrimesCo u n tA s y nc ( i *1000000+2 , 1000000). GetAwaiter ();
14 awaiter . OnCompleted (() = >
15 {
16 Console . WriteLine ( awaiter . GetResult ());
17 if ( i ++ < 10) D is pl ay P r i m e C o u n t s F r o m ( i );
18 else { Console . WriteLine (" Done "); _tcs . SetResult ( null ); }
19 });
20 }
21 }

Its pretty simple in C# 5.0.


1 async Task Di sp la yP ri me Cou nt s ()
2 {
3 for ( int i = 0; i < 10; i ++)
4 Console . WriteLine ( await GetPrimesCountAsync ( i * 1000000 + 2 , 1000000) +
5 " primes between " + ( i * 1000000) + " and " + (( i + 1) * 1000000 - 1));
6 Console . WriteLine (" Done !");
7 }

C# 5.0 introduces async and await keywords. eliminates plumbing for async code. as simple as sync code. “await”
simplifies attaching continuations. e.g. also code to handle if sync completion. and some other details.
1 var result = await expression ;
2 statement ( s );
179

3 var awaiter = expression . GetAwaiter ();


4 awaiter . OnCompleted (() = >
5 {
6 var result = awaiter . GetResult ();
7 statement ( s );
8 );
returning to example. we can call it with await and use “async” keyword so compiler treats await specially. async
can be applied to methods returning void or Task or Task¡TResult¿.
1 Task < int > GetPrimesCountAsync ( int start , int count )
2 {
3 return Task . Run (() = >
4 P ara ll el En um er ab le . Range ( start , count ). Count ( n = >
5 Enumerable . Range (2 , ( int ) Math . Sqrt ( n ) - 1). All ( i = > n % i > 0)));
6 }
7
8 int result = await GetPrimesCountA s y nc (2 , 1000000);
9 Console . WriteLine ( result );
10 async void Di sp la yP ri me sC oun t ()
11 {
12 int result = await GetPrimesCo u n tA s y nc (2 , 1000000);
13 Console . WriteLine ( result );
14 }
async doesnt change method so no need to list in interface. can add async when implementing. methods with
async are called asynchronous. when await. method returns to caller. but before returning a continuation attached to
the task. if exception rethrown, otherwise return value assigned to await statement.
lets see the expansion again. await expression returns int because Task¡int¿ also possible to wait on void Task.
1 void Dis play Pr im es Co un t ()
2 {
3 var awaiter = GetPrimesCountA s y nc (2 , 1000000). GetAwaiter ();
4 awaiter . OnCompleted (() = >
5 {
6 int result = awaiter . GetResult ();
7 Console . WriteLine ( result );
8 });
9 }
10 await Task . Delay (5000);
11 Console . WriteLine (" Five seconds passed !");
capturing local state in await. real power of await. when execution resumes in continuation, local vars have the
same values compiler translates into state machines. a general method. if we do ourself we may be doing the complex
code we showed before. if sync context, same thread e.g. UI. otherwise whatever free thread lets write a UI program
that remains responsive with a cpu bound task. lets start with the sync version.
1 async void Di sp la yP ri me Co unt s ()
2 {
3 for ( int i = 0; i < 10; i ++)
4 Console . WriteLine ( await GetPrimesCountAsync ( i * 1000000 + 2 , 1000000));
5 }
Synchronous version. unresponsive. 2step in making async.
1 class TestUI : Window
2 {
3 Button _button = new Button { Content = " Go " };
4 TextBlock _results = new TextBlock ();
5 public TestUI ()
6 {
7 var panel = new StackPanel ();
180 CHAPTER 34. LECTURE 34

8 panel . Children . Add ( _button );


9 panel . Children . Add ( _results );
10 Content = panel ;
11 _button . Click += ( sender , args ) = > Go ();
12 }
13 void Go ()
14 {
15 for ( int i = 1; i < 5; i ++)
16 _results . Text += GetPrimesCount ( i * 1000000 , 1000000) +
17 " primes between " + ( i * 1000000) + " and " + (( i + 1) * 1000000 - 1) +
18 Environment . NewLine ;
19 }
20 int GetPrimesCount ( int start , int count )
21 {
22 return P ar al le lE nu me ra ble . Range ( start , count ). Count ( n = >
23 Enumerable . Range (2 , ( int ) Math . Sqrt ( n ) - 1). All ( i = > n % i > 0));
24 }
25 }
asynchronous version. simplicity. call async functions. and await them. Go leases time on UI thread. Task.Run is
the real parallel.
1 Task < int > GetPrimesCountAsync ( int start , int count )
2 {
3 return Task . Run (() = >
4 P ara ll el En um er ab le . Range ( start , count ). Count ( n = >
5 Enumerable . Range (2 , ( int ) Math . Sqrt ( n ) - 1). All ( i = > n % i > 0)));
6 }
7
8 async void Go ()
9 {
10 _button . IsEnabled = false ;
11 for ( int i = 1; i < 5; i ++)
12 _results . Text += await Ge t Pr i m es C o un t A sy n c ( i * 1000000 , 1000000) +
13 " primes between " + ( i * 1000000) + " and " + (( i + 1) * 1000000 - 1) +
14 Environment . NewLine ;
15 _button . IsEnabled = true ;
16 }
simple but have to handle re-entrancy. and real parallel code does not use shared state. another example. download
web pages and sum their lengths. System.Net.WebClient.DownloadDataTaskAsync method. returns Task¡byte[]¿ so
await returns byte[].
1 async void Go ()
2 {
3 _button . IsEnabled = false ;
4 string [] urls = " www . albahari . com www . oreilly . com www . linqpad . net ". Split ();
5 int totalLength = 0;
6 try
7 {
8 foreach ( string url in urls )
9 {
10 var uri = new Uri (" http ://" + url );
11 byte [] data = await new WebClient (). Do wnloa dDat aTask Asyn c ( uri );
12 _results . Text += " Length of " + url + " is " + data . Length +
13 Environment . NewLine ;
14 totalLength += data . Length ;
15 }
16 _results . Text += " Total length : " + totalLength ;
17 }
18 catch ( WebException ex )
181

19 {
20 _results . Text += " Error : " + ex . Message ;
21 }
22 finally { _button . IsEnabled = true ; }
23 }

mirrors how we would write it sync. even though control returns to caller after first await, the finally blocks is not
run until method is logically completed. lets see underneath on the message loop.
1 while (! thisApplication . Ended )
2 {
3 wait for something to appear in message queue
4 Got something : what kind of message is it ?
5 Keyboard / mouse message -> fire an event handler
6 User BeginInvoke / Invoke message -> execute delegate
7 }

event handler run via this loop. Go runs as far as await and then returns to this loop. compilers expansion of await
ensures a continuation is setup. because we awaited on a UI thread, the continuation is posted on the sync context,
which ensures it runs via message loop. Go keeps running pseudo-concurrently with UI thread. True concurrency
occurs while DownloadDataTaskAsync is running.
vs. course grained where the loop itself on worker thread. gets difficult when progress reporting.
1 _button . Click += ( sender , args ) = >
2 {
3 _button . IsEnabled = false ;
4 Task . Run (() = > Go ());
5 };
6
7 void Go ()
8 {
9 for ( int i = 1; i < 5; i ++)
10 {
11 int result = GetPrimesCount ( i * 1000000 , 1000000);
12 Dispatcher . BeginInvoke ( new Action (() = >
13 _results . Text += result + " primes between " + ( i * 1000000) +
14 " and " + (( i + 1) * 1000000 - 1) + Environment . NewLine ));
15 }
16 Dispatcher . BeginInvoke ( new Action (() = > _button . IsEnabled = true ));
17 }
182 CHAPTER 34. LECTURE 34
Chapter 35

Lecture 35

Lets revise the downloading code from last lecture.


1 async void Go ()
2 {
3 _button . IsEnabled = false ;
4 string [] urls = " www . albahari . com www . oreilly . com www . linqpad . net ". Split ();
5 int totalLength = 0;
6 try
7 {
8 foreach ( string url in urls )
9 {
10 var uri = new Uri (" http ://" + url );
11 byte [] data = await new WebClient (). Do wnloa dDat aTask Asyn c ( uri );
12 _results . Text += " Length of " + url + " is " + data . Length +
13 Environment . NewLine ;
14 totalLength += data . Length ;
15 }
16 _results . Text += " Total length : " + totalLength ;
17 }
18 catch ( WebException ex )
19 {
20 _results . Text += " Error : " + ex . Message ;
21 }
22 finally { _button . IsEnabled = true ; }
23 }

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. we can expand PrintAnswerToLife like this.
nuances aside.
1 async Task PrintA nswerT oLife ()
2 {
3 await Task . Delay (5000);
4 int answer = 21 * 2;
5 Console . WriteLine ( answer );
6 }
7 async Task Go ()
8 {
9 await PrintA nswerT oLife ();
10 Console . WriteLine (" Done ");
11 }

whenever task finishes, execution returns to whoever awaited for the task. you can return Task¡TResult¿ if the
method returns TResult. internally that results in TCS signaled with a value.

183
184 CHAPTER 35. LECTURE 35

1 Task PrintAnsw erToLi fe ()


2 {
3 var tcs = new TaskCompletionSo u r c e < object >();
4 var awaiter = Task . Delay (5000). GetAwaiter ();
5 awaiter . OnCompleted (() = >
6 {
7 try
8 {
9 awaiter . GetResult ();
10 int answer = 21 * 2;
11 Console . WriteLine ( answer );
12 tcs . SetResult ( null );
13 }
14 catch ( Exception ex ) { tcs . SetException ( ex ); }
15 });
16 return tcs . Task ;
17 }
18
19
20 async Task <int > GetAnswerToLife ()
21 {
22 await Task . Delay (5000);
23 int answer = 21 * 2;
24 return answer ;
25 }

Lets see the async version vs. the sync version.


1 async Task Go ()
2 {
3 await PrintA nswerT oLife ();
4 Console . WriteLine (" Done ");
5 }
6 async Task PrintA nswerT oLife ()
7 {
8 int answer =
9 await GetAnswerToLife ();
10 Console . WriteLine ( answer );
11 }
12 async Task <int > GetAnswerToLife ()
13 {
14 await Task . Delay (5000);
15 int answer = 21 * 2;
16 return answer ;
17 }
18 void Go ()
19 {
20 Prin tAnswerToLife ();
21 Console . WriteLine (" Done ");
22 }
23 void PrintAnsw erToLi fe ()
24 {
25 int answer = GetAnswerToLife ();
26 Console . WriteLine ( answer );
27 }
28 int GetAnswerToLife ()
29 {
30 Thread . Sleep (5000);
31 int answer = 21 * 2;
32 return answer ;
185

33 }

same ease of programming as sync. intentional. so three steps. write sync. use async and await. return Task and
Task¡TResult¿ so awaitable. This means only Task.Run for real parallel cpu task and TCS for real parallel IO task.
rest of TCS are taken care of by compiler.
async call graph exec. brief sync exec on thread calling Go. everyone await and returns. when Delay fires a thread.
remaining statements run. eventually Gos task is marked completed.
1 async Task Go ()
2 {
3 var task = PrintAnswerToLife ();
4 await task ;
5 Console . WriteLine (" Done ");
6 }
7 async Task PrintA nswerT oLife ()
8 {
9 var task = GetAnswerToLife ();
10 int answer = await task ;
11 Console . WriteLine ( answer );
12 }
13 async Task <int > GetAnswerToLife ()
14 {
15 var task = Task . Delay (5000);
16 await task ;
17 int answer = 21 * 2;
18 return answer ;
19 }

Lets discuss Parallelism. Go is not awaited, allowed and required here. so lets see how to run two tasks in parallel
and then await them. true concurrency at bottom level operations. if a sync context, only pseudo-concurrency. so
only switched on await. that means we can increment shared var without locking. but cant assume same value before
and after await.
1 var task1 = PrintAnswerToLife ();
2 var task2 = PrintAnswerToLife ();
3 await task1 ;
4 await task2 ;
5
6
7 async Task <int > GetAnswerToLife ()
8 {
9 _x ++;
10 await Task . Delay (5000);
11 return 21 * 2;
12 }

async lambda expr.


1 Func < Task > unnamed = async () = >
2 {
3 await Task . Delay (1000);
4 Console . WriteLine (" Foo ");
5 };
6
7 await NamedMethod ();
8 await unnamed ();
9 myButton . Click += async ( sender , args ) = >
10 {
11 await Task . Delay (1000);
12 myButton . Content = " Done ";
13 };
186 CHAPTER 35. LECTURE 35

14 myButton . Click += ButtonHandler ;


15 ...
16 async void ButtonHandler ( object sender , EventArgs args )
17 {
18 await Task . Delay (1000);
19 myButton . Content = " Done ";
20 };
21
22 Func < Task < int > > unnamed = async () = >
23 {
24 await Task . Delay (1000);
25 return 123;
26 };
27 int answer = await unnamed ();
Cancellation. Cancel is on CancellationTokenSource. most have builtin cancellation support.
1 class Cancel lation Token
2 {
3 public bool I s C a n c e l l a t i o n R e q u e s t e d { get ; private set ; }
4 public void Cancel () { I s C a n ce l l a t i o n R e q u e s t e d = true ; }
5 public void T h r o w I f C a n c e l l a t i o n R e q u e s t e d ()
6 {
7 if ( Is Ca n ce l la ti o nR e qu es t e d )
8 throw new O p e r a t i o n C a n c e l e d E x c e p t i o n ();
9 }
10 }
11 async Task Foo ( Cancel lation Token cancellationToken )
12 {
13 for ( int i = 0; i < 10; i ++)
14 {
15 Console . WriteLine ( i );
16 await Task . Delay (1000);
17 cancellationToken . T h r o w I f C a n c e l l a t i o n R e q u e s t e d ();
18 }
19 }
20 async Task Foo ( Cancel lation Token cancellationToken )
21 {
22 for ( int i = 0; i < 10; i ++)
23 {
24 Console . WriteLine ( i );
25 await Task . Delay (1000 , cancellationToken );
26 }
27 }
28 var cancelSource = new Ca n ce l la ti o n T o k e n S o u r c e ();
29 Task . Delay (5000). ContinueWith ( ant = > cancelSource . Cancel ());
30 //...
31
32 var cancelSource = new Ca n ce l la ti o n T o k e n S o u r c e (5000);
33 try { await Foo ( cancelSource . Token ); }
34 catch ( O p e r a t i o n C a n c e l e d E x c e p t i o n ex )
35 { Console . WriteLine (" Cancelled "); }
can even use cancellation with Task.Wait. i.e. sync methods but have to call cancel from another task. infact you
can give a time interval after which auto cancelled. useful for timeouts.
Progress reporting. thread safety issues. iprogress and progress. progress ctor.
1 async Task Foo ( Action < int > o n P r o g r e ss P e r ce n t C ha n g e d )
2 {
3 return Task . Run (() = >
4 {
187

5 for ( int i = 0; i < 1000; i ++)


6 {
7 if ( i % 10 == 0) o nP r o g r e s s P e r c e n t C h a n g e d ( i / 10);
8 // Do something compute - bound ...
9 }
10 });
11 }
12
13 Action < int > progress = i = > Console . WriteLine ( i + " %");
14 await Foo ( progress );
15
16 var progress = new Progress < int >( i = > Console . WriteLine ( i + " %"));
17 await Foo ( progress );
18
19 public interface IProgress < in T >
20 {
21 void Report ( T value );
22 }
23
24
25 Task Foo ( IProgress < int > o n P r o g r e s s P er c e n tC h a n ge d )
26 {
27 return Task . Run (() = >
28 {
29 for ( int i = 0; i < 1000; i ++)
30 {
31 if ( i % 10 == 0)
32 o n P r o g r e s s P e rc e n t Ch a n g ed . Report ( i / 10);
33 // Do something compute - bound ...
34 }
35 });
36 }
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. Returns quickly to the caller (has only a small initial synchronous phase). Does not tie up
a thread if I/O-bound.
Task Combinators.
1 Task < int > winningTask = await Task . WhenAny ( Delay1 () , Delay2 () , Delay3 ());
2 Console . WriteLine (" Done ");
3 Console . WriteLine ( winningTask . Result );
4
5
6 int answer = await await Task . WhenAny ( Delay1 () , Delay2 () , Delay3 ());
7 Task < string > task = SomeAsyncFunc ();
8 Task winner = await ( Task . WhenAny ( someOperation , Task . Delay (5000)));
9 if ( winner != task ) throw new TimeoutException ();
10 string result = await task ;
188 CHAPTER 35. LECTURE 35
Chapter 36

Lecture 36

we can implement timeout with whenany task combinator. on the other hand WhenAll waits for all. di↵erence is that
should task1 fault, we never get to.

1 int answer = await await Task . WhenAny ( Delay1 () , Delay2 () , Delay3 ());
2 Task < string > task = SomeAsyncFunc ();
3 Task winner = await ( Task . WhenAny ( someOperation , Task . Delay (5000)));
4 if ( winner != task ) throw new TimeoutException ();
5 string result = await task ;
6 await Task . WhenAll ( Delay1 () , Delay2 () , Delay3 ());
7
8 Task task1 = Delay1 () , task2 = Delay2 () , task3 = Delay3 ();
9 await task1 ; await task2 ; await task3 ;
10
11 Task task1 = Task . Run (() = > { throw null ; } );
12 Task task2 = Task . Run (() = > { throw null ; } );
13 Task all = Task . WhenAll ( task1 , task2 );
14 try { await all ; }
15 catch
16 {
17 Console . WriteLine ( all . Exception . InnerExceptions . Count );
18 }
19 Task <int > task1 = Task . Run (() = > 1);
20 Task <int > task2 = Task . Run (() = > 2);
21 int [] results = await Task . WhenAll ( task1 , task2 );
22 async Task < int > GetTotalSize ( string [] uris )
23 {
24 IEnumerable < Task < byte [] > > downloadTasks = uris . Select ( uri = >
25 new ( WebClient ). D ownl oadDa t a T a s k A s y n c ( uri ));
26 byte [][] contents = await Task . WhenAll ( downloadTasks );
27 return contents . Sum ( c = > c . Length );
28 }
29 async Task < int > GetTotalSize ( string [] uris )
30 {
31 IEnumerable < Task < int > > downloadTasks = uris . Select ( async uri = >
32 ( await new WebClient (). D own loadD ataT askAs ync ( uri )). Length );
33 int [] contentLengths = await Task . WhenAll ( downloadTasks );
34 return contentLengths . Sum ();
35 }

189
190 CHAPTER 36. 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. lock contention and lot of cumbersome code. 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. combining
on the user. following is thread-unsafe. locking may make slow. concurrentBag.
1 public static void Invoke ( params Action [] actions );
2
3 Parallel . Invoke (
4 () = > new WebClient (). DownloadFile (" http :// www . linqpad . net " , " lp . html ") ,
5 () = > new WebClient (). DownloadFile (" http :// www . jaoo . dk " , " jaoo . html "));
6
7 var data = new List < string >();
8 Parallel . Invoke (
9 () = > data . Add ( new WebClient (). DownloadString (" http :// www . foo . com ")) ,
10 () = > data . Add ( new WebClient (). DownloadString (" http :// www . far . com ")));
11
12
13 public static P ar al le lL oo pR es ult For (
14 int fromInclusive , int toExclusive , Action < int > body )
15
16 public static P ar al le lL oo pR es ult ForEach < TSource > (
17 IEnumerable < TSource > source , Action < TSource > body )
18
19 for ( int i = 0; i < 100; i ++)
20 Foo ( i );
21
22 Parallel . For (0 , 100 , i = > Foo ( i ));
23
24 Parallel . For (0 , 100 , Foo );
25
26 foreach ( char c in " Hello , world ")
27 Foo ( c );
28
29 Parallel . ForEach (" Hello , world " , Foo );
30
31 var keyPairs = new string [6];
32 Parallel . For (0 , keyPairs . Length ,
33 i = > keyPairs [ i ] = RSA . Create (). ToXmlString ( true ));
191

Next we discuss using loop counter, breaking out of loops, and using per-thread counters. loop counters are easy
with sequential. use overloaded version. what is parallel loop state.
1 int i = 0;
2 foreach ( char c in " Hello , world ")
3 Console . WriteLine ( c . ToString () + i ++);
4
5 public static P ar al le lL oo pR es ult ForEach < TSource > (
6 IEnumerable < TSource > source ,
7 Action < TSource , ParallelLoopState , long > body )
8
9 Parallel . ForEach (" Hello , world " , (c , state , i ) = >
10 { Console . WriteLine ( c . ToString () + i ); });
11
12 public class Par allelL oopSta te
13 {
14 public void Break ();
15 public void Stop ();
16 public bool IsExceptional { get ; }
17 public bool IsStopped { get ; }
18 public long ? L o w e s t B r e a k I t e r at i o n { get ; }
19 public bool S h o u l d E x i t C u r r e n t I t e r a t i o n { get ; }
20 }

a normal break in parallel. di↵ between Break and Stop. Break reaches atleast the sequential point. what about
local value. use overload.
1 foreach ( char c in " Hello , world ")
2 if ( c == ’ , ’)
3 break ;
4 else
5 Console . Write ( c );
6
7
8 // OUTPUT : Hello
9
10
11 Parallel . ForEach (" Hello , world " , (c , loopState )= >
12 {
13 if ( c == ’ , ’)
14 loopState . Break ();
15 else
16 Console . Write ( c );
17 });
18
19 // OUTPUT : Hlloe
20
21 public static P ar al le lL oo pR es ult For < TLocal >(
22 int fromInclusive ,
23 int toExclusive ,
24 Func < TLocal > localInit ,
25 Func < int , ParallelLoopState , TLocal , TLocal > body ,
26 Action < TLocal > localFinally );
27
28 object locker = new object ();
29 double total = 0;
30 Parallel . For (1 , 10000000 ,
31 i = > { lock ( locker ) total += Math . Sqrt ( i ); });

problem above. locking slows down. what if every thread took lock once. possible with summation.
192 CHAPTER 36. LECTURE 36

1 object locker = new object ();


2 double grandTotal = 0;
3 Parallel . For (1 , 10000000 ,
4 () = > 0.0 ,
5 (i , state , localTotal ) = >
6 localTotal + Math . Sqrt ( i ) ,
7 localTotal = >
8 { lock ( locker ) grandTotal += localTotal ; }
9 );
Concurrent collections include concurrent stack, concurrent queue, concurrent bag, concurrent dictionary. They
are optimized for concurrent. but also useful for thread-safe. conventional outperform in all but highly concurrent
situations. thread-safe collection doesnt guarantee thread safe code. you enumerate, another modifies, you get com-
bination of old and new. no concurrent version of List. stack queue bag implemented with linked list but less mem
efficient as a consequence. e.g. the following code is 3 times slower but not with reads. also some atomic test and act.
like TryPop.
IProducerConsumerCollection¡T¿ has no need to lock. adds TryAdd and TryTake methods. with stack, most
recent, queue oldest, and bag whatever. concurrentbag is an unordered collection. its kind of linked list for each
thread. add has almost no contention.
BlockingCollection¡T¿ wait instead of returning false. wrapper class. also lets you limit the size. called bounded
blocking collection. ctor takes a iproducerconsumer and limit. default is to make a queue. can also give multiple
collecitons and use AddtoAny TakefromAny. can also take GetConsumingEnumerable. Lets make a producer consumer
queue.
1 public class PCQueue : IDisposable
2 {
3 BlockingCollection < Action > _taskQ = new BlockingCollection < Action >();
4 public PCQueue ( int workerCount )
5 {
6 for ( int i = 0; i < workerCount ; i ++)
7 Task . Factory . StartNew ( Consume );
8 }
9 public void Enqueue ( Action action ) { _taskQ . Add ( action ); }
10 void Consume ()
11 {
12 foreach ( Action action in _taskQ . G et Co ns umi ng En ume ra bl e ())
13 action ();
14 }
15 public void Dispose () { _taskQ . CompleteAdding (); }
16 }
17
18 public class PCQueue : IDisposable
19 {
20 BlockingCollection < Task > _taskQ = new BlockingCollection < Task >();
21 public PCQueue ( int workerCount )
22 {
23 for ( int i = 0; i < workerCount ; i ++)
24 Task . Factory . StartNew ( Consume );
25 }
26 public Task Enqueue ( Action action , Can cellat ionTok en cancelToken
27 = default ( Cancel lation Token ))
28 {
29 var task = new Task ( action , cancelToken );
30 _taskQ . Add ( task );
31 return task ;
32 }
33 public Task < TResult > Enqueue < TResult >( Func < TResult > func ,
34 CancellationToken cancelToken = default ( Cance llatio nToken ))
35 {
193

36 var task = new Task < TResult >( func , cancelToken );


37 _taskQ . Add ( task );
38 return task ;
39 }
40 void Consume ()
41 {
42 foreach ( var task in _taskQ . Get Co ns umi ng En ume ra bl e ())
43 try
44 {
45 if (! task . IsCanceled ) task . RunSynchronously ();
46 }
47 catch ( I n v a l i d O p e r a t i o n E x c e p t i on ) { }
48 }
49 public void Dispose () { _taskQ . CompleteAdding (); }
50 }
194 CHAPTER 36. LECTURE 36
Chapter 37

Lecture 37

In the last lecture, finished discussion on tasks and multithreading. important part of event driven and visual pro-
gramming. to remain responsive. the task parallel library. Parallel.Invoke, For, Foreach. loop counter, break, stop,
per-thread counter. concurrent collections, stack, queue, bag, dictionary. ended with a producer consumer queue with
tasks.
Now we’ll discuss event driven programming on the web and mobile. client side programming and event-handling.
server side web programming in other courses.
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
e↵ects. e.g. immediately give error msg when wrong data, give total when add to shopping cart, slideshow instead of
image list, expand collapse information, popup tooltips. immediate feedback. no delay like server side. no constant
loading reloading. so feels like desktop programs.
e.g. you visited google maps. JS (javascript) in action. zoom in zoom out. prev. map sites used reloading.
Javascript was introduced in 95 by netscape. about as old as web. but mostly hobby things like flies with
mouse or messages that move like stock ticker. many scripts but didnt work in all browsers, even crashed them
often. JS has nothing to do with Java, originally named LiveScript but renamed to associate with the then hot Java.
initial interoperability problems in netscape and IE. often added incompatible features. MS introduced jScript. their
version of JS for IE. these days mostly handled. standardization. some quirks left. called ECMAScript. the official
standardization name. refueled by high profile sites like google using JS in last decade. now JS even used by some
non-web scripting. even flash ActionScript based on it. or write widgets, phone apps etc.
JS is a prog language. can be hard for some. also browser incompatibilities make testing difficult. jQuery is a JS
library intended to make JS programming easier. 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. doctype is of html5 here. tells browser how to render the page. what
standards. five types of html in use: HTML 4.01 Transitional, HTML 4.01 Strict, XHTML 1.0 Transitional, XHTML
1.0 Strict, and HTML5. all current browsers understand them all. starting and closing tags like XML. at least three
tags. html root tag, head tag containing title etc, and body tag containing all parts to be rendered in browser window.
¡p¿¡/p¿ is paragraph ¡strong¿¡/strong¿ is emphasis ¡a href=”http:...”¿¡/a¿ is a hyperlink. XML attribute and value.
validating html means checking if all tags appropriately closed etc.
1 <! DOCTYPE html >
2 < html >
3 < head >
4 < meta charset = utf -8 >
5 < title > Hey , I am the title of this web page . </ title >
6 </ head >
7 < body >
8 Hey , I am some body text on this web page .
9 </ body >
10 </ html >

195
196 CHAPTER 37. LECTURE 37

originally there was only HTML. CSS is a formatting language. html only to structure, so ¡h1¿ ¡h2¿ are both
headings with di↵ imp ¡ul¿ is an unordered list. CSS adds design. CSS style is a rule telling web browser how to
display an element. e.g. you can make CSS rule to make all ¡h1¿ tags 36 px tall, in courier font, and in orange. CSS
can do more powerful stu↵, like add border, change margins, and even control exact placement on web page. JS can
add/remove/change CSS properties based on input or mouse clicks. even animate from one property to another. like
yellow to red. or animate across screen by changing position.
a single CSS style is a rule that tells how to format. make “this” look like “that”. selector and declaration block.
e.g. selector can be headline, paragraph of text, photo etc. declaration block can turn text blue, add red border around
a paragraph, position the photo at center of page etc. e.g. p color: red; font-size: 1.5em; selector, declaration block
has declarations. each is a property value pair and then “;”.
JS lets a page re-act. smart web forms. lets user know when they miss important info, make elements appear or
disappear, or move around a webpage. even load new content from web server without reloading. more engaging and
e↵ective web sites.
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. responsive. other client side technologies are applets,
silverlight, flash. often requires a plugin or start slow because of downloading. sometimes even di↵ to see if flash or
JS. once yahoo maps was flash. then re-written. right click and see if About the Flash Player Ajax brings client-side
server-side together. JS talks to server, downloads content, and update webpage. google maps lets you move to new
areas. JS is a prog lang and can be used on server side. e.g. Node.js supports JS on server-side.
compiled vs scripted languages (interpreted). JS interpreter is in web browser. lets write a prog to ask visitor
name, get response, and print a welcome msg. web browser has layout or rendering engine (understanding HTML and
CSS) and a JS interpreter. tell web browser about JS in a ¡script¿¡/script¿ tag. Here is a script in html 4.01 and in
html5.
1 <! DOCTYPE HTML PUBLIC " -// W3C // DTD HTML 4.01// EN " " http :// www . w3 . org / TR / html4 / strict . dtd " >
2 < html >
3 < head >
4 < title > My Web Page </ title >
5 < script type =" text / javascript " >
6
7 </ script >
8 </ head >
9
10
11
12 <! doctype html >
13 < html >
14 < head >
15 < meta charset =" UTF -8" >
16 < title > My Web Page </ title >
17 < script >
18
19 </ script >
20 </ head >

usually in head section and at one place. but its ok to put it anywhere and in multiple tags. script can also be
placed after ¡/body¿ so script loaded after page displayed can also use external script files. easy to share. separate
tags if you want inline code AND “src” attrib for external file. can and often use multiple external files.
1 <! doctype html >
2 < html >
3 < head >
4 < meta charset =" UTF -8" >
5 < title > My Web Page </ title >
6 < script src =" navigation . js " > </ script >
7 </ head >
8
197

9
10 <! doctype html >
11 < html >
12 < head >
13 < meta charset =" UTF -8" >
14 < title > My Web Page </ title >
15 < script src =" navigation . js " > </ script >
16 < script src =" slideshow . js " > </ script >
17 < script >
18 alert ( ’ hello world ! ’);
19 </ script >
20 </ head >
Lets open hello.html in web browser.

1 < book = javascript \& jquery the Missing Manual page 30 >
2 < script >
3 document . write ( ’ <p > Hello world ! </p > ’);
4 </ script >

before the web page because of placement. web page appears after OK pressed. use document.write and ¡script¿
tag anywhere.
1 < link href ="../ _css / site . css " rel =" stylesheet " >
2 < script src ="../ _js / jquery -1.6.3. min . js " > </ script >
3 < script >
4 $ ( function () {
198 CHAPTER 37. LECTURE 37

5 $ ( ’ body ’). hide (). fadeIn (3000);


6 });
7 </ script >

lot of basic syntax like C++, C#. create a variable using “var x”, names begin with letter, $, or . var days =
[’Mon’, ’Tues’, ’Wed’, ’Thurs’, ’Fri’, ’Sat’, ’Sun’]; alert(days[0]); var playList = []; var prefs = [1, 223, ’www.oreilly.com’,
false]; prefs.push(’test’); prefs.push(’test’,test2); arrays grow prefs.unshift(’test’); prefs.unshift(’test’,test2); insert at
start shift() gets/removes the first element. queue using push/shift pop() removes last. stack alert and prompt
functions.

1 var TAX = .08;


2 function calculateTotal ( quantity , price ) {
3 var total = quantity * price * (1 + TAX );
4 var formattedTotal = total . toFixed (2);
5 return formattedTotal ;
6 }
7
8 var saleTotal = calculateTotal (2 , 16.95);
9 document . write ( ’ Total cost is : \$ ’ + saleTotal );

if, while, for, dowhile like C#. function declarations. no types. return value.
Lets discuss jQuery now. many JS programs select elements, add new content, hide and show content, modify tag’s
attributes, determine value of form fields, and react to user actions. the details complicated specially with browser
interoperability. libraries o↵er a set of functions to make these tasks easy.
only 30k compressed library size. easy to learn. used on millions of sites. free. dev community. plugins !!!
where to get jQuery.js. Use CDNs dont need to host your own. often cached. google one is v popular.

1 < script src =" http :// ajax . aspnetcdn . com / ajax / jQuery / jquery -1.6.3. min . js " >
2 </ script >
3
4 < script src =" http :// code . jquery . com / jquery -1.6.3. min . js " > </ script >
5
6 < script src =" http :// ajax . googleapis . com / ajax / libs / jquery /1.6.3/ jquery . min . js " >
7 </ script >
8
9 < script src =" js / jquery -1.6.3. min . js " > </ script >
10 < script >
11 \ $ ( document ). ready ( function () {
12 // your programming goes here
13 });
14 </ script >
15
16 \ $ ( function () {
17 // your programming goes here
18 }); // end ready

second script tag for jQuery prog. $(document).ready() waits until HTML of webpage loads and then runs the
function. browser processes in order and to work with elements you want them downloaded. shortcut for ready
function.
199

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.
two steps. select sth, do sth with it. do sth can be change prop, add/remove element, extra info, add/remove class
attrib, or a combination of these.
200 CHAPTER 37. LECTURE 37
Chapter 38

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.

1 document . getElementById ( ’ banner ’);


2
3 document . g etElementByTagName ( ’a ’);

to select ¡a¿ tags with class navButton, you have to select all ¡a¿ tags, then iterate and find the ones with the
right class. in jQuery $(‘selector’) e.g. $(‘#banner’) is the tag with id banner. $(‘#banner’).html(‘¡h1¿JavaScript was
here¡/h1¿’);. html is a jQuery helper function.
Basic selectors are ID selectors, element selectors, class selectors.
1 <p id =" message " > Special message </ p >
2 var messagePara = document . getElementById ( ’ message ’);
3 var messagePara = $ ( ’\# message ’);
4
5
6 var linksList = document . getEleme n t s B y T a g N a m e ( ’a ’);
7 var linksList = $ ( ’a ’);
8
9
10 $ ( ’. submenu ’)
11 $ ( ’. submenu ’). hide ();

Advanced selectors are descendent selectors $(’#navBar a’) , child selectors $(’body ¿ p’) , adjacent sibling
$(’h2 + div’) , attribute selectors $(’img[alt]’), $(’input[type=”text”]’), $(’a[href=”mailto:”]’),
ˆ $(’a[href$=”.pdf”]’),
$(’a[href*=”missingmanuals.com”]’) , form element selectors later. jQuery filters are :even :odd $(’.striped tr:even’)
:first :last :not $(’a:not(.navButton)’); :has $(’li:has(a)’) — di↵ from descendent :contains $(’a:contains(Click Me!)’)
:hidden :visible $(’div:hidden’).show();

201
202 CHAPTER 38. LECTURE 38

jQuery selection. dont end up with DOM lists. rather jQuery equivalents automatic loops. $(’#slideshow
img’).hide(); chaining functions... $(’#popUp’).width(300).height(300); $(’#popUp’).width(300).height(300).text(’Hi!’).fadeIn(100
lets see jQuery functions to add content
take this example .html() can read and change alert($(’#errors’).html()); will show ¡h2¿Errors:¡/h2¿. $(’#er-
rors’).html(’¡p¿There are four errors in this form¡/p¿’);. .text() wont replace tags. $(’#errors h2’).text(’No errors
found’); encodes html tags to .text() so ¡p¿ would become &ltp&gt .append()... .prepend() $(’#errors’).append(’¡p¿There
are four errors in this form¡/p¿’); .before() .after() ¡input type=”text” name=”userName” id=”userName”¿ $(’#user-
Name’).after(’¡span class=”error”¿User name required¡/span¿’); ¡input type=”text” name=”userName” id=”userName”¿¡span
class=”error”¿User name required¡/span¿ .remove() $(’#popup’).remove(); .replaceWith() $(’#product101’).replaceWith(¡p¿Adde
to cart¡/p¿’);.
1 < div id =" container " >
2 < div id =" errors " >
3 <h2 > Errors : </ h2 >
4 </ div >
5 </ div >
6
7 alert (\ $ ( ’\# errors ’). html ());
8
9 \ $ ( ’\# errors ’). html ( ’ <p > There are four errors in this form </ p > ’);
10
11 \ $ ( ’\# errors h2 ’). text ( ’ No errors found ’);
12
13 \ $ ( ’\# errors ’). append ( ’ <p > There are four errors in this form </ p > ’);
14
15 \ $ ( ’\# errors ’). prepend ( ’ <p > There are four errors in this form </ p > ’);
16
17 \ $ ( ’\# userName ’). after ( ’ < span class =" error " > User name required </ span > ’);
18
19 \ $ ( ’\# popup ’). remove ();
20
21 \ $ ( ’\# product101 ’). replaceWith ( <p > Added to cart </ p > ’);
22 \ $ ( ’ a [ href \^=" http ://"] ’). addClass ( ’ externalLink ’);
23 <a href =" http :// www . oreilly . com /" >
24 <a href =" http :// www . oreilly . com /" class =" externalLink " >

Attributes can be manipulated with addClass removeClass toggleClass. and css. var bgColor = $(’#main’).css(’background-
color’); $(’body’).css(’font-size’, ’200$(’p.highlight’).css(’border’, ’1px solid black’); multiple css props can be changed
together.
1 var baseFont = \ $ ( ’ body ’). css ( ’ font - size ’);
2 baseFont = parseInt ( baseFont , 10);
3 \ $ ( ’ body ’). css ( ’ font - size ’ , baseFont * 2);
4
5
6 \ $ ( ’\# highlightedDiv ’). css ({
7 ’ background - color ’: ’\# FF0000 ’ ,
8 ’ border ’: ’2 px solid # FE0037 ’
9 });

for changing html attribute, css and addClass are just shortcuts general purpose attr() and removeAttr() var image-
File = $(’#banner img’).attr(’src’); $(’#banner img’).attr(’src’,’images/newImage.png’); $(’body’).removeAttr(’bgColor’);.
acting on each element in a selection. when you do want something special. each() and anonymous function. use
“this” for current element as DOM obj. $(this) for current element as jQuery selection.
1 var imageFile = \ $ ( ’\# banner img ’). attr ( ’ src ’);
2 \ $ ( ’\# banner img ’). attr ( ’ src ’ , ’ images / newImage . png ’);
3 \ $ ( ’ body ’). removeAttr ( ’ bgColor ’);
4
5 \ $ ( ’ selector ’). each ( function () {
203

6 // code goes in here


7 });
8
9
10 \ $ ( ’ a [ href \^= http ://] ’). each ( function () {
11 var extLink = \ $ ( this ). attr ( ’ href ’);
12 \ $ ( ’\# bibList ’). append ( ’ < li > ’ + extLink + ’ </ li > ’);
13 });

events. things happen to webpage. page loading, mouse move, key press you respond to events. mouse events: click,
dblclick, mousedown, mouseup, mouseover, mouseout, mousemove. doc/window events: load, resize, scroll, unload.
form events: submit, reset, change, focus, blur. keyboard: keypress (over n over), keydown, keyup.
step 1: select elements, step 2: assign an event, step 3: pass function to event.
1 $ ( ’\# menu ’). mouseover ( function () {
2 $ ( ’\# submenu ’). show ();
3 }); // end mouseover
ready() vs. load event
1 \ $ ( function () {
2 // do something on document ready
3 });
jquery events. hover. toggle is like hover except worked on and o↵ by clicks. event object is passed to all functions
handling events.
1 < script >
2 \ $ ( document ). ready ( function () {
3 \ $ ( ’ html ’). dblclick ( function () {
4 alert ( ’ ouch ’);
5 }); // end double click
6 \ $ ( ’a ’). mouseover ( function () {
7 var message = " <p > You moused over a link </ p >";
8 \ $ ( ’. main ’). append ( message );
9 }); // end mouseover
10 \ $ ( ’\# button ’). click ( function () {
11 \ $ ( this ). val (" Stop that !");
12 }); // end click
13 }); // end ready
14 </ script >
15 \ $ ( ’\# menu ’). hover ( function () {
16 \ $ ( ’\# submenu ’). show ();
17 } , function () {
18 \ $ ( ’\# submenu ’). hide ();
19 }); // end hover
204 CHAPTER 38. LECTURE 38
Chapter 39

Lecture 39

Event properties. String.fromCharCode(evt.which) evt.preventDefault(); or return false; to stop normal behavior


e.g. links, form submit etc. remove events $(’.tabButton’).unbind(’click’); default event bubbling and can stop it
evt.stopPropagation(); generic way to bind events (click, mouseover etc. special) $(’#selector’).bind(’click’, myData,
functionName); $(’selector’).bind(’click’, functionName); equivalent is $(’selector’).click(functionName);
can bind multiple events
1 \ $ ( document ). click ( function ( evt ) {
2 var xPos = evt . pageX ;
3 var yPos = evt . pageY ;
4 alert ( ’ X : ’ + xPos + ’ Y : ’ + yPos );
5 }); // end click

1 \ $ ( ’ selector ’). bind ( ’ click ’ , functionName );


2 \ $ ( ’\# selector ’). bind ( ’ click ’ , myData , functionName );
3
4
5 \ $ ( document ). bind ( ’ click keypress ’ , function () {
6 \ $ ( ’\# lightbox ’). hide ();
7 }); // end bind
8
9
10 \ $ ( ’\# theElement ’). bind ( ’ click ’ , function () {
11 // do something interesting
12 }); // end bind
13 \ $ ( ’\# theElement ’). bind ( ’ mouseover ’ , function () {
14 // do something else interesting

205
206 CHAPTER 39. LECTURE 39

15 }); // end bind


16
17
18 \ $ ( ’\# theElement ’). bind ({
19 ’ click ’ : function () {
20 // do something interesting
21 } , // end click function
22 ’ mouseover ’ : function () {
23 // do something interesting
24 }; // end mouseover function
25 }); // end bind

FAQ example.

1 < script src ="../ _js / jquery -1.6.3. min . js " > </ script >
2 < script >
3 \ $ ( document ). ready ( function () {
4 \ $ ( ’. answer ’). hide ();
5 \ $ ( ’\# main h2 ’). toggle (
6 function () {
7 \ $ ( this ). next ( ’. answer ’). fadeIn ();
8 \ $ ( this ). addClass ( ’ close ’);
9 },
10 function () {
11 \ $ ( this ). next ( ’. answer ’). fadeOut ();
12 \ $ ( this ). removeClass ( ’ close ’);
13 }
14 ); // end toggle
15 });
16 </ script >

jQuery animations. $(’element’).fadeOut(’slow’);. fast normal slow or number of ms . default 200 400 600. fadeIn,
fadeOut, fadeToggle. slideDown, slideUp, slideToggle.
207

Login slider example


1
2 \ $ ( document ). ready ( function () {
3 \ $ ( ’\# open ’). toggle (
4 function () {
5 \ $ ( ’\# login form ’). slideDown (300);
6 \ $ ( this ). addClass ( ’ close ’);
7 },
8 function () {
9 \ $ ( ’\# login form ’). fadeOut (600);
10 \ $ ( this ). removeClass ( ’ close ’);
11 }
12 ); // end toggle
13 }); // end ready

generic animate. any numeric css prop. border-left-width becomes borderLeftWidth cuz JS doesnt understand
hyphen even += -=.
1 \ $ ( ’\# message ’). animate (
2 {
3 left : ’650 px ’ ,
4 opacity : .5 ,
5 fontSize : ’24 px ’
6 },
7 1500
8 );
9
10
208 CHAPTER 39. LECTURE 39

11 \ $ ( ’\# moveIt ’). click ( function () {


12 \ $ ( this ). animate (
13 {
14 left : ’+=50 px ’
15 },
16 1000);
17 });

easing. linear or swing $(’#element’).slideUp(1000,’linear’); can event pass a function to run when the animation
finishes
1 \ $ ( ’\# element ’). slideUp (1000 , ’ linear ’);
2
3 \ $ ( ’\# photo ’). fadeIn (1000 , function () {
4 \ $ ( ’\# caption ’). fadeIn (1000);
5 });
6
7 \ $ ( ’\# photo ’). width (0). height (0). css ( ’ opacity ’ , 0);
8 \ $ ( ’\# caption ’). hide ();
9 \ $ ( ’\# photo ’). animate (
10 {
11 width : ’200 px ’ ,
12 height : ’100 px ’ ,
13 opacity : 1
14 },
15 1000 ,
16 function () {
17 \ $ ( ’\# caption ’). fadeIn (1000);
18 }
19 ); // end animate

Can chain e↵ects.


$(’#photo’).fadeIn(1000).delay(10000).fadeOut(250);
photo gallery example.
1 \ $ ( ’\# gallery a ’). click ( function ( evt ) {
2 evt . preventDefault ();
3 var imgPath = \ $ ( this ). attr ( ’ href ’);
4 var oldImage = \ $ ( ’\# photo img ’);
5 var newImage = \ $ ( ’ < img src =" ’ + imgPath + ’" > ’);
6 newImage . hide ();
7 \ $ ( ’\# photo ’). prepend ( newImage );
8 newImage . fadeIn (1000);
9 oldImage . fadeOut (1000 , function (){
10 \ $ ( this ). remove ();
11 }); // end fadeout
12 }); // end click
13 \ $ ( ’\# gallery a : first ’). click ();

forms.
1 < input name =" quantity " type =" text " id =" quantity " >
2
3 < input name =" total " type =" text " id =" total " >
4
5 var unitCost = 9.95;
6 var amount = \ $ ( ’\# quantity ’). val ();
7 var total = amount * unitCost ;
8 total = total . toFixed (2);
9 \ $ ( ’\# total ’). val ( total );
209

submit event.
1 \ $ ( document ). ready ( function () {
2 \ $ ( ’\# signup ’). submit ( function () {
3 if (\ $ ( ’\# username ’). val () == ’ ’) {
4 alert ( ’ Please supply a name in the Name field . ’);
5 return false ;
6 }
7 }); // end submit ()
8 }); // end ready ()
focus, blur, click, change (menus). react to choice from a list menu
cant do everything at client. page disappearing and reappearing. ajax lets webpage ask for info and update itself
when it comes. asynchronous JS and XML. term coined in 2005 for interactive sites coming from google. like google
maps, gmail.
210 CHAPTER 39. LECTURE 39
Chapter 40

Lecture 40

In Last Lecture, we talk about event object and its properties. binding and unbinding events. jQuery animations,
easing, chaining. FAQ, login slider, photo gallery. forms and form selectors. now the real power. ajax.
what can be done. display NEW html content without reloading the page. submit form and instantly display
results. login without leaving the page. e.g. star rating widget. browsing through database info like you scroll down
on fb, twitter. nothing radical. except without loading a new page. can achieve same with HTML and server side
prog. ajax make pages feel more responsive and desktop like.

JS, server-side programming, and web browser, all work together. web browser: XMLHttpRequest object. makes
ajax possible. talks to web server and get response. JS: sends request, waits for response, process response, updates
web page. web server: receives request and responds as HTML, plain text, XML, JSON. or application server for more
complicated tasks. need web server for ajax examples.
For talking to web server, we create XMLHttpRequest (also called XHR in short) var newXHR = new XML-
HttpRequest(); again browser incompatibilities call open to specify what kind of data and where it will go can GET

211
212 CHAPTER 40. LECTURE 40

or POST newXHR.open(’GET’, ’shop.php?productID=34’); write a callback function it will remove, add, change el-
ements send data newXHR.send(null); GET newXHR.send(’q=javascript’); POST receive response callback invoked
and XHR receives status, text response, and possibly an XML response status = 200/304 all ok, 404 file not found,
500 internal server error, 403 access forbidden responseText has text of JSON or HTML, responseXML less commonly
used
the jQuery way. simplifies all steps except that of changing the webpage simplest is load function which loads HTML
into an area of web page e.g. load news in a div from a web-server $(’#headlines’).load(’todays news.html’); can only
load from same site... relative urls possible to add only a part $(’#headlines’).load(’todays news.html #news’);.
1 \ $ ( ’\# headlines ’). load ( ’ todays_news . html ’);
2
3 \ $ ( ’\# headlines ’). load ( ’ todays_news . html \# news ’);
4
5
6 \ $ ( ’\# newslinks a ’). click ( function () {
7 var url = \ $ ( this ). attr ( ’ href ’);
8 \ $ ( ’\# headlines ’). load ( url + ’ \# newsItem ’);
9 return false ;
10 });
11 \ $ . get ( url , data , callback );
12 \ $ . post ( url , data , callback );

get() and post(). need server side to do anything else. server may not return html e.g. database records as xml or
json. jQuery handles di↵erences of GET and POST. no selector. stand by themselves.
1 $ . get ( ’ rateMovie . php ’ , ’ rating =5 ’);
2
3 $ . post ( ’ rateMovie . php ’ , ’ rating =5 ’);

formatting data. can send a product number, entire form, signup. format as query string of JS obj literal.
URL http://www.chia-vet.com/prod- ucts.php?prodID=18&sessID=1234. GET has limit. often thousands of chars.
$.get(’rateMovie.php’,’rating=5’); $.post(’rateMovie.php’,’rating=5’); $.post(’rateMovie.php’,’rating=5&user=Bob’);
’favFood=Mac & Cheese’ // incorrect ’favFood=Mac%20%26%20Cheese’ // properly escaped var queryString = ’fav-
Food=’ + encodeURIComponent(’Mac & Cheese’); $.post(’foodChoice.php’, queryString); better way is obj literal.
1 {
2 name1 : ’ value1 ’ ,
3 name2 : ’ value2 ’
4 }
5
6 \ $ . post ( ’ rankMovie . php ’ , { rating : 5 });
7
8 var data = { rating : 5 };
9
10 \ $ . post ( ’ rankMovie . php ’ , data );
11
12 var data = {
13 rating : 5 ,
14 user : ’Bob ’
15 }
16
17 \ $ . post ( ’ rankMovie . php ’ , data );
18
19 var data = \ $ . post ( ’ rankMovie . php ’ ,
20 {
21 rating : 5 ,
22 user : ’Bob ’ }
23 ); // end post

Serialize using name/value of form elements var formData = $(’#login’).serialize(); $.get(’login.php’,formData,loginResults);


213

processing data returned. call back first arg is data. servers often use XML of JSON. second arg is string about
status success. e.g. movie rating.

1 function processResponse ( data , status ) {


2 var newHTML ;
3 newHTML = ’<h2 > Your vote is counted </ h2 > ’;
4 newHTML += ’<p > The average rating for this movie is ’;
5 newHTML += data + ’. </p > ’;
6 \ $ ( ’\# message ’). html ( newHTML );
7 //
8 }

1 \ $ ( ’\# message a ’). click ( function () {


2 var href =\ $ ( this ). attr ( ’ href ’);
3 var querystring = href . slice ( href . indexOf ( ’? ’)+1);
4 \ $ . get ( ’ rate . php ’ , querystring , processResponse );
5 return false ; // stop the link
6 });
7
8
9 function processResponse ( data ) {
10 var newHTML ;
11 newHTML = ’<h2 > Your vote is counted </ h2 > ’;
12 newHTML += ’<p > The average rating for this movie is ’;
13 newHTML += data + ’. </p > ’;
14 \ $ ( ’\# message ’). html ( newHTML );
15 }
214 CHAPTER 40. LECTURE 40

error handler.
1 \ $ . get ( url , data , successFunction ). error ( errorFunction );
2
3 \ $ . get ( ’ rate . php ’ , querystring , processResponse ). error ( errorResponse );
4
5 function errorResponse () {
6 var errorMsg = " Your vote could not be processed right now .";
7 errorMsg += " Please try again later .";
8 \ $ ( ’\# message ’). html ( errorMsg );
9 }
JS format. method for exchanging data. JSON is JS so its quick n easy for JS. no XML like parsing. JSON is a
JS obj literal. (MUST use quotations if names have spaces etc.)
1 {
2 firstName : ’ Frank ’ ,
3 lastName : ’ Smith ’ ,
4 phone : ’503 -555 -1212 ’
5 }
215

6
7 {
8 ’ firstName ’: ’ Frank ’ ,
9 ’ lastName ’: ’ Smith ’ ,
10 ’ phone ’: ’503 -555 -1212 ’
11 }

server returns a string formatted like a JSON obj literal. jQuery getJSON method. like get but data passed to
callback will be a JSON object.
1 var bday = {
2 person : ’ Raoul ’ ,
3 date : ’10/27/1980 ’
4 };
5 bday . person // ’ Raoul ’
6 bday . date // ’10/27/1980 ’

obj literals can be composed of other obj literals


1 var data = {
2 contact1 : {
3 firstName : ’ Frank ’ ,
4 lastName : ’ Smith ’ ,
5 phone : ’503 -555 -1212 ’
6 },
7 contact2 : {
8 firstName : ’ Peggy ’ ,
9 lastName : ’ Jones ’ ,
10 phone : ’415 -555 -5235 ’
11 }
12 };
13
14 data . contact1 . firstName
15 \ $ . each ( JSON , function ( name , value ) {
16 });
17 \ $ . getJSON ( ’ contacts . php ’ , ’ limit =2 ’ , processContacts );
216 CHAPTER 40. LECTURE 40
Chapter 41

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];. can combine. nested message send. NSMutableArray *arrayInstance = [[NSMutableArray
alloc] init];. message = [receiver selector arguments]. e.g. add obj to array. [arrayInstance addObject:anotherObject];.
another message you can send to mutablearray. replaceObjectsInRange:withObjectsFromArray:range:. pairing of
labels and arguments a feature of objective-C. in other langs. arrayInstance.replaceObjectsInRangeWithObjectsFromArrayRange(a
anotherArray, anotherRange);. in objective-C. [arrayInstance replaceObjectsInRange:aRange withObjectsFromAr-
ray:anotherArray range:anotherRange];.
destroy using [arrayInstance release];. should also arrayInstance = nil;. otherwise dangling. but sending message
to nil is ok. nil is like null.
1 int main ( int argc , const char * argv [])
2 {
3 NSAutoreleasePool * pool = [[ NSAu torele asePoo l alloc ] init ];
4 NSMutableArray * items = [[ NSMutableArray alloc ] init ];
5 [ items addObject : @ " One "];
6 [ items addObject : @ " Two "];
7 [ items addObject : @ " Three "];
8 [ items insertObject : @ " Zero " atIndex :0];
9 for ( int i = 0; i < [ items count ]; i ++){
10 NSLog ( @ "% @ " , [ items objectAtIndex : i ]);
11 }
12 [ items release ];
13 items = nil ;
14 [ pool drain ];
15 return 0;
16 }
NSString. [items addObject:@”One”]; @ is shortcut for creating NSString. NSString *myString = @”Hello,
World!”;. int len = [myString length];. len = [@”Hello, World!” length];. myString = [[NSString alloc] initWith-
String:@”Hello, World!”];. len = [myString length];.
NSLog. format string. int a = 1; float b = 2.5; char c = ’A’; NSLog(@”Integer: Integer: 1 Float: 2.5 Char: A
NSArray and NSMutableArray. also NSDictionary and NSSet. holds references. cannot hold primitives and C
structures. can call [array count]. int numberOfObjects = [array count]; [array insertObject:object atIndex:numberOfObjects];
cant add beyond end. exception. [array addObject:[NSNull null]]; // otherwise cannot hold nil. NSString *object =
[array objectAtIndex:0];
subclassing. root class of entire hierarchy. NSObject. objective-C keywords start with @. instance variables.
1 # import < UIKit / UIKit .h >
2 @interface Possession : NSObject
3 {
4 }
5 @end

217
218 CHAPTER 41. LECTURE 41

6
7
8 # import < Foundation / Foundation .h >
9 @interface Possession : NSObject
10 {
11 NSString * possessionName ;
12 NSString * serialNumber ;
13 int valueInDollars ;
14 NSDate * dateCreated ;
15 }
16 @end

1 # import < Foundation / Foundation .h >


2 @interface Possession : NSObject
3 {
4 NSString * possessionName ;
5 NSString * serialNumber ;
6 int valueInDollars ;
7 NSDate * dateCreated ;
8 }
9 - ( void ) setPosses sionNa me :( NSString *) str ;
10 - ( NSString *) possessionName ;
11 - ( void ) setSerialNumber :( NSString *) str ;
12 - ( NSString *) serialNumber ;
13 - ( void ) setValueI nDolla rs :( int ) i ;
14 - ( int ) valueInDollars ;
15 - ( NSDate *) dateCreated ;
16 @end
17
18
19 # import " Possession . h "
20 @implementation Possession
21 // Getter
22 - ( NSString *) possessionName
23 {
24 // Returna pointer to the object this Possession calls its possessionName
25 return possessionName ;
26 }
27 // Setter
28 - ( void ) setPosses sionNa me :( NSString *) newPossessionName
29 {
30 // Change the instance variable to point at another string ,
31 // this Possession will now call this new string its possessionName
32 possessionName = new PossessionName ;
33 }
34
219

35
36 // Createa new Possession instance
37 Possession * p = [[ Possession alloc ] init ];
38 // Set possessionName to a new NSString
39 [ p setPos sessionName : @ " Red Sofa "];
40 // Get the pointer of the Possession ’ s possessionName
41 NSString * str = [ p possessionName ];
42 // Print that object
43 NSLog ( @ "% @ " , str ); // This would print " Red Sofa "
Getter setters can be made like above example. Lets see instance methods (and overriding).
1 - ( NSString *) description
2 {
3 NSString * descriptionString =
4 [[ NSString alloc ] initWithFormat : @ "\% @ (\% @ ): Worth \ $ \% d , recorded on \% @ " ,
5 possessionName ,
6 serialNumber ,
7 valueInDollars ,
8 dateCreated ];
9 return des cripti onStri ng ;
10 }
initializers start with init naming convention. id = any object. every object has isa pointer to class and thats how
methods are called. like vtable. self and super. other initializers.
1 - ( id ) i n i t W i t h P o s s e s s i o n N a m e :( NSString *) name
2 valueInDollars :( int ) value
3 serialNumber :( NSString *) sNumber ;
4
5
6 - ( id ) i n i t W i t h P o s s e s s i o n N a m e :( NSString *) name
7 valueInDollars :( int ) value
8 serialNumber :( NSString *) sNumber
9 {
10 // Call the superclass ’ s designated initializer
11 self = [ super init ];
12 // Did the superclass ’ s designated initializer succeed ?
13 if ( self ){
14 // Give the instance variables initial values
15 [ self setPos sessio nName : name ];
16 [ self setSerialNumber : sNumber ];
17 [ self setVal ueInDo llars : value ];
18 dateCreated = [[ NSDate alloc ] init ];
19 }
20 // Return the address of the newly initialized object
21 return self ;
22 }
23
24
25
26 - ( id ) init
27 {
28 return [ self i n i t W i t h P o s s e s s i o n N a m e : @ " Possession "
29 valueInDollars :0
30 serialNumber : @ ""];
31 }
class methods
1 @interface Possession : NSObject
2 {
220 CHAPTER 41. LECTURE 41

3 NSString * possessionName ;
4 NSString * serialNumber ;
5 int valueInDollars ;
6 NSDate * dateCreated ;
7 }
8 + ( id ) randomPossession ;
9 - ( id ) i n i t W i t h P o s s e s s i o n N a m e :( NSString *) name
10 valueInDollars :( int ) value
11 serialNumber :( NSString *) sNumber ;
12
13
14
15 + ( id ) randomPossession
16 {
17 // Create an array of three adjectives
18 NSArray * randomAdjectiveL ist = [ NSArray arrayWithObjects : @ " Fluffy " ,
19 @ " Rusty " ,
20 @ " Shiny " , nil ];
21 // Create an array of three nouns
22 NSArray * randomNounList = [ NSArray arrayWithObjects : @ " Bear " ,
23 @ " Spork " ,
24 @ " Mac " , nil ];
25
26 int adjectiveIndex = rand ()\% [ r an d o mA d j ec t i ve L i st count ];
27 int nounIndex = rand ()\% [ randomNounList count ];
28 NSString * randomName = [ NSString stringWithFormat : @ "\% @ \% @ " ,
29 [ randomAdjectiveList objectAtIndex : adjectiveIndex ] ,
30 [ randomNounList objectAtIndex : nounIndex ]];
31 int randomValue = rand ()\% 100;
32 NSString * randomSerialNumb er = [ NSString stringWithFormat : @ "\% c \% c \% c \% c \% c " ,
33 ’0 ’+ rand ()\% 10 ,
34 ’A ’+ rand ()\% 26 ,
35 ’0 ’+ rand ()\% 10 ,
36 ’A ’+ rand ()\% 26 ,
37 ’0 ’+ rand ()\% 10];
38 // Once again , ignore the memory problems with this method
39 Possession * newPossession =
40 [[ self alloc ] i ni tW ith Po s s e s s i o n N a m e : randomName
41 valueInDollars : randomValue
42 serialNumber : r an domSerialNumber ];
43 return newPossession ;
44 }
obj-C is dynamically typed. NSMutableArray *items = [[NSMutableArray alloc] init]; [items doSomethingWeird];
2009-07-19 01:34:53.602 RandomPossessions[25326:10b]. *** -[NSCFArray doSomethingWeird]: unrecognized selector
sent to instance 0x104b40. objective-C has try-catch. usually for runtime errors that the programmer made better for
loop.
properties, simplified accessors.
1 @interface Possession : NSObject
2 {
3 NSString * possessionName ;
4 NSString * serialNumber ;
5 int valueInDollars ;
6 NSDate * dateCreated ;
7 }
8 + ( id ) randomPossession ;
9 - ( id ) i n i t W i t h P o s s e s s i o n N a m e :( NSString *) name
10 valueInDollars :( int ) value
11 serialNumber :( NSString *) sNumber ;
221

12 - ( id ) i n i t W i t h P o s s e s s i o n N a m e :( NSString *) name ;
13 @property NSString * possessionName ;
14 @property NSString * serialNumber ;
15 @property int valueInDollars ;
16 @property NSDate * dateCreated ;
17 @end
18
19
20 @implementation Possession
21 @synthesize possessionName , serialNumber , valueInDollars , dateCreated ;
22
23
24 @property ( nonatomic , copy ) NSString * possessionName ;
25 @property ( nonatomic , copy ) NSString * serialNumber ;
26
27 - ( void ) setPosses sionNa me :( NSString *) str
28 {
29 id t = [ str copy ];
30 [ possessionName release ];
31 possessionName = t ;
32 }
copy and mutableCopy.
222 CHAPTER 41. LECTURE 41
Chapter 42

Lecture 42

alloc and dealloc methods. manual reference counting. obj knows owner count retainCount. retain and release
methods. should you release a created object that is returned ?. Want to say don’t release but i don’t want to be the
owner. autorelease. added to NSAutoReleasePool. NSObject *x = [[[NSObject alloc] init] autorelease];.

1 NSObject * x = [[[ NSObject alloc ] init ] autorelease ];


2
3 - ( NSString *) description
4 {
5 NSString * descriptionString =
6 [[ NSString alloc ] initWithFormat : @ "\% @ (\% @ ): Worth \ $ \% d , Recorded on \% @ " ,
7 possessionName ,
8 serialNumber ,
9 valueInDollars ,
10 dateCreated ];
11 return [ de script ionStri ng autorelease ];
12 }
13
14
15
16 - ( NSString *) description
17 {
18 return [ NSString stringWithFormat : @ "\% @ (\% @ ): Worth \ $ \% d , Recorded on \% @ " ,
19 possessionName ,
20 serialNumber ,
21 valueInDollars ,
22 dateCreated ];

223
224 CHAPTER 42. LECTURE 42

23 }
24
25
26 - ( void ) setPosses sionNa me :( NSString *) str
27 {
28 [ str retain ];
29 [ possessionName release ];
30 possessionName = str ;
31 }
32
33
34
35 - ( void ) dealloc
36 {
37 [ possessionName release ];
38 [ serialNumber release ];
39 [ dateCreated release ];
40 [ super dealloc ];
41 }

retain count rules. init, new, copy in name. assume you own. any other means. assume in autorelease. if you dont
own and want to make sure, call retain. no longer need and own than release or autorelease. when 0 count, dealloc
called.

protocols i.e. interfaces.

last lecture about ajax. really learned how similar event driven programming is in JS than wpf. what about mobile.
same paradigm, di↵erent language. same concepts, di↵erent incarnation. ios programming. learn objective-C. event
driven programming. well see examples but you may not be able to try them. need a mac computer and Xcode, teh
iOS simulator. lets make a simple app.

a quiz showing a question and revealing the answer. create new project (window based applica.). name it.
225

similar to visual studio. the interface in xml. xib file. compiled to a nib file. ios application a directory containing
executables and resources. sounds familiar.
226 CHAPTER 42. LECTURE 42

xib editing. select window to add controls. drag buttons. give them names.
227

mvc pattern. view objects. visible things. UIView subclasses. model objects. hold data and know nothing about
interface. often use standard containers. controllers keep things in sync.
228 CHAPTER 42. LECTURE 42

IBOutlet, IBAction.

1 @interface QuizAppDelegate : NSObject < UIApplicationDelegate >


2 {
3 int currentQuestionIndex ;
4 // The model objects
5 NSMutableArray * questions ;
6 NSMutableArray * answers ;
7 // The view objects
8 IBOutlet UILabel * questionField ;
9 IBOutlet UILabel * answerField ;
10 }
11 @property ( nonatomic , retain ) IBOutlet UIWindow * window ;
12 - ( IBAction ) showQuestion :( id ) sender ;
13 - ( IBAction ) showAnswer :( id ) sender ;
14 @end

setting connections. from the obj with pointer to the obj you want that pointer to point at. control-drag from
target to object. check connection in connection inspector.

1 @interface QuizAppDelegate : NSObject < UIApplicationDelegate >


2 {
3 int currentQuestionIndex ;
4 // The model objects
5 NSMutableArray * questions ;
6 NSMutableArray * answers ;
7 // The view objects
8 IBOutlet UILabel * questionField ;
9 IBOutlet UILabel * answerField ;
10 }
11 @property ( nonatomic , retain ) IBOutlet UIWindow * window ;
12 - ( IBAction ) showQuestion :( id ) sender ;
13 - ( IBAction ) showAnswer :( id ) sender ;
14 @end
229
230 CHAPTER 42. LECTURE 42

1 @implementation QuizAppDelegate
2 - ( id ) init
3 {
4 // Call the init method implemented by the superclass
5 self = [ super init ];
6 if ( self ){
7 // Create two arrays and make the pointers point to them
8 questions = [[ NSMutableArray alloc ] init ];
9 answers = [[ NSMutableArray alloc ] init ];
10 // Add questions and answers to the arrays
11 [ questions addObject : @ " What is7 + 7?"];
12 [ answers addObject : @ "14"];
13 [ questions addObject : @ " What is the capital of Vermont ?"];
14 [ answers addObject : @ " Montpelier "];
15 [ questions addObject : @ " From what is cognac made ?"];
16 [ answers addObject : @ " Grapes "];
17 }
18 // Return the address of the new object
19 return self ;
20 }
21
22
23
24 - ( IBAction ) showQuestion :( id ) sender
25 {
26 // Step to the next question
27 c u r r e n t Q u e s t i o n I n d e x ++;
28 // Am I past the last question ?
29 if ( currentQuestionIndex == [ questions count ]){
30 // Go back to the first question
31 c u r r e n t Q u e s t i o n I n dex = 0;
231

32 }
33 // Get the string at that index in the questions array
34 NSString * question = [ questions objectAtIndex : c u r r e n t Q u e s t i o n I n d e x ];
35 // Log the string to the console
36 NSLog ( @ " displaying question : % @ " , question );
37 // Display the string in the question field
38 [ questionField setText : question ];
39 // Clear the answer field
40 [ answerField setText : @ "???"];
41 }
42 - ( IBAction ) showAnswer :( id ) sender
43 {
44 // What is the answer to the current question ?
45 NSString * answer = [ answers objectAtIndex : c u r r e n t Q u e s t i o n I n d e x ];
46 // Display it in the answer field
47 [ answerField setText : answer ];
48 }
232 CHAPTER 42. LECTURE 42
Chapter 43

Lecture 43

In Last Lecture, we discussed objective C memory management rules, Wrote our first iPhone app: a quiz app, xib and
nib files and interface editor, MVC pattern, IBOutlet IBAction, Connection Inspector, then wrote init, showQuestion,
and showAnswer.

Core Location Framework. Lets make a whereami application. classes that enable finding geographical position.
distanceFilter and desiredAccuracy properties.

1 # import < UIKit / UIKit .h >


2 # import < CoreLocation / CoreLocation .h >
3
4 @interface W h e re a mi A p pD e l eg a t e : NSObject < UIApplicationDelegate >
5 {
6 CLLocationManager * locationManager ;
7 }
8 @property ( nonatomic , retain ) IBOutlet UIWindow * window ;
9 @end
10
11 - ( BOOL ) application :( UIApplication *) application
12 d i d F i n i s h L a u n c h i n g W i t h O p t i o n s :( NSDictionary *) launchOptions
13 {
14 // Create location manager object
15 locationManager = [[ CLLoc ationManager alloc ] init ];
16 // We want all results from the location manager
17 [ locationManager setDis tanceF ilter : k C L D i s t a n c e F i l t e r N o n e ];
18 // And we want it to be as accurate as possible
19 // regardless of how much time / power it takes
20 [ locationManager se tD es ir ed Ac cu rac y : k C L L o c a t i o n A c c u r a c y B e s t ];
21 // Tell our manager to start looking for its location immediately
22 [ locationManager s t a r t U p d a t i n g L o c a t i o n ];
23 // This line may say self . window , don ’ t worry about that
24 [[ self window ] makeKeyAndVisib le ];
25 return YES ;
26 }

233
234 CHAPTER 43. LECTURE 43

Delegation. locationManager:didUpdateToLocation:fromLocation: sent to delegate which we want WhereamiAp-


pDelegate to be.

1 - ( void ) locationManager :( CLL ocationManager *) manager


2 d i dUp da t e To L o ca t i on :( CLLocation *) newLocation
3 fromLocation :( CLLocation *) oldLocation
4 {
5 NSLog ( @ "% @ " , newLocation );
6 }
7 - ( void ) locationManager :( CLL ocationManager *) manager
8 didFailWithError :( NSError *) error
9 {
10 NSLog ( @ " Could not find location : % @ " , error );
11 }

Delegation is a design pattern. an OO approach to callbacks. allows callback methods to share data. a delegate
can only be sent messages specified in its protocol. for every object that can have a delegate, there is a corresponding
protocol.
1 @protocol C L L o c a t i o n M a n a g e r D e l e g a t e < NSObject >
2 @optional
3 - ( void ) locationManager :( CLL ocationManager *) manager
4 d id U p da t e To L o ca t i on :( CLLocation *) newLocation
5 fromLocation :( CLLocation *) oldLocation ;
6 - ( void ) locationManager :( CLL ocationManager *) manager
7 didUpdateHeading :( CLHeading *) newHeading ;
8 - ( BOOL ) l o c a t i o n M a n a g e r S h o u l d D i s p l a y H e a d i n g C a l i b r a t i o n :( CLLocationManager *) manager ;
9 - ( void ) locationManager :( CLL ocationManager *) manager
10 didEnterRegion :( CLRegion *) region ;
11 - ( void ) locationManager :( CLL ocationManager *) manager
12 didFailWithError :( NSError *) error ;
13 @end
235

1 - ( void ) f i n i s h e d F i n d i n g L o c a t i o n :( CLLocation *) newLocation


2 {
3 SEL updateMethod = @selector ( locationManager : d id U p da t e To L o ca t i on : fromLocation :);
4 if ([[ self delegate ] respo nd sT oS el ec tor : updateMethod ]){
5 // If the method is implemented , then we send the message .
6 [[ self delegate ] locationManager : self
7 d i dU p d at e T oL o c at i on : newLocation
8 fromLocation : oldLocation ];
9 }
10 }
11
12 @interface W h e re a mi A p pD e l eg a t e : NSObject
13 < UIApplicationDelegate , CLLocationManagerDelegate >
14 - ( void ) dealloc
15 {
16 if ([ locationManager delegate ] == self )
17 [ locationManager setDelegate : nil ];
18 [ locationManager release ];
19 [ window release ];
20 [ super dealloc ];
21 }
236 CHAPTER 43. LECTURE 43

protocols are like interfaces in other langs i.e. no implementation. protocols for delegations delegate protocols.
can be used to ask things from the delegate or inform of updates. can be @optional methods. by default required.
here all were optional. every object implements respondsToSelector: something like this (above). class has to declare
protocols it implements like other langs. no warning anymore.
memory and delegation. delegates are usually controllers. delegates never retained. retain cycle. assign attrib.
237

weak reference. lets display a map of current location.


Several instances of MKAnnotationView appear as icons on the MKMapView. An MKMapView displays the map
and the labels for the recorded locations. A UIActivityIndicatorView indicates that the device is working and not
stalled. A UITextField allows the user to input text to label the current location on the map.
drag the map view onto UIWindow.
1 # import < MapKit / MapKit .h >
2
3
4 @interface W h e re a mi A p pD e l eg a t e : NSObject
5 < UIApplicationDelegate , CLLocationManagerDelegate >
6 {
7 CLLocationManager * locationManager ;
8 IBOutlet MKMapView * worldView ;
9 IBOutlet U I Ac ti v it y In di c at o r V i e w * activ ityInd icator ;
10 IBOutlet UITextField * loc ati on Ti tl eF ie ld ;
11 }
12 @property ( nonatomic , retain ) IBOutlet UIWindow * window ;
13 @end

all we do is set showsUserLocation property of MKmapview and it will show users location.
1 - ( BOOL ) application :( UIApplication *) application
2 d i d F i n i s h L a u n c h i n g W i t h O p t i o n s :( NSDictionary *) launchOptions
3 {
4 locationManager = [[ CLLoc ationManager alloc ] init ];
5 [ locationManager setDelegate : self ];
6 [ locationManager setDis tanceF ilter : k C L D i s t a n c e F i l t e r N o n e ];
7 [ locationManager se tD es ir ed Ac cu rac y : k C L L o c a t i o n A c c u r a c y B e s t ];
8 // [ locationManager st artU p d a t i n g L o c a t i o n ];
9 [ worldView s e t S h o w s U s e r L ocation : YES ];
10 // This line may say self . window , don ’ t worry about that
11 [[ self window ] makeKeyAndVisib le ];
238 CHAPTER 43. LECTURE 43

12 return YES ;
13 }
14
15
16 - ( void ) mapView :( MKMapView *) mv di dUpda teUs erLoc atio n :( MKUserLocation *) u
17 {
18 C L L o c a t i o n C o o r d i n a t e 2 D loc = [ u coordinate ];
19 M KCo or di na te Re gi on region = M K C o o r d i n a t e R e g i o n M a k e W i t h D i s t a n c e ( loc , 250 , 250);
20 [ worldView setRegion : region animated : YES ];
21 }
too big the dot on world map. want to zoom in. when to send a zoom in message. instead MKMapView has
delegate.

1 # import < Foundation / Foundation .h >


2 # import < CoreLocation / CoreLocation .h >
3 # import < MapKit / MapKit .h >
4 @interface MapPoint : NSObject < MKAnnotation >
5 {
6 NSString * title ;
7 C L L o c a t i o n C o o r d i n a t e 2 D coordinate ;
8 }
9 // A new designated initializer for instances of MapPoint
10 - ( id ) i ni tWit hC oo rd ina te :( C L L o c a ti on Co ord in at e2D ) c title :( NSString *) t ;
11 // This isa required property from MKAnnotation
12 @property ( nonatomic , readonly ) CL Lo cat io nC oo rdi na te 2D coordinate ;
13 // This is an optional property from MKAnnotation
14 @property ( nonatomic , copy ) NSString * title ;
15 @end
lets add an annotation. MKAnnotation protocol lets create a new MapPoint class.
1 # import " MapPoint . h "
2 @implementation MapPoint
3 @synthesize coordinate , title ;
4 - ( id ) i ni tWit hC oo rd ina te :( C L L o c a ti on Co ord in at e2D ) c title :( NSString *) t
5 {
6 self = [ super init ];
7 if ( self ){
8 coordinate = c ;
9 [ self setTitle : t ];
10 }
11 return self ;
12 }
13 - ( void ) dealloc
14 {
15 [ title release ];
16 [ super dealloc ];
239

17 }
18 @end
in xib file set text fields delegate to be the instance of WhereamiAppDelegate. this means we can implement
methods from UITextFieldDelegate.
1 @interface W h er e a mi A p pD e l eg a t e : NSObject
2 < UIApplicationDelegate , CLLocationManagerDelegate ,
3 MKMapViewDelegate , UITextFieldDelegate >
4
5
6
7 - ( BOOL ) t e x t F i e l d S h o u l d R e t u r n :( UITextField *) tf
8 {
9 // This method isn ’ t implemented yet - but will be soon .
10 [ self findLocation ];
11 [ tf r e s i g n F i r st R e s p o n d e r ];
12 return YES ;
13 }
14
15 @interface W h e re a mi A p pD e l eg a t e : NSObject
16 < UIApplicationDelegate , CLLocationManagerDelegate ,
17 MKMapViewDelegate , UITextFieldDelegate >
18 {
19 CLLocationManager * locationManager ;
20 IBOutlet MKMapView * worldView ;
21 IBOutlet U I Ac ti v it y In di c at o r V i e w * activ ityInd icator ;
22 IBOutlet UITextField * loc ati on Ti tl eF ie ld ;
23 }
24 @property ( nonatomic , retain ) IBOutlet UIWindow * window ;
25 - ( void ) findLocation ;
26 - ( void ) foundLocation :( CLLocation *) loc ;
27 @end
28
29
30 # import " W hereamiAppDelegate . h "
31 # import " MapPoint . h "
32 @implementation W h er e a mi A p pD e l eg ate
33
34 - ( void ) findLocation
35 {
36 [ locationManager s t a r t U p d a t i n g L o c a t i o n ];
37 [ activityIndicator startAnimating ];
38 [ locationTitleField setHidden : YES ];
39 }
40
41 - ( void ) foundLocation :( CLLocation *) loc
42 {
43 C L L o c a t i o n C o o r d i n a t e 2 D coord = [ loc coordinate ];
44 // Create an instance of MapPoint with the current data
45 MapPoint * mp = [[ MapPoint alloc ] i ni tWi th Co or di na te : coord
46 title :[ lo ca ti on TitleField text ]];
47 // Add it to the map view
48 [ worldView addAnnotation : mp ];
49 // MKMapView retains its annotations , we can release
50 [ mp release ];
51 // Zoom the region to this location
52 M KCo or di na te Re gi on region = M K C o o r d i n a t e R e g i o n M a k e W i t h D i s t a n c e ( coord , 250 , 250);
53 [ worldView setRegion : region animated : YES ];
54 [ locationTitleField setText : @ ""];
240 CHAPTER 43. LECTURE 43

55 [ activityIndicator stopAnimating ];
56 [ locationTitleField setHidden : NO ];
57 [ locationManager s t o p U p d a t i n g L o c a t i o n ];
58 }
59
60 - ( void ) locationManager :( CLL ocationManager *) manager
61 d id U p da t e To L o ca t i on :( CLLocation *) newLocation
62 fromLocation :( CLLocation *) oldLocation
63 {
64 NSLog ( @ "\% @ " , newLocation );
65 // How many seconds ago was this new location created ?
66 NSTimeInterval t = [[ newLocation timestamp ] timeIntervalSinceNow ];
67 // CLLocationManagers will return the last found location of the
68 // device first , you don ’ t want that data in this case .
69 // If this location was made more than 3 minutes ago , ignore it .
70 if (t < -180){
71 // This is cached data , you don ’ t want it , keep looking
72 return ;
73 }
74 [ self foundLocation : newLocation ];
75 }
Chapter 44

Lecture 44

Lets discuss touch events. touch events are hallmark of mobile devices lets make a drawing app like brushes.

a finger or fingers touches the screen - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

a finger or fingers move across the screen (This message is sent repeatedly as a finger moves.) - (void)touchesMoved:(NSSet
*)touches withEvent:(UIEvent *)event;

a finger or fingers is removed from the screen - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;

a system event, like an incoming phone call, interrupts a touch before it ends - (void)touchesCancelled:(NSSet
*)touches withEvent:(UIEvent *)event;

241
242 CHAPTER 44. LECTURE 44

events added to event queue. A UITouch object created and tracked for a finger. set of UITouches passed. one per
finger. only the moving, begining, or ending event passed. lets make our app.
1 # import < Foundation / Foundation .h >
2 @interface Line : NSObject {
3 CGPoint begin ;
4 CGPoint end ;
5 }
6 @property ( nonatomic ) CGPoint begin ;
7 @property ( nonatomic ) CGPoint end ;
8 @end
9
10 # import " Line . h "
11 @implementation Line
12 @synthesize begin , end ;
13 @end
14
15
16 # import < Foundation / Foundation .h >
17 # import < UIKit / UIKit .h >
243

18 @interface TouchDrawView : UIView


19 {
20 N SM u t ab l e Di c t io n a ry * linesInProcess ;
21 NSMutableArray * completeLines ;
22 }
23 - ( void ) clearAll ;
24 @end

use IB to set the view to default


1 # import " TouchDrawView . h "
2 # import " Line . h "
3 @implementation TouchDrawView
4 - ( id ) initWithCoder :( NSCoder *) c
5 {
6 self = [ super initWithCoder : c ];
7 if ( self ){
8 linesInProcess = [[ NSMutableDictionary alloc ] init ];
9 completeLines = [[ NSMutableArray alloc ] init ];
10 [ self s e t M u l t i p l e T o u c h E n a b l e d : YES ];
11 }
12 return self ;
13 }
14
15
16 - ( void ) dealloc
17 {
18 [ linesInProcess release ];
19 [ completeLines release ];
20 [ super dealloc ];
21 }
22
23 - ( void ) clearAll
24 {
25 // Clear the collections
26 [ linesInProcess removeAllObjects ];
27 [ completeLines removeAllObjects ];
28 // Redraw
29 [ self setNeedsDisplay ];
30 }
31
32 - ( void ) drawRect :( CGRect ) rect
33 {
34 CGContextRef context = U I G r a p h i c s G e t C u r r e n t C o n t e x t ();
35 C G C o n t e x t S e t L i n e W i d t h ( context , 10.0);
36 C GC o n te x t Se t L in e C ap ( context , kCGLineCapRound );
37 // Draw complete lines in black
38 [[ UIColor blackColor ] set ];
39 for ( Line * line in completeLines ){
40 C G C o n t e x t M o v e T o P o int ( context , [ line begin ]. x , [ line begin ]. y );
41 C G C o n t e x t A d d L i n e T oP oi n t ( context , [ line end ]. x , [ line end ]. y );
42 C G Co n t ex t St r o ke P a th ( context );
43 }
44 // Draw lines in process in red
45 [[ UIColor redColor ] set ];
46 for ( NSValue * v in linesInProcess ){
47 Line * line = [ linesInProcess objectForKey : v ];
48 C G C o n t e x t M o v e T o P o int ( context , [ line begin ]. x , [ line begin ]. y );
49 C G C o n t e x t A d d L i n e T oP oi n t ( context , [ line end ]. x , [ line end ]. y );
50 C G Co n t ex t St r o ke P a th ( context );
244 CHAPTER 44. LECTURE 44

51 }
52 }
53
54 - ( void ) touchesBegan :( NSSet *) touches
55 withEvent :( UIEvent *) event
56 {
57 for ( UITouch * t in touches ){
58 // Is this a double tap ?
59 if ([ t tapCount ] > 1){
60 [ self clearAll ];
61 return ;
62 }
63 // Use the touch object ( packed in an NSValue ) as the key
64 NSValue * key = [ NSValue valueWithPointer : t ];
65 // Create a line for the value
66 CGPoint loc = [ t locationInView : self ];
67 Line * newLine = [[ Line alloc ] init ];
68 [ newLine setBegin : loc ];
69 [ newLine setEnd : loc ];
70 // Put pair in dictionary
71 [ linesInProcess setObject : newLine forKey : key ];
72 // There isa memory leak in this method
73 // You will find it using Instruments in the next chapter
74 }
75 }
76
77 - ( void ) touchesMoved :( NSSet *) touches
78 withEvent :( UIEvent *) event
79 {
80 // Update linesInProcess with moved touches
81 for ( UITouch * t in touches ){
82 NSValue * key = [ NSValue valueWithPointer : t ];
83 // Find the line for this touch
84 Line * line = [ linesInProcess objectForKey : key ];
85 // Update the line
86 CGPoint loc = [ t locationInView : self ];
87 [ line setEnd : loc ];
88 }
89 // Redraw
90 [ self setNeedsDisplay ];
91 }
92
93 - ( void ) touchesEnded :( NSSet *) touches
94 withEvent :( UIEvent *) event
95 {
96 [ self endTouches : touches ];
97 }
98
99
100 - ( void ) touchesCancelled :( NSSet *) touches
101 withEvent :( UIEvent *) event
102 {
103 [ self endTouches : touches ];
104 }
105
106 - ( void ) endTouches :( NSSet *) touches
107 {
108 // Remove ending touches from dictionary
109 for ( UITouch * t in touches ){
245

110 NSValue * key = [ NSValue valueWithPointer : t ];


111 Line * line = [ linesInProcess objectForKey : key ];
112 // If this is a double tap , ’ line ’ will be nil ,
113 // so make sure not to add it to the array
114 if ( line ){
115 [ completeLines addObject : line ];
116 [ linesInProcess removeObjectForKey : key ];
117 }
118 }
119 // Redraw
120 [ self setNeedsDisplay ];
121 }
246 CHAPTER 44. LECTURE 44

Lets use Blocks in ios 4.0 to change colors based on angle and length.
1 @interface Line : NSObject {
2 CGPoint begin ;
3 CGPoint end ;
4 UIColor * color ;
5 }
6 @property ( nonatomic ) CGPoint begin ;
7 @property ( nonatomic ) CGPoint end ;
8 @property ( nonatomic , retain ) UIColor * color ;
9 @end
10
11 @implementation Line
12 @synthesize color ;
13 - ( id ) init
14 {
15 self = [ super init ];
16 if ( self ){
17 [ self setColor :[ UIColor blackColor ]];
247

18 }
19 return self ;
20 }
21 - ( void ) dealloc
22 {
23 [ color release ];
24 [ super dealloc ];
25 }
26
27
28
29 - ( void ) drawRect :( CGRect ) rect {
30 CGContextRef context = U I G r a p h i c s G e t C u r r e n t C o n t e x t ();
31 C G C o n t e x t S e t L i n e W i d t h ( context , 10.0);
32 C GC o n te x t Se t L in e C ap ( context , kCGLineCapRound );
33 // [[ UIColor blackColor ] set ];
34 for ( Line * line in completeLines ){
35 [[ line color ] set ];
36 C G C o n t e x t M o v e T o P o int ( context , [ line begin ]. x , [ line begin ]. y );
37 C G C o n t e x t A d d L i n e T oP oi n t ( context , [ line end ]. x , [ line end ]. y );
38 C G Co n t ex t St r o ke P a th ( context );
39 }
40 [[ UIColor redColor ] set ];
41 for ( NSValue * v in linesInProcess ){
42 Line * line = [ linesInProcess objectForKey : v ];
43 C G C o n t e x t M o v e T o P o int ( context , [ line begin ]. x , [ line begin ]. y );
44 C G C o n t e x t A d d L i n e T oP oi n t ( context , [ line end ]. x , [ line end ]. y );
45 C G Co n t ex t St r o ke P a th ( context );
46 }
47 }

1 - ( void ) t r a n s f o r m L i n e C o l o r s W i t h B l o c k :( UIColor * (^)( Line *)) colorForLine


2 {
3 for ( Line * l in completeLines ){
248 CHAPTER 44. LECTURE 44

4 UIColor * c = colorForLine ( l );
5 [ l setColor : c ];
6 }
7 [ self setNeedsDisplay ];
8 }
9
10
11
12 - ( void ) colorize
13 {
14 // Vertical means more red , horizontal means more green ,
15 // longer means more blue
16 // A block variable named colorScheme is created here :
17 UIColor * (^ colorScheme )( Line *)= ^( Line * l ){
18 // Compute delta between begin and end points
19 // for each component
20 float dx = [ l end ]. x - [ l begin ]. x ;
21 float dy = [ l end ]. y - [ l begin ]. y ;
22 // If dx is near zero , red = 1 , otherwise , use slope
23 float r = ( fabs ( dx ) < 0.001? 1.0: fabs ( dy / dx ));
24 // If dy is near zero , green = 1 , otherwise , use inv . slope
25 float g = ( fabs ( dy ) < 0.001? 1.0: fabs ( dx / dy ));
26 // blue = length over 300
27 float b = hypot ( dx , dy )/ 300.0;
28 return [ UIColor colorWithRed : r green : g blue : b alpha :1];
29 };
30 // Pass this colorScheme block to the method
31 // that will iterate over every line and assign
32 // the computed color to that line
33 [ self t r a n s f o r m L i n e C o l o r s W i t h B l o c k : colorScheme ];
34 }

colors when you shake.


1 - ( BOOL ) c a n B e c o m e F i r s t R e s p o n d e r
2 {
3 return YES ;
4 }
5 - ( void ) didMoveToWindow
6 {
7 [ self b e c o m e F i rs t R e s p o n d er ];
8 }
9 - ( void ) motionBegan :( UIEventSubtype ) motion
10 withEvent :( UIEvent *) event
11 {
12 [ self colorize ];
13 }

blocks capture variables like anonymous functions in C#. inline block objects (values copied). blocks are an
alternate to callbacks. blocks are used for GCD. kind of like tasks.
grand central dispatch. dispatch queues pools of threads managed.
threads.
1 - ( void ) doCalculation {
2 /* Do your calculation here */
3 }
4 - ( void ) c a l c u l a t i o n T h r e a d E n t r y {
5 @autoreleasepool {
6 NSUInteger counter = 0;
7 while ([[ NSThread currentThread ] isCancelled ] == NO ){
249

8 [ self doCalculation ];
9 counter ++;
10 if ( counter >= 1000){
11 break ;
12 }
13 }
14 }
15 }
16 - ( BOOL ) application :( UIApplication *) application
17 d i d F i n i s h L a u n c h i n g W i t h O p t i o n s :( NSDictionary *) launchOptions {
18 /* Start the thread */
19 [ NSThread d e t a c h N e w T h r e a dS e le c to r : @selector ( ca lc ula ti on Thr ea dE ntr y )
20 toTarget : self
21 withObject : nil ];
22 self . window = [[ UIWindow alloc ] initWithFrame :
23 [[ UIScreen mainScreen ] bounds ]];
24 self . window . backgroundColor = [ UIColor whiteColor ];
25 [ self . window makeKe yAndVisible ];
26 return YES ;
27 }

calling back on UI thread

1 dispatch_queue_t mainQueue = di s pa t c h _ g e t _ m a i n _ q u e u e ();


2 dispatch_async ( mainQueue , ^( void ) {
3 [[[ UIAlertView alloc ] initWithTitle : @ " GCD "
4 message : @ " GCD is amazing !"
5 delegate : nil
6 cancelButtonTitle : @ " OK "
7 otherButtonTitles : nil , nil ] show ];
8 });
250 CHAPTER 44. LECTURE 44

1 void (^ printFrom1To1000 )( void ) = ^{


2 NSUInteger counter = 0;
3 for ( counter = 1;
4 counter <= 1000;
5 counter ++){
251

6 NSLog ( @ " Counter = % lu - Thread = % @ " ,


7 ( unsigned long ) counter ,
8 [ NSThread currentThread ]);
9 }
10 };
11
12
13 dispatch_queue_t concurrentQueue =
14 d i s p a t c h _ g e t _ g l o b a l _ q u e u e ( DISPATCH_QUEUE_PRIORITY_DEFAULT , 0);
15 dispatch_sync ( concurrentQueue , printFrom1To1000 );
16 dispatch_sync ( concurrentQueue , printFrom1To1000 );
252 CHAPTER 44. LECTURE 44
Chapter 45

Lecture 45

lets download an image asynchronously.


1 dispatch_queue_t concurrentQueue =
2 d i s p a t c h _ g e t _ g l o b a l _ q u e u e ( DISPATCH_QUEUE_PRIORITY_DEFAULT , 0);
3 dispatch_async ( concurrentQueue , ^{
4 __block UIImage * image = nil ;
5 dispatch_sync ( concurrentQueue , ^{
6 /* Download the image here */
7 });
8 dispatch_sync ( d i s p a t c h _ g e t _m ai n _q u eu e () , ^{
9 /* Show the image to the user here on the main queue */
10 });
11 });
12
13
14 - ( void ) viewDidAppear :( BOOL ) paramAnimated {
15 dispatch_queue_t concurrentQueue =
16 d i s p a t c h _ g e t _ g l o b a l _ q u e u e ( DISPATCH_QUEUE_PRIORITY_DEFAULT , 0);
17 dispatch_async ( concurrentQueue , ^{
18 __block UIImage * image = nil ;
19 dispatch_sync ( concurrentQueue , ^{
20 /* Download the image here */
21 /* iPad ’ s image from Apple ’ s website . Wrap it into two
22 lines as the URL is too long to fit into one line */
23 NSString * urlAsString = @ " http :// images . apple . com / mobileme / features "\
24 "/ images / i p a d _ f i n d y o u r i p a d _ 2 0 1 0 0 5 1 8 . jpg ";
25 NSURL * url = [ NSURL URLWithString : urlAsString ];
26 NSURLRequest * urlRequest = [ NSURLRequest requestWithURL : url ];
27 NSError * downloadError = nil ;
28 NSData * imageData = [ NSURLConnection
29 se nd Sy nch ro no usR eq ue st : urlRequest
30 retu rningR espons e : nil
31 error :\& downloadError ];
32 if ( downloadError == nil \&\&
33 imageData != nil ){
34 image = [ UIImage imageWithData : imageData ];
35 /* We have the image . We can use it now */
36 }
37 else if ( downloadError != nil ){
38 NSLog ( @ " Error happened = \% @ " , downloadError );
39 } else {
40 NSLog ( @ " No data could get downloaded from the URL .");
41 }

253
254 CHAPTER 45. LECTURE 45

42 });
43 dispatch_sync ( d i s p at ch _ ge t _m ai n _q u eu e () , ^{
44 /* Show the image to the user here on the main queue */
45 if ( image != nil ){
46 /* Create the image view here */
47 UIImageView * imageView = [[ UIImageView alloc ]
48 initWithFrame : self . view . bounds ];
49 /* Set the image */
50 [ imageView setImage : image ];
51 /* Make sure the image is not scaled incorrectly */
52 [ imageView setContentMode : U I V i e w C o n t e n t M o d e S c a l e A s p e c t F i t ];
53 /* Add the image to this view controller ’ s view */
54 [ self . view addSubview : imageView ];
55 } else {
56 NSLog ( @ " Image isn ’ t downloaded . Nothing to display .");
57 }
58 });
59 });
60 }
255

generate 10k random numbers if needed. read 10K random numbrs, sort n display. UITableView.

1 - ( NSString *) fileLocation {
2 /* Get the document folder ( s ) */
3 NSArray * folders =
4 N S S e a r c h P a t h F o r D i r e c t o r i e s I n D o m a i n s ( NSDocumentDirectory ,
256 CHAPTER 45. LECTURE 45

5 NSUserDomainMask ,
6 YES );
7 /* Did we find anything ? */
8 if ([ folders count ] == 0){
9 return nil ;
10 }
11 /* Get the first folder */
12 NSString * documentsFolder = [ folders objectAtIndex :0];
13 /* Append the file name to the end of the documents path */
14 return [ documentsFolder
15 s t r i n g B y A p p e n d i n g P a t h C o m p o n e n t : @ " list . txt "];
16 }
17 - ( BOOL ) h a s F i l e A l r e a d y B e e n C r e a t e d {
18 BOOL result = NO ;
19 NSFileManager * fileManager = [[ NSFileManager alloc ] init ];
20 if ([ fileManager fileExistsAtPath :[ self fileLocation ]]){
21 result = YES ;
22 }
23 return result ;
24 }
25
26
27
28
29 dispatch_queue_t concurrentQueue =
30 d i s p a t c h _ g e t _ g l o b a l _ q u e u e ( DISPATCH_QUEUE_PRIORITY_DEFAULT , 0);
31 /* If we have not already saved an array of 10 ,000
32 random numbers to the disk before , generate these numbers now
33 and then save them to the disk in an array */
34 dispatch_async ( concurrentQueue , ^{
35 NSUInteger n u m b e r O f V a l u e sRe qu ir ed = 10000;
36 if ([ self h a s F i l e A l r ea d y B e e n C r e a t e d ] == NO ){
37 dispatch_sync ( concurrentQueue , ^{
38 NSMutableArray * arrayOfRandomNumbers =
39 [[ NSMutableArray alloc ] initWithCapacity : n u m b e r O f V a l u e s R e q u i r e d ]
40 NSUInteger counter = 0;
41 for ( counter = 0;
42 counter < num be rO fVa lu es Req ui re d ;
43 counter ++){
44 unsigned int randomNumber =
45 arc4random () % (( unsigned int ) RAND_MAX + 1);
46 [ arrayOfRandomNumbers addObject :
47 [ NSNumber numb erWi thUns igne dInt : randomNumber ]];
48 }
49 /* Now let ’ s write the array to disk */
50 [ arrayOfRandomNumbers writeToFile :[ self fileLocation ]
51 atomically : YES ];
52 });
53 }
54 __block NSMutableArray * randomNumbers = nil ;
55 /* Read the numbers from disk and sort them in an
56 ascending fashion */
57 dispatch_sync ( concurrentQueue , ^{
58 /* If the file has now been created , we have to read it */
59 if ([ self h a s F i l e A l r e a d y B e e n C r e a t e d ]){
60 randomNumbers = [[ NSMutableArray alloc ]
61 in it Wi thC on te nts Of Fi le :[ self fileLocation ]];
62 /* Now sort the numbers */
63 [ randomNumbers sortUsingComparator :
257

64 ^ NSComparisonResult ( id obj1 , id obj2 ) {


65 NSNumber * number1 = ( NSNumber *) obj1 ;
66 NSNumber * number2 = ( NSNumber *) obj2 ;
67 return [ number1 compare : number2 ];
68 }];
69 }
70 });
71
72 dispatch_async ( d i s p a t c h _ g et _ ma i n_ qu e ue () , ^{
73 if ([ randomNumbers count ] > 0){
74 /* Refresh the UI here using the numbers in the
75 randomNumbers array */
76 }
77 });
78 });

dispatch after dispatches after a delay. timers. dependencies. group of tasks.


Course overview.
Where did we start from. Where to go from here.
started with handling multiple input sources in C++, discovered message loop refactored, understood events,
event processing, source, target, event object downloaded VS and C# language and its features, examples of OO
programming in C#.
Discussed delegates, events, exception handling, attributes, collections. worked with XML docs. wpf history and
xaml. property elements and markup extensions. mixing xaml and procedural code.
Discussed logical and visual trees. dependency properties. change notifications. prop val. inheritance. attached
properties. sizing, positioning, and transforming elements.
transforms. panels stackpanel, wrappanel, canvas, dockpanel, grid. content overflow, clipping, scaling, scrolling.
events, input events, attached events, touch events (manipulation... high level). commands, persisting and restoring.
Covered resources. binary and logical. static vs dynamic logical resources. data binding, binding object, binding
markup extension. binding to collection, implicit datacontext. datatemplates and value converters. customizing
collection view. sorting, filtering, grouping, navigating. data providers. xml and object data providers.
concurrency and threads. captured variables. synchronization context and tasks. continuations. task completion
source. sync vs async.
course grained vs fine grained sync. async wait keywords in C# 5.0. parallelism. cancellation and progress
reporting. task combinator and task parallel library. Parallel.Invoke, For, ForEach. concurrent collections.
JS history and jQuery library. HTML CSS JS. client side vs server side. dom. jQuery selectors and filters. changing
attributes and elements. events and animations. ajax. xmlhttprequest, get put load. JSON.
mobile development. objective C history. call syntax and OO concepts. properties. retain count and memory
management. xib, nib, iboutlet, ibaction, interface builder.
button events and a QA app. protocols and delegates. location and map kits. touch events and blocks. GCD and
multithreading.
CS411-Visual Basics
(Solved Macq’s)
LECTURE FROM
(22 to 45)
Junaidfazal08@gmail.com JUNAID MALIK
Bc190202640@vu.edu.pk FOR MORE VISIT 0304-1659294
VULMSHELP.COME
AL-JUNAID TECH INSTITUTE
Question # 1: In Xaml browser application, how much isolated memory we
can use?
o 256 kb

o 128 kb

o 512 kb PG # 132

o 1024 kb

Question # 2: Which property will be used if we want to restrict the user


to don‟t increase thewidth of a WPF element from a specific amount?

o MaxWidth Page # 81

o MaximumWidth

o WidthMaximum

o None of given options


Question # 3: Which one is the correct syntax for declaring attribute?

o [Obsolete] page # 42

o {Obsolete}

o (Obsolete)

o *Obsolete

Question # 4: In C#, comments are written using .

o # and */ /*

o // and /* */ page # 14

o # and /*

o // and */ /*

Question # 5: An event that is raised whenever the value of


"CanExecute" changes is knownas .

o CanExecute
AL-JUNAID TECH INSTITUTE
o CanExecuteChanged

o Command

o Execute
Question # 6: is an event that is introduced into an event
processing system byan event producer.

o Event Producer

o Event Consumer

o Raw Event Page # 11

o Event Stream

Question # 7: Whenever an attribute value is enclosed in curly


braces "{}", the XAMLcompiler/parser treats it as a/an rather
than a/an .

o Markup event, property

o Markup property, Event

o Literal string, Markup extension value

o Markup extension value, literal string page # 65

Question # 8: HTML is called layer.


o Physical
o Presentation

o Behavioral

o Structural PG # 195

Question # 9: CSS is called layer.

o Physical

o Presentation PG # 179

o Behavioral
AL-JUNAID TECH INSTITUTE
o Structural

Question # 10: JS (JavaScript) is called layer.

o Physical

o Presentation

o Behavioral PG # 179

o Structural

Question # 11: Shift key is true if the shift key is when the
event occurs.

o Down PG # 187

o Up

o None of the given

o Move
Question # 12: Which of the following response show internal server error?

o 404

o 500

o 200

o 304

Question # 13: The original name of JavaScript was .

o JavaScript

o LiveScript PG # 179

o wireScript
AL-JUNAID TECH INSTITUTE
o none of the given

Question # 14: One of the ways to create an instance of a class is .

o System array PG # 14

o Factory method

o Sequential heap

o XAML compiler

Question # 15: Which "transform" property can help us to flip the element
from its center?

o ScaleY

o None of given options

o ScaleX

o RenderTransformOrigin PG # 85

Question # 16: If we want that "Stretch" property of child element takes


the available "heightor width of Parent" and shape of child elements
doesn‘t change, then we should write ―Stretch
= ‖.

o 1

o Fill PG # 100

o UniformToFill

o Uniform
Question # 17: When a button makes itself disabled, then the value of
"Focusable" property is
?
AL-JUNAID TECH INSTITUTE
o False

o Null

o True

o None of the given options

Question # 18: ManipulationCompleted gets raised after _ is


raised for all fingers.

o TouchMove

o TouchUp PG # 116

o TouchDown

o TouchRight

Question # 19: CSS is a language.

o Object Oriented

o Structuring

o Formatting PG # 180

o Non

Question # 20: JavaScript code is written inside file having extension .

o JSC

o JS

o Javasript

o JVS
Question # 21: Which of the following is TRUE about Object data
providers?

o This is useful for binding XML data


o This is useful for binding objects which are designed for binding
AL-JUNAID TECH INSTITUTE
o This is useful for binding objects which are not designed for
binding PG # 151
o None of the given

Question # 22: Which of the following is TRUE about IsAsync in context of


data binding?

o This is used to access the property of an object in background

o This is used to access the property of an object in foreground

o This is used to create data source object in background

o This is used to create data source object in foreground

Question # 23: Refresh" is a predefined building command classified as:

o Navigation command PG # 121

o Media command

o Application command

o Editing command
Question # 24: Which of the following is NOT true about threads?

o Threads are useful to handle simultaneous requests.

o A program can have more than one thread

o Data cannot be share among the threads.

o Each thread can proceed independently of other threads.

Question # 25: Which of the following is correct way to start execution


of a thread objectnamed as myThread?

o myThread.Go();

o myThread.Start(); PG # 156

o myThread.Begin();
AL-JUNAID TECH INSTITUTE
o myThread.initialize ();

Question # 26: The best way to implement simple threading in Windows


Forms programs is touse the class.

o BackgroundWorker

o Windowsform

o Simplethreadworker

o None of the given


Question # 27: A child Window is just like any other top-level window:
but it automatically gets closed when the parent is closed and
minimized when the parent is minimized. Such aWindow is sometimes
called a .

o Modeless Dialog PG # 124

o Inherited Window

o Super Window

o Sibling Window
Question # 28: In .Net, a task that does not return a value is represented
by the
.

o System.Threading.Tasks.Task<TResult>

o System.Threading.Tasks.Task

o System.Threarding.Tasks.

o None of the given options

Question # 29: In TAP, progress is handled through an interface,


which ispassed to the asynchronous method a parameter.

o IProgress<T>

o Progress<T> (Action<T>)
AL-JUNAID TECH INSTITUTE
o Iprogress (T)

o Progress<T>
Question # 30: In navigation Windows, the frames are more like a/an .

o HTML frame Page #128

o .Net frame

o Java frame
o Image frame
Question # 31: keeps the navigation history in

navigation based applications.

o Journal
o Frame
o Web browser
o Web page
Question # 32: URI stands for:
o Universal Resource Identifier
o Uniform Resource Identifier
o Uniform Resource Identification
o Universal Resource Identification

Question # 33: In Objective-C, which of the following statements can be


used to displaysomething in the "answer" field?
o [answerField:answer];
o [setTextanswer];
o [answerFieldsetText:answer]; PG # 208
o [ setText answeranswerField]
Question # 34: Which one of the following is used, if we want to add
resources in Window?
o <windowResources></windowResources>
o <windowsResources></windowsResources>
o <window.Resources></window.Resources> PG #
136
Question # 36: Which of the following is used to set the view to default?
o NSCoder
AL-JUNAID TECH INSTITUTE
o clearAll
o IB PG # 217
o Redraw
Question # 37: In context of data binding, when we want to apply both
sorting and groupingtogether then the rule is that .
o Grouping will be applied before sorting
o Sorting will be applied before Grouping PG # 150
o Both shall be applied different properties
o None of the given
Question # 38: What is the word ―Color‖ in given below code? UIColor" (^)
(Line*,int anotherArg)
o Return Type of Block
o Notation to specify that it is a block
o Name of Variable
o Block Variable PG # 222
o <windows.Resources></windows.Resources>
Question # 35: If we assign an NSString to a possession for its
possessionName, and then werelease the string, it will be.
o Allocated
o Decreased
o Instance created
o Destroyed
Question # 39: helps us in provisioning ease of access
to data source for databinding.
o Data Provider
o Interfaces
o Source
o Data Organizer
Question # 40: What is the purpose of given below code?
[self.viewaddSubview:imageView];
o To make sure that image is not scaled incorrectly
o To create the image View
o To set the image
o Add the image to this View controllers PG # 226
Question # 41: What is the purpose of
given below code? NSArray *folders
NSSearchPathForDirectoriesInDomains(NSD
ocumentDirectory,NSUserDomaianIask,
YES);
o Get the document folder(s) PG # 226
o Create the folder
AL-JUNAID TECH INSTITUTE
o Get the first folder
o Add the image to first folder
Question # 42: Which JQuery object is used with bind() function to pass
data to an eventhandling function?
o Target
o Bind
o Data PG # 187
o Jobj
Question # 43: Which of the following technologies is not used in AJAX?
o DOM
o DHTML
o Flash
o Css

Question # 44: Which function is used to create cancel button event of


dialog box .
o OnInitCancel()
o OnClickCancel()
o CancelClick()

o OnCancel()
Question # 45: Consider the following C# code segment:
button.Background = (Brush) new BrushConverter().ConvertFrom
(―SystemColors.WindowBrush ‖ ); Which one of the following isequivalent
XAML code?

o <Button Background= ―SystemColors.WindowsBrush‖ />

o Button Background= ―SystemColor.WindowsBrush ‖ />

o <Button Background= ―SystemColor.WindowBrush ‖ />


o <Button Background= “SystemColors.WindowBrush”/>
PG # 132
Question # 46: Multi touch events are categorized into and .
o Touch events, touchup events
o Touchdown events, touchup events
o Advanced touch events, low‐level manipulation events
o Basic touch events, higher‐level manipulation events
Question # 47: Which of the following components generates an input
Event?
o Printer

o Multi Touch
AL-JUNAID TECH INSTITUTE
o Plotter
o Speaker
Question # 48: Using requires more overhead
than because of theextra tracking.
o StaticResource, DynamicResource
o DynamicResource, StaticResource PG # 137
o PermanentResource, TemporaryResource
o TemporaryResource, PermanentResource
Question # 49: We use "UIElement" property ClipToBounds= ―false‖ when
.

o We want area child element don‘t cross the boundary of parent


o None of given
o We want area of child element is allowed to cross the
boundary of parentPG # 97
o Parent area also increases on increasing of area of child element
Question # 50: is used to perform navigation.
o Session

o Hyperlink PG # 127

o Hypertext markup language code


o Internet protocol
Question # 51: To design a complex Interface, which of the following
technique is best toachieve the required results?
o Panels composed in three panels

o Panels composed within panels


o Panels composed in two panels
o Panels composed in single panel

Question # 52: Which of the following is not a string format property


throughout WPF?
o ContentStringFormat
o ItemStringFormat
o RowHeaderStringFormat

o StringFormat
Question # 53: In multi touch events, a/an id is
assigned to each individualevent.

o Device
o Processor
o CPU
AL-JUNAID TECH INSTITUTE
o Event
Question # 54: Commonly we have two types of custom command
bindings named as .
o StartBindings and StopBindings

o EventBindings and InstanceBindings

o ButtonBindings and TextboxBindings


o KeyBindings and MouseBindings PG # 122

Question # 55: Which of the following is an example of tunnel key event?


o Key up
o Preview key entered

o Preview key down

o Key down
Question # 56: In context of data binding, contains the
current item to get itsynchronized with data Source.
o String

o Template

o View

o List

Question # 57: and are the two important


properties of Bindingobject.

o Start, Destination

o Items, Selected

o Source, Path

o BindTo, BindFrom
Question # 58: Which one of the following panels is most powerful,
versatile andcustomizable?

o Grid Panel PG # 92

o Canvas panel
AL-JUNAID TECH INSTITUTE
o Doc panel

o Stack panel

Question # 59: In order to resize the row and column in Grid panel, is
used.
o Grid divider

o Grid compiler

o Grid converter

o Grid splitter PG # 95

Question # 60: Data binding is about tying together arbitrary .NET .

o Objects PG # 140

o Functions

o Properties

o Variables

Question # 61: supports the creation of applications


that run directly in a webbrowser.

o WPF

o C/C++

o C#

o HTML
Question # 62: Which of the following operation cannot be performed by
using a View?

o Grouping

o Filtering

o Sorting

o Searching PG # 146
Question # 63: To check that the user either pressed left Alt key or right
AL-JUNAID TECH INSTITUTE
Alt key, the is used.

o IsKeyDown

o IsDown

o keyboardDevice.IsKeyDown PG # 113

o KeyStates.IsKeyDown

Question # 64: In _ browser app, you


change"<TargetZone>Internet</TargetZone>"to
"<TargetZone>Custom</TargetZone>"
 Partial-trust
 Full-reject
 Partial-reject
 Full-trust

Question # 65: provides the logic behind the "Back" and


"Forward" buttons.

o Hyperlink

o Navigation Window

o IFrame

o Journal PG # 138

Question # 66: In multi touch events, when multiple fingers are


touching simultaneously,these events get raised for each finger.

o Independently

o Completely

o Partially

o Dependently

Question # 67: In a code segment, if the Visibility=‖Collapsed‖ then


which of the following events are not generated?

o Key down Events


AL-JUNAID TECH INSTITUTE
o Mouse Events PG # 113

o Routed Events

o Keyboard Events
Question # 68: A Window can spawn number of
additional Windows byinstantiating a Window‐derived Class and
calling Show (...).

o Four

o Any PG # 124

o Six

o Five

Question # 69: Frame has a property used in enabling or


disabling the bar.

o ShowsNavigationUI

o BlocknavigationUI

o NavigationUIVisibility PG # 129

o NavigationUIBlock

Question # 70: If we insert some objects in a single cell in Grid panel,


then these objects areplaced on

o One on Top of the other

o One after the other

o One on Bottom of the other

o One on Side of the other

Question # 71: A _ receives keyboard events only if it has


keyboard focus.

o Mouse

o Keyboard Controls
AL-JUNAID TECH INSTITUTE
o Keyboard

o UIElement
Question # 72: To remove data binding between the source and the
target, we can use
function.

o ClearBinding PG # 151

o ResetBinding

o StopBinding

o RemoveBinding

Question # 73: A/An screen is an image that appears while


a game or program isloading.

o Opening

o Initial

o Splash

o Startup

Question # 74: We can perform sorting through View by using an


object of class

o ViewOrder

o ViewDescription

o SortOrder

o SortDescription PG # 158
Question # 75: "Binding" technique binds two properties together and
keeps a
open.

o Memory location

o Selection
AL-JUNAID TECH INSTITUTE
o Choice

o Communication channel PG # 140

Question # 76: Which one of the following can be used to set dependency
property values?

o Temporary resource

o Permanent resource

o Dynamic resource PG # 137

o Static resource

Question # 77: Which one of the following is used, if we want to add


a window resource inprocedural code?

o Window.Resource.Add ();

o <Widows.Resources></Widows.Resources>

o Window.Resoruces.Add();

o NONE
Question # 78: We use "GetDefaultView" method of to get
the default View.

o CollectionViewSource PG # 146

o DataSource

o ViewDescription

o ViewCollection
Question # 79: In case of HTML page navigation, you must
use the of"Navigate"
that a URI.

o Overload, rejects

o IFrame, rejects

o IFrame, accepts
AL-JUNAID TECH INSTITUTE
o Overload, accepts

Question # 80: The Java programming language has a specific


class for creating splashscreens, called .

o Java.awt.start

o Java.lang.splash

o Java.start.screen

o Java.awt.SplashScreen
Question # 81: In case of integrating Navigation to XBAP,
"ShowNavigationUI" should be setto in order to bypass integration.

o False

o True

o Null

o 0

Question # 82: Which of the followings are keyboard events?

o Key entered, key exist

o Key strike, key release

o Key pressed, key released

o Key down, key up PG # 113

Question # 83: To plug custom logic, you need to add a to the


element thatwill execute the command or any parent element.

o Execute command

o Helpcanexecute

o CommandBinding

o RoutedUlCommand
AL-JUNAID TECH INSTITUTE
Question # 84: A class that implements the ‗lCommand‘ and
supports ‗bubbling‘ just like arouted event is known as .

o RoutedUlCommand PG # 121

o Canexecute

o Executed command

o CanexecuteChanged

Question # 85: Which of the following is not true about task completion
source?

o Provide exception handling facility

o Support result return facility

o Provide Continuation facility

o it is executable thing PG # 175

Question # 86: "JavaScript" is available in web browser.

o Interpreter

o Compiler

o Linker

o Conjunction
Question # 87: The "Task Based Asynchronous pattern" method returns
either a "Task" or a "Task<TResult>", based on whether the
corresponding method returns "void" ora type "TResult".

o Callback

o Return

o Synchronous

o Asynchronous

Question # 88: Which of the following C# Method reports a progress


AL-JUNAID TECH INSTITUTE
change?

o Finalize

o OnReport

o GetType

o GetHashCode

Question # 89: Threadpool is used to .

o To make easy the process of thread creation

o To make easy debugging process

o To save time of thread creation PG# 160

o To avoid complexity
Question # 90: Which of the following is not a part of "cancellation" task?

o The calling thread does forcibly end the task

o Notice and respond to the cancellation request in your user delegate

o Pass a cancellation token to your user delegate and optionally to the


task instance

o Create and start a cancelable task

Question # 91: DOM is a representation of data.


o Tree

o Graphical

o Object

o None of the given

Question # 92: which of the following Object creates a cancellation token?

o OperationCanceledtoken

o OperationCanceled
AL-JUNAID TECH INSTITUTE
o CancellationToken

o CancellationTokenSource PG#172

Question # 93: which of the following is not a "JQuery" filter?

o Even

o Odd

o Has

o Write PG#184

Question # 94: Which of the following ―Event‖ property is used to


show the ―distance (in pixels)‖ of the mouse pointer from the left edge
of the browser window?

o pageY

o pageX PG # 187

o ScreenX

o ScreenY

Question # 95: ―async‖ and keywords in C# are the


heart of asynchronousprograming.

o Return

o Await

o Wait

o String
Question # 96: Mode of binding is
opposite to OneWay mode ofbinding.

o OneWay To source PG#153

o TwoWay

o One Time
AL-JUNAID TECH INSTITUTE
o Two Time

Question # 97: Can add/remove/change ―CSS‖


properties based on input or mouse clicks.

o J#

o JQuery

o HTML

o None of the given option PG#180


Question # 98: ―JavaScript‖ is scripting Language.

o Interpreter

o Browser

o Server

o Client

Question # 99: solves ―JavaScript‖ complexity and browser


incompatibilities.

o Jhtml

o RQuery

o JQuery PG#179

o J#

Question # 100: is more than one thing happening at the


same time.

o Cohesion

o Congruence

o Coherence

o Concurrency
AL-JUNAID TECH INSTITUTE
Question # 101: Which of the following ―Event ―properties is used with
―key press event‖ to determine the numeric code for the key that was
pressed? .

o Page X

o Which PG#187

o Shift Key

o Target

Question # 102: Which of the following is correct way to temporarily


stop execution of athread object named as ―myThread‖ for 500
milisec?

o myThread.Sleep(0.50);

o myThread.Stop(0.05);

o myThread.Sleep(500);

o myThread.Stop(500);

Question # 103: HTML is a helper function.

o RQuery

o Browser

o jQuery PG#184

o JS
Question # 104: Which of the following server(s) support ―AJAX‖?

o Both SMTP and HTTP

o HTTP

o www

o SMTP

Question # 105: Why we use ―Alloc‖ message?


AL-JUNAID TECH INSTITUTE
o To create a class

o To create an instance

o To extend functions

o To inherent methods

Question # 106: Objective – c introduces messaging


in c?

o Smalltalk style PG# 197

o Short session

o Group

o New Style

Question # 107: Threadpool create and reduce real threads using


hillclimbing algo to
.

o To maximize CPU usage Pg#160

o To reduce the cost of thread creation

o To maximize memory utilization

o To minimize CPU usage

Question # 108: Which of the following is not handled by the ―Task Parallel
Library (TPL)‖?

o Partitioning of the work

o Progress report handling

o Scheduling of threads

o Scales the degree of concurrency


Question # 109: "Callback" method is used to the operation.
o Terminate
o Pause
AL-JUNAID TECH INSTITUTE
o Invoke
o Revoke
Question # 110: While dealing with "threads" in ".Net", one can avoid
performance bottlenecks and enhance the overall responsiveness of his
/ her application by using
programming.
o Multithreading programming
o Synchronous programming
o Parallel programming
o Asynchronous programming
Question # 111: Interact with web page layout

o Java script

o HTML

o XML

o DOM

Question # 112: are high order functions that compose,


combine, or otherwisemodify functions in useful and interesting ways.

o Combinators

o None of the given

o Separators

o Modifiers

Question # 113: Which of these are defined as the model object?

o UILabel *questionField;

o NSMutableArray *questions@field;

o NSMutableArray *questions; PG # 205

o Question= 0;
AL-JUNAID TECH INSTITUTE
Question # 114: Which of the following "Event" property is used to
show the "distance (inpixels)" of the mouse pointer from top edge of the
Monitor?

o ScreenY PG#187
o pageX
o pageY
o ScreenX

Question # 115: What is ―nil‖ like?

o Null Page # 197

o zero

o terminate

o move to new line


Question # 116: Which of the following "Event" property is used to
show the "distance (inpixels)" of the mouse pointer from top edge
of the browser window?

o pageY Page # 187

o pageX

o screenX

o screenY

Question # 117: Observe the following piece of code taken out from
Main() function: Thread myThread = new Thread (Go); myThread.Strat();
myThread.Join(); What will be the effect ofinstruction myThread.Join()?

o Execution of myThread will be joined with existing running threads

o myThread will be executed after Main thread is completed

o Main thread execution will be suspended till completion of


myThread

o Both Main thread and myThread can now

share the data Question # 118: What message


AL-JUNAID TECH INSTITUTE
is used to send to destroy the object?

o stop

o delete

o free

o release

Question # 119: What is NSMutableArray?

o Object

o Class Reference

o Method

o Group

Question # 120: AJAX stands for .

o Abstract JSON and XML

o Asynchronous JavaScript and XHtml

o Asynchronous JavaScript and XML


o Abstract Java and XML Library

Question # 121: What is the purpose of the following "JQuery" code?


$(‗#navbar a‘)

o Find all the element whose name is navbar and then find a
descendent a

o Find all the element whose name is navbar and then find a
ancestor a

o Find all the element whose ID is navbar and then find a


AL-JUNAID TECH INSTITUTE
descendent a

o Find all the element whose ID is navbar and then find a ancestor
a

Question # 122: The pairing of labels and arguments is an important


feature of .

o C++

o Scripts

o Objective-C page # 197

o PHP
Question # 123: Web servers receive request and responds as .

o Html only

o Plan Text only

o JSON only

o Html, plain text and JSON Page #192


Question # 124: Which of the following class supports data
parallelism in "Task ParallelLibrary"?
o System.Threading.Tasks
o System.Task.Parallel
o System.threading.Task.Parallel

System.Task.Threading.Parallel Question # 125: Which of the


following "Event" property is used to show the "distance (inpixels)"
of the mouse pointer from left edge of the Monitor?
o pageX
o pageY
o ScreenY
o ScreenX PG# 187
AL-JUNAID TECH INSTITUTE
Question # 126: which of the following response show file not found error?

o 404

o 500

o 200

o 304

CURRENT PAPER SOLVED 2022


1. When the thread in the ThreadPool completes its task, it is returned to a queue______:
 Terminating queue
 Ready queue
 Waiting queue
 Running queue
2. Which of the following is not a feature of “C#”?
 Operator overloading is not allowed.
 Multiple Inheritance is not supported but interfaces a
 Enumeration members are scoped.
 Global variables or functions are not allowed.
3. @ symbol is used to create an instance of _________.
 NSString
 NSlog
 Alloc
 NStemp
4. _________ statement is true about WhenAll task combinator in C# threading.
 It combines all the task result into one array.
 It combines all the exceptions.
 It doesn’t re-throw exceptions
 Both 1&2
5. In Objective-C, which of the following statement can be used to display so______.
 [answerField:answer];
 [setText:answer];
 [answerFieldText:answer]; OR "[answerField setText:answer]
 [setText:answer:answerField];
6. While using Ajax, _________ object has to be created to communicate to server’
 HtmlRequest
 XML.HttpRequest
 XMLRequest
 HTMLXMLRequest
7. Which Event is fired when finger touching the Element is lifted in______
 OnFingerUp
 OnTouchNot
 OnTouchUp
 OnTouchMove
AL-JUNAID TECH INSTITUTE
8. Task in Threading C# 5.0 provide us the facility of handling __________ and progress.
 Cancellation
 Polymorphism
 Inheritance
 Action
9. __________ is the correct syntax in Jquery to use selector and get id of html element.
 $(‘#elementname’);
 #(‘$elementname’);
 $(‘--elementname’);
 #(‘$elementname’);
10. We can use __________ to create a single-instance application through WPF.
 Mutex
 Win32 window
 Thread
 Identifier
11. What is the------
[self.viewaddSubview:imageView];
 To make sure that image is not scaled incorrect
 To create the image view
 To set the image
 Add the image to this view controllers
12. While localizing binary recources, which of the following is used to localize the string
 LocalBml
 LocBml
 LocalBaml
 LocBaml
13. __________ method stops the default action of a selected element from happening by a
user:
 PreventDefault()
 StopDefault()
 Halt Default()
 End Default
14. __________ event is raised when the navigation is stopped, or when a new navigation is
requested----
 Navigated
 Navigating
 navigationStopped
 NavigationFailed
15. In objective C, _______ will show image on screen.
 UIImageView
 UIImage
 UserInterfaceImageView
 UIView
16. ___________ compiler compiles objective C code.
 GCC
 Nasm
 LCC
 Turbo
AL-JUNAID TECH INSTITUTE
17. _________ provides a thread-safe Last-In-First-Out data structure.
 ConcurrentQueue
 ConcurrentStack
 ConcurrentDictionary
 ConcurrentBag
18. Which of the following is NOT a mode of binding in context of----
 OneWay
 TwoWay
 OneTime
 TwoTime
19. __________ is the official specification of JS
 ExmaScript
 ECMAScript
 EMAScript
 EMCAScript
20. Which one is not “Read Only” Property of WPF elements?
 desiredSize
 Max
 ActualWidth
 ActualHeight
21. Objective C is an Extension of_______
 C++
 C
 C#
 Andriod
 MUHAMMAD FAISAL 
MIT 4th Semester
Al-Barq Campus (VGJW01) Gujranwala
faisalgrw123@gmail.com
CS411 Mega OBJECTIVE File for Final Term Papers
CS411 – VISUAL PROGRAMMING

Question No: 1 (Marks: 1) - Please choose one


A\An ________ displays the map and the labels for the recorded locations.

 mkmapview (Page#213)
 uiactivityindicatorview
 uitextfield
 mapmkview

Question No: 2 (Marks: 1) - Please choose one


________ properties based on input or mouse clicks.

 HTML
 CSS (Page#180)
 C#
 XML
Question No: 3 (Marks: 1) - Please choose one
Which of the following "Event" property is used to show the "distance (in pixels)" of the
mouse pointer from left edge of the Monitor?

 pageX
 pageY
 ScreenY
 ScreenX (Page#205)

Question No: 4 (Marks: 1) - Please choose one


__________ was introduced in 95 by netscape.

 C ++
 . Net
 Javascript (Page#179)
 PHP

Question No: 5 (Marks: 1) - Please choose one


Web servers receive request and responds as _____________.

 Html only
 Plan Text only
 JSON only
 Html, plan text and JSON (Page#211)

Question No: 6 (Marks: 1) - Please choose one


Concurrent collections may not useful when you want a thread-safe collection three static
methods in the Parallel class.

True
False (Page#175)
Question No: 7 (Marks: 1) - Please choose one
We can return a ________from void function without explicitly return it.

 value
 event
 task (Page#169)
 function

Question No: 8 (Marks: 1) - Please choose one


The pairing of labels and arguments is an important feature of ___________.

 C++
 Scripts
 Objective-C (Page#217)
 PHP

Question No: 9 (Marks: 1) - Please choose one


Thread pool save time of thread ________.

 insertion
 creation (Page#160)
 deletion
 updation

Question No: 10 (Marks: 1) - Please choose one


What is NSMutableArray?

 Object
 Class Reference (Page#217)
 Method
 Group
Question No: 11 (Marks: 1) - Please choose one
In the ________, the target is updated whenever the source changes.

 Binding Object
 Binding Mode (Page#153)
 Data Mode
 Data Object

Question No: 12 (Marks: 1) - Please choose one


Which of the following "Event" property is used to show the "distance (in pixels)" of the
mouse pointer from top edge of the Monitor?

 ScreenY (Page#205)
 pageX
 pageY
 ScreenX

Question No: 13 (Marks: 1) - Please choose one


Without binding you could not insert custom logic.

True
False (Page#153)

Question No: 14 (Marks: 1) - Please choose one


What is “nil” like?

 Null (Page#217)
 zero
 terminate
 move to new line
Question No: 15 (Marks: 1) - Please choose one
Sorting is applied ________ grouping.

 at initial stage
 anytime
 before (Page#150)
 after

Question No: 16 (Marks: 1) - Please choose one


Which of the following "Event" property is used to show the "distance (in pixels)" of the
mouse pointer from top edge of the browser window?

 pageY (Page#205)
 pageX
 screenX
 screenY

Question No: 17 (Marks: 1) - Please choose one


Prop. Paths in Bindings are useful for master/detail interfaces.

True (Page#150)
False

Question No: 18 (Marks: 1) - Please choose one


Objective-C introduces ________________ messaging in C.

 Smalltalk style (Page#217)


 Short sessions
 Group
 New style
Question No: 19 (Marks: 1) - Please choose one
Template can be shared as ________.

1) data items
2) events
3) resources (Page#144)
4) files

Question No: 20 (Marks: 1) - Please choose one


Objective – c introduces _________________ messaging in c?

1) Smalltalk style (Page#217)


2) Short session
3) Group
4) New Style

Question No: 21 (Marks: 1) - Please choose one


Navigation means managing the ________ item.

1) initial
2) last
3) current (Page#150)
4) any

Question No: 22 (Marks: 1) - Please choose one


Threadpool create and reduce real threads using hillclimbing algo to ___________.

1) To maximize CPU usage (Page#174)


2) To reduce the cost of thread creation
3) To maximize memory utilization
4) To minimize CPU usage
Question No: 23 (Marks: 1) - Please choose one
________ style is a rule telling web browser how to display an element.

 HTML
 Java
 C#
 CSS (Page#180)

Question No: 24 (Marks: 1) - Please choose one


HTML is a _________ helper function.

 RQuery
 Browser
 jQuery (Page#201)
 JS

Question No: 25 (Marks: 1) - Please choose one


Today websites reach interactivity of ________applications.

 web based
 desktop (Page#179)
 both of above
 none of given

Question No: 26 (Marks: 1) - Please choose one


__________ is more than one thing happening at the same time.

 Cohesion
 Congruence
 Coherence
 Concurrency (Page#169)
Question No: 27 (Marks: 1) - Please choose one
Long running operations make application __________.

 implicit
 responsive
 unresponsive (Page#160)
 explicit

Question No: 28 (Marks: 1) - Please choose one


Which of the following “Event “properties is used with “key press event” to determine
the numeric code for the key that was pressed? .

 Page X
 Which (Page#205)
 Shift Key
 Target

Question No: 29 (Marks: 1) - Please choose one


Thread-safe collection guaranteed the thread safe code.

True
False (Page#177)

Question No: 30 (Marks: 1) - Please choose one


MS introduced jscript. Their version of JS for IE.

True (Page#179)
False
Question No: 31 (Marks: 1) - Please choose one
Jquery solves ________ complexity and browser incompatibilities.

i. . Net
ii. C
iii. JS (Page#179)
iv. C#

Question No: 32 (Marks: 1) - Please choose one


Difference between Break and Stop is that Break reaches at least the sequential point.

True (Page#175)
False

Question No: 33 (Marks: 1) - Please choose one


Sorting criteria should be same as grouping otherwise output make sense.

True
False (Page#150)

Question No: 34 (Marks: 1) - Please choose one


__________ is more than one thing happening at the same time.

i. Cohesion
ii. Congruence
iii. Coherence
iv. Concurrency (Page#169)
Question No: 35 (Marks: 1) - Please choose one
A\An ________ indicates that the device is working and not stalled.

 mkmapview
 uiactivityindicatorview (Page#213)
 uitextfield
 mapmkview

Question No: 36 (Marks: 1) - Please choose one


We can join and use shared data.

True (Page#161)
False

Question No: 37 (Marks: 1) - Please choose one


__________ solves “JavaScript” complexity and browser incompatibilities.

 Jhtml
 RQuery
 JQuery (Page#195)
 J#

Question No: 38 (Marks: 1) - Please choose one


Template can even be auto-applied to some type by setting its datatype prop.

True (Page#144)
False
Question No: 39 (Marks: 1) - Please choose one
We use ________ to avoid compiler errors.

 data
 xdata (Page#150)
 ydata
 none of the given

Question No: 40 (Marks: 1) - Please choose one


____________Can add/remove/change “CSS” properties based on input or mouse clicks.

 J#
 JQuery
 HTML
 None of the given option (Page#196)

Question No: 41 (Marks: 1) - Please choose one


________ is typing together arbitrary objects.

 data frame
 data store
 data binding (Page#140)
 markup extension

Question No: 42 (Marks: 1) - Please choose one


_____________ Mode of binding is opposite to OneWay mode of binding.

 OneWay To source (Page#165)


 TwoWay
 One Time
 Two Time
Question No: 43 (Marks: 1) - Please choose one
Collection view source can be used to create ________ views and applied to targets.

 various
 old
 new (Page#150)
 initial

Question No: 44 (Marks: 1) - Please choose one


Which of the following “Event” property is used to show the “distance (in pixels)” of the
mouse pointer from the left edge of the browser window?

 pageY
 pageX (Page#205)
 ScreenX
 ScreenY

Question No: 45 (Marks: 1) - Please choose one


When an item with no header selected, then a ________ returned.

 key value
 prime value
 default value (Page#140)
 numeric value

Question No: 46 (Marks: 1) - Please choose one


Which of the following is not a "JQuery" filter?

 Even
 Odd
 Has
 Write (Page#201)
Question No: 47 (Marks: 1) - Please choose one
Binding has a ________ prop and a ________ prop.

 source, destination
 source, target (Page#140)
 target, destination
 none of the given

Question No: 48 (Marks: 1) - Please choose one


Which of the following Object creates a cancellation token?

 OperationCanceledtoken
 OperationCanceled
 CancellationToken
 CancellationTokenSource (Page#186)

Question No: 49 (Marks: 1) - Please choose one


We can not bind to a collection.

True
False (Page#141)

Question No: 50 (Marks: 1) - Please choose one


Threadpool is used to __________.

 To make easy the process of thread creation


 To make easy debugging process
 To save time of thread creation (Page#174)
 To avoid complexity
Question No: 51 (Marks: 1) - Please choose one
________ and later merge the journal and provide a more streamlined interface.

 IE 6
 IE 7 (Page#132)
 IE 8
 IE 9

Question No: 52 (Marks: 1) - Please choose one


Methods with async are called asynchronous.

True (Page#166)
False

Question No: 53 (Marks: 1) - Please choose one


Exception is raised when an item with no header selected, then a default value returned.

True
False (Page#140)

Question No: 54 (Marks: 1) - Please choose one


HTML is called ____________ layer.

 Physical
 Presentation
 Behavioral
 Structural (Page#195)
Question No: 55 (Marks: 1) - Please choose one
Data can be:

 xml file
 web service
 db table
 all of the given (Page#140)

Question No: 56 (Marks: 1) - Please choose one


We can mix Items and item source.

True
False (Page#142)

Question No: 57 (Marks: 1) - Please choose one


________helps apps remain oblivious to the visual tree.

 Routed Events
 Input Events (Page#116)
 Output Events
 Obvious Events

Question No: 58 (Marks: 1) - Please choose one


Frame work element and framework content element both have a Resources prop.
Often are style or data providers.

True (Page#135)
False
Question No: 59 (Marks: 1) - Please choose one
Any assembly marked with allow partially trusted callers and placed in ________ can be
called by partial-trust code

 PAC
 SAC
 GAC (Page#132)
 RAC

Question No: 60 (Marks: 1) - Please choose one


Additional events can be used for fine grained progress.

True (Page#133)
False

Question No: 61 (Marks: 1) - Please choose one


Many XBAP take advantage of navigation.

True
False (Page#132)

Question No: 62 (Marks: 1) - Please choose one


Routed events are like ___________ on top of .Net properties.

 Event properties
 Layer
 Properties
 Dependency properties (Page#116)
Question No: 63 (Marks: 1) - Please choose one
You can still use rich text and media, isolated storage up to ________, arbitrary files on
host web server, use browser file open dialog for local files.

 312kb
 412kb
 512kb (Page#132)
 1000kb

Question No: 64 (Marks: 1) - Please choose one


One of the purposes of journal is we use this in photo gallery for undoable image rotation.

True (Page#129)
False

Question No: 65 (Marks: 1) - Please choose one


Use embedded resource to define a binary resource.

True
False (Page#113)

Question No: 66 (Marks: 1) - Please choose one


Which of the following is Not a routing strategy?

 Tunneling
 Indirect (Page#117)
 Bubbling
 Direct
Question No: 67 (Marks: 1) - Please choose one
Navigation can also happen between ________.

 xml files
 html files (Page#128)
 iso files
 http files

Question No: 68 (Marks: 1) - Please choose one


The ________ statement iterates over each element in an "enumerable" object.

 Foreach (Page#191)
 Dowhile
 While
 For

Question No: 69 (Marks: 1) - Please choose one


You can get an instance of navigation service by calling the static
navigationservice.getnavigationservice method.

True (Page#128)
False

Question No: 70 (Marks: 1) - Please choose one


The more the standardization on builtin commands, the more seamless and declarative
the interaction can be between controls.

True (Page#123)
False
Question No: 71 (Marks: 1) - Please choose one
Windows installer benefits include:

 showing custom setup UI


 arbitrary code at setup time
 register COM components and file associations
 All of the given options (Page#127)

Question No: 72 (Marks: 1) - Please choose one


Persisting and Restoring can use registry or file system.

True (Page#127)
False

Question No: 73 (Marks: 1) - Please choose one


The corresponding type converter class for “Brush” class will be _________.

 BrushConverter (Page#149)
 CastBrush
 BrushCast
 None of the given options

Question No: 74 (Marks: 1) - Please choose one


Button and textbox have direct knowledge of each other.

True
False (Page#123)
Question No: 75 (Marks: 1) - Please choose one
__________ provides logic behind back and fwd.

 Hyperlink
 Journal (Page#129)
 Container
 Navigation

Question No: 76 (Marks: 1) - Please choose one


App code-behind can not be omitted altogether.

True
False (Page#125)

Question No: 77 (Marks: 1) - Please choose one


WPFS controls have built-in behavior tied to various commands.

True (Page#121)
False

Question No: 78 (Marks: 1) - Please choose one


Stylus can behave like a ___________ but has ___________resolution.

 Keyboard, lower
 Mouse, lower
 Mouse, higher (Page#122)
 Keyboard, higher
Question No: 79 (Marks: 1) - Please choose one
Translation behavior has desired displacement, desireddeceleration, and initialvelocity.

True (Page#117)
False

Question No: 80 (Marks: 1) - Please choose one


Rotation behavior has desiredexpansion, desireddeceleration, initialradius, and initialvelocity.

True
False (Page#117)

Question No: 81 (Marks: 1) - Please choose one


_________ defines a number of built-in commands.

 OSPF
 WPF (Page#121)
 SPF
 PWF

Question No: 82 (Marks: 1) - Please choose one


By convention "tunneling event" names are prefixed with ________ and just come_________ the
bubbling event occurs.

 View, after
 View, before
 Preview, before (Page#117)
 Preview, after
Question No: 83 (Marks: 1) - Please choose one
Commands have automatic support for ________ gestures.

 input (Page#121)
 output
 both input & output
 none of the given

Question No: 84 (Marks: 1) - Please choose one


Any number of child windows can be made by instantiating a Window derived class and
calling Show.

True (Page#124)
False

Question No: 85 (Marks: 1) - Please choose one


Translation behavior has desired rotation, desired deceleration, and initial velocity.

True
False (Page#117)

Question No: 86 (Marks: 1) - Please choose one


All instances of routeduicommand implement icommand and support bubbling.

True (Page#121)
False
Question No: 87 (Marks: 1) - Please choose one
________ are a more abstract and loosely coupled version of events.

 values
 commands (Page#121)
 functions
 numbers

Question No: 88 (Marks: 1) - Please choose one


Which "transform" property can help us to flip the element from its center?

 ScaleY
 ScaleX
 RenderTransformOrigin (Page#126)
 None of given options

Question No: 89 (Marks: 1) - Please choose one


Manipulation ________starting event when all fingers loose contact even before a
completed event.

 event
 container
 inertia (Page#117)
 function

Question No: 90 (Marks: 1) - Please choose one


Page does everything window does except:

 uploading and downloading


 onclosed and onclosing (Page#128)
 onclosed and navigating
 navigating and onclosing
Question No: 91 (Marks: 1) - Please choose one
________behavior has desired rotation, desired deceleration, and initial velocity.

 Rotation (Page#117)
 Translation
 Expansion
 None of the given

Question No: 92 (Marks: 1) - Please choose one


An "UIElement" receives mouse events only if "IsHitTestVisible" is ________.

 0
 False
 Null (Page#121)
 True

Question No: 93 (Marks: 1) - Please choose one


By default, initialvelocity and initialradius are initialized with the ________ values.

 coming
 current (Page#117)
 multiple
 significant

Question No: 94 (Marks: 1) - Please choose one


Starting and started events ________to customize or cancel or disallow some manipulations.

 stop
 end
 not allowed
 allow (Page#116)
Question No: 95 (Marks: 1) - Please choose one
With navigation, content is usually in ________a simpler version of Window.

 Frame
 Page (Page#128)
 Box
 Button

Question No: 96 (Marks: 1) - Please choose one


Manipulations always done relative to a manipulation ________.

 event
 container (Page#117)
 inertia
 function

Question No: 97 (Marks: 1) - Please choose one


Modal dialogs include ________which are actually provided by win32.

 interfaces
 common dialogs (Page#126)
 designs
 structure

Question No: 98 (Marks: 1) - Please choose one


________ behavior has desiredexpansion, desireddeceleration, initialradius, and initialvelocity.

 Rotation
 Translation
 Expansion (Page#117)
 None of the given
Question No: 99 (Marks: 1) - Please choose one
A Page can interact with its navigation container by using ________, which exposes
relevant functionality regardless of whether the container is a navigation window or a
Frame.

 navigation class

 navigation service class (Page#128)

 navigation page class

 navigation box class

Question No: 100 (Marks: 1) - Please choose one


One ________Thread and one render thread can create more with Dispatcher.Run which
can improve responsiveness.

 EU

 UI (Page#125)

 IU

 IE

________________________________________________________________________
CS411
VISUAL PROGRAMMING
Final Term Quizzes MCQ's

1) While Manipulation, we combine information from multiple __________.

functions
events (Page#116)
integers
numbers

2) In Xaml browser application, how much isolated memory we can use?

256kb
128
512
1024
3) _________ behavior has desired displacement, desireddeceleration, and initialvelocity.

Rotation
Translation (Page#117)
Expansion
None of the given

4) AJAX stands for ___________.

Abstract JSON and XML


Asynchronous JavaScript and XHtml
Asynchronous JavaScript and XML
Abstract Java and XML Library

5) Which of the following technologies is not used in AJAX?

DOM
DHTML
Flash
CSS

6) To be boundary aware manipulationboundaryfeedback ________ is used.

event (Page#118)
container
inertia
function
7) Which of these are defined as the model object?

UILabel *questionField;
NSMutableArray *questions@field;
NSMutableArray *questions;
Question= 0;

8) Which of the following is correct way to temporarily stop execution of a thread object
named as “myThread” for 500 milisec?

myThread.Sleep(0.50);
myThread.Stop(0.05);
myThread.Sleep(500);
myThread.Stop(500);

9) “async” and _____________ keywords in C# are the heart of asynchronous programming.

Return
Await
Wait
String

10) Controls have logic to ________ with commands through Command property.

design
interface (Page#121)
structure
none of the given
11) Which of the following C# Method reports a progress change?

Finalize
OnReport
GetType
GetHashCode

12) Which of the followings are keyboard events?

Key entered, key exist


Key strike, key release
Key down, key up
Key pressed, key released

13) In case of HTML page navigation, you must use the _______ of "Navigate" that _________ a URI.

Overload, rejects
Overload, accepts
IFrame, rejects
IFrame, accepts

14) Which one of the following can be used to set dependency property values?

Temporary resource
Permanent resource
Dynamic resource
Static resource
15) Child window like parent window but gets closed when parent and similarly
minimized, also called ________.

modeless area
modeless dialog (Page#124)
modeless interface
modeless design

16) "Binding" technique binds two properties together and keeps a _________ open.

Memory location
Communication channel
Selection
Choice

17) A/An _________ screen is an image that appears while a game or program is loading

Opening
Startup
Initial
Splash

18) If we insert some objects in a single cell in Grid panel, then these objects are placed on _________.

One on Top of the other


One after the other
One on Bottom of the other
One on Side of the other
19) In a code segment, if the Visibility=”Collapsed” then which of the following events are not generated?

Routed Events
Keyboard Events
Key down Events
Mouse Events

20) Which of the following operation cannot be performed by using a View?

Sorting
Grouping
Searching
Filtering

21) lickonce benefits include:

builtin support for automatic updates


rollback to prev versions
both of above options (Page#127)
none of the given

22) In order to resize the row and column in Grid panel, _________ is used.

Grid converter
Grid splitter
Grid divider
Grid compiler
23) ___________and __________ are the two important properties of Binding object.

Start, Destination
Items, Selected
Source, Path
BindTo, BindFrom

24) In multi touch events, a/an __________ id is assigned to each individual event.

Device
Event
CPU
Processor

25) Which of the following operation cannot be performed by using a View?

Filtering
Sorting
Grouping
Searching

26) Page also contains a few of its own properties that control the behavior of the ________.

container
parent container (Page#128)
child container
none of the given
27) Using ___________ requires more overhead than __________ because of the extra tracking.

StaticResource, DynamicResource
PermanentResource, TemporaryResource
TemporaryResource, PermanentResource
DynamicResource, StaticResource

28) Which function is used to create cancel button event of dialog box __________.

OnClickCancel()
OnInitCancel()
OnCancel()
CancelClick()

29) Which of the following response show file not found error?

404
500
200
304

30) __________ are high order functions that compose, combine, or otherwise modify functions
in useful and interesting ways.

Modifiers
Separators
Combinators
None of the given
31) Hyperlink element is used to link to ________.

html
xaml (Page#129)
http
website

32) “JavaScript” is _________ scripting Language.

Server
Client
Interpreter
Browser

33) The Java programming language has a specific class for creating splash screens, called _________.

Java.awt.start
Java.lang.splash
Java.start.screen
Java.awt.SplashScreen

34) To remove data binding between the source and the target, we can use _________ function.

StopBinding
RemoveBinding
ClearBinding
ResetBinding
35) You get Integrated Navigation in ________.

XAML
SDK
XBAP (Page#132)
HTML

36) In multi touch events, when multiple fingers are touching simultaneously, these events
get raised for each finger ___________.

Completely
Partially
Independently
Dependently

37) The __________ user interfaces, enabled by WPF, is getting a lot of attention.

Loutish
Polished
Coarse
Distracted

38) When your C# program is compiled, it creates a file called a/an_________, which is normally
an executable or DLL library.

BIOS
C++
Assembly
Text
39) __________where multiple GUI elements and many sources of events exist.

Control Language Interface


Content property
Event properties
Visual programming

40) In Visual Studio 2012, expression blend is _________ WPF feature.

80%
70%
100%
90%

41) To define a binary resource, add a ________ and set the build action resource
or content (loose file).

folder
file (Page#133)
icon
page

42) A (n) _______________ is a component of the structure of an event.

Event Architecture
Event Request
Event Attribute
Event Response
43) A ____________ block has access to an "Exception" object that contains information about
the error.

Try
Catch
Throw
Finally

44) One of the ways to create an instance of a class is _____________.

Sequential heap
System array
Factory method
XAML compiler

45) There is/are __________ type/s of parameter/s for attributes.

Four
Three
One
Two

46) A (n) ____________ is a set of associated events.

Event Consumer
Event Producer
Event Channel
Event Stream
47) If we require to set components in table (column and row) format, then which panel will be used?

StackPanel
DockPanel
Gridpage
TabPanel

48) _________ Method is used to move the file from one directory to another.

Import
Move
Export
None of given options

49) Not implementing some methods of the interface in the class is ___________.

A warning
An exception
An error
Acceptable

50) Logical resources are introduced by wpf. Arbitrary .net object stored and named in an elements
Resources prop. Typically meant to be shared by multiple ________ objects.

parent
child
event (Page#135)
function
51) A (n) _____________is a subscription mechanism for events.

Raw Event
Event Stream
Event Channel
Event Producer

52) "Situation" is an event occurrence that requires a (n) __________.

Class
Object
Reaction
Action

53) XML is a stricter version of ____________.

CSS
C#
Java
HTML

54) ________ contacts the service provider or the server.

Event-driven
Service Requester
Both of the above
None of the given options
55) Any class, including the same class that the event is declared in, may register one of
its methods with the ________.

Event
Delegate
Function
Class

56) _________ data source is provided by a Data Context.

Explicit
Implicit (Page#142)
Value
Context

57) __________ decouple producers and consumers.

Requests
Events
Functions
All of these

58) To declare an anonymous method, you just use keyword “__________”.

handler
event
delegate
none of the given
59) The common type system of C# has ________ types and ________ types.

Reference, Value
Value, Reference
Function, Data
Data, Function

60) There are ________ methods to read XML document.

Two
Three
Four
Five

61) Collectionviewsource has its own sortdescriptions and groupdescriptions properties


and a Filter event to be used from ________.

event
container
xaml (Page#150)
xtml

62) ________ can leave your program in an inconsistent state by not releasing resources
or doing some other type of cleanup.

Functions
Exception
Abstraction
All of these
63) _________ are called by garbage collector.

Constructors
Destructors
Both of above
None of the given

64) Attributes are generally applied ________ in front of type and type member declarations.

Logically
Physically
Both of above
None of given

65) Multiple ________ are conventionally stored in multiple files.

Classes
Values
Variables
Functions

66) The ______, ________ and ________of applications that use events, either directly
or indirectly is called event-based programming.

Model, Code, Operation


Analyze, Design, Operation
Design, Coding, Operation
Code, Operation, Maintain
67) C# is a _________ and .NET is a _________.

Platform, Language
Language, platform
Package, Language
Language, Package

68) Windows Presentation Foundations (WPF) was publicly announced in ___________.

2000
2001
2002
2003

69) WPF stands for:

Windows Powerful Foundations


Windows Presentation Formations
Windows Presentation Functions
Windows Presentation Foundations

70) _________ declaratively instantiate the source object with a parameterized constructor.

data object
.net object (Page#152)
binding object
files object
71) Value-types hold their value in ___________ where they are declared.

Variable
Memory
Object
Reference

72) Indexers can take any number of ________.

Arrays
Variables
Parameters
All of these

73) Attributes add ____________to year program.

Clearance
Errors
Meta Data
Ambiguity

74) Cast back to base type to call a/an ________ method of base.

Instance
Base Class
Overridden
Derived Class
75) ________ is said to be stateless if the way it processes one event does not influence
the way it processes any subsequent events.

Event Producer
Raw Event
Event Processing
Event Stream

76) ________ is built from request-response and it moves away from monolithic applications.

Event-driven architecture (EDA)


Service-oriented architecture (SOA)
Both of above
None of the given option

77) Object variables are references to the ________ object not the object themselves.

Original
Alternative
Primary
None of the given

78) An indexer enables your class to be treated like a/an __________.

Class
Function
Array
Pointer
79) Polymorphism needs the signatures to be the __________.

Different
Same
Alternative
None of the given

80) In the Binding Mode, the source is __________whenever the target changes.

remain same
updated (Page#153)
revised
expired

81) Types of class members in C# are __________ and ___________.

ostatic, instance
oinstance, static
opublic, private
ostatic, private

82) Events may live ________ events like in event logs.

Inside
Outside
Both of above
None of the given
83) In event-driven architecture (EDA), ___________ sends event to ____________.

Event Consumer, Event Producer


Event Producer, Event Consumer
Event Handler, Event Producer
Event Generator, Event Producer

84) Additional XML namespaces (on the root or on children) must be _________ to be used on
any identifiers from that namespace.

Given a common prefix


Qualified with “Pre” keyword
Given a distinct prefix
Qualified with “Ext” keyword

85) Thread pool creates or reduces ________threads using a hill climbing algo to
maximize cpu usage and reduce slicing.

render
real (Page#160)
STA thread
none of the given

86) The interface forces each component to expose specific ________ members that will
be used in a certain way.

Public
Private
Both of above
None of the given
87) ___________ allows to keep the user interface description and implementation separate.

GDI
WPF
Avalon
Altia

88) Dependency properties are represented by _____________.

System.Windows.DependencyProperty
System.Windows.Dependency.Property
System.Windows.Dependency
System.Windows.Property.Dependency

89) Suppose we want to restrict the user to don‟t decrease the height of a WPF element
from a specific amount then which property will be used?

HeightMinimum
MinimumHeight
MinHeight
None of the given

90) _________indirectly uses task completion source to implement methods returning Tasks.

Debugger
Linker
Compiler (Page#169)
Loader
91) If we want to scale an object in the 2-D x-y coordinate system then which transform
class will be used?

Rotate Transform
Matrix Transform
Translate Transform
Skew Transform

92) Which of the following is/are not derived from “Control” class?

ListBox
StatusBar
Button
None of the given

93) Wait for a single event is ____________operation.

Waiting
Waste
Blocking
Idle

94) ___________ method reads the whole document in memory.

XPath
XmlDocument
XmlReader
XmlLine
95) Which of the following events may or may not relate to an actual occurrence?

Probabilistic Events
Actual Events
Real Events
Expected Events

96) The System.Console is a ___________ which enables us to do Console Input and Output.

Structure
Class
Namespace
Library

97) Clean room design is useful as a defense against __________.

Copyright
Trade secret infringement
Copyright and trade secret infringement
None of the given options

98) Clean room design is also called__________.

Clear Room Design


Wall Technique Design
Chinese Wall Technique
French Wall Technique
99) Which of the following is an occurrence within a particular system or domain?

Object
Event
Result
Message

100) TAP abbreviated as:

Task-based Async Plan


Task-based Async Pattern (Page#173)
Task-based Async Program
Task-based Async Preview

101) During the program execution, program can be stopped with the help of _________.

Attributes
Compiler
Breakpoints
Exception Handling

102) Which of the following does NOT include in event processing operations?

Deleting Events
Reading Events
Terminating Events
Transforming Events
103) The result of Exception can bring __________ in the program.

Reliability
Stability
Inconsistency
Consistency

104) Graphical user interfaces and the event-driven model is not applied on which of the following?

Web Application
Console Application
Mobile Application
Desktop Application

105) Events are based on the principle of ____________.

Request
Response
Coupling
Decoupling

106) ___________methods do not have names.

Attribute
Non-Anonymous
Anonymous
None of given
107) Which of the following is an entity that introduces event into the system?

Event Channel
Event Producer
Event Stream
Event Consumer

108) Anonymous methods ____________ the code size.

Double
Expand
Reduce
Extend

109) __________ events may or may not relate to an actual occurrence

Layer
Properties
Event properties
Probabilistic

110) Task Parallel ________exploit multicore for real parallel tasks.

Structure
Library (Page#175)
Class
Namespace
111) The Main method returns a non-zero value which indicates the__________.

Source of Program
Error in Program
Termination of Program
Exception in Program

112) WPF4 was released in ___________.

2012
2010
2005
2003

113) Extension methods can only be defined in ____________ class.

Static class
Dynamic class
Normal class
String class

114) AML is compressed representation of _________.

CAML:NS
XAML
XAML:NS
CAML
115) Question # 56: ________ processing operations include reading, creating, transforming,
and deleting events.

Observed Events
Common event
Deducted Events
Probabilistic Events

116) Static ctor exists to initialize class static members and called only __________.

Once
Twice
Anytime
All of the given

117) The __________ in the namespace indicate a hierarchy of nested namespaces.

Arrows
Dots
Semicolon
Brackets

118) _________ Interact with web page layout.

Java script
HTML
XML
DOM
119) Which of the following response show internal server error?

404
500
200
304

120) _________ is a formatting language.

HTML
CSS (Page#180)
Java
C#

121) Which of the following class supports data parallelism in "Task Parallel Library"?

System.Threading.Tasks
System.Task.Parallel
System.Task.Threading.Parallel
System.threading.Task.Parallel

122) What is the purpose of the following "JQuery" code? $(„#navbar a‟)

Find all the element whose name is navbar and then find a descendent a
Find all the element whose ID is navbar and then find a descendent a
Find all the element whose name is navbar and then find a ancestor a
Find all the element whose ID is navbar and then find a ancestor a
123) What message is used to send to destroy the object?

stop
delete
free
release

124) While dealing with "threads" in ".Net", one can avoid performance bottlenecks and
enhance the overall responsiveness of his / her application by using _________ programming.

Multithreading programming
Asynchronous programming
Synchronous programming
Parallel programming

125) DOM is a ___________ representation of data.

Tree
Graphical
Object
None of the given

126) "Callback" method is used to _______ the operation.

Invoke
Revoke
Terminate
Pause
127) Which of the following is not handled by the “Task Parallel Library (TPL)”?

Partitioning of the work


Scales the degree of concurrency
Scheduling of threads
Progress report handling

128) Why we use “Alloc” message?

To create a class
To create an instance
To extend functions
To inherent methods

129) Which of the following server(s) support “AJAX”?

WWW
SMTP
HTTP
Both SMTP and HTTP

130) Which of the following is not a part of "cancellation" task?

The calling thread does forcibly end the task


Notice and respond to the cancellation request in your user delegate
Pass a cancellation token to your user delegate and optionally to the task instance
Create and start a cancelable task
131) Jquery simplifies all steps except that of changing the webpage simplest is load
function which loads ________ into an area of web page.

Function
Library
HTML (Page#193)
XAML

132) The "Task Based Asynchronous pattern" method returns either a "Task" or a "Task<TResult>",
based on whether the corresponding __________ method returns "void" or a type "TResult".

Callback
Synchronous
Asynchronous
Return

133) "JavaScript" __________is available in web browser.

Compiler
Linker
Interpreter
Conjunction

134) Which of the following is not true about task completion source?

it is executable thing (Page#175)


Provide Continuation facility
Support result return facility
Provide exception handling facility
135) A class that implements the „lCommand‟ and supports „bubbling‟ just like a routed
event is known as ___________.

Executed command
CanexecuteChange
RoutedUlCommand
Canexecute

136) To plug custom logic, you need to add a __________ to the element that will execute the
command or any parent element.

Execute command
Helpcanexecute
CommandBinding
RoutedUlCommand

137) In case of integrating Navigation to XBAP, "ShowNavigationUI" should be set to


_________ in order to bypass integration.

True
Null
False
0

138) We use "GetDefaultView" method of ___________ to get the default View.

DataSource
ViewDescription
ViewCollection
CollectionViewSource
139) Which one of the following is used, if we want to add a window resource in procedural code?

Window.Resource.Add ();
Window.Resoruces.Add();
<Widows.Resources></Widows.Resources>
<Window.Resources></Window.Resources>

140) We can perform sorting through View by using an object of__________ class.

SortOrder
ViewDescription
SortDescription
ViewOrder

141) Question # 261: A __________ receives keyboard events only if it has keyboard focus.

Keyboard Controls
UIElement
Mouse
Keyboard

142) Frame has a __________ property used in enabling or disabling the bar.

NavigationUIBlock
ShowsNavigationUI
BlocknavigationUI
NavigationUIVisibility
143) A Window can spawn ____________ number of additional Windows by instantiating a
Window‐derived Class and calling Show (...).

Four
Six
Five
Any

144) ___________ provides the logic behind the "Back" and "Forward" buttons.

Hyperlink
IFrame
Journal
Navigation Window

145) A\An ________ allows the user to input text to label the current location on the map.

mkmapview
uiactivityindicatorview
uitextfield (Page#213)
mapmkview

146) In ________ browser app, you change"<TargetZone>Internet</TargetZone>" to


"<TargetZone>Custom</TargetZone>"

Partial‐reject
Full‐trust
Partial‐trust
Full‐reject
147) To check that the user either pressed left Alt key or right Alt key, the __________ is used.

IsDown
KeyStates.IsKeyDown
IsKeyDown
keyboardDevice.IsKeyDown

148) __________ supports the creation of applications that run directly in a web browser.

C#
WPF
HTML
C/C++

149) Which one of the following panels is most powerful, versatile and customizable?

Doc panel
Stack panel
Grid Panel
Canvas panel

150) Touch events are hallmark of __________.

computers
laptops
mobile devices (Page#216)
none of the given

________________________________________________________________________
Protocols are like ________ in other languages.

web pages
interfaces (Page#212)
structures
codes

Data binding is about tying together arbitrary .NET _________.

Functions
Properties
Objects
Variables

An event that is raised whenever the value of "CanExecute" changes is known as __________.

Command
Execute
CanExecute
CanExecuteChanged

Multi touch events are categorized into ____________ and _____________.

Touch events, touchup events


Touchdown events, touchup events
Basic touch events, higher-level manipulation events
Advanced touch events, low-level manipulation events
In context of data binding, __________ contains the current item to get it synchronized
with data Source.

String
Template
List
View

Which of the following is an example of tunnel key event?

Key up
Preview key entered
Preview key down
Key down

_________ has simple commands called tags.

JAVA
CSS
C#
HTML (Page#179)

Commonly we have two types of custom command bindings named as ____________.

StartBindings and StopBindings


KeyBindings and MouseBindings
EventBindings and InstanceBindings
ButtonBindings and TextboxBindings
Which of the following is not a string format property throughout WPF?

ItemStringFormat
StringFormat
ContentStringFormat
RowHeaderStringFormat

To design a complex Interface, which of the following technique is best to achieve the
required results?

Panels composed in three panels


Panels composed in two panels
Panels composed within panels
Panels composed in single panel

__________ is used to perform navigation.

Session
Hyperlink
Internet protocol
Hypertext markup language code

The Java programming language has a specific class for creating splash screens, called __________.

Java.awt.start
Java.lang.splash
Java.start.screen
Java.awt.SplashScreen
We use "UIElement" property ClipToBounds= “false” when __________.

We want area child element don‟t cross the boundary of parent


We want area of child element is allowed to cross the boundary of parent
Parent area also increases on increasing of area of child element
None of given

In Parallelism true concurrency at ________level operations.

upper
bottom (Page#171)
high
lower

Consider the following C# code segment: button.Background =


(Brush) new BrushConverter().ConvertFrom (“SystemColors.WindowBrush”);
Which one of the following is equivalent XAML code?

Button Background= “SystemColor.WindowsBrush”/>

Button Background= “SystemColor.WindowBrush”/>

Button Background= “SystemColors.WindowsBrush”/>

Button Background= “SystemColors.WindowBrush”/>

All elements of WPF have following property/properties.

Width
Height
Height and Width
None of given options
With the help of WPF, an ugly looking application can be _______ by the designers.

Rearranged
Re-created
Rejected
Re-themed

Which of the following components generates an input Event?

Printer
Plotter
Multi-Touch (Page#114)
Speaker

Graphical user interfaces and the event-driven model are not applied on which of the following?

Web Applications
Mobile applications
Desktop Applications
Console Applications

C# is most often used with some implementation of the ___________.

Compact Language Interface


Common Language Infrastructure
Control Language Infrastructure
Control Language Interface
In C#, comments are written using ____________.

# and */ /*

// and /* */

# and /*

// and */ /*

Binding binds ________ properties together and keeps a communication channel open.

two (Page#140)
three
four
five

Attributes are declared ________ the class/function.

Outside
After
Within
Above

XML document is readable by ___________.

Human only
Machine only
No one
Machine and Human both
"Console" is a/an _________ class in the "System" namespace.

Input
Dynamic
Static
Virtual

The only __________ .Net language has an intrinsic understanding of dependency Properties.

Vb.net
Xaml
C#
J#

Which of the following grabs the “OK” button by only knowing its name?

Button okButton = (Button)window.GetName("okButton")


Button okButton = (Button)window.getElementByName("okButton")
Button okButton = (Button)window.FindName("okButton")
Button okButton = (Button)window.GetButton("okButton")

Unlike type converters, however, markup extensions are invoked from XAML with __________.

Bridge assemblies
Explicit and consistent syntax
Wrapper code
None of the given options
Which statement is True about interfaces?

An interface can contain only methods, variables, events, and indexers.


An interface can contain only variables, properties, events, and indexers.
An interface can contain only methods, properties, variables, and indexers.
An interface can contain only methods, properties, events, indexers.

Events can be ____________.

Specialized
Composed
Generalized
All of the given options

g++ is a command of __________.

Dev C++
Unix based system
Windows based system
None of the given options

___________ reads entire document in memory.

Xmldocuments
Xmlreader
Both of above
None of the given
___________ may contain events.

Requests
Service
Messages
Applications

A customer order can be represented as __________.

Event
Request
Event or Request
All of the given

Markup extensions are invoked from ________ with explicit and consistent syntax.

C#
HTML
XAML
None of the given

All the members of interfaces are implicitly__________.

Private
Static
Public
Abstract
A compiled C# file is called __________.

Complied File
Source File
Assembly File
EXE File

__________ add declarative information to your programs.

Attributes
Functions
Exception
Objects

Anonymous method is a method without a name.

True
False

“out” parameters which are not used for return values or the “params” argument for variable arguments.

True
False

_________types have the notion of referential identity.

Value
Reference
Both of above
None of the given
__________let any classes behave like an array.

Properties
Fields
Indexers
Finalizers

________ are algorithms that operate on data.

Variables
Functions
Methods
Classes

_________ is an event that is introduced into an event processing system by an event producer.

Event Producer
Event Consumer
Raw Event
Event Stream

Events and ________ work hand in hand.

Parameters
Delegates
Functions
Data Members
C# event is a class member that is ________ whenever the event it was designed for occurs (fires).

Activated
Deactivated
Transformed
Associated

________ is a static class in the System namespace.

Console
Pointer
Variable
Function

Default value of first member is __________.

0
1
2
3

__________ are inherited by classes which provide the real implementation.

Functions
Variables
Interfaces
Objects
__________ is basically array of arrays.

Stack
Pointer
Jagged
Function

The initial name for C# was ___________.

COAL
COOP
COAP
COOL

BAML is compressed representation of _________.

CAML:NS
XAML
XAML:NS
CAML

Extension methods ________ access the private data members of the class in which they are extended.

May
Cannot
May not
Can
Which of the following is/are not derived from “Control” class?

ListBox
StatusBar
Both of above
None of the given

__________ events may or may not relate to an actual occurrence.

Observed Events
Deducted Events
Probabilistic Events
None of the above

__________ is an entity that receives events from the system.

Event Producer
Event Consumer
Event Channel
Event Generator

The easiest way to declare an event is to put the event keyword in front of a ________ member.

Interface
Delegate
Class
Struct
________ can be used on non-data bound but inside the element it almost always make
sense to use data binding.

Event
Template (Page#144)
Data
Function

________ is typing together arbitrary objects.

data frame
data store
data binding (Page#140)
markup extension

--------------------------------Wish U Best of L|U|C|K for EXAMS -----------------------------


CS411 Visual Programming
Solved Past Papers
what is difference between hover() and toggle()? (2 marks)
Difference b/w hover() and toggle() is that toggle() works by clicking
it on and off whereas hover() works just by positioning the mouse
over it.

Core Locations Framework contains which types of classes ? (2 Marks)


Answer: Page 218
Core Locations classes that enable finding geographical position.
distanceFilter and desiredAccuracy properties.

can Operating System distinguish between window contain WPF and


window Contain Win32? (2 Marks)
when we preferred BeginInvoke instead of Invoke method? (2 Marks)
there are times when you want to invoke a delegate and wait for its
execution to complete before the current thread continues. In those
cases the Invoke call is what you want.
In multi-threading applications, you may not want a thread to wait
on a delegate to finish execution, especially if that delegate performs
I/O (which could make the delegate and your thread block). In those
cases the BeginInvoke would be useful.

what is difference between server Side programming and Client Side


Programming ? (3 Marks)
Server-side programming, is the general name for the kinds of
programs which are run on the Server.
Uses

For more content visit: fb.com/groups/imransvu/


 Process user input.
 Display pages.
 Structure web applications.
 Interact with permanent storage (SQL, files).
Much like the server-side, Client-side programming is the name for all
of the programs which are run on the Client.
Uses
 Make interactive webpages.
 Make stuff happen dynamically on the web page.
 Interact with temporary storage, and local storage (Cookies,
localStorage).
 Send requests to the server, and retrieve data from it.
 Provide a remote service for client-side applications, such as software
registration, content delivery, or remote multi-player gaming.
Also check here for more detail

define iOS feature of Block and also provide its syntax ? (3 Marks)
Blocks are a new feature that was introduced in iOS 4.0 and Mac
OSX 10.6. Blocks can greatly simplify code. They can help you
reduce code, reduce dependency on delegates, and write cleaner, more
readable code.
A Block is a chunk of code that can be executed at some future time.
Blocks are first-class functions, which is a fancy way of saying that
Blocks are regular Objective-C objects. Since they’re objects, they
can be passed as parameters, returned from methods and functions,
and assigned to variables.
Syntax: return_type (^block_name)(param_type, param_type, ...)

For more content visit: fb.com/groups/imransvu/


define Term "View" and also write name of items that are supported
by it ? (3 Marks)
name of Touch Events only three ? (3 Marks)
ontouchdown(e)
capturetouch(e)
ontouchmove(e)

write a not on Retain count and also its working and usage? (5 Marks)
"Retain count rules. Init, new, copy in name. Assume you own. Any
other means. Assume in autorelease. If you dont own and want to
make sure, call retain. No longer need and own than release or
autorelease. When 0 count, dealloc called." - Direct from handbook, I
have no idea what it means.

define in detail modes of data binding (5 marks)


Binding Modes:
 One-Way
 Two-Way
 OneWayToSource
 OneTime
One way : The target is updated whenever the source changes.
Two-Way Binding means change to either the target or source
updates the other
OneWayToSource is the opposite of One-Way binding. the source is
changed whenever the target changes.
One-Time binding is like one-way except changes to the source are
not reflected at the target. The target retains a snapshot of the source
at the time the Binding is initiated.

For more content visit: fb.com/groups/imransvu/


ek code tha us ki output btani the localization may say tha ? (5 Marks)
ek case the kay ek admin nay online order bucking kawani hay magr
usay nahe pta kay kitnay items ho gay tou us ko veriable kay name
assign kary may problem ho rahe hay java Script kay according is
problem ka soulution btay (5 Marks)
1---The dimension of the given array is
Int[][]matrix=new int[][]
{ new int[]{0,1,2}
New int[]{3,4,5}
New int[]{6,7,8,9}
};
3by 2
1by 9
3 by 3
2 by 3

2-----which of the following response show internal server error


404
500
200
304

3-------which of the following response show file not found error


404
500
200
304

For more content visit: fb.com/groups/imransvu/


4---interact with web page layout
Java script
HTML
XML
DOM

5---which of the following technologies is not used in AJAX


DOM
DHTML
Flash(I think)
Css

6----in Xaml browser application ,how much isolated memory we can


use?
256kb
128
512
1024

-----------------subjective------
1---what are the other names of “java script”?/2 marks
ECMAScript, Jscript(not confirmed)

2---Define the term “ios application bundle” /2 marks

For more content visit: fb.com/groups/imransvu/


"a bundle is a directory that allows related resources such as an
application's executable and its graphics to be grouped together,
appearing as a single file to the user." - Wikipedia

3---Can the operating system distinguish between windows with WPF


contents and windows with Win32 contents /2
Yes, we can even create Host WPF content in a Win32 window. and
vice versa.

4---As we know that ICollectionView has a property called “filter”


which provides the facility for selective removal of itemsbased on an
arbitrary condition.this property is also known as
Predicate<Object>type.What is meant by this Predicate<Object.type?
/2
Filtering gives a property Filter of type Predicate¡Object¿.

5----what will be the efficient way of applying the same style on all
p[aragraphs of HTML page?also provide an example //3
A technique is to collect all our CSS rules in one place, a style sheet,
and then apply the style sheet to every single element on the page.
An embedded style sheet affects every element on the page. In order
to create an embedded style sheet, we need to go to the head of the
document.
/span>html>
/span>head>
/span>title>Hello World</title>
/span>style type="text/css">
p {color: #008000; background: #ffff00}

For more content visit: fb.com/groups/imransvu/


</style>
</head>
/span>body>
/span>h1>Hello World</h1>
</body>

6---which property tells the location manager about how accurate the
location finding should be?and why the accuracy is important? /3
[locationmanager setdesiredaccuracy:kcllocationaccuracybest];
7---we know that whatever we bind to a collection (anything that
implements IEnumerable,a default view is implicitly inserted between
the source and target objects.you are required to define the term “view’
and also the names of the items which are supported by it.. /3
Can anyone please solve this I am having trouble understanding this.

8---how can you refresh the current page in WPF Navigation based
application? /3
This.navigationservice.Refresh();
9---Tasks using objective C
 Create location manager object
 Apply accuracy filter on location manager object created in first step
 Tell the manager to start looking for its location immediately
// Create location manager object Locationmanager=
[[cllocationmanager alloc] init];
// We want all results from the location manager [locationmanager
setdistancefilter:kcldistancefilternone];

For more content visit: fb.com/groups/imransvu/


// And we want it to be as accurate as possible // regardless of how
much time/power it takes [locationmanager
setdesiredaccuracy:kcllocationaccuracybest];
// Tell our manager to start looking for its location immediately
[locationmanager startupdatinglocation]; Goto lecture # 41

10---consider the following code lines and explain what are we trying
to achieve from them /5
Msbuild/t:updateuid Projectname.csproj
locBaml/parse Projectname.g.en-US .resources/out.en-US.csv

11---wriring an XAML code to create a “grid panel” having two


buttons/5
Final Paper of CS411
Date:- 28/08/2014
Question 01 ):;M Separete server side language and Clinnt side
language.(3Ma1'ks)JS(Java
Script),Cold Fusion, PHP, ASP.net
Question 02 ):- iOS Wfiywzlcation was give in Question. where we
were asked about the type of touch event's?
Questimi 03):- Differentiate b/W XIB and NIB.(2MarkS)
Question 04):: When using nexrigatign in ent is typically organized in
which elements‘?
Question 05):-W15lMarnwg nfthree'ba§i3 touch events.(3MaH<-s)
Question (>6);;WQ which code line We have created 2resources. (5M)
<resour¢;eInclude = "images\VU1.jpg"\>
<Conte1i‘tInclude = "images§Vl I2.jpg"\>

For more content visit: fb.com/groups/imransvu/


Question 07):- Explain Model-View-ControllerPattern" in the context
of iOS programming. Also give examp1es.(5Marks)

For more content visit: fb.com/groups/imransvu/


CS411-Visual Basics
(Solved Subjective)
LECTURE FROM
(22 to 45)
Junaidfazal08@gmail.com JUNAID MALIK
Bc190202640@vu.edu.pk FOR MORE VISIT 0304-1659294
VULMSHELP.COME
AL-JUNAID TECH INSTITUTE
Q1: Which event combines information from independent touch devices updating
simultaneously and package data inan easy-to-consume form?
Answer:
startupdatinglocation and stopupdatinglocation
Q2: when we set filter property to null, what will
happen?
Answer:

To undo filtering, you can set the Filter property to


null:
Nothing will happen Filer:{category:null}

Q3: Selectors and declarations are two blocks of which website layer?

Answer:
A CSS rule set consists of a selector and a declaration block:
H1 {color:blue; font-size:12px;}
H1 is selector
The selector points to the HTML element you want to style.
The declaration block contains one or more declarations separated by semicolons.Each
declaration includes a property name and a value, separated by a colon.
Q4: Write syntax to create instance of XMLHttpRequest?
Answer:
Xmlhttp = new
XMLHttpRequest();
xmlhttp.open("GET","ajax_info.tx
t",true); xmlhttp
Q5: How you refresh current page in WPF Navigation based application?
Answer: This.navigationservice.Refresh();
Q6: Name and Explain two categories of binary’s resources?
Answer:
Resource: embed resources into the assembly
Content: This leaves resources as loose files and upon compilation this resource
information is notembedded into assembly

Q7: Enlist three benefits of ObjData Provider?


AL-JUNAID TECH INSTITUTE
Answer: By utilizing the XML or Object data providers, we can bind to different types
of objects inour applications
ObjectDataProvider provides a convenient way to create and use objects as binding source
objects inXAML
ObjectDataProvider enables you to create your object in XAML and make it available
as a binding source. It provides the following properties that enable you to execute a
query on your object and bindto the results.
Use the ConstructorParameters property to pass parameters to the constructor of
your object. Use the MethodName property to call a method and use the
MethodParameters property to passparameters to the method. You can then bind
to the results of the method.

Q8: Ajax is interaction of which type of technologies?

Answer:
Ajax interactions can be used to do things such as validate form entries (while the
user is enteringthem) using server-side logic, retrieve detailed data from the server,
dynamically update data on apage, and submit partial forms from the page.
Q9: Describe purpose of using navigation in page in one line? And how we perform
navigation?

Answer: Navigation means managing the current item, not the other kind of nav.
navigation in threemain ways: Calling the Navigate method, Using Hyperlinks, Using
the journal.

Q10: Write Output:


msbuild/t:updateuidProjectName.csProj
LocBaml/parseProjectName_g_en_US.resources/
out:-US-csvAnswer:
msbuild /t:updateuid ProjectName.csproj
running this gives every object element in every XAML file in the project on x:Uid
directive with aunique value and
LocBaml /parse ProjectName.g.en-US.resources /out:en-US.csv
this generate a simple .csv file containing all the property values you should need to
localize
Q11: When browser sends request to web server, in which formats server sends back
information toweb server? Give 4 examples?
AL-JUNAID TECH INSTITUTE
Answer:
Web servers receive request and responds as Html, plain text and XML,
JSON

Q12: Ali wants to bind the entire set of XML data to Tree n Menue write
the code?
Answer:
Text="{Binding Source={x:Reference treeview}, Path=selecteditem.Header}"
<xmldataprovider x:Key="dataprovider" xpath="gamestats">
If you want to bind to xml tree.

<xmldataprovider x:Key="dataprovider" xpath="gamestats" Source="gamestats.xml"/>


<Label Content="{Binding Source={staticresource
dataprovider},Xpath=gamestat/highscore,
Path=outerxml}"/>
Q13: How to localize binary resource. Write code.
Answer: localizing binary resources. Can partition into satellite assembly and use locbaml
to managestring localization. To spec. A default culture and auto. Build a satellite
assembly, you can to set uiculture. Need to open project file in a text ed. Add under
debug, release etc. Or where it effects all prop. If you rebuild your project with this
setting in place, youll find an en-US folder alongside yourassembly, containing the
satellite assembly named assemblyname.resources.dll. Also mark assemblywith the
neutral resource language matching.
<Project >
<propertygroup>
<uiculture>en-US</uiculture>
[assembly:
neutralresourceslanguage("en-US",
Ultimateresourcefallbacklocation.S
atellite)]
Next, apply Uid directive to any element needing localization. Msbuild /t:updateuid
projectname.csproj. Locbaml /parse projectname.g.en-US.resources /out:en-US.csv.
Now edit and localize all strings. Locbaml /generate Project-Name.resources.dll
/trans:fr-CA.csv /cul:fr-CA. Thencopy the assembly with a name matching the locale.
To test, System.Threading.Thread.currentthread.currentuiculture (and
System.Threading.Thread.currentthread.currentculture) to an instance of the desired
AL-JUNAID TECH INSTITUTE
cultureinfo.
Q14: Which object is the core of Ajax?

Answer: GET or POST


The XMLHttpRequest object is a data transport object that is the core of AJAX
AL-JUNAID TECH INSTITUTE
Q15: Write code of the property which tells the location manager n accuracy.

Answer: Distancefilter and desiredaccuracy properties.


// Create location manager object
Locationmanager= [[cllocationmanager
alloc] init];
// We want all results from the location manager
[locationmanager
setdistancefilter:kcldistancefilternone];
// And we want it to be as accurate as possible
// regardless of how much time/power it takes
[locationmanager
setdesiredaccuracy:kcllocationaccuracybest];
// Tell our manager to start looking for its location
immediately[locationmanager startupdatinglocation];
// This line may say self.window, don’t worry
about that[[self window] makekeyandvisible];
Return YES;
}

Q16: Ali wants to select and hide all <p>tags from html. Give syntax for this in
JavaScript andJQuery?

Answer:

var element =
document.getElementsByTagName("p"); for
(index = element.length - 1; index >= 0; index--)
{
element[index].parentNode.removeChild(element
[index]);
}
$(document).ready(function(){
$(“button”).Click(function(){
$(“p”).hide();
});
AL-JUNAID TECH INSTITUTE
});

Q17: How we can implement content, like add pictures, change content in a
page?
Answer: <listbox x:Name="picturebox"
Itemssource="{Binding Source={staticresource photos}}" >
</listbox >
The jquery simplifies all steps except that of changing the webpage simplest is load
function whichloads HTML into an area of web page e.g. Load news in a div from a web-
server
$(’#headlines’).load(’todays news.html’); can only load from same site... Relative urls
possible to addonly a part $(’#headlines’).load(’todays news.html #news’);.

Q18:. How a server response to browser's request? Give at least 4 examples


Answer:
JS, server-side programming, and web browser, all work together. Web browser:
xmlhttprequest object. Makes ajax possible. Talks to web server and get response. JS:
sends request, waits for response, process response, updates web page. Web server:
receives request and responds as HTML,plain text, XML, JSON. Or application server
for more complicated tasks. Need web server for ajax examples.

Q19: binding

Answer: In last lecture, we discused data binding, binding object, markup extension, bind
to any propwith inotifypropertychanged, target must be dependency property, bind to obj.
So no property path, binding to collection, issynchronized with current item, datacontext,
displaymemberpath, stringformat, datatemplate, valueconverter.

Q21: Choose selected data items i.e target items just like last 7 days pictures?

Answer: Filtering gives a property Filter of type Predicate¡Object¿. Its null by default
e.g. Show onlyphotos from last 7 days.

Q22: Jquery code: $ ('li:has(a)') output ???

Answer:
AL-JUNAID TECH INSTITUTE
The code $('li:has(a)') matches a <li> if a <a> exists anywhere among its descendants, not
just as adirect child.
AL-JUNAID TECH INSTITUTE
Q23: How can we present a window from automatically being activated when its
is first show?

Answer: There are Activated & Deactivated events. Activate method (like
setforegroundwindow).Showactivated=false, initially not shown
Public static void Main()
{
Mainwindow window =
new mainwindow();
Window.Show();
}

Q24: When it is preferable to use begininvoke then invoke?

Answer: Long running operations make application unresponsive. Because


main thread used for rendering UI and responding to events. Start up worker
thread and update UI when finished. But UI updation usually possible only on
UI thread. So, forward the request to UI thread.(or marshal it). Lowlevel way is
to call begininvoke or Invoke on the elements Dispatcher object. It takes a
delegate and queues it on the UI thread. Invoke does same but then blocks until
it is done. So you can return a value. But if you dont need begininvoke is
better.

Q25: Identify client side languages and server side languages cold fusion, asp.net,
java script and php?

Answer: Server-Side Coding


JS is a prog lang and can be used on server side. The document sent to the
browser may often containclient-side scripts. ASP.NET, PHP, Java,
ColdFusion, Perl, Python, and Ruby are examples of languages used for
server-side coding.

Q26: What are the 2 problems of memory management in IOs?

Answer: Freeing or overwriting data that is still in use. This causes memory
corruption, and typicallyresults in your application crashing, or worse, corrupted
AL-JUNAID TECH INSTITUTE
user data.
Not freeing data that is no longer in use causes memory leaks. A memory leak
is where allocated memory is not freed, even though it is never used again.
Leaks cause your application to use ever- increasing amounts of memory,
which in turn may result in poor system performance or (in iOS) your
application being terminated.

Q27: Write the Properties


of touch point?
Answer:
TouchPoint has Position, Size, Bounds,
TouchDevice, Action(Down, Up, Move).
Q29: What is the technique used in Cocoa framework for memory management.

Answer:
Cocoa framework use reference counting model for memory management

Q30: When using navigation in WPF, content is typically organized in which


element?

When using navigation in WPF, content is typically organized


in Page elements. Page elements can then be hosted in one of
two built-in navigation containers: NavigationWindow or
Frame.
These containers provide a way to navigate from one page to another, a “journal”
that keeps track ofnavigation history, and a series of navigation-related events.

Q31: why we write navigation in one line line in a web page? syntax of
navigation?

Answer: // Or navigate to a page via a URI


This.navigationservice.Navigate(new
Uri("photopage.xaml", urikind.Relative));
This.commandbindings.Add( new
commandbinding(applicationcommands.Help, helpexecuted,
AL-JUNAID TECH INSTITUTE
helpcanexecuted));

Q32: Write properties of MousePoint?


Answer:
pageX page Y
screenX screenY
Q33: What is
"Command" in WPF?

Answer: Commands are a more abstract and loosely coupled version of events
e.g. cut copy paste commands. They are exposed in various ways. They can be
enabled disabled e.g. if there is nothing topaste.

Q34: identify Application commands and


component commands:close select to end
Help,find and Move to right
Answer:
Application commands: close , help, find

Component commands: move to right , select to end

Q36: how can we destroy an object in objective-C?

Answer:
Set the variable referencing to that object to nil.
Or
Destroy using [array Instance release]; Should also array Instance = nil;
Otherwise dangling. butSending message to nil is ok. nil is like null

Q37: Does Java script have any connection with java or not. Give valid reason?

Answer:
No connection with java
Actually java was popular before invention of JavaScript The first name of
JavaScript was not
AL-JUNAID TECH INSTITUTE
JavaScript .... Due to popularity of java. that new language change its name to
JavaScript

Q38: what is the other name of JavaScript?


Answer:
JS has nothing to do with Java, originally named LiveScript but renamed to
associate with the then hotJava

Q39: Media Commands, Navigation Commands, Editing Commands, application


commands andcomponents commands?
ApplicationCommands

e..g Close, Copy, Cut, Delete, Find, Help, New,


Open, Paste, Print, PrintPreview, Properties, Redo, Replace, Save, SaveAs,
SelectAll, Stop, Undo, andmore.
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,Next-
Track, 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
AL-JUNAID TECH INSTITUTE
e.g. AlignCenter, AlignJustify, AlignLeft, AlignRight, Correct-
SpellingError, DecreaseFontSize, DecreaseIndentation, EnterLineBreak,
EnterParagraphBreak,IgnoreSpellingError,
IncreaseFontSize, IncreaseIndentation, MoveDownByLine,
MoveDownByPage,MoveDownByParagraph,
MoveLeftBy-
Character, MoveLeftByWord, MoveRightByCharacter, MoveRightByWord, and
more.

Q40 : Which element must be added to the project file to specify a default
culturefor resources automatically build an appropriate satellite assembly?

Answer:

Build a satellite assembly, you can to set UICulture. Need to open project file
in a text ed. add underdebug, release etc. or where it effects all prop.

Q41: Which data provider exposes.NET object as a data source?


Answer:

ObjectDataProvider exposes .net object as a data source.

Q42: what is difference between hover() and toggle()?

Answer:
Difference b/w hover() and toggle() is that toggle() works by clicking it on and
off whereas hover()works just by positioning the mouse over it.

Q43: Core Locations Framework contains which types of classes ?

Answer: Page 218


Core Locations classes that enable finding geographical position.
distanceFilter and desiredAccuracyproperties.
AL-JUNAID TECH INSTITUTE
Q44: when we preferred BeginInvoke instead of Invoke method?

Answer:
There are times when you want to invoke a delegate and wait for its execution to
complete before thecurrent thread continues. In those cases the Invoke call is
what you want.
In multi-threading applications, you may not want a thread to wait on a delegate
to finish execution,especially if that delegate performs I/O (which could make
the delegate and your thread block). In those cases the BeginInvoke would be
useful.

Q45: what is difference between server Side programming and Client Side
Programming? (3Marks)

Answer:
Server-side programming is the general name for the kinds of programs which are
run on the Server.
Uses
Process user input.
Display pages.
Structure web applications.
Interact with permanent storage (SQL, files).
Much like the server-side, Client-side programming is the name for all of the
programs which are runon the Client.
Uses
Make interactive webpages.
Make stuff happen dynamically on the web page.
Interact with temporary storage, and local storage (Cookies, localStorage).
Send requests to the server, and retrieve data from it.
Provide a remote service for client-side applications, such as software
registration, contentdelivery, or remote multi-player gaming.
Also check here for more detail

Q46: define iOS feature of Block and also provide its syntax? (3 Marks)

Answer:
Blocks are a new feature that was introduced in iOS 4.0 and Mac OSX 10.6.
AL-JUNAID TECH INSTITUTE
Blocks can greatly simplify code. They can help you reduce code, reduce
dependency on delegates, and write cleaner,more readable code.
A Block is a chunk of code that can be executed at some future time.
Blocks are first-class functions, which is a fancy way of saying that Blocks
are regular Objective-Cobjects. Since they’re objects, they can be passed as
parameters, returned from methods and functions, and assigned to variables.
Syntax: return_type (^block_name)(param_type, param_type, ...)
Q47: Name of Touch Events only three?
 touchenter
 touchleave
 touchmove
 previewtouchmove
 touchdown
 touchup
Q48: write a not on Retain count and also its working and usage?

Answer:
"Retain count rules. Init, new, copy in name. Assume you own. Any other
means. Assume in autorelease. If you dont own and want to make sure, call
retain. No longer need and own than releaseor autorelease. When 0 count,
dealloc called." - Direct from handbook, I have no idea what it means.

Q49: define in detail modes of data binding (5 marks)


Binding Modes:
One-Way
Two-Way
OneWayToSource
OneTime
One way : The target is updated whenever the source changes.
Two-Way Binding means change to either the target or source updates the other
OneWayToSource is the opposite of One-Way binding. the source is changed
whenever the target changes.
One-Time binding is like one-way except changes to the source are not reflected at
the target. The target retains a snapshot of the source at the time the Binding is
initiated.
AL-JUNAID TECH INSTITUTE
Q50: Define the term “ios application bundle” /2 marks

Answer:
"a bundle is a directory that allows related resources such as an application's
executable and itsgraphics to be grouped together, appearing as a single file to
the user." - Wikipedia
Q51: Can the operating system distinguish between windows with WPF
contents and windowswith Win32 contents?
Answer:
Yes, we can even create Host WPF content in a Win32 window. and vice versa.

Q52: As we know that ICollectionView has a property called “filter” which


provides the facilityfor selective removal of itemsbased on an arbitrary
condition.this property is also known as Predicate<Object>type.What is
meant by this Predicate<Object.type?

Answer:
Filtering gives a property Filter of type Predicate¡Object¿.

Q53: Can Operating System distinguish between window contain WPF and
window ContainWin32?
ANSWER:
There are three major differences between a WPF application and a Windows
Forms application: Layout, Render, Presentation
Layout:
WPF layout system provides a greater flexibility in arranging the
elements on the fly.
Render:
You can use any Transform as Render Transform to easily implement
smooth zoom/rotate, or develop custom GPU-based shader effects, and much
more in WPF.
Presentation:
When developing WPF Applications you have to stop thinking in
Windows Forms: No more UI events, accessing controls by their names and writing
logic in code-behind and start to think in WPF: Binding, Commands, Resources,
Styles, Templates, Converters, DependencyProperties and their callbacks.
AL-JUNAID TECH INSTITUTE
Q54: what will be the efficient way of applying the same style on all
p[aragraphs of HTMLpage?also provide an example?
Answer:
A technique is to collect all our CSS rules in one place, a style sheet, and then
apply the style sheet to every single element on the page. An embedded style
sheet affects every element on the page. In orderto create an embedded style
sheet, we need to go to the head of the document.
/span>html>
/span>head>
/span>title>Hello World</title>
/span>style type="text/css">
p {color: #008000; background: #ffff00}
</style>
</head>
/span>body>
/span>h1>Hello World</h1>
</body>

Q55: which property tells the location manager about how accurate the
location finding shouldbe?and why the accuracy is important?

Answer:
[locationmanager setdesiredaccuracy:kcllocationaccuracybest];

Q54: we know that whatever we bind to a collection (anything that


implements IEnumerable,adefault view is implicitly inserted between the
source and target objects.you are required to define the term “view’ and
also the names of the items which are supported by it.
ANSWER:
View" refers to things which are displayed to a user and UIview elements
are supported by it.
A collection view supports features in WPF:
-Navigation
-Filetering
-sorting
AL-JUNAID TECH INSTITUTE
-Grouping
Q56: how can you refresh the current page in WPF Navigation based
application?

Answer:
This.navigationservice.Refresh();

Q57: Tasks using objective C


Create location manager object
Apply accuracy filter on location manager object
created in first stepTell the manager to start looking
for its location immediately

Answer:

// Create location manager object Locationmanager= [[cllocationmanager alloc]


init];
// We want all results from the location manager [locationmanager
setdistancefilter:kcldistancefilternone];
// And we want it to be as accurate as possible // regardless of how much
time/power it takes[locationmanager
setdesiredaccuracy:kcllocationaccuracybest];
// Tell our manager to start looking for its location immediately
[locationmanagerstartupdatinglocation];

Q58: define Term "View" and also write name of items that are supported
by it?

Q 59: What is Difference between Navigation Window and Frame?


ANSWER:
Navigation window gives you a navigation Bar by default while Frame does not.
Navigation Window is more like a top-level window while Frame more like an HTML
frame or iframe.
Q 59: Journal and stack
Answer:
). Journal provides logic behind back and fwd.
). Two internal stacks are:
AL-JUNAID TECH INSTITUTE
Undo
Redo
Q 60: For example, you can set a title that is used in the drop-down menu associated with
the Back and Forward buttons as follows:
Answer:
This.navigationservice.Title = Main Photo Gallery Page;
Q 61: Navigation in three main ways:
Answer:
Calling the Navigate method, Using Hyperlinks, Using the journal.
Q 62: Navigate to a page instance?
Answer:
Photopage nextpage= new photopage();
This.navigationservice.Navigate(nextpage);

Q 63: Navigate to a page via a URI


Answer:
This.navigationservice.Navigate(new Uri("photopage.xaml", urikind.Relative));
Q 64: Navigate to a page by instance or URI?
Answer:
Application.Properties["photoid"] = 10;
This.navigationservice.Navigate(/* */);
If (Application.Properties["photoid"] != null)
Loadphoto((Application.Properties["photoid"]);

Q 65: What is difference between Clickonce caching VS increments ?


. Or you can clear cache mamory. Change some settings by its a xbap(xml browser
application). But partial trust restricts many api. E.g. Above call exception. Requires
fileiopermission which is not by default. Hit n trial to find what works. Local registry
and file system, new windows (popups ok), unmanaged, but others dependent on
browser, or on implementation details. Browserinterophelper.isbrowserhosted
property to check if its a XBAP.

(Isi se related aik example he or iska jo question ban sakta he wo bhi diya howa he.)

Q 65: How to open file from local system?


Answer:
String filecontents = null;
Openfiledialog ofd= new openfiledialog
();
If(ofd.showdialog() == true)// Result could be true, false, or null
{
AL-JUNAID TECH INSTITUTE
Using(Stream s= ofd.openfile())
Using(streamreader sr= new streamreader(s))
{
Filecontents= sr.readtoend();
}
}
Q 66: What are the binary resources and logical resources?
Answer:
Binary resources are .net framework. Even compiled(murattab) xaml stored as a
resource. Can be embedded(sarayyat) in assembly. Loose file that may or may not be
known at compile time. Can be localizable or not. Localizabl mean change dependency
on the current culture. To define a binary resource, add a file and set the build action
resource or content (loose file).

Logical resource
Logical resources are introduced by wpf. Arbitrary .net object stored and named in an
elements Resources property. Base close of both Frameworkelement and framework
content element both have a Resources property. Often are style or data providers
Q 67: There are also full-trust browser apps. In the project file you change?
Answer:
<targetzone>Internet</targetzone> To this:
<targetzone>Custom</targetzone>
And in clickonce application manifest you add:
<permissionset class="System.Security.permissionset"
version="1" ID="Custom" samesite="site"
Unrestricted="true"/>

Q 68: What are the resources?


Answer:
Bitmap, fonts, string tables
Q 69: WPF builds on top, has binary?
Answer:
WPF builds on top, has binary resources and logical resources. Binary resources are what
rest of .net framework considers a resource. Even compiled XAMLstored as a resource.
Can be embedded in assembly, loose file that may or may not be known at compiletime.
Can be localizable or not. To define a binary resource, add a file and set the build action
resource or content (loose file). Don’t use embedded resource. Its misleading name but
WPF doesn’t fully support. Adding as content and loading directly are kind of equal but
resource is neat. Should be embed if localizable or single binary file benefits. Let’s see
AL-JUNAID TECH INSTITUTE
how to assign binary resource whether embed or loose. Won’t work if not added to
project. If not added be explicit about the path.

Q 70: How to specify default culture of the application?


ANSWER:
<Project>
<propertygroup>
<uiculture>en-US</uiculture>
[assembly: neutralresourceslanguage("en-US",
Ultimateresourcefallbacklocation.Satellite)]
Q 71: How to use logical resources?
ANSWER:
By using logical resources, you can change brushes in one place and have different
effects.
Q 72: what is the difference between static resources and dynamic resources?
ANSWER:
Dynamic resource reapplied every time it changes nothing special about 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 also summarize the entire
control.
Dynamic Resources can manipulate at runtime and are evaluated at runtime.
While static recourses cannot manipulate at runtime.
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Image Height="21" Source="zoom.gif"/>
</Window >
Is equivalent to this Window:

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<Image x:Key="zoom" Height="21" Source="zoom.gif"/>
</Window.Resources >
<stackpanel>
<staticresource resourcekey="zoom"/>
</stackpanel >
</Window >

Q 73: How to change block of line background color in C# using XAML?


ANSWER:
AL-JUNAID TECH INSTITUTE
C\#:
Button.Background = systemcolors.windowbrush;
(using XAML)
XAML:
<Button Background=" { staticresource systemcolors.windowbrushkey}"/>
(color change karnay kay bad resources kisterha se sat karnay he)
C\#:
Button.Background = (Brush)findresource("systemcolors.windowbrushkey");

XAML:
<Button Background="{ staticresource{x:Static systemcolors.windowbrush}}"/>
Q 74: What is data binding? With example.
ANSWER:
Data binding means an arbitrary .net obj. Data binding, data templates, data
triggers are related concepts. Data can be collection obj, custom obj, xml file, web
service, db table, even WPF element eg button. So data binding is typing together
arbitrary objects. Classic scenario is a visual rep. (e.g. List box or data grid) of items in
an xml file, db, or in-memory collection. Instead of iterating and adding items, tell
listbox to get its data from another source, keep them up to date, format them etc.
Binding binds two properties together and keeps a communication channel open. Setup
Binding handles all the sync.
Example(imp)
Public mainwindow()
{
Initializecomponent();
Binding binding= new Binding();
// Set source object
Binding.Source=
treeview;
// Set source property
Binding.Path= new propertypath("selecteditem.Header");
// Attach to target property
Currentfolder.setbinding(textblock.textproperty, binding);
}

Q 75: How to display member path property to improve display? Listbox


ANSWER:
<listbox x:Name="picturebox"
Itemssource="{Binding Source={staticresource photos}}">
</listbox >
Q 76: write a program for synchronize? Or Example of synchronize?
ANSWER:
AL-JUNAID TECH INSTITUTE
<listbox issynchronizedwithcurrentitem="True" displaymemberpath="Name"
Itemssource="{Binding Source={staticresource photos}}"></listbox>
<listbox issynchronizedwithcurrentitem="True" displaymemberpath="datetime"
Itemssource="{Binding Source={staticresource photos}}"></listbox>
<listbox issynchronizedwithcurrentitem="True" displaymemberpath="Size"
Itemssource="{Binding Source={staticresource photos}}"></listbox>

Q 77: Data context? Example of Data context?


ANSWER:
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.
<stackpanel datacontext="{staticresource photos}">
<Label x:Name="numitemslabel"
Content="{Binding Path=Count}"/>
<listbox x:Name="picturebox" displaymemberpath="Name"
Itemssource="{Binding}">
</listbox >
</stackpanel >

Q 78: How many ways of control rendering?


ANSWER:
There are three ways of control rendering.
String formatting
Data template
Value conversion. (Value convertor)
Q 79:What is data template?
ANSWER:
<listbox x:Name="picturebox"
Itemssource="{Binding Source={staticresource photos}}">
<listbox.itemtemplate>
<datatemplate>
<Image Source="{Binding Path=fullpath}" Height="35"/>
</datatemplate >
</listbox.itemtemplate >
</listbox >

Q 80: When you sort on one field?


ANSWER:

Sortdescription sort = new sortdescription("Name", listsortdirection.Ascending);


AL-JUNAID TECH INSTITUTE
Q 81: When you sort on different field?
ANSWER:
View.sortdescriptions.Add(new sortdescription("datetime",
listsortdirection.Descending);View.sortdescriptions.Add(new sortdescription("Name",
listsortdirection.Ascending);
Q 82: Click event handlers for three different Buttons?
ANSWER:
Void sortbyname_Click(object
sender,routedeventargs e)
{
Sorthelper("Name");
}
Void sortbydatetime_Click(object sender, routedeventargs e)
{
Sorthelper("datetime");
}
Void sortbysize_Click(object sender, routedeventargs e)
{
Sorthelper("Size");
}
Void sorthelper(string propertyname)
{

Q 83: Get the default view


ANSWER:
Icollectionview view = collectionviewsource.getdefaultview(
This.findresource("photos"));
// Check if the view is already sorted ascending by the current
propertyIf(view.sortdescriptions.Count> 0
&& view.sortdescriptions[0].propertyname == propertyname
&& view.sortdescriptions[0].Direction== ", listsortdirection.Ascending)
{
// Already sorted ascending, sot o g g l eby sorting descending
View.sortdescriptions.Clear();
View.sortdescriptions.Add(new sortdescription(
Propertyname, listsortdirection.Descending));
}
Else
{
// Get the default view (ye bhi he)
Icollectionview view = collectionviewsource.getdefaultview(
This.findresource("photos"));
// Do the grouping 46 view.groupdescriptions.Clear();
View.groupdescriptions.Add(new
propertygroupdescription("datetime"));
AL-JUNAID
<liszbox x:Name="picturebox"
TECH INSTITUTE
Q 84: How to filter?
ANSWER:
Icollectionview view = collectionviewsource.getdefaultview(
This.findresource("photos"));
View.Filter= delegate(object o) {
Return((o as Photo).datetimedatetime.Now).Days<=7;
};
// Get the default view (iske default view k liye)
Icollectionview view = collectionviewsource.getdefaultview(
This.findresource("photos"));
Q 85: To binding project?
ANSWER:

"{Binding Path=/}"
Binding the date or time property?
"{Binding Path=/datetime}"
Binding pictures ya binding convert data sources
"{Binding Path=Photos/}"
Binding to the data time property of different data sources
"{Binding Path=Photos/datetime}"

Q 86: What is navigation?


ANSWER:
Navigation means managing the current item, not the other kind of nav.
Icollectionview has current item current position and also methods for changing them.
Navigation means managing the current item not the other kind of nav. Navigation
in three main ways: calling the navigation method, using hyperlinks, using journal.
Q 86: Properties for binding paths?
ANSWER:
Property Paths in Bindings are useful for master/detail interfaces. Sorting, grouping,
filtering automatic
Q 87: Collectionviewsource
ANSWER:
Collectionviewsource can be used to create new views and applied to targets.
Collectionviewsource has its own sort descriptions and group descriptions properties and
a Filter event to beused from XAML
Q 88: What are data providers?
ANSWER:
Data provider is the kind of classes. Which give access through simpler way in
containing data. You could bind to db, registry, excelspreadsheet etc.
AL-JUNAID TECH INSTITUTE
Xmldataprovider and objectdataprovider
<xmldataprovider x:Key="dataprovider" xpath="gamestats" Source="gamestats.xml"/>
<Label Content="{Binding Source={staticresource dataprovider},
Xpath=gamestat/highscore, Path=outerxml}"/>

Q 89: What is the use of data provider?


, data providers (xml and object), used xml data provider to fill a listbox.

Q 90: What is objectdataprovider?


ANSWER:
Objectdataprovider is .net object as a data source. So that we can add binding
directly to a .net obj. We declare directly source object with a parameterized constructor.
We have more options for asynchronous data binding. When binding not quickly
asynchronous. So it does not stuck. WPF has two ways to mark asynchronous that are
asynchronous property of Binding.
Isasync prop of Binding and write in Details.
Q 91:
Answer:
1.Xmldataprovider, 2. objectdataprovider
1. Xmldataprovider: Is used to declare xml data access for data binding.
The XmlDataProvider.IsAsynchronous property is set to true by default, which means
that the XmlDataProvider retrieves data and produces the collection of XML nodes
asynchronously by default.
2. objectdataprovider: It enable us to create object in xml and available it for binding
source.
 ObjectDataProvider enables you to create your object in XAML.
 Make it available as a binding source.
 It provides the properties that enable you to execute a query on your object.

Q 92: How we can define the object data provider?


ANSWER:
<Window.Resources>
<local:Photos x:Key="photos"/>
<objectdataprovider x:Key="dataprovider"
Objectinstance="{staticresource photos}"/>
</Window.Resources >
<Window.Resources>

Q 94: What is method data binding? Example


ANSWER:
AL-JUNAID TECH INSTITUTE
Binding to a method is useful for classes that are not designed for data binding Imagine
photos class had getfoldername method.

Example:
<objectdataprovider.constructorparameters>
<sys:Int32>23</sys:Int32>
</objectdataprovider.constructorparameters >
</objectdataprovider >
<objectdataprovider
x:Key="dataprovider"
Objecttype="{x:Type local:Photos}"
Methodname="getfoldername"/>

Data binding allows declaratively binding two different properties in XAML.In other
words, data binding is a general technique that binds data sources from the provider and
consumer together and synchronizes them. Binding binds two properties together and
keeps a communication channel open.

Q 95: What is different between convert method and convert back method?
ANSWER:
Convert method is used during bringing data from source to target.
While convert back used during bringing data from target to source.

Q 96: How many ways of binding mode explain one way with example or explain two
ways with example?
ANSWER:
One way: The target is updated whenever the source changes.
Two-way: We can change either the target or updates source.
Onewaytosource: This is the opposite of oneway. The source is updated whenever the
target changes. The target retains a snapshot of the source at the time the Binding is
initiated.
Updatesourcetrigger. Do you want the two-way source to be updated on every key
stroke. Propertychanged. Changed when target property value changes. Lostfocus.
Changed when focus lost. Explicit. Call bindingexpression.updatesource which you
can get from any frameworkelement.getbindingexpression

Q 97: Definition of validation rule?


ANSWER:
AL-JUNAID TECH INSTITUTE
Validation rule are just like simple classes that are use to ensure the
proper working of the application.
7: define exceptions validation rule?
Exceptions validation rule says that you can update a source if updating source does not
cast an exception.
Q 98:
What is the purpose of concurrency?
ANSWER:
1. Responsive user interface.
2. Simultaneous requests.
3. Parallel programming.

Concurrency is the task of running and managing the multiple computations at


the same time. While parallelism is the task of running multiple computations
simultaneously.

Q 99: How to create a thread?


ANSWER:
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");
}
}

Typical Output:
Xxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
xxxxxxxxxxxxxxxxxxxxxxxxxx

Q 100: What is time slicing?


ANSWER:
AL-JUNAID TECH INSTITUTE
Handouts() . 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.
Join and Sleep. A thread is “blocked” when waiting

Q 101: What is thread safety?


ANSWER:
Class threadsafe
{
Static bool_done;
Static readonly object_locker = new object();
Static void Main()
{
New
Thread(Go).Start();
Go();
}
Static void Go()
{
Lock (_locker)
{
If(!_done){ Console.writeline("Done");_done= true; }
}
}
}

Q 102: What is locker variable?


ANSWER:
Class threadsafe
{
Static bool_done;
Static readonly object_locker = new object();
Static void Main()
{
New
Thread(Go).Start();
Go();
}
Static void Go()
{
Lock (_locker)
{
If(!_done){ Console.writeline("Done");_done= true; }
}
}
}
Q 103:
AL-JUNAID TECH INSTITUTE
Passing Data to Threads
ANSWER:
Static void Main()
{
Thread t= new Thread(()=> Print("Hello from
t!"));T.Start();
}
Static void Print(string message) { Console.writeline(message);}

For(int i= 0; i < 10; i++)


New Thread (()=> Console.Write(i)).Start();
Typical Output:
0223557799
For(int i= 0; i < 10; i++)
{
Int temp= i;
New Thread (()=> Console.Write(temp)).Start();
}
Q 104: What is difference between begin invoke and Invoke?
OR
Which type of methods are begin invoke and invoke?
ANSWER:
Long running operations make application unresponsive. Main thread used
for rendering UI and responding to events. But UI updating usually possible only on UI
thread. Begin invoke and invoke are such methods that can be called from any other
thread. Begin invoke is a low level primitive. Invoke does same but then blocks until it is
done. You can return a value. But if you don’t need it begininvoke is better.
Invoke: calling thread waits for completion before continuing.
Begin Invoke: calling thread doesn't wait for completion.
EXAMPLE:
Partial class mywindow: Window
{
Public mywindow()
{
Initializecomponent();
New
Thread(Work).Start();
}
Void Work()
{
Thread.Sleep(5000);
Updatemessage("The
answer");
}
AL-JUNAID TECH INSTITUTE
Void updatemessage(string message)
{
Action action=()=> txtmessage.Text= message;
Dispatcher.begininvoke(action);
}
}

Q 105: How can we use thread pool?


ANSWER:
Threadpool save time of thread creation. Background can degrade performance.
Threadpool creates or reduces real threads using a hillclimbing algo to maximize cpu
usage and reduce slicing.
Property: Thread.currentthread.isthreadpoolthread

Q 106: How many ways for calling threads from threadpool?


ANSWER:
There are two ways.
Threadpool.queueuserworkitem(notused=> Console.writeline ("Hello"));
Task.Run(()=> Console.writeline ("Hello from the thread pool"));
Q 107: How many ways or benefits of task?
ANSWER:
1. Easy return value from thread.
2. Exception handling.
3. Continuation.
Task.Run(()=> Console.writeline ("Foo"));
New Thread (()=> Console.writeline ("Foo")).Start();

Task task= Task.Run (()=>


{
Thread.Sleep (2000);
Console.writeline
("Foo");
});
Console.writeline (task.iscompleted);
Task.Wait();

Q 108: What is result of this code?


ANSWER:
Var tcs = new taskcompletionsource<int>();
New Thread (()=>{
Thread.Sleep(5000); tcs.setresult(42);
AL-JUNAID
}).Start();
TECH INSTITUTE
Task<int> task = tcs.Task;
Console.writeline (task.Result

Q 109: How to use delay method


ANSWER:
Task.Delay(5000).getawaiter().oncompleted(()=> Console.writeline
(42));Task.Delay(5000).continuewith(ant => Console.writeline (42));

Q 110: How many ways or benefits of task?


ANSWER:
1. Easy return value from thread.
2. Exception handling.
3. Continuation.

Q 111: What is the difference between Synchronous and Asynchronous?


ANSWER:
Asynchronous typically return quickly. Called non-blocking. Thread. Start, task. Run,
attaching continuations.
Synchronous represents a set of activities that starts happening together at the same
time. A synchronous call waits for the method to complete before continuing with
program flow. An asynchronous method runs synchronously until it reaches its first
await expression, at which point method is suspended until the awaited task is complete.
In the meantime, control returns to the caller of the method. asynchronous typically
return quickly. In asynchronous method calling in C#, two or more method runs on
different threads. When you will call any method asynchronously then it creates another
thread to complete that task. That's why in asynchronous call, calling method doesn't get
blocked, and they can run simultaneously with called method.
A synchronous method call can create a delay in program execution that causes a bad
user experience. An asynchronous method calls (creation of a thread) will return
immediately so that the program can perform other operations while the called method
completes its work in certain situations.
Asynchronous JavaScript and XML (AJAX) is a development technique used to
create interactive web applications or rich internet applications. AJAX uses a number of
existing technologies together, including: XHTML, CSS, JavaScript, Document Object
Model, XML, XSLT, and the XMLHttpRequest object.

Q 112: How CPU bound Synchronization task?


ANSWER:
{
AL-JUNAID
Return
TECH INSTITUTE
Parallelenumerable.Range(start, count).Count(n =>
Enumerable.Range(2,(int)Math.Sqrt(n) - 1).All(i => n % i> 0));
}
Void displayprimecounts()
{
For(int i= 0; i < 10; i++)
Console.writeline(getprimescount(i* 1000000 + 2,
1000000)+
" primes between "+(i* 1000000)+ " and "+((i+ 1)* 1000000 - 1));
Console.writeline("Done!");
}
Q 113: How to asynchronous Task displayprimecounts()?
ANSWER:
{
For(int i= 0; i < 10; i++)
Console.writeline(await getprimescountasync(i * 1000000 +2,
1000000)+" primes between "+(i* 1000000)+ " and "+((i+ 1)*
1000000 - 1)); Console.writeline("Done!");
}

Q 114: Write the syntax of “await”?


ANSWER:
Var result= await
expression;Statement(s);
Q 115: What is difference between sync and await keywords?
ANSWER:

Eliminates plumbing for asynchronous code. As simple as sync code.“await” simplifies


attaching continuations.
We can call it with await and use “asynchronous” keyword so compiler treats await
specially. asynchronous can be applied to methods returning void or Task or Task¡tresult¿.
Q 116: how can we write the message loop?
ANSWER:
While(!Thisapplication.Ended)
{
Wait for something to appear in message
queueGot something: what kind of message
is it?
Keyboard/mouse message-> fire an event handler
User begininvoke/Invoke message-> execute delegate
AL-JUNAID TECH INSTITUTE
}

Q 117: How can we return a Task from void function without explicitly return?
ANSWER:
Enables synchronize call through chains. Compiler indirectly uses taskcompletionsource
to implement methods returning Tasks. We can expand printanswertolife like this.
Async Task Go()
{
Await
printanswertolife();
Console.writeline("Done"
);
}
Async Task printanswertolife()
{
Int answer =
Await getanswertolife();
Console.writeline(answer);
}
Async Task <int> getanswertolife()
{
Await
Task.Delay(5000);Int
answer = 21 * 2;
Return answer;
}
Void Go()
{
Printanswertolife();
Console.writeline("Done");
}
Void printanswertolife()
{
Int answer =
getanswertolife();
Console.writeline(answer);
}
Int getanswertolife()
{
Thread.Sleep(500
0);Int answer =21
* 2; Return
answer;
}
Q 118: how many steps to use asynchronous in programming?
AL-JUNAID TECH INSTITUTE
Answer:
There are three steps
1. Write sync
2. Use asynchronous and await
3. Return the task in place of void.

This means only Task. Run for real parallel cpu task and TCS for realparallel IO task.
Rest of TCS are taken care of by compiler.

Q 119: Write the code of asynchronous chaining?


ANSWER:
Async Task Go()
{
Var task=
printanswertolife();Await
task;
Console.writeline("Done");
}

Q 120: What is parallelism?


ANSWER:
Parallelism is the ability to have parallel execution of two tasks at a time on the system
that has multiple courses.
Parallelism is the task of running multiple computations simultaneously.
Example:
Var task1 =
printanswertolife(); Var task2
= printanswertolife(); Await
task1;
Await task2;
Async Task <int> getanswertolife()
{
_x++;
Await
Task.Delay(5000);
Return 21* 2;
}
Async
Q 121: What is pseudo-concurrency?
ANSWER:
Pseudo-concurrency means a program is running and wait for something then resuming
and then awaiting.
AL-JUNAID TECH INSTITUTE
Q 122: What is Cancellation?
ANSWER:
Class cancellationtoken
{
Public bool iscancellationrequested { get; private set;}
Public void Cancel() { iscancellationrequested = true; }
Public void throwifcancellationrequested()
{
If(iscancellationrequested)
Throw new operationcanceledexception();
}
}

Q 123: Cancellation by using task?


ANSWER:
Var cancelsource= new cancellationtokensource();
Task.Delay (5000).continuewith(ant => cancelsource.Cancel());

Q 124: What is async call graph execution?


ANSWER:

1. Every await and return


2. When delay fights a thread
3. Remaining statements run.
4. Eventually go starts is not as completed.

Q 125: When Task Combinators is used?

 When we have one task we can use it.


 We can also use it in multiple tasks as well.
EXAMPLE:
Task<int> winningtask = await
Task.whenanyConsole.writeline
("Done"); Console.writeline
(winningtask.Result); 4 (Delay1(),
Delay2(), Delay3());
Int answer = await await Task.whenany(Delay1(), Delay2(), Delay3());

Q 126: When all tasks are combinated ?


ANSWER:
Await task1; await task2; await task3;
AL-JUNAID TECH INSTITUTE
Task task1 = Task.Run (()=> { throw
null;} ); Task task2 = Task.Run (()=> {
throw null;} ); Task all = Task.whenall
(task1, task2);
Try{ await all;}
Catch
{
Console.writeline (all.Exception.innerexceptions.Count);
}
Q 127: How many steps partition of Task Parallel Library?
ANSWER:
1. Small chunks
2. process,
3. collate the results in thread-safe manner

Q 128: How many types of parallelism?


ANSWER:
1. Data parallelism
2. Task parallelism

Q 129: What are the three steps of implementing parallelism? Also differentiate between
data parallelism and task parallelism?
ANSWER:
Three steps of Parallelism:
 Partition Problem
 Process
 Combine the results

Data Parallelism
Data parallelism refers to scenarios in which the same operation is performed
(that is, in parallel). In data parallel operations, the source collection is partitioned so
that multiple threads can operate in different segments.
Task parallelism
 Task parallelism is the process of running tasks in parallel.
 Task parallelism divides tasks and allocates those tasks to separate threads
for processing.
. It is based on unstructured parallelism. It means the parallel work unit may start
and finish in places scattered according to executing of the program.
AL-JUNAID TECH INSTITUTE
Q 130: Define parallelism with an example?
ANSWER:
Public static void Invoke(params Action[]
actions);Parallel.Invoke(
()=> new webclient().downloadfile("http://www.linqpad.net", "lp.html"),() => new
webclient().downloadfile ("http://www.jaoo.dk", "jaoo.html"));
Q 131: How many static methods of parallel class?
ANSWER:
There are three static methods of parallel class
1. Parallel.Invoke
2. Parallel.for
3. Parallel.foorieg
For(int i= 0; i < 100; i++)
Foo(i);
Parallel.For(0,100, i=> Foo(i));
Parallel.For(0,100, Foo);
Foreach (char c in "Hello,
world")Foo(c);
Parallel.foreach("Hello, world", Foo);

Q 132: What is loop counter?


ANSWER:
Breaking out of loops, and using per-thread counters. Loop counters areeasy with
sequential. Use overloaded version
Q 133: What is parallel loop state? EXAMPLE
ANSWER:
Public class parallelloopstate
{
Public void
Break();Public
void Stop();
Public bool isexceptional{
get;}Public bool isstopped{
get;}
Public long? Lowestbreakiteration { get;}
Public bool shouldexitcurrentiteration{
get;}20 }

Q 134: Difference between Break and Stop?


ANSWER:
AL-JUNAID TECH INSTITUTE
Break reaches at least the sequential point while stop does not reaches at least the
sequential point.
Q 135: What Concurrent collections include?
ANSWER:
Concurrent collections include concurrent stack, concurrent queue, concurrent bag,
concurrent dictionary.
Q 136: What is Blockingcollection? EXAMPLE
ANSWER:
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public class BlockingCollection<T> : IDisposable,
System.Collections.Generic.IEnumerable<T>,
System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection

Q 137: What is Html?


ANSWER:
Hypertext markup language
Q 138: How many kinds of layers of web pages?
ANSWER:
There are three types of layers.
1. Html (structural)
2. CSS (presentation)
3. JavaScript (behavioral) JavaScript was introduced in 95 by Netscape

Q 139: Version of java script.


ANSWER:
Their version of JS for IE. These days mostly handled. Standardization. Some quirks left.
Called ecmascript. The official standardization name. Refueled by high profile sites like
google using JS in last decade.

Q 140: What is Java script?


ANSWER:
JS is a programming language. Jqueryis a JS library.It make JS programming easier.
Jquery solves JS complexity and browser incompatibilities. Can do things in single
LOC(abbreviation(mukhafaf he) of lines of codes )
 HTML: structural layer
 CSS: presentation layer
 JS: behavioral layer.
AL-JUNAID TECH INSTITUTE
Q 141: What are the five types of Html?
ANSWER:
There are 5 types
 HTML 4.01 Transitional
 HTML 4.01 Strict,
 XHTML 1.0 Transitional
 XHTML 1.0 Strict
 HTML5

Q 142: How many types of tags?


ANSWER:
There are three types of tags.
1. Html root tag
2. head tag containing title etc.
3. Body tag containing all parts to be rendered in browser window.

<!DOCTYPE html >


<html>
<head>
<meta charset=utf-8>
<title>Hey, I am the title of this web page.</title>
</head >
<body>

Q 142: What is the difference between CSS and Html?


CSS
CSS stand for cascading style sheets. It is used to style the web documents. It
provides the background color. It is also used to style the font and change its size. We can
style many different web pages. It’s a presentation layer.
Html
Html stands for hyper text markup language. It is the language used to define the
structure of web page. Html is used along with CSS and java script to design web pages.
Html is basic building block of website. It’s a structural layer.

Q 143: What is Selector and declarationblock?


ANSWER:
Selector can be headline, paragraph of text, photo etc. Declaration block can turn
text blue, addred border around a paragraph.
P color: red; font-size: 1.5em;selector,
Declaration block has declarations.
AL-JUNAID TECH INSTITUTE
Q 144: What is difference between Client side and Server side?
ANSWER:
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. Responsive. Other client side technologies are applet’s, silverlight, flash.
Often requires a plugin or start slow because of downloading. Sometimes even diff to see
if flash or JS. Once yahoo maps was flash. Then re-written. Rightclick and see if About
the Flash Player Ajax brings client-side server-side together. JS talks to server,
downloads content, and update webpage. Google maps Let’s you move to new areas. JS
is a prog lang andcan be used on server side. E.g. Node.js supports JS on server-side.

Q 145: What are Compiled and scripted languages?


ANSWER:
JS interpreter is in web browser.
<!Doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<script>
</script>
</head>
Q 146: Print hello word using Html?
ANSWER:
<!Doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<script src="navigation.js"></script>
<script src="slideshow.js"></script>
<script>Alert('hello world!');</script></head>

Q 147: How many basic selectors?


ANSWER:
There are three basic selectors.
Basic selectors are ID selectors, element selectors, class selectors.
Q 147: How many advanced selectors?
ANSWER:
 Descendent selectors $(’#navbar a’) ,
 Child selectors $(’body ¿ p’) ,
 Adjacent sibling $(’h2 + div’) ,
AL-JUNAID TECH INSTITUTE
 Attribute selectors $(’img[alt]’),

Q 149: Let’s see jquery functions to add content?


<div id="container">
<div id="errors">
<h2>Errors:</h2>
</div >
</div >
Q 150: What are events?
ANSWER:
Things happen to webpage. Page loading, mouse move, key press you respond to events.
Q 150: What are Mouse events?
ANSWER:
click, dblclick, mousedown, mouseup, mouseover, mouseout, mousemove.
Q 151: What are Document window events?
ANSWER:
Load, unload, resize, scroll,
Q 152: What are Form events?
Submit, reset, change, focus, blur
Q 153: Keyboard events?
ANSWER:
keypress (over n over), keydown, keyup.

Q 154: What is difference between Ready() and Load event?


ANSWER:
Search frome internat
Q 155: What are the event properties? Or write a note on event properties?
ANSWER:
evt.preventdefault();
To stop normal behavior
Links, form submit etc
Remove events $(’.tabbutton’).unbind(’click’);
default event bubbling
evt.stoppropagation();
\$(document).click(function
(evt){Var xpos= evt.pagex;
Var ypos= evt.pagey;

Q 156: What are the event properties?


ANSWER:
Event Properties Description
AL-JUNAID TECH INSTITUTE
1. PageX The distance (in pixels) of the mouse
pointer from the left edge of the browser
window.
2. PageY The distance (in pixels) of the mouse
pointer from the top edge of the browser
window.
3. ScreenX The distance (in pixels) of the mouse
pointer from the left edge of the
monitor.
4. ScreenY The distance (in pixels) of the mouse
pointer from the top edge of the
monitor.
5. Shiftkey Is true if the shift key is down when the
event occurs.
6. Which Use with the keypress event to
determine the numeric code for the key
that was pressed (see tip,next).
7. Target The object that was the “target” of the
event for example, for aclick() event, the
element that wa clicked.

Q 157: What are Jquery animations?


ANSWER:
Fadein, fadeout, fadetoggle. Slidedown, slideup, slidetoggle.
Q 157: Login slider example.
ANSWER:

\$(document).ready(function (){
\$(’\#open’).toggle(
Function(){
\$(’\#login form’).slidedown(300);
\$(this).addclass(’close’);
},
Function(){
\$(’\#login form’).fadeout(600);
\$(this).removeclass(’close’);
}
);// end toggle
});// end ready

Q 158: Photo gallery example.


ANSWER:
AL-JUNAID TECH INSTITUTE
\$(’\#gallery a’).click(function(evt) {
Evt.preventdefault();
Var imgpath=\$(this).attr(’href’);
Var oldimage=\$(’\#photo img’);
Var newimage=\$(’<img src="’+ imgpath+’">’);
Newimage.hide();
\$(’\#photo’).prepend(newimage);
Newimage.fadein(1000);
Oldimage.fadeout(1000,function(){
\$(this).remove();
});// end fadeout
});// end click
\$(’\#gallery a:first’).click();

Q 159: Forms example.


ANSWER:

<input name="quantity" type="text" id="quantity">


<input name="total" type="text"
id="total">Var unitcost= 9.95;
Var amount =\$(’\#quantity’).val();
Var total= amount* unitcost;
Total= total.tofixed(2);
\$(’\#total’).val(total);
Q 160: What are selectors?
ANSWER:

public ComplexSelector ConcludeSelector(Selector selector)


{
if (!IsReady)
{
selectors.Add(new CombinatorSelector { selector = selector, transform =
null });
IsReady = true;
}

return this;
AL-JUNAID TECH INSTITUTE
}
Q 161: Define ajax? What is java script working?
ANSWER:
ajax allows us to talk server with in java script.JavaScript, server-side
programming, and web browser, all work together. Web browser: xmlhttprequest object.
Makes ajax possible. Talks to web server and get response

Steps for using ajax.(ye zaroor yad karo ye handouts men bh he)
AJAX communicates with the server using XMLHttpRequest object ..... User sends a
request from the UI and a javascript call goes to XMLHttpRequest object. HTTP
Request is sent to the server by XMLHttpRequest object. Server interacts with the
database using JSP, PHP, ASP.net etc.

Q 162: Difference between a GET() and POST().


ANSWER:
In GET method, values are visible in the URL. In POST method, values are not
visible in the URL. GET has a limitation on the length of the values, generally 255
characters. POST has no limitation on the length of the values since they are submitted
via the body of HTTP.
Q 163: how can we write formdata in variable? And what is the syntax of Serialize
method?
ANSWER:
Var formdata=$(’#login’).serialize();
$.get(’login.php’,formdata,loginresults);
AL-JUNAID TECH INSTITUTE
CURRENT START FROM HERE SPRING 2022
Q 164: How Ajax communicates with the web server?
Answer:
Web page request send to the web server then web server give response.
If web page sends two request then web server give two responses.

Q 165: How can we error handle in XML?


ANSWER:
Error handler.
\$.get(url, data, successfunction).error(errorfunction);
\$.get(’rate.php’, querystring,
processresponse).error(errorresponse);Function errorresponse(){
Var errormsg= "Your vote could not be processed right now.";
Errormsg+= "Please try again later.";
\$(’\#message’).html(errormsg);
}

Q 166: What is JSON?


ANSWER:
JS format. Method for exchanging data. JSON is JS so its quick n easy for JS.
No XML like parsing.JSON is a JS obj literal.
Server returns a string formatted like a JSON obj literal. JQuery get JSON method.
Callback will be a JSONobject.
Q 167: What is JSON?
ANSWER:
AL-JUNAID TECH INSTITUTE
JSON (JavaScript Object Notation) is independent- language, easy to understand and
self-describing. It is used as an alternative to XML. Human-readable and machine also. It
is used for data-interchange. The benefit of JSON is that it has a very compact size as
compared to XML documents of the same purpose and data.

Q 168: Alloc and dealloc methods.


ANSWER:
dealloc methods.

If you dont own and want to make sure, call retain. No longer need and own than release
or autorelease. When 0 count, dealloc called.
- (void)dealloc
{
[possessionname release];
[serialnumber release];
[datecreated release];
[super dealloc];
}

Alloc Method:

[System.CLSCompliant(false)]
public static void* Alloc (UIntPtr elementCount, UIntPtr elementSize);

Q 169: Write two difference between "Interface" and "Class"?


ANSWER:
A Class is a full body entity with members, methods along with their
definition and implementation while an Interface is just a set of
definition that you must implement in your Class inheriting that
Interface.

Q 170: How we can create & started a new thread? write code create start
a theread.?
ANSWER:
private void Form1_Load(object sender, System.EventArgs e)
{
Thread trd = new Thread(new ThreadStart(this.ThreadTask));
trd.IsBackground = true;
AL-JUNAID TECH INSTITUTE
trd.Start();
}

Q 171: Write step to talk to a webserver while using ajax?


ANSWER:
public class WebForm1 :
System.Web.UI.Page
{
private void Page_Load(object
sender, System.EventArgs e)
{

Ajax.Utility.RegisterTypeForAjax
(typeof(WebForm1));
}
}

Q 172: Write a code Asynchronous lambda expresstion will derived two


number & returen the value.
ANSWER:
interface Addable{
int add(int a,int b);
}
public class LambdaExpressionExample5{
public static void main(String[] args) {

Addable ad1=(a,b)->(a+b);
System.out.println(ad1.add(10,20));
Addable ad2=(int a,int b)->(a+b);
System.out.println(ad2.add(100,200));
}
}
AL-JUNAID TECH INSTITUTE
Q 173: What is the code of “for loop” to add the n even number in JavaScript?
ANSWER:
<script <script>
type="text/javascript">
function add(x)
function sum() {
{ return x%2==0;
}
var n,i, sum = 0; function findsum(y)
n = parseInt(document.getMyProgram {
let sum=0;
("first").value);for (i = 1; i < = n; i++) for( var i=1; var<=y; i++)
if(add(i))
{ {
if(i%2 == 0) sum+=i;
}
{ }
sum = sum+i; document.write(findsum)
</script>
}
}
document.get<MyProgram ("num").innerHTML ="Sum of " +n+ " even natural
numbers is
:"+sum;
}
</script>

Q 174: What are the five types of HTML?


ANSWER:

Five types of html in use:

1. HTML 4.01 Transitional


2. HTML 4.01 Strict
3. XHTML 1.0 Transitional
4. XHTML 1.0 Strict
5. HTML5
Q 175: How to define binary resource and what are the categories of binary
resources inWPF?
AL-JUNAID TECH INSTITUTE
ANSWER:
Binary resources are what rest of .net framework considers a resource. To
define a binaryresource, add a file and set the build action resource or content
(loose file).
Binary resource has two categories
Binary resource can be embedded to assembly
Binary resource can be loose file that may or may not be known at compile time.
It can belocalizable or not.
Q 176: Write the properties of touch point in C#.
ANSWER:
The properties of Touchpoint are Position, Size, Bounds, touchdevice, Action
(Down, Up,Move).
Q 177:
What will be the output of the code.Async void displayprimecounts()
{
For (int i = 0; i < 10; i++)
Console.writeline(await getprimescountasync(i) }
ANSWER:

It is a code for UI program that remains responsive with a cpu bound task. In the
given codes wehave used for loop. When the first call of getprimecounts is given then
control will be returned and remaining code will go in continuation. We have called
await from inside the for loop.
Because i is also captured and is available in the continuation, so i will also be
incremented in each iteration. We will move onward from await when
getprimescountasync is finished and atthat time we resume as just returned from
await expression.
Q 178: Create a single instance application using WPF.
ANSWER:
Single instance application means that it should be run only one time.

Bool mutexisnew;
Using (System.Threading.Mutex m = New System.Threading.Mutex(true, uniquename,
outmutexisnew))
{
AL-JUNAID TECH INSTITUTE
If (mutexisnew)
// This is the first instance. Run the
application.Else
// There is already an instance running. Exit!
}

Q 179: Write the XAML code to create a list box with three items.
ANSWER:
<listbox xmlns=“http://schemas.microsoft.com/winfx/2006/xaml/presentation”>
<listbox.Items>
<listboxitem Content= “Item 1”/>
<listboxitem Content= “Item 2”/>
<listboxitem Content= “Item 3”/>
</listbox.Items>
</listbox>
Q 180: What is the purpose of Block in Objective-C.
ANSWER:
Blocks are a language-level feature added to Objective-C, which allow you to create
distinct segments of code that can be passed around to methods or functions as if
they were values. Blocks are Objective-C objects, which means they can be added to
collections like NSArray orNSDictionary.
Q 181: Define the Data template using XAML?
ANSWER:
Data template is a bit of XAML that describes how bound data is displayed. A data
template cancontain elements that are each bound to a data property along with
additional markup that describes layout, color and other appearance.
Q 182: Differentiate between Get and Post Method.
ANSWER:
In GET method, values are visible in the URL. In POST method, values are not
visible in the URL. GET has a limitation on the length of the values, generally 255
characters. POST has nolimitation on the length of the values since they are submitted
via the body of HTTP.
AL-JUNAID TECH INSTITUTE
GET results can be bookmarked. POST results cannot be
bookmarked. GET Parameters remain in web. In Post Parameters
are not saved in web.
Get method supports only string data types. Post This method supports different data
types, suchas string, numeric, binary, etc.
Q 183: Define iOS language feature block also write its syntax.
ANSWER:
Block is a chunk of code that can be executed at some future time. Blocks are
first-class functions, which is a fancy way of saying that Blocks are regular
Objective-C objects. Since they're objects, they can be passed as parameters,
returned from methods and functions, andassigned to variables.
The syntax to define a block literal uses the caret symbol ( ^ ), like this:
^{ NSLog(@"This is a block"); }

Q 184: Write the difference between onetime binding and onewayTo Source
binding.Also give example of both in XAML.
ANSWER:
In one time binding, control value is updated only when the application is initialized.
This means you cannot change the value from source to control; as for changing the
value, you have to write code in code behind file, so that you can change value from
the back-end programming.In One way to source binding, target control updates the
source control, which means if you change the value of the target control, it will
update the value of the source control. It is just the opposite to One way binding.
one time binding Example
txtvalue.Text = "50";
mySlider.Value = Convert.ToInt32(txtvalue.Text);
One way to source binding Example
<TextBox Name="txtvalue" Text="{Binding ElementName=myCS411, Path=Value,
Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}">
</TextBox>

Q 185: Give the structure of protocols in Objective-C.


ANSWER:
Objective-C allows you to define protocols, which declare the methods expected to be
AL-JUNAID TECH INSTITUTE
used fora particular situation. Protocols are implemented in the classes conforming to
the protocol.
A simple example would be a network URL handling class, it will have a protocol with
methodslike processCompleted delegate method that intimates the calling class once the
network URL fetching operation is over.
A syntax of protocol is shown below.
@protocol ProtocolName
@required
// list of required
methods@optional
// list of optional methods
@end

Q 186: Write steps to talk to a webserver while using AJAX.


ANSWER:
1. Specify the HTTP method (such as POST or GET).
2. Provide the URL of the server-side resource to be contacted.
3. Let the XHR (xml http request) instance know how it can inform you of its progress.
4. Provide any body content for requests such as POST.

Q 187: Given below in XAML code for stack panel.


<stack panel> </stack panel>
You are required to modify the given code to give the stack panel gradient
background.Use three colors in gradient.
ANSWER:

<lineargradientbrush x:Key="backgroundbrush" startpoint="0,0" endpoint="1,1">


<gradientstop Color="Blue" Offset="0"/>
<gradientstop Color="White" Offset="0.5"/>
<gradientstop Color="Red" Offset="1"/>
</lineargradientbrush >
Q 188: Why we need concurrency in our application?
ANSWER:
Any circumstance under which an object interrupts the processing of a message to
AL-JUNAID TECH INSTITUTE
processanother opens the possibility of race conditions and, thus,
requires the use of concurrency controls so concurrency is More than one thing
happening at the same time.
We need concurrency for comparison of
events. We need concurrency for Responsive
user interface
We need concurrency to handle Simultaneous
requestsWe need concurrency in Parallel
programming.
Q 189: Write XAML code which rotate the button at the angle of 90 degrees.
ANSWER:
<Button>
<Button.rendertransform>
<transformMyButton>
<rotatetransform Angle="90"/>
</transformMyButton >
</Button.rendertransform >
OK
</Button >

Q 190: Consider the XAML code


<TextBox Name= “txt1”>< /TextBox>
<Button Name= “btn1”></Button>
Modify the given code so, whatever the text is written inside textbox it is
automaticallywritten as Button text.
Note: - Modify the XAML code only do not write C# code.

<TextBox Name= “txt1”>txt1< /TextBox>


<Button Name= “btn1”>btn1</Button>

Q 191: Differentiate the need of Binding and Command in WPF.


Data binding is a mechanism in WPF applications that provides a simple and easy way
for Windows Runtime apps to display and interact with data. In this mechanism, the
management ofdata is entirely separated from the way data. Data binding allows the
flow of data between UI elements and data object on user interface.
AL-JUNAID TECH INSTITUTE
The command is the action to be executed. The command source is the object which
invokes the command. The command target is the object that the command is being
executed on. The command binding is the object which maps the command logic to
the command. Commands are a more abstract and loosely coupled version of events
e.g. Cut copy paste commands. They are exposed in various ways. They can be
enabled disabled e.g. If there is nothing to paste. Two-waycommunication gets
cumbersome especially if you don’t want the list of controls hard-coded.
WPF defines a number of built-in commands. Commands have automatic support
for inputgestures (such as keyboard shortcuts). Some of wpfs controls have built-
in behavior tied tovarious commands.
Q 191: Which type of information is provided in following windows properties in
WPF?
a) Owner
b) OwnedWindows
ANSWER:
Whenever an application makes a window then the concept of parent window and
child window arises. The key difference between child window and parent window is
that if we close the child window then there will be no effect on parent window but if
we close the parent window than child window will alsoclosed. The owner property
contains the information of parent window while OwnedWindows containsthe
information about the list of child window.

Q 192: Define the term “Retain Cycle” in Objective-C.


ANSWER:
Retain Cycle is the condition When 2 objects keep a reference to each other and are
retained, it creates a retain cycle since both objects try to retain each other, making it
impossible to release.For example a situation in which object "First" retains object
"Second", and object "Second" retains object "First" at the same time.
Q 193: Write the names of data binding modes in WPF.
ANSWER:
Binding Mode can be
 Oneway
 Twoway
 Onewaytosource
 Onetime
AL-JUNAID TECH INSTITUTE
Q 194: Identify application commands and component command.
i) Close
ii)Find
iii)Selecttoend
d) help
e) MoveRight
ANSWER:
Application commands
Close, Find and Help
Component command
MoveRight and
Selecttoend
Q 195: What are three steps of implementing parallelism. Also differentiate
between Dataand Task parallelism.
ANSWER:
Data Parallelism means that we may have a lot of data on which we want to do the
same operation. In task parallelism, we may have lot of task, which we have to do in
parallel, which are different tasks. In Data parallelism we do the same task on data
which is easiest kind of parallelism. All the task will start from one point in data
parallelism. In task parallelism differenttask will starts at different points and ends on
different points
There are three steps while implementing parallelism.
1. Partition your Problem
2. Process your partition
3. Combine the Result.
Q 196: What are the two possible destinies for object marked as auto
release usingobject-C. Also declares an object as autorelease.
ANSWER:
Auto release is another message that we can send to an object. Auto release is like
saying the object that I no longer want to hold the reference to this object but don’t
delete this object immediately. Auto release solve the problem that when you want to
return something but do notwant to hold the reference.
Retain and release is the two possible destinies for object marked as onto release using
object-C.The deallocation is only done by the object itself in Object-C.
AL-JUNAID TECH INSTITUTE
Nsobject *x = [[[nsobject alloc] init] autorelease];
Q 197: What do you means by Dangling pointer and memory leak?
ANSWER:
Dangling pointer means that we have allocated some memory and then we freed that
memory butthe pointer is still pointing at the same place. Memory leaks means that
we allocate some memory, we have a pointer pointing to it, and then we make the
pointer points to somewhere else. Now you have no pointer to this allocated memory.
Q 198: Write the difference between one way and two way data Binding
ANSWER:
One way
The target is updated whenever the source changes.
Two way
A change to either the target or source updates the
other.One way to source
This is the opposite of one way. The source is updated whenever the target
changes.One-time
This works just like one way, except changes to the source are not reflected at the
target. Thetarget retains a snapshot of the source at the time the Binding is initiated.
Q 199: Can the operating system distinguish between window with WPF content
andwindow win32 content?
ANSWER:
No, operating system cannot distinguish between window with WPF content and
window win32content. We can even create Host WPF content in a Win32 window,
with this technique; we can use the advanced graphics capabilities of WPF within the
framework of a standard Win32 window and application. We can also host a Win32
window in WPF content, with this technique you can use an existing custom Win32
control in the context of other WPF content, and pass dataacross the boundaries.

Q 200: Which element must be added to the project file to specify a default
culture forresources and automatically build an appropriate satellite assembly.
ANSWER:
If we have a main executable assembly and then there are some DLLs assembly one
for each culture you want to support, then, all the content which is culture specific
AL-JUNAID TECH INSTITUTE
will go into satelliteassembly and rest of all the main logic will reside in main
assembly. Main assembly combinedwith any satellite assembly is a complete
application.
Myprogram.exe is main assembly and MyProgram.resources.dll is satellite assembly.
The programs are executable by combination of both assemblies. The currently
chosen culture willuse MyProgram.resources.dll
We will specify the default culture in project file by using uiculture tag. We will give
uiculturetag in property group like debug version or release version to make it culture
specific.

Q 201: Write the difference between interface and class.


ANSWER:
A class is a blueprint from which we can create objects that share the same
configuration - properties and methods. An interface is a group of related properties
and methods that describean object, but neither provides implementation nor
initialization for them.

Q 202: How can we create objects in objective-C? also provide syntax.


ANSWER:
Objective-C is a thin layer atop C and is a "strict superset" of C, meaning that it is
possible to compile any C program with an Objective-C compiler and to freely include C
language code within an Objective-C class.

NSMutablearray *arrayInstance =
[NSMutablearray alloc];[arrayInstance init];
NSMutablearray *arrayInstance = [[NSMutablearray alloc] init];
message = [receiver selector
arguments] [arrayInstance
addObject:anotherobject];.

Objective-C is a thin layer atop C and is a "strict superset" of C, meaning that it is


possible to compile any C program with an Objective-C compiler and to freely
include C language code within an Objective-C class.
Objective-C derives its object syntax from Smalltalk. All of the syntax for non-object-
oriented operations (including primitive variables, pre-processing, expressions, function
AL-JUNAID TECH INSTITUTE
declarations, andfunction calls) are identical to those of C, while the syntax for object-
oriented features is an implementation of Smalltalk-style messaging.
Q 203: Write any two design Goals for JQuery?
ANSWER:
JQuery was introduced to make development with JavaScript easier. It will reduce the
development time. Use it to add animation and even handling on your website. JQuery
simplifiesHTML document traversing, event handling, animating, and Ajax
interactions for rapid web development.
Q 204: Write the names of command library classes?
ANSWER:
Application commands
Component commands
Media commands
Navigation Commands
Editing commands

Q 205: How we can create & started a new thread? write code create start a
thread.
ANSWER:
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");
}
}
Q 206: List three commands define by “Icommand” interface.
AL-JUNAID TECH INSTITUTE
icommand defines Execute, canexecute, canexecutechanged as a Command.
Q 208: Write a function in JavaScript that will add ten even numbers using a for
loop.
ANSWER:
<html>
<body>
<script type= “text/javascript”>
<!--
var a=1; var
sum=0;
for(a=1;a<=10; a++)
{ If(a%2==0)
{sum=sum+a}
}
document.write(sum);
//-->
</script>
</body>
</html>
Q 209: What are the three major types in JavaScript?
ANSWER:
JavaScript allows you to work with three primitive data types: numbers, strings of text
(known as“strings”), and boolean truth values (known as “booleans”).

Q 210: Consider the following code lines and explain what we are trying to
achieve fromthem.
Msbuild/t:updateuid
Projectname.csproj.locBaml/parseProjectname.g.en-
US .resources/out.en-US.csv
ANSWER:
Running this gives every object element in every XAML file in the project on x:Uid
directivewith a unique value and LocBaml /parse ProjectName.g.en-US.resources
/out:en-US.csv, thisgenerate a simple .csv file containing all the property values you
should need to localize.
or
AL-JUNAID TECH INSTITUTE
We are trying to localize the element using Uid directive. Here updateuid will specify
the files,which are needed to be localized, so updateuid will give Uid to all XAML
file after searching itfrom csproj file. Then locBaml will convert it to string resources
to out.en-US.csv file. All the strings will accumulate in comma-separated file. Now
we can convert it to any new language satellite assembly by locBaml /generate.
Q 211: Separate server side language and Client side language.
ANSWER:
Server side language
PHP, ASP.net, Cold Fusion, Ruby, Python, JAVA, C#, C++ are server side languages.
Client side language
JS(Java Script), CSS, HTML are Client side languages.
Q 212: What is the purpose of the following objective-C code
NSData *imageData = [NSURLconnection
sendSynchronousRequest:urlRequest
ReturningResponse:nil
error:&downloadError];
ANSWER:
The given code is used to download data. Sendsynchronousrequest is used as a function
of Nsurlconnection to download data. As there could come an error in downloading
data so we havemake a variable name downloadError. If ReturningResponse is nil than
data will be downloaded otherwise error message will display on screen.
Q 213: Write C# code which navigate to URI using the Navigate Method.
ANSWER:
Navigate to a page via a URI
This.navigationservice.Navigate(new Uri("photopage.xaml", urikind.Relative));

Q 214: Explain at-least two memory management problems using Objective-C


ANSWER:
Memory leak and Dangling pointer are the two main memory management problem
using objective-C. In Objective-C all objects are created on the heap, this means
objects continue toconsume memory until they’re explicitly deallocated. They are
not cleaned up automatically
when the code that uses them goes out of scope. If our application loses all references
(pointers)to an object but doesn’t deallocate it first, the memory it consumes is
AL-JUNAID TECH INSTITUTE
wasted. This waste is typically called a memory leak, and if your application has too
many memory leaks, it becomessluggish due to running out of available memory. If
we deallocate an object too early and then reference it again, our application could
crash or exhibit incorrect and random behavior.
Q 216: AJAX is the interaction of which type of technology? Name them.
ANSWER:
Ajax is made up of the following technologies:
 XHTML and CSS for presenting information
 Document Object Model (DOM) for dynamically interacting with and
displaying thepresented information
 XMLHttpRequest (XHR) object to manipulate data asynchronously with the web
server.

Q 217: When manipulationDelta event is raised in WPF touch events? Also


mention thename of manipulation delta event properties.
ANSWER:
The ManipulationDelta event occurs multiple times when the user drags fingers over
the screen during a manipulation and again when inertia occurs. We can use the
isInertial property to checkwhether the event is occurring during inertia. The element
on with ManipulationDelta event occurs is not affected in any way when the event
occurs. You must provide the logic to the element that is to be manipulated.
Manipulationdelta class has properties, Translation, Scale, Rotation and Expansion.
Q 218: What is the purpose of using navigation in pages, mention 5 ways to
performnavigation.
ANSWER:
The purpose of navigation is to ascertain the present position and to determine the
speed, direction to arrive at the port or point of destination. Page navigation allows us
to flow from onepage to another without frustration.
Browseback, browseforward, browsehome, browsestop, Favorites, firstpage, gotopage,
lastpage, nextpage, previouspage, Refresh, Search, Zoom are different way to perform
navigation.
Q 219: Write the event properties of JQuery of PageX and PageY, ScreenX and
ScreenY.
ANSWER:
AL-JUNAID TECH INSTITUTE
PageX is the distance (in pixels) of the mouse pointer from the left edge of browser
window. PageY is the distance (in pixels) of the mouse pointer from the Top edge
of browser window.ScreenX is the distance (in pixels) of the mouse pointer from the
left edge of monitor.
ScreenY is the distance (in pixels) of the mouse pointer from the Top edge of monitor.

Q 220: Write name of main method available in dispatcher class of C#


ANSWER:
System.Windows.Threading is the main method available in dispatcher class of C#
BeginInvoke(Delegate, DispatcherPriority, Object[])
Q 221: What does it means
[Locationmanager setdistanceFilter:kcldistancefilternone];
ANSWER:
Above code means that we want all results from the location manager

Q 222: Give the syntax to hide all <p> tags in html using JS and JQuery.
General Syntax
ANSWER:
$(selector).hide(speed, easing, callback)
Hide all <p> elements:
$("button").click(function(){
$("p").hide();
});
Q 223: Explain Automatic looping and chaining function with example in
JQuery.
ANSWER:
JQuery enable us to change the tag by using looping. So JQuery provide us automatic
looping. JQuery provide us functions that are applied to all the elements of JQuery
Selection object. First,we make selection and then apply it on the all elements. We can
perform multiple operation afterselection and is called chaining function. JQuery does
not return any DOM list but it give us special selection object on which we can apply
different function and it applies on all the selection and it is called automatic looping.
Chaining means that a function can be chain means we can call function one after the
other.
Automatic Looping Example
AL-JUNAID TECH INSTITUTE
$( ‘#slideshow img’).hide();
In this example it will hide all the elements which came under above selection.
Chaining Function Example
$( ‘#popup’).width(300).height(300);
Q 224: Define “dealloc msg” and who is responsible for sending message in
objective-C?
ANSWER:
Dealloc message will freeze the object. The object itself cannot be deallocated. We use
referencecounting for deallocation means we count the references towards the object.
If a new pointer points towards our object, than it will increase the count and if a
pointer leaves the pointing towards object, it will decrease the count. When the count
reaches Zero, we should call dealloc. The pointer owner, which are pointing towards
object will call dealloc and free the memory. Thedeallocation is only done by the
object itself no one else should tell the object to deallocate. The retain and release call
are used for allocation and deallocation of memory.
Q 225: How we can convert Synchronous method into asynchronous in C# 5.0?
ANSWER:
We can convert Synchronous method into asynchronous in C# 5.0 by inserting some
specialkeywords like await and async. Async will tell the compiler that we will use
await key word.var result= await expression;
statement(s);
await will call the getawaiter of the expression and when the awaiter complete its work
then
Q 226: What are manipulation events? When does it work?
ANSWER:
Manipulation events are manipulationstarting and manipulationstarted,
manipulationdelta, manipulationcompleted. We combine information from multiple
events. Manipulation eventswork if ismanipulationenabled=true on this or a parent
and basic events not handled.
Q 227: What is static and dynamic resources.
ANSWER:
Static Resources retrieved once by referencing element and used for the lifetime of
the resources. Whereas, Dynamic Resources retrieve every time they are used. The
downside of Dynamic resources is that they tend to decrease application performance.
AL-JUNAID TECH INSTITUTE
Dynamic resource reapplied every time it changes nothing special about the resources.
Dynamic use more overhead
but demand loaded. Dynamic can only be used to set dependency property. Static can
even abstract whole controls. In case of dynamic resource, we actually subscribe to
the updates of thesource, if the source changes, dynamic resource will also change. In
static resource we use the value only one time. Static cannot do a forward difference.

Q 228: How can we prevent a window from automatically being activated.


ANSWER:
When a window with its Show Activated property set to false is opened, the window is
not activated and its Activated event is not raised until a user manually activates the
window byselecting it. After the window is selected, it activates and deactivates
normally.

Q 229: Write the code so that the style of paragraph will be same in CSS
ANSWER:
A single CSS style is a rule that tells how to format. Make “this” look like “that”. There
are Selector and declaration block. E.g. Selector can be headline, paragraph of text,
photo etc. Declaration block can turn text blue, add red border around a paragraph,
position the photo atcenter of page etc.
p { Color : red; font-size: 1.5em};
Here p is the selector, which means all paragraph that are contains in p tag. In
rule/declarationblock, we set color of paragraph red and font size 1.5em. selector,
declaration block has declarations. Each is a property value pair and then “;”.

Q 230: Three Gradient color code in c#


ANSWER:

Q 231: Purpose of Navigation. Also Describe the Way of Navigation.


ANSWER:
AL-JUNAID TECH INSTITUTE
Navigation control in ASP.NET manages the data passing between ASPX pages. Web
applications are having multiple pages interconnected with each other.
Way Of Navigation:
1. Client-side navigation.
2. Cross-page posting.
3. Client-side browser redirect.
4. Server-side transfer.

Q 232: What is the Purpose of DATA


BLINDING?ANSWER:
Data binding provides a way for developers to create a read/write link between the
controls on a form and the data in their application
Q 233: JavaScript even number 1 to 10.
ANSWER:
<html>
<body>
<script>

Var a =1;
Var sum =0;
For(a=1; a<=10; a++)
{
If (a%2==0)
{
Sum =sum+a;
}
}
Document(sum);
</script>
</body>
</html>
Q 234: Protocol in objective
C.ANSWER:
Objective-C allows you to define protocols, which declare the methods expected to be
used for a particular situation. This chapter describes the syntax to define a formal
protocol, and explains how to mark a class interface as conforming to a protocol, which
means that the class must implement the required methods

You might also like