Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Windows Phone Programming
1. Windows
Phone
Programming
Pasi
Manninen
JAMK
University
of
Applied
Sciences
Slide
version
Nov
24th,
2013
2. Windows
Phone
–
Dev
Center
• hGps://dev.windowsphone.com/en-‐us/home
• Submit
app
• Get
sdk
• View
Samples
Windows
Phone
Programming,
Pasi
Manninen.
2
3. MSDN
Library
• hGp://msdn.microsoR.com/library
•
•
•
•
•
API
reference
Samples
Downloads
Docs
Etc..
Windows
Phone
Programming,
Pasi
Manninen.
3
4. MicrosoR
Developer
Network
• hGp://msdn.microsoR.com/en-‐US/
•
•
•
•
Download
the
Tools
News
Blocs
Etc…
Windows
Phone
Programming,
Pasi
Manninen.
4
5. MicrosoR
Dreamspark
• hGps://www.dreamspark.com/
• Materials
• Student
• Educator
• InsYtuYon
Windows
Phone
Programming,
Pasi
Manninen.
5
6. Zune
• hGp://zune.net/en-‐US/
•
•
•
•
ConnecYng
a
phone
to
windows
and
Visual
Studio
UpdaYng
Windows
Phone
soRware
Synchonizing
media
files
With
Windows
Phone
7
development
Windows
Phone
Programming,
Pasi
Manninen.
6
7. Windows
Phone
Device
• PreGy
powerful
device
• OperaYng
system
opYmized
to
mobile
device
• At
least
1
GHz
processor,
800x480
px
resoluYon
(landscape
or
portrait)
Touch,
Gestures,
GPS,
WiFi,
3G,
GPRS,
Accelerometer,
Compass,
Gyroscope,
Camera,
a
few
hardware
BuGons,
Keyboard
(in
some
devices),
Storage,
Bing
Maps,
…
Windows
Phone
Programming,
Pasi
Manninen.
7
8. Windows
Phone
Programming
• WriYng
programs
for
Windows
Phone
is
the
same
as
wriYng
for
any
.NET
plagorm
• Edit,
compile
and
debug
within
Visual
Studio
• You
can
incorporate
.third
party
NET
libraries
(assemblies)
into
your
applicaYons
• Required
SoRware:
– Visual
Studio
– Windows
Phone
SDK
– Emulator
– Expression
Blend
(design)
– Zune
(to
install
applicaYon
do
real
device
in
WP7)
Windows
Phone
Programming,
Pasi
Manninen.
8
9. MicrosoR
Visual
Studio
• Visual
Studio
Express
– Free,
complete
Windows
Phone
Development
environment
– Integrated
debugger,
on-‐device
debugging
– Deployment
to
an
emulator
or
real
device
• Visual
Studio
Professional,
UlYmate
– Used
here
in
class
– Includes
”everything”
Windows
Phone
Programming,
Pasi
Manninen.
9
10. Windows
Phone
SDK
• Windows
Phone
SDK
consists
of
Visual
Studio
IDE
– toolbox
containing
phone
controls
– a
phone-‐based
designer
skin
– project
templates
specific
for
phone
applicaYon
development
– Windows
Phone
Emulator
Windows
Phone
Programming,
Pasi
Manninen.
10
11. Windows
Phone
Emulator
• Emulator
runs
on
PC
• Contains
exactly
the
same
code
as
the
real
phone,
but
compiled
for
the
Windows
PC
• Developer
can
see
how
the
programs
look
like
on
a
device,
remains
unYl
next
restart
• Accelerometer,
locaYon,
orientaYon,
Map,
…
,
can
be
tested
• Take
screenshot
Windows
Phone
Programming,
Pasi
Manninen.
11
12. OrientaYon
Emulator
• Emulator
allows
you
to
move
a
3D
phone
• Signals
sent
to
the
sensors
in
the
emulator
match
the
viewed
posiYon
• Movements
can
be
recorded
and
replayed
Windows
Phone
Programming,
Pasi
Manninen.
12
13. LocaYon
EmulaYon
• Current
locaYon
can
be
selected
or
searched
• Zoom
in
and
out
• ParYcular
routes
can
be
added,
recorded
and
playback
later
Windows
Phone
Programming,
Pasi
Manninen.
13
14. Expression
Blend
• Create
rich
web
experiences,
games,
desktop
apps,
and
more
• Design
apps
that
use
the
full
power
of
Silverlight
• Take
your
ideas
from
concept
to
finished
project
• Work
effecYvely
with
design
tools,
Expression
Blend
and
Visual
Studio
Windows
Phone
Programming,
Pasi
Manninen.
14
15. Windows
Phone
Device
(tesYng)
• Device
development
is
similar
to
development
with
the
emulator
• ConnecYon
with
the
device
requires
Zune
soRware
in
WP7
(require
USB
drivers)
• The
device
used
for
development
must
be
unlocked
(or
registered)
Windows
Phone
Programming,
Pasi
Manninen.
15
16. Silverlight
and
XNA
applicaYons
• Two
different
kind
of
applicaYons
can
be
build
• Silverlight
– Business
applicaYons
and
simple
casual
games
• XNA
(in
WP7)
– 2D
and
3D
games
with
hardware
accelerated
graphics
• Combined
Silverlight
with
XNA
graphics
Windows
Phone
Programming,
Pasi
Manninen.
16
17. CreaYng
an
ApplicaYon
• Select
the
type
of
your
applicaYon
(XNA
or
Silverlight)
when
you
create
the
new
project
in
Visual
Studio
• Silverlight
applicaYon
can
include
an
XNA
game
on
one
page
• There
is
no
technical
reason
why
you
could
not
create
a
Silverlight
game
or
an
XNA
business
applicaYon
Windows
Phone
Programming,
Pasi
Manninen.
17
18. Windows
Phone
Marketplace
• ApplicaYon
can
be
tested
free
on
the
emulator
• To
sell
applicaYon
or
deploy
it
to
a
real
device,
register
as
a
developer
(cost
$99
per
year)
• Students
can
register
as
developers
for
free
via
MicrosoR
DreamSpark
• Publish
any
number
of
applicaYons
for
sale
and
up
to
100
(!)
free
ones
in
year
• To
get
70%
of
the
price
selling
apps
• demo”
and
“Yme
trialled”
versions
of
your
applicaYon
can
be
distributed
Windows
Phone
Programming,
Pasi
Manninen.
18
19. Programs
on
Windows
Phone
• Programs
for
Windows
Phone
are
wriGen
in
.NET
and
run
within
a
Managed
Code
environment
on
the
device
• The
phone
performs
Just
in
Time
compilaYon
of
the
intermediate
language
(MicrosoR
Intermediate
Language
–
MSIL)
• The
programs
that
run
are
assemblies
that
are
signed
by
the
developer
• The
user
interface
code
must
be
C#
or
Visual
Basic
Windows
Phone
Programming,
Pasi
Manninen.
19
20. Just
In
Time
CompilaYon
Visual
Studio
Development
Environment
C#
source
file
C#
compiler
Assembly
file
containing
MSIL
§
§
§
Just
In
Time
compiler
Machine
code
in
memory
Windows
Phone
Programming,
Pasi
Manninen.
20
21. ExecuYon
Model
Overview
• The
execuYon
model
is
designed
to
provide
end
users
with
a
fast,
responsive
experience
at
all
Ymes
• Windows
Phone
allows
only
one
applicaYon
to
run
in
the
foreground
at
any
given
Yme
Windows
Phone
Programming,
Pasi
Manninen.
21
22. Demo
–
HelloWindowsPhone
MicrosoR
Visual
Studio
Create
a
project
SoluYon
Explorer
Silverlight
&
C#
Running
applicaYon
in
emulator
• Debugging
•
•
•
•
•
Windows
Phone
Programming,
Pasi
Manninen.
22
23. Demo
-‐
Visual
Studio
SoluYon
Explorer
• The
SoluYon
Explorer
is
another
pane
in
Visual
Studio
• It
shows
all
the
elements
in
a
parYcular
soluYon
• This
includes
all
the
applicaYon
resources
and
XAML
files
Windows
Phone
Programming,
Pasi
Manninen.
23
24. Demo
-‐
The
MainPage.xaml
• The
MainPage.xaml
file
contains
the
XAML
that
describes
how
the
main
page
looks
• If
you
add
further
pages
to
the
applicaYon
they
will
appear
as
xaml
pages
in
the
soluYon
Windows
Phone
Programming,
Pasi
Manninen.
24
25. Demo
-‐
The
code
behind
a
xaml
page
• Each
xaml
page
has
a
file
of
C#
behind
it
• This
code
is
in
a
class
called
MainPage
which
extends
the
PhoneApplicationPage
class
• The
code
just
contains
the
constructor
that
is
called
when
the
page
instance
is
loaded
• The
constructor
calls
a
method
that
iniYalises
all
the
components
on
the
page
Windows
Phone
Programming,
Pasi
Manninen.
25
26. Demo
-‐
Add
a
few
controls
• Demo:
adding
machine
• Drag
and
drop
controls
to
MainPage
from
Toolbox
• See
generated
code:
<!-‐-‐ContentPanel
-‐
place
addiYonal
content
here-‐-‐>
<Grid
x:Name="ContentPanel"
Grid.Row="1"
Margin="12,0,12,0">
<TextBlock
Height="30"
HorizontalAlignment="LeR"
Margin="12,22,0,0"
Name="textBlock1“
Text="Adding
machine"
VerYcalAlignment="Top"
/>
<TextBox
Height="72"
HorizontalAlignment="Center"
Margin="12,73,0,0"
VerYcalAlignment="Top"
Width="444"
Name="firstNumberTextBox"
Text="0"
TextAlignment="Center"
/>
<TextBlock
Height="30"
HorizontalAlignment="LeR"
Margin="24,151,0,0"
Name="textBlock2"
Text="+"
VerYcalAlignment="Top"
Width="426"
TextAlignment="Center"
/>
<TextBox
Height="72"
HorizontalAlignment="LeR"
Margin="12,187,0,0"
Width="444"
Name="secondNumberTextBox"
Text="0"
VerYcalAlignment="Top"
TextAlignment="Center"
/>
<BuGon
Content="Equals"
Height="72"
HorizontalAlignment="LeR"
Margin="153,282,0,0"
Name="buGon1"
VerYcalAlignment="Top"
Width="160"
Click="buGon1_Click"
/>
<TextBlock
Height="30"
HorizontalAlignment="LeR"
Margin="24,395,0,0"
Width="426"
Name="resultTextBlock"
Text="0"
VerYcalAlignment="Top"
TextAlignment="Center"
/>
</Grid>
Windows
Phone
Programming,
Pasi
Manninen.
26
27. Demo
-‐
Code
behind
MainPage
• Double
click
BuGon
control
to
add
event
handling
and
add
following
code
to
process
calculaYon
and
test
your
project
private
void
buGon1_Click(object
sender,
RoutedEventArgs
e)
{
float
v1
=
float.Parse(firstNumberTextBox.Text);
float
v2
=
float.Parse(secondNumberTextBox.Text);
float
result
=
v1
+
v2;
resultTextBlock.Text
=
result.ToString();
}
Windows
Phone
Programming,
Pasi
Manninen.
27
28. More
Controls
–
Silverlight
Toolkit
• Provides
new
components,
funcYonality,
and
an
efficient
way
to
help
shape
product
development.
• Toolkit
releases
include
open
source
code,
samples
&
docs,
plus
design-‐Yme
support
for
the
Windows
Phone
plagorm
as
well
as
the
Silverlight
browser
plugin.
• hGp://phone.codeplex.com/
Windows
Phone
Programming,
Pasi
Manninen.
28
30. Exercise:
Using
the
Toolkit
• Download
a
new
version
of
the
Toolkit
• Add
a
reference
to
the
project
• Add
a
namespace
to
the
XAML
• To
add
new
controls
to
Toolbox
you
need
to
"Choose
Items…“
• Add
a
few
Toolkit
Controls
to
your
MainPage
//
namespace
for
silverlight
toolkit
controls
xmlns:toolkit="clr-‐
namespace:MicrosoR.Phone.Controls;assembly=MicrosoR.Phone.Controls.Toolkit"
Windows
Phone
Programming,
Pasi
Manninen.
30
32. Available
Layouts
• Canvas,
Grid
• StackPanel
(horizontal
or
verYcal)
• WrapPanel
(Silverlight
Toolkit)
More
info:
hGp://msdn.microsoR.com/en-‐us/library/windowsphone/
develop/gg680262(v=pandp.11).aspx
Windows
Phone
Programming,
Pasi
Manninen.
32
33. Dynamic
PosiYon
and
Layout
• Use
dynamic
posiYoning
• Pixel
based
posiYoning
is
used
only
inside
a
control
(for
exp.
Margins)
• Grid
elements:
Auto,
*,
fixed
size
• Remember
horizontal
and
verYcal
alignment
• Auto
width,
Auth
height
• Min
and
max
widht
and
height
Windows
Phone
Programming,
Pasi
Manninen.
33
34. OrientaYon
• Each
page
in
the
applicaYon
must
declare
orientaYon
modes
it
supports
• An
orientaYon
change
can
be
observed
(OrientaYonChanged
event)
• SupportedOrienta8ons
can
be
set
of
one
of
the
following
values
– Portrait
– PortraitOrLandscape
– Landscape
• The
Orienta8on
aGribute
defines
the
default
orientaYon
of
the
page
– None,
Portrait,
Landscape,
PortraitUp,
PortraitDown,
LandscapeLeR,
LandscapeRight
<!–
only
portrait
is
supported
now
-‐-‐>
<phone:SupportedOrienta8ons="Portrait"
Orienta8on="Portrait”>
Windows
Phone
Programming,
Pasi
Manninen.
34
35. Example
-‐
OrientaYon
• Demo
with
only
portrait
orientaYon
• Demo
with
PortraitOrLandscape
• Demo
with
OrientaYonChanged
event
Windows
Phone
Programming,
Pasi
Manninen.
35
36. GlobalizaYon
and
LocalizaYon
• Develop
your
applicaYon
for
more
than
one
language,
you
need
to
globalize
and
localize
your
applicaYon
• Most
are
implement
already
built
into
the
.NET
Framework
• ApplicaYon
should
display
data,
such
as
date
informaYon
and
numbers,
in
a
way
that
is
familiar
to
the
user,
and
should
correctly
handle
user
input
• Use
CultureInfo
class
for
GlobalizaYon
• More
info
here:
hGp://msdn.microsoR.com/en-‐us/library/
windowsphone/develop/ff637522(v=vs.105).aspx
Windows
Phone
Programming,
Pasi
Manninen.
36
37. GlobalizaYon
and
LocalizaYon
• Use
CultureInfo
class
for
GlobalizaYon
• There
is
good
example
in
MSDN
for
GlobalizaYon
– sdkGlobalizaYonCS
• Download
sample
here
– hGp://code.msdn.microsoR.com/wpapps/
GlobalizaYon-‐Sample-‐a2237b7a
Windows
Phone
Programming,
Pasi
Manninen.
37
38. Exercise:
GlobalizaYon
and
LocalizaYon
• ApplicaYon
can
be
easily
localized
• Separate
resources,
such
as
strings,
images,
and
videos,
from
your
code
into
separate
resource-‐
only
files
• Exercise:
– Create
a
new
project
– Add
resource
files
for
each
language
– Define
default
culture
– Add
supported
cultures
to
project.csproj
file
and
use
localized
strings
in
your
applicaYon
(no
hard
coded)
Windows
Phone
Programming,
Pasi
Manninen.
38
39. Page
Styles
–
Single
Page
• ApplicaYon
can
contains
one
single
page,
or
mulYble
single
pages
• Data
can
be
passed
between
applicaYon
pages
• Single
page
can
be
used
behind
other
different
page
styles
(opened
for
example
from
Panorama)
• Portrait,
Landscape
or
both
Windows
Phone
Programming,
Pasi
Manninen.
39
40. NavigaYon
Service
• NavigaYonService
class
can
be
used
to
navigaYon
between
pages
• Use
methods:
– Navigate,
– GoBack,
GoForward
– AddBackEntry,
RemoveBackEntry
//
navigate
to
another
page
in
applicaYon
NavigaYonService.Navigate(new
Uri("/SecondPage.xaml",
UriKind.RelaYve))
Windows
Phone
Programming,
Pasi
Manninen.
40
41. Passing
Parameters
between
Pages
• Parameters
can
be
added
to
URI
string
//
navigate
to
another
page
in
applicaYon
and
pass
variable
string
msg
=
”sample
text
here”;
NavigaYonService.Navigate(new
Uri("/SecondPage.xaml?msg="
+
msg,
UriKind.RelaYve));
• Read
variables
from
QueryString
in
another
page
//
navigated
to
the
page
protected
override
void
OnNavigatedTo(System.Windows.NavigaYon.NavigaYonEventArgs
e)
{
base.OnNavigatedTo(e);
string
msg=””;
IDicYonary<string,
string>
parameters
=
NavigaYonContext.QueryString;
if
(parameters.ContainsKey(”msg”))
msg
=
parameters[”msg"];
}
• Isolated
Strorage
can
be
also
used
Windows
Phone
Programming,
Pasi
Manninen.
41
42. Exercise:
Passing
data
between
Pages
•
•
•
•
Create
a
new
Project
(portrait
page)
Create
addiYonal
page
NavigaYng
between
pages
Passing
Parameters
Windows
Phone
Programming,
Pasi
Manninen.
42
43. Page
Styles
-‐
Panorama
• Panoramic
experiences
are
a
part
of
the
naYve
Windows
Phone
look
and
feel
• Unique
way
to
view
controls,
data,
and
services
• A
panorama
experience
consists
of
a
Panorama
control
and
one
or
more
PanoramaItem
controls
• There
is
Panorama
Template
available
in
project
templates
Windows
Phone
Programming,
Pasi
Manninen.
43
44. Exercise:
Create
a
Panorama
ApplicaYon
• CreaYng
a
project
with
Windows
Phone
applicaYon
(don’t
use
panorama
template)
• Se†ng
the
background
image
• Add
controls
and
contents
• Test
applicaYon
in
emulator
Windows
Phone
Programming,
Pasi
Manninen.
44
45. Page
Styles
-‐
Pivot
• The
Windows
Phone
Pivot
control
provides
a
quick
way
to
manage
views
or
pages.
• Filtering
large
datasets,
viewing
mulYple
data
sets,
or
switching
applicaYon
views
• A
pivot
experience
consists
of
a
Pivot
control
and
one
or
more
PivotItem
controls
• There
is
Pivot
Template
available
in
project
templates
Windows
Phone
Programming,
Pasi
Manninen.
45
46. Exercise:
Create
a
Pivot
ApplicaYon
• Create
a
new
project
with
Windows
Phone
applicaYon
(don’t
use
pivot
template)
• Add
Pivot
control
and
PivotItems
• Add
some
content
to
your
applicaYon
• Test
in
emulator
Windows
Phone
Programming,
Pasi
Manninen.
46
47. Themes
• A
theme
is
a
set
of
resources
used
to
personalize
the
visual
elements
on
a
Windows
Phone
• Default
control
set
is
available
(overridable
in
applicaYon
level)
• Themes
are
specified
in
the
Se†ngs
app
by
tapping
Theme
hGp://msdn.microsoR.com/en-‐us/library/windowsphone/develop/ff402557(v=vs.105).aspx
(Theme
overview)
hGp://msdn.microsoR.com/en-‐us/library/windowsphone/develop/ff769552(v=vs.105).aspx
(Theme
Resourcess)
hGp://msdn.microsoR.com/en-‐us/library/windowsphone/develop/ff769545(v=vs.105).aspx
(How
to
use)
Windows
Phone
Programming,
Pasi
Manninen.
47
48. Theme
Resources
•
•
•
•
•
•
•
Brush
Resources
Color
Resources
Applied
in
the
designer
using
the
control
properYes,
or
Font
Names
through
XAML
using
Thickness
the
{StaYcResource}
markup
extension.
Font
Sizes
Text
Styles
Theme
Visibility
and
Opacity
Windows
Phone
Programming,
Pasi
Manninen.
48
49. Example:
Theme
Resources
• Applying
Theme
Resources
• Determining
Theme
background
and
Accent
color
• TesYng
ApplicaYon
Windows
Phone
Programming,
Pasi
Manninen.
49
50. Styles
• Style
is
a
set
of
values
of
properYes
• Style
can
be
applied
to
many
controls
• A
Style
contains
a
collecYon
of
one
or
more
SeGer
objects
• Scope:
Page,
ApplicaYon,
Library
• Order:
Local
value,
Style,
<Style
TargetType="TextBlock"
x:Key="TextBlockStyle">
<SeGer
Property="Foreground"
Value="Navy"/>
<SeGer
Property="FontSize"
Value="14"/>
Theme,
Default
value
<SeGer
Property="VerYcalAlignment"
Value="BoGom"/>
</Style>
• Implicit
style:
<TextBlock
Style="{StaYcResource
TextBlockStyle}">
– applied
to
specific
control
First
Name:
</TextBlock>
– can
be
without
key
aGribute
– style
is
applied
to
all
controls
it’s
scope
Windows
Phone
Programming,
Pasi
Manninen.
50
51. Example:
Styles
• Create
a
two
styles
(TextBlock,
TextBox)
• Use
Style
and
SeGers
to
define
a
basic
values
for
controls
• Reference
Style
as
a
StaYcResource
Windows
Phone
Programming,
Pasi
Manninen.
51
52. Data
Binding
•
•
•
•
Very
important
subject
Provides
coupling
between
data
and
UI
One
and
two
way
binding
MSDN
Example
-‐
AddingMachine
Windows
Phone
Programming,
Pasi
Manninen.
52
53. Sample
Data
with
ListBox
• Expression
Blend
provides
sample
data
for
ListBoxes
• The
structure
of
sample
data
can
be
specified
• Various
types
of
data
can
be
contained
in
it
• Easy
to
switch
to
an
actual
data
model
• ListBox
can
be
associated
with
ObservableCollecYon<T>
• Displayed
data
is
located
in
the
collecYon
• One
list
box
item
is
displayed
with
a
data
template
hGp://msdn.microsoR.com/en-‐us/library/ee341450(v=expression.40).aspx
(Generate
sample
data)
Windows
Phone
Programming,
Pasi
Manninen.
53
54. Using
DataTemplate
<ListBox
x:Name="AllListBox"
Height="560"
HorizontalAlignment="LeR"
public
class
TheatreArea
Margin="0,0,0,0"
{
VerYcalAlignment="Top"
toolkit:TiltEffect.IsTiltEnabled="True"
public
short
id
{
get;
set;
}
Width="400"
SelecYonChanged="AllListBox_SelecYonChanged">
public
string
name
{
get;
set;
}
<ListBox.ItemTemplate>
public
string
image
{
get;
set;
}
<DataTemplate>
public
string
address
{
get;
set;
}
<StackPanel
Margin="5">
}
<Grid>
<Grid.ColumnDefiniYons>
<ColumnDefiniYon
Width="100"/>
public
List<TheatreArea>
theatreAreas
=
new
List<TheatreArea>();
<ColumnDefiniYon
Width="*"/>
</Grid.ColumnDefiniYons>
<Image
Source="{Binding
image}"
Width="100"
Height="83"/>
<StackPanel
Grid.Column="1">
AllListBox.ItemsSource
=
app.theatreAreas;
<TextBlock
Text="{Binding
name}"
FontSize="26"
Foreground="White"
Margin="10,0,0,0"
VerYcalAlignment="Top"/>
<TextBlock
Text="{Binding
address}"
FontSize="20"
Foreground="White"
Margin="10,0,0,0"
/>
</StackPanel>
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
DataTemplate
is
just
a
lump
of
XAML
that
describes
how
some
properYes
are
going
to
be
displayed
Windows
Phone
Programming,
Pasi
Manninen.
54
55. Exercise:
Bind
data
to
ListBox
Control
• Create
a
new
project
• Create
Customer
and
Customers
classes
to
store
customers
data
• Bind
data
to
ListBox
control
with
ItemsSource
• Display
selected
customer
with
MessageBox
Windows
Phone
Programming,
Pasi
Manninen.
55
56. Model-‐View-‐ViewModel
(MVVM)
• Consists
of
three
different
components
– View:
Here
you
put
all
the
XAML
– ViewModel:
Here
you
put
all
the
presentaYon
logic
that
connects
the
UI
and
the
data
– Model:
Here
you
put
all
data
classes
and
business
objects
that
you
will
need
www.windowsphonegeek.com
Windows
Phone
Programming,
Pasi
Manninen.
56
57. Exercise:
MVVM
with
ListBox
Control
• Create
a
new
project
• Create
Customer
and
Customers
classes
as
in
previous
exercise
• Create
a
new
CustomerDetailsPage
to
edit
customer
data
• Create
a
new
ViewModel
class
to
pass
selected
customer
data
to
view
• Share
applicaYon
data
between
pages
with
App
class
• Use
ObservableCollecYon
to
store
customers
data
Windows
Phone
Programming,
Pasi
Manninen.
Look
more
informaYon
about
MVVM
and
Observable
collecYon
from
course
web
page
material:
-‐
4.6
Using
ViewModel
Classes
57
58. Events
• Behavior
of
an
applicaYon
is
event
driven
• Plagorm
provides
callbacks
to
the
applicaYon
– Launching,
click,
OnNavigatedTo,
etc…
• Callback
funcYons
should
return
“quickly”
Windows
Phone
Programming,
Pasi
Manninen.
58
59. Handle
Events
• Use
Event
Handler
in
XAML
• Adding
the
Event
Handler
in
code
• Using
a
Lambda
Expression
<BuGon
Content="Events
with
XAML"
Click="buGon1_Click"
/>
private
void
buGon1_Click(object
sender,
RoutedEventArgs
e)
{
MessageBox.Show("First
buGon
is
pressed.");
}
buGon2.Click
+=
new
RoutedEventHandler(buGon2_Click);
buGon3.Click
+=
(e,
o)
=>
{
MessageBox.Show("Third
buGon
is
pressed.");
};
Windows
Phone
Programming,
Pasi
Manninen.
59
60. Threads
–
UI
Thread
• The
main
thread
in
Silverlight
for
Windows
Phone
• Only
the
UI
thread
can
access
UI
elements
• Tasks
handled
by
the
UI
thread
• Parse
and
create
objects
from
XAML
• Draw
all
visuals
the
first
Yme
they
are
drawn
• Process
per-‐frame
callbacks
and
execute
other
user
code
• Maintaining
a
lightweight
UI
thread
is
the
key
to
wriYng
a
responsive
applicaYon
Windows
Phone
Programming,
Pasi
Manninen.
60
61. Threads
–
ComposiYon
Thread
• Handles
some
work
that
the
UI
thread
would
normally
handle
• Combines
graphics
textures
and
passes
them
to
the
GPU
for
drawing
• Storyboard-‐driven
animaYons
are
automaYcally
cached
and
handled
by
the
GPU
– ScaleTransform,
TranslateTransform
– RotateTransform,
PlaneProjecYon
• Like
“Compose”
textures
and
passed
them
to
the
GPU
Windows
Phone
Programming,
Pasi
Manninen.
61
62. Threads
–
Worker
Thread
• Avoid
complex
processes
that
block
the
UI
thread
• Use
secondary
thread,
called
a
background
thread,
and
do
this
processing
asynchronously
• For
example,
the
Web
service
APIs
are
all
designed
to
be
used
asynchronously
so
they
do
not
block
the
UI
thread
• Dispatcher
mechanism
is
used
to
synchronize
worker
and
UI
threads
• Dispatcher
can
be
found
in
many
applicaYon
classes
Windows
Phone
Programming,
Pasi
Manninen.
62
63. Example:
Worker
Thread
• Update
Slider
from
another
thread
• Start
and
stop
thread
• Use
Dispatcher
BeginInvoke
to
update
Slider
from
another
thread
private
void
threadMethod()
{
while
(true)
{
if
(YmeToQuit)
return;
//
here
goes
the
important
parallel
job
to
do
Thread.Sleep(50);
//
the
job
done,
update
UI
-‐
executes
delegate
asynchronously
on
the
UI
thread
Dispatcher.BeginInvoke(delegate()
{
updateSlider();
});
}
}
Windows
Phone
Programming,
Pasi
Manninen.
63
64. Example:
Background
Worker
• Class
provides
an
easy
way
to
run
Yme-‐consuming
operaYons
on
a
background
thread
• Enables
check
the
state
of
the
operaYon
and
cancellaYon
//
run
Yme-‐consuming
operaYons
on
a
background
thread
private
BackgroundWorker
bw
=
new
BackgroundWorker();
//
indicate
operaYon
progress,
compleYon,
and
cancellaYon
bw.WorkerReportsProgress
=
true;
bw.WorkerSupportsCancellaYon
=
true;
//
method
to
do
background
work
bw.DoWork
+=
new
DoWorkEventHandler(bw_DoWork);
//
method
to
report
process
to
UI
bw.ProgressChanged
+=
new
ProgressChangedEventHandler(bw_ProgressChanged);
//
method
when
all
done
or
cancelled
bw.RunWorkerCompleted
+=
new
RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
Windows
Phone
Programming,
Pasi
Manninen.
64
65. Loading
data
from
network
• Windows
Phone
Device
uses
WiFi,
3G
and
GPRS
to
get
connected
• Remember
-‐
mobile
phone
does
not
have
a
working
connecYon
at
all
Ymes
• Any
network
request
must
provide
progress
informaYon
and
use
Ymeouts
to
ensure
that
a
failed
network
doesn’t
cause
them
to
get
stuck
• All
network
requests
must
be
calls
to
services
that
will
deliver
a
result
asynchronously
Windows
Phone
Programming,
Pasi
Manninen.
65
66. The
WebClient
Class
• Provides
common
methods
for
sending
data
to
and
receiving
data
from
a
resource
idenYfied
by
a
URI
• Uses
the
WebRequest
class
to
provide
access
to
resources
• How
to
work:
– Create
a
WebClient
instance
– Bind
methods
to
the
complete
events
– Display
result
from
loaded
data
Windows
Phone
Programming,
Pasi
Manninen.
66
67. Example:
WebClient
•
•
•
•
•
Create
UI
to
show
loaded
webpage
data
Create
a
WebClient
instance
Bind
a
method
to
the
completed
event
Start
async
downloading
process
Show
loaded
data
in
TextBox
private
void
loadBuGon_Click(object
sender,
RoutedEventArgs
e)
{
//
WebClient
instance
webClient.DownloadStringAsync(new
Uri(urlTextBox.Text));
private
WebClient
webClient;
private
void
webClient_DownloadStringCompleted(object
}
sender,
DownloadStringCompletedEventArgs
e)
{
//
create
a
WebClient
instance
webClient
=
new
WebClient();
if
(e.Error
==
null)
{
//
binds
a
method
to
the
completed
event
webClient.DownloadStringCompleted
+=
new
pageTextBlock.Text
=
e.Result;
DownloadStringCompletedEventHandler(
}
}
webClient_DownloadStringCompleted);
Windows
Phone
Programming,
Pasi
Manninen.
67
68. Example:
HGpClient
in
WP8
• Create
UI
to
show
loaded
webpage
data
• Create
a
HGpClient
instance
– Nuget
it
to
your
project
• Use
async
and
await
in
methods
• Start
async
downloading
process
private
async
void
loadBuGon_Click(object
sender,
RoutedEventArgs
e)
{
hGpClient
=
new
HGpClient();
Uri
uri
=
new
Uri(urlTextBox.Text);
System.DiagnosYcs.Debug.WriteLine("Before");
pageTextBlock.Text
=
await
hGpClient.GetStringAsync(uri);
System.DiagnosYcs.Debug.WriteLine("ARer");
}
Windows
Phone
Programming,
Pasi
Manninen.
68
69. LINQ
(Language
Integrated
Query)
• LINQ
is
a
technology
that
is
part
of
the
.NET
system
libraries
• It
builds
on
C#
language
features
to
provide
easy
data
transfer
between
structured
data
storage
and
the
object
models
used
by
modern
languages
• LINQ
can
decode
an
XML
document
and
create
objects
with
data
properYes
• CollecYons
of
objects
can
be
bound
to
Silverlight
lists
which
contain
display
templates
Windows
Phone
Programming,
Pasi
Manninen.
69
70. Example:
Parse
XML
• Create
a
new
project
and
sample
XML
data
to
Asset
folder
• Use
XDocument
to
load
XML
file
• Parse
object
with
LINQ
<employees>
<employee>
<FirstName>Leonard</FirstName>
<LastName>Hubert</LastName>
<Email>leonard.hubert@domain.com</Email>
</employee>
…
</employees>
class
Employee
{
public
string
FirstName
{
get;
set;
}
public
string
LastName
{
get;
set;
}
public
string
Email
{
get;
set;
}
}
<ListBox
x:Name="EmployeeListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel
Orientation="Vertical">
<TextBlock
Text="{Binding
FirstName}"/>
<TextBlock
Text="{Binding
LastName}"/>
<TextBlock
Text="{Binding
Email}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
//
load
xml
data
XDocument
doc
=
XDocument.Load("Assets/employees.xml");
//
parse
objects
from
XML
data
var
data
=
from
query
in
doc.Descendants("employee")
select
new
Employee
{
FirstName
=
(string)query.Element("FirstName"),
LastName
=
(string)query.Element("LastName"),
Email
=
(string)query.Element("Email")
};
employees
=
data.ToList();
Windows
Phone
Programming,
Pasi
Manninen.
70
71. Example:
Parse
JSON
• Create
a
new
project
and
sample
JSON
data
to
Asset
folder
• Use
HGpClient
and
SimpleJSON
in
project
(install
with
NuGet)
• Deserialize
JSON
string
into
object’s
and
bind
data
to
view
private
async
void
ParseJSON()
{
Uri
uri
=
new
Uri("http://../employees.json",
UriKind.Absolute);
//
get
json
string
from
a
web
Task<string>
getStringTask
=
(new
HttpClient()).GetStringAsync(uri);
string
xmlString
=
await
getStringTask;
//
Deserialize
JSON
string
to
dynamic
object
IDictionary<string,
object>
json
=
(IDictionary<string,
object>)SimpleJson.DeserializeObject(xmlString);
//
employees
list
IList
JSONEmployees
=
(IList)json["employees"];
//
Find
employee
details
...
...
for
(int
i
=
0;
i
<
JSONEmployees.Count;
i++)
{
//
Create
a
new
Employee
Employee
employee
=
new
Employee();
//
Employee
object
from
JSON
IDictionary<string,
object>
JSONEmployee
=
(IDictionary<string,
object>)JSONEmployees[i];
employee.FirstName
=
(string)
JSONEmployee["FirstName"];
employee.LastName
=
(string)
JSONEmployee["LastName"];
employee.Email
=
(string)
JSONEmployee["Email"];
//
add
to
list
employees.Add(employee);
}
//
bind
to
list
EmployeeListBox.ItemsSource
=
employees;)json["employees"];
}
Windows
Phone
Programming,
Pasi
Manninen.
71
72. LINQ
Example
–
Weather
Forecast
public
class
Forecast
{
public
string
query
{
get;
set;
}
//
cityname,
countryname
public
string
observaYon_Yme
{
get;
set;
}
public
string
date
{
get;
set;
}
public
string
temp_C
{
get;
set;
}
public
string
tempMaxC
{
get;
set;
}
public
string
tempMinC
{
get;
set;
}
public
string
weatherIconUrl
{
get;
set;
}
public
string
windspeedKmph
{
get;
set;
}
public
string
humidity
{
get;
set;
}
}
//
parse
returned
data
from
WebClient
call
XDocument
document
=
XDocument.Parse(e.Result);
var
data
=
from
query
in
document.Descendants("current_condiYon")
select
new
Forecast
{
observaYon_Yme
=
(string)
query.Element("observaYon_Yme"),
temp_C
=
(string)query.Element("temp_C"),
weatherIconUrl
=
(string)query.Element("weatherIconUrl"),
humidity
=
(string)query.Element("humidity"),
windspeedKmph
=
(string)query.Element("windspeedKmph")
};
Windows
Phone
Programming,
Pasi
Manninen.
72
73. Example:
Picasa
Image
Gallery
with
JSON
• Access
to
your
public
and
private
image
albums
in
Google
Picasa
• AuthenYcates
to
Google
• Get
image
albums
data
with
JSON
string
• Parse
data
with
Simple
JSON
• Use
Silverlight
Toolkit
WrapPanel
to
display
images
hGp://www.developer.nokia.com/Community/Wiki/Picasa_Image_Gallery_with_JSON_in_WP7
Windows
Phone
Programming,
Pasi
Manninen.
73
74. Exercise:
Employees
Store
Employees
data
to
XML
files
Load
XML
data
with
WebClient
Parse
loaded
XML
data
with
LINQ
Show
all
the
employees
in
Main
Page
with
ListBox
control
• Show
selected
employee
data
in
Employee
Page
• Use
PhoneCallTask,
SmsComposeTask
and
EmailComposeTask
classes
to
send
message
to
selected
employee
•
•
•
•
Windows
Phone
Programming,
Pasi
Manninen.
74
75. Exercise:
Weather
Forecast
• Create
a
Panorama
applicaYon
to
show
Weather
Forecast
• Get
Weather
Online
API
key
• Load
and
parse
XML
based
forecast
data
with
LINQ
• Use
own
made
DataTemplate
to
show
forecast
data
• Use
Isolated
Storage
to
save
applicaYon
se†ngs
Windows
Phone
Programming,
Pasi
Manninen.
75
76. ApplicaYon
Life
Cycle
–
NavigaYon
Stack
• The
history
of
applicaYon
acYvaYons
are
kept
in
a
navigaYon
stack
• New
applicaYon
is
placed
into
the
stack,
and
when
back
buGon
is
pressed
current
applicaYon
is
terminated
and
previous
applicaYon
is
acYvated
• Long
pressing
the
back
buGon
can
overtake
some
of
the
previous
applicaYons
• Only
one
3rd
party
applicaYon
can
run
simultaneusly
• Launching
the
applicaYon
freezes
the
execuYon
of
the
current
applicaYon
(Dormant
state)
• Frozen
applicaYon
may
be
removed
from
the
memory
(Tombstoned
state)
Windows
Phone
Programming,
Pasi
Manninen.
76
77. Dormand
and
Tombstoned
• If
the
user
navigates
away
from
an
applicaYon
it
becomes
dormant
– It
is
sYll
in
memory,
along
with
all
its
data,
but
it
is
not
running
– It
may
be
directly
resumed
at
a
later
Yme
• If
a
dormant
applicaYon
is
removed
from
memory
it
is
said
to
be
tombstoned
– It
is
no
longer
in
memory,
but
it
might
sYll
be
resumed
because
it
is
sYll
in
the
back
stack
Windows
Phone
Programming,
Pasi
Manninen.
77
78. Live
Cicle
Events
• ApplicaYon
Class
receives
events:
– ApplicaYon_Launching
– ApplicaYon_AcYvated
– ApplicaYon_DeacYvated
– ApplicaYon_Closing
• Page
NavigaYon
Events
– OnNavigatedTo
– OnNavigatedFrom
Windows
Phone
Programming,
Pasi
Manninen.
78
79. Dormant
/
Tombstoned
• The
AcYvaYon
handler
can
test
a
flag
to
determine
the
type
of
resume
taking
place
private
void
Application_Activated(object
sender,
ActivatedEventArgs
e)
{
if
(e.IsApplicationInstancePreserved)
{
//
Dormant
–
all
data
in
place
}
else
{
//
Tombstoned
–
all
data
gone,
need
to
reload
}
}
Windows
Phone
Programming,
Pasi
Manninen.
79
80. Tombstone
tesYng
in
Emulator
• By
default
applicaYons
running
in
the
emulator
are
not
tombstoned
• Open
Project
ProperYes
>
Debug
Tab
and
change
the
default
behavior
in
debugging
Windows
Phone
Programming,
Pasi
Manninen.
80
81. Maintain
the
state
of
applicaYon
//
OnNavigatedFrom
State["logEntry"]
=
logTextBox.Text;
• Page
State
– store
page
data
(state)
to
State
dicYonary
– works
(used)
between
OnNavigatedTo
and
OnNavigatedFrom
methods
• ApplicaYon
State
– store
applicaYon
data
(state)
to
State
dicYonary
– works
(used)
between
AcYvated
and
DeacYvated
//
OnNavigatedTo
if
(State.ContainsKey("logEntry"))
{
logTextBox.Text
=
State["logEntry"]
as
String;
}
//
ApplicaYon_AcYvated
object
LogTextObject
=
PhoneApplicaYonService.Current.State["logEntry"];
if
(LogTextObject
!=
null)
{
LogText
=
LogTextObject
as
String;
}
//
ApplicaYon_DeacYvated
PhoneApplicaYonService.Current.State.Remove("logEntry");
if
(LogText
!=
null)
PhoneApplicaYonService.Current.State.Add(
"logEntry",
LogText);
Windows
Phone
Programming,
Pasi
Manninen.
81
82. Isolated
Storage
• Persistent
storage,
unYl
the
applicaYon
is
uninstalled
• Data
storage
opYons
//
ApplicaYon_Launching
IsolatedStorageSe†ngs
isolatedStore
=
IsolatedStorageSe†ngs.ApplicaYonSe†ngs;
LogText
=
"";
try
{
LogText
=
(string)isolatedStore["Log"];
}
catch
{
}
– IsolatedSe†ngs
(key/value
pairs)
– Files
and
folders
//
ApplicaYon_Closing
IsolatedStorageSe†ngs
isolatedStore
=
– Streams
IsolatedStorageSe†ngs.ApplicaYonSe†ngs;
• Protected
file
system
of
an
applicaYon
isolatedStore.Remove("Log");
isolatedStore.Add("Log",
LogText);
isolatedStore.Save();
• hGp://msdn.microsoR.com/en-‐us/library/
windowsphone/develop/ff402541(v=vs.
92).aspx
Windows
Phone
Programming,
Pasi
Manninen.
82
83. Example:
ApplicaYon
and
Page
State
• Use
Page
State
to
test
OnNavigatedTo
and
OnNavigatedFrom
methods
in
one
page
• Store
data
to
App
class
to
test
sharing
data
between
pages
• Use
ApplicaYon
State
to
test
AcYvated
and
DeAcYvated
Methods
• Use
IsolatedStorage
to
store
data
between
launch
Ymes
• Test
Tombstone
mode
Windows
Phone
Programming,
Pasi
Manninen.
83
84. Isolated
Storage
vs.
Stage
Storage
• Isolated
storage
is
so
called
because
the
data
for
an
applicaYon
is
isolated
from
all
other
applicaYons
– Can
be
used
as
file
store
where
applicaYons
can
store
folders
and
files
– It
is
slow
to
access,
since
it
is
based
on
NVRAM
technology
– It
can
also
be
used
to
store
name/value
pairs,
e.g.
program
se†ngs
• State
storage
is
so
called
because
it
is
used
to
hold
the
state
of
an
applicaYon
– It
can
be
used
to
store
name/value
pairs
which
are
held
in
memory
for
Dormant
or
Tombstoned
applicaYons
– It
provides
very
quick
access
to
data
Windows
Phone
Programming,
Pasi
Manninen.
84
85. Local
folder
in
WP8
• The
local
folder
is
the
root
folder
of
your
app’s
data
store
• Known
in
Windows
Phone
OS
7.1
as
isolated
storage,
the
local
folder
is
isolated
from
other
apps
• Use
this
folder
to
persist
data
on
the
phone
• Data
for
Windows
Phone:
hGp://msdn.microsoR.com/en-‐us/library/windowsphone/develop/ff402541(v=vs.105).aspx
Windows
Phone
Programming,
Pasi
Manninen.
85
86. Example:
Local
Data
Storage
in
WP8
• Read
data
from
– se†ngs
(Isolated)
– file
(Isolated)
– resources
– database
– SD
Card
Windows
Phone
Programming,
Pasi
Manninen.
86
87. Exercise:
IsolatedStorage
(se†ngs)
• Store
user’s
username
and
login
in
to
Isolated
Storage
• Load
data
from
Isolated
Storage
when
applicaYon
starts
next
Yme
• Use
IsolatedStorageSe†ngs
Class
to
store
data
Windows
Phone
Programming,
Pasi
Manninen.
87
88. Exercise:
Isolated
Storage
(file)
• Obtain
a
virtual
store
for
an
applicaYon
• Create
a
parent
folder
• Create
and
add
text
to
an
isolated
storage
file
• Read
the
text
placed
in
the
storage
file
Windows
Phone
Programming,
Pasi
Manninen.
88
89. Exercise:
Isolated
Storage
(database)
•
•
•
•
CreaYng
a
applicaYng
UI
Building
the
Data
Context
CreaYng
the
Database
CompleYng
the
ApplicaYon
Windows
Phone
Programming,
Pasi
Manninen.
89
90. Example:
Movies
in
Finnkino
Theatre’s
• Look
this
code
example
to
learn
more
about
loading
data
from
net
and
handling
tombstone
mode
in
applicaYon
hGp://www.developer.nokia.com/Community/Wiki/Movies_in_Finnkino_Theatre's
Windows
Phone
Programming,
Pasi
Manninen.
90
91. XNA
Example:
ShooYng
game
• A
simple
shooter
game
• A
staYonary
cannon
is
shooYng
to
enemy
paratroopers
falling
down
from
the
sky
• Very
simple
game
physics
• Rules
Player
gets
5
points
for
each
enemy
paratrooper
shot
down
Speed
of
falling
of
an
enemy
increases
each
Yme
it
is
shot
down
Player
has
three
lives
at
the
start
of
the
game
Player
looses
a
life
each
Yme
an
enemy
leaves
the
screen
without
being
shot
down
– Once
the
number
of
lives
falls
down
to
0,
it’s
game
over
–
–
–
–
• Touch
input
will
be
used
in
this
sample
applicaYon
– Finger
dragging
for
cannon
barrel
rotaYon
– Tap
gesture
for
shooYng
Windows
Phone
Programming,
Pasi
Manninen.
91
92. Games
in
WP8
• XNA
games
sYll
work
on
Windows
Phone
8
as
in
compaYbility
mode
• XNA
cannot
access
to
Windows
Phone’s
NFC,
wallet,
lenses,
Bluetooth
APIs
etc.
• Developers
can
use
in
WP8
– C#,
C++
(Visual
Studio)
– MonoGame,
Cocos2d-‐x,
SharpDX,
DirectX
TK
(toolkit),
Unity
3D,
…
• Games
for
Windows
Phone
8:
hGp://msdn.microsoR.com/en-‐us/library/windowsphone/develop/jj206992(v=vs.105).aspx
Windows
Phone
Programming,
Pasi
Manninen.
92
93. Launcher
and
Choosers
•
•
•
On
Windows
Phone
plagorm
interacYons
between
applicaYons
are
accomplished
by
using
Launchers
and
Choosers
Launchers
and
Choosers
start
another
applicaYon
to
perform
a
dedicated
task
Choosers
typically
returns
some
data
Launcher
Examples
– PhoneCallTask
– SearchTask
– SMSComposeTask
– WebBrowserTask
– EmailComposeTask
– MarketPlaceDetailTask
– MarketPlaceHubTask
– MarketPlaceSearchTask
– MediaPlayerLauncher
•
Choosers
Examples
– EmailAddressChooserTask
– PhoneNumberChooserTask
– PhotoChooserTask
– AddressChooserTask
– BingMapsDirecYonsTask
See
the
complete
list
here
– hGp://msdn.microsoR.com/en-‐us/library/windowsphone/develop/ff769550(v=vs.105).aspx
– hGp://msdn.microsoR.com/en-‐us/library/windowsphone/develop/ff769543(v=vs.105).aspx
Windows
Phone
Programming,
Pasi
Manninen.
93
94. Calling
a
Launcher
or
Chooser
• When
an
applicaYon
calls
a
Launcher
or
Chooser
the
new
task
gets
control
• When
the
task
is
complete
the
applicaYon
regains
control
• If
the
user
never
returns
from
the
Launcher/
Chooser
the
applicaYon
never
gets
control
back
• This
when
the
new
task
gets
control
an
applicaYon
may
get
tombstoned
Windows
Phone
Programming,
Pasi
Manninen.
94
95. Example:
Launcher
Tasks
•
•
•
•
Basic
UI
Make
a
phone
call
Send
SMS
message
Send
Email
message
using
MicrosoR.Phone.Tasks;
//
make
a
phone
call
PhoneCallTask
phoneTask
=
new
PhoneCallTask();
phoneTask.DisplayName
=
nameTextBox.Text;
phoneTask.PhoneNumber
=
phoneTextBox.Text;
phoneTask.Show();
Windows
Phone
Programming,
Pasi
Manninen.
95
96. Example:
Chooser
Tasks
• Basic
UI
• Get
name
and
phone
number
• Use
PhoneNumberChooserTask
Windows
Phone
Programming,
Pasi
Manninen.
96
97. Exercise:
Web
Browser
Task
• Add
TextBox
to
ask
URL
from
user
• Use
WebBrowserTask
to
load
and
show
a
web
page
hGp://msdn.microsoR.com/en-‐us/library/windowsphone/develop/hh394020(v=vs.105).aspx
Windows
Phone
Programming,
Pasi
Manninen.
97
98. Exercise:
Photo
Chooser
Task
• Add
Image
control
to
your
page
• Use
PhotoChooserTask
to
load
and
show
image
in
page
hGp://msdn.microsoR.com/en-‐us/library/windowsphone/develop/hh394019(v=vs.105).aspx
Windows
Phone
Programming,
Pasi
Manninen.
98
99. Camera
use
cases
• CameraCaptureTask,
launches
another
applicaYon
to
take
a
picture
• PhotoChooserTask,
launches
another
applicaYon
to
choose
one
of
already
taken
pictures
• Embedding
camera
to
your
applicaYon
– a
place
holder
for
the
view
finder
on
your
page
– use
MicrosoR.Devices.PhotoCamera
instance
and
CameraBuGons
for
accessing
HW
buGons
– add
capturing
logic
and
needed
event
handlers
Windows
Phone
Programming,
Pasi
Manninen.
99
100. Example:
CameraCaptureTask
• Basic
UI
• Get
image
from
camera
with
CameraCaptureTask
• Show
captured
image
with
Image
control
Windows
Phone
Programming,
Pasi
Manninen.
100
101. Example:
Custom
Camera
• Use
Canvas
to
show
preview
of
the
Camera
• Use
PhotoCamera
to
handle
image
capturing
• Save
captured
image
to
MediLibrary
(in
microsoR.xna.framework.dll)
Windows
Phone
Programming,
Pasi
Manninen.
101
102. Play
sound
with
MediaElement
• TradiYonal
way
to
play
sound
in
Silverlight
• Easy
to
use
(useful
events,
methods)
• Can
play
media
from:
xap,
isolated
storage,
net
(using
streaming)
• Can’t
play
media
in
background
• Use
MediaElement
control
in
XAML
or
create
it
in
code
to
control
media
Windows
Phone
Programming,
Pasi
Manninen.
102
103. Example:
Music
with
MediaElement
• Basic
UI
with
MediaElement
control
• Play
music
from
XAP
or
net
<MediaElement
Name="mediaElement"
AutoPlay="False"
/>
<BuGon
Content="Play
from
xap"
Name="playXAPBuGon"
Click="playXAPBuGon_Click"
/>
<BuGon
Content="Play
from
net"
Name="playNetBuGon"
Click="playNetBuGon_Click"
/>
//
in
constuctor
mediaElement.MediaOpened
+=
MediaElement_MediaOpened;
private
void
playXAPBuGon_Click(object
sender,
RoutedEventArgs
e)
{
mediaElement.Source
=
new
Uri("/Kalimba.mp3",
UriKind.RelaYve);
}
private
void
playNetBuGon_Click(object
sender,
RoutedEventArgs
e)
{
mediaElement.Source
=
new
Uri("hGp://domain/Kalimba.mp3",
UriKind.Absolute);
}
private
void
MediaElement_MediaOpened(object
sender,
RoutedEventArgs
e)
{
(sender
as
MediaElement).Play();
}
Windows
Phone
Programming,
Pasi
Manninen.
103
104. Play
sound
with
MediaPlayerLauncher
• MediaPlayerLauncher
allows
the
developers
to
play
video
or
music
• MediaPlayerLauncher
will
launch
the
Media
Player
and
plays
the
Media
file
specified
• Can
play
media
from:
xap,
isolated
storage,
net
(using
streaming)
• one
or
more
of
the
Media
Player
controls
can
be
specified
Windows
Phone
Programming,
Pasi
Manninen.
104
105. Example:
Music
with
MediaPlayerLaucher
• Basic
UI
• Play
music
from
XAP
or
net
MediaPlayerLauncher
objMediaPlayerLauncher
=
new
MediaPlayerLauncher();
objMediaPlayerLauncher.Media
=
new
Uri("Kalimba.mp3",
UriKind.RelaYve);
objMediaPlayerLauncher.LocaYon
=
MediaLocaYonType.Install;
objMediaPlayerLauncher.Controls
=
MediaPlaybackControls.Pause
|
MediaPlaybackControls.Stop
|
MediaPlaybackControls.All;
objMediaPlayerLauncher.OrientaYon
=
MediaPlayerOrientaYon.Portrait;
objMediaPlayerLauncher.Show();
Windows
Phone
Programming,
Pasi
Manninen.
105
106. Play
sound
with
MediaPlayer
and
MediaLibrary
• MediaPlayer
can
play
sound
from
MediaLibrary
• Lot’s
of
metadata
is
available
(like
albums,
songs,
art,
history
of
playback…)
as
a
collecYon
• Music
can
be
played
as
a
background
• Uses
XNA
framework
behind
• Playing
sound
is
always
list
based
(MediaPlayer
gives
collecYon
with
Sounds)
-‐>
”opposite
to
MediaElement”
Windows
Phone
Programming,
Pasi
Manninen.
106
107. Example:
Music
with
MediaPlayer
• Very
basic
UI
• Use
MediaLibrary
sounds
• Call
XNA
update
method
with
DispatcherTimer
• Play
random
song
from
MediaLibrary
Note:
Music
plays
in
background
Windows
Phone
Programming,
Pasi
Manninen.
107
108. Background
Audio
Agent
• Can
play
audio
in
background
from
MediaLibrary,
Isolated
Storage
or
Net
• Can’t
play
from
xap
(copy
to
Isolated
Storage
first)
• You
need
to
add
second
project
to
your
soluYon
– Windows
Phone
Audio
Playback
Agent
• Background
Audio
Overview
for
Windows
Phone
:
hGp://msdn.microsoR.com/en-‐us/library/
windowsphone/develop/hh394039(v=vs.
105).aspx
Windows
Phone
Programming,
Pasi
Manninen.
108
109. Example:
Streaming
MP3
Player
• Get
music
albums
data
from
server
side
with
PHP
and
JSON
data
• Use
Audio
Playback
Agent
to
stream
music
from
server
• Use
Panorama
and
single
pages
• Store
playlists
to
Isolated
Storage
hGp://www.developer.nokia.com/Community/Wiki/Streaming_MP3_player_in_WP7
Windows
Phone
Programming,
Pasi
Manninen.
109
110. Exercise:
Play
Background
Audio
• Create
a
new
project
• Create
Windows
Phone
Audio
Playback
Agent
project
to
your
soluYon
• Add
some
audio
files
• Create
a
UI
with
prev,
play,
next
BuGons
to
control
Playback
agent
• Copy
audio
files
from
xap
to
Isolated
Storage
when
applicaYon
starts
(App.xaml.cs)
hGp://msdn.microsoR.com/en-‐us/library/windowsphone/develop/hh202978(v=vs.105).aspx
Windows
Phone
Programming,
Pasi
Manninen.
110
111. Play
or
Stream
Video
File
• You
can
play
media
files
on
a
Windows
Phone
using
the
MediaPlayerLauncher
or
using
the
MediaElement
API
MediaPlayerLauncher
mediaPlayerLauncher;
mediaPlayerLauncher
=
new
MediaPlayerLauncher();
mediaPlayerLauncher.Controls
=
MediaPlaybackControls.All;
mediaPlayerLauncher.LocaYon
=
MediaLocaYonType.None;
mediaPlayerLauncher.Media
=
new
Uri("hGp://ptm.fi/wp/temp.mp4",UriKind.Absolute);
mediaPlayerLauncher.Show();
Windows
Phone
Programming,
Pasi
Manninen.
111
112. Example:
Custom
Video
Player
• Create
UI
with
MediaElement,
Slider
and
TextBlocks
• Use
MediaElement
API
to
set
Source
and
Play
video
stream
• Listen
MediaElement
DownloadProgressChanged
event
• Check
video
Yme
in
ComposiYonTarget
Rendering
Event
MediaElement.Source
=
new
Uri("hGp://ptm.fi/wp/temp.mp4",
UriKind.Absolute);
MediaElement.Play();
MediaElement.DownloadProgressChanged
+=
(s,
e)
=>
{
downloadTextBlock.Text
=
string.Format("{0:0.0%}",
MediaElement.DownloadProgress);
};
ComposiYonTarget.Rendering
+=
(s,
e)
=>
{
//
get
video
Yme
,
show
Yme
string
in
textblock
move
slider
};
Windows
Phone
Programming,
Pasi
Manninen.
112
113. Exercise:
Record
Video
• There
is
a
one
excellent
tutorial
to
record
and
save
video
to
Isolated
Storage
in
MSDN
• Look,
design
and
create
a
new
page
using
this
tutorial
from
MSDN
hGp://msdn.microsoR.com/en-‐us/library/windowsphone/develop/hh394041(v=vs.105).aspx
Windows
Phone
Programming,
Pasi
Manninen.
113
114. Accessing
the
Microphone
• Use
the
Microphone
class
from
the
XNA
Framework
to
get
audio
input
• XNA
Game
Studio
game
loop
has
to
be
simulated
• Audio
can
be
captured
from
the
microphone
and
store
it
to
the
MemoryStream
object
• Recorted
audio
can
be
played
with
SoundEffect
(for
example)
• Use
Isolated
Storage
to
save
you
audio
file
Windows
Phone
Programming,
Pasi
Manninen.
114
115. Example:
Save
Microphone
data
to
Isolated
Storage
• Basic
UI
with
a
few
BuGons
• Capture
BuGon
– simulate
the
XNA
Game
Studio
game
loop
– reads
data
from
microphone
to
memory
stream
object
• Play
audio
from
memory
stream
object
with
soundEffect
• Save
audio
data
to
Isolated
Storage
• Read
bytes
from
Isolated
Storage
and
play
with
soundEffect
Windows
Phone
Programming,
Pasi
Manninen.
115
116. Gesture
Support
in
Silverlight
• Silverlight
for
Windows
Phone
allows
process
touch
input
by
using
manipulaYon
events
• Manipula8onStarted
– This
event
occurs
when
the
user
starts
a
direct
manipulaYon
by
placing
their
finger
or
fingers
on
the
screen
• Manipula8onDelta
– This
event
occurs
repeatedly
while
the
user
is
moving
their
finger
or
fingers
on
the
screen
• Manipula8onCompleted
– This
event
occurs
when
the
user
removed
their
finger
or
fingers
from
the
screen
Windows
Phone
Programming,
Pasi
Manninen.
116
117. Exercise:
Handle
ManipulaYon
Events
• Create
a
new
Windows
Phone
project
• Add
Canvas
and
one
Rectangle
in
it
• Add
ManipulaYonDelta
event
handling
to
handle
rectangle
scaling
and
moving
//
Scale
the
rectangle
(correct
these
lines
from
tutorial)
if
(e.DeltaManipulaYon.Scale.X
>
0)
this.scale.ScaleX
*=
e.DeltaManipulaYon.Scale.X;
if
(e.DeltaManipulaYon.Scale.Y
>
0)
this.scale.ScaleY
*=
e.DeltaManipulaYon.Scale.Y;
hGp://msdn.microsoR.com/en-‐us/library/ff426933(VS.95).aspx
Windows
Phone
Programming,
Pasi
Manninen.
117
118. Exercise:
Teletext
• Try
to
simulate
Teletext
applicaYon
in
Windows
Phone
• Hints:
– Windows
Phone
doesn’t
support
GIF
files,
use
ImateTools
extension
(use
NuGet
to
install
it
to
your
project)
– More
informaYons
to
ImageTools
here:
hGp://imagetools.codeplex.com/
– Handle
ManipulaYonCompleted
event
to
display
next
or
previous
image
– Base
URL
for
example
Yle’s
Teletext
is
hGp://www.yle.fi/teksYtv/images/
P100_01.gif
Windows
Phone
Programming,
Pasi
Manninen.
118
119. LocaYon
• LocaYon
Service
allows
you
to
create
locaYon-‐aware
applicaYons
• Service
obtains
locaYon
data
from
mulYple
sources
such
as
GPS,
Wi-‐Fi,
and
cellular
• Remember
minimize
power
consumpYon
– Use
the
lower-‐accuracy,
power-‐opYmized
se†ng
for
the
LocaYon
Service
unless
your
applicaYon
absolutely
requires
higher
accuracy
– Wi-‐Fi
and
cellular
radio
less-‐accurate
than
GPS
– Turn
the
LocaYon
Service
on
only
when
your
applicaYon
needs
it,
and
turn
it
off
when
you
are
done
with
it
Windows
Phone
Programming,
Pasi
Manninen.
119
120. LocaYon
–
Basic
Use
• Choose
the
Right
Level
of
Accuracy
for
LocaYon
Data
– naYve
code
layer
handles
choosing
the
best
source
automaYcally
– developer
need
to
choose
between
high
accuracy
or
the
default
with
GeoCoordinateWatcher
//
default
GeoCoordinateWatcher
watcher
=
new
GeoCoordinateWatcher(GeoPosiYonAccuracy.Default);
//
high
GeoCoordinateWatcher
watcher
=
new
GeoCoordinateWatcher(GeoPosiYonAccuracy.High);
• Set
a
Reasonable
Movement
Threshold
– sensors
are
usually
designed
to
be
very
sensiYve
– set
minimum
change
in
posiYon
with
MovementThreshold
property
//
20
meters
watcher.MovementThreshold
=
20;
Windows
Phone
Programming,
Pasi
Manninen.
120
121. LocaYon
-‐
Events
• StatusChanged
event
is
raised
whenever
the
status
of
the
LocaYon
Service
changes
• PosiYonChanged
occurs
when
the
locaYon
service
detects
a
change
in
posiYon
//
listen
status
watcher.StatusChanged
+=
new
EventHandler<GeoPosiYonStatusChangedEventArgs>(watcher_StatusChanged);
//
listen
posiYon
watcher.PosiYonChanged
+=
new
EventHandler<GeoPosiYonChangedEventArgs<GeoCoordinate>>(watcher_PosiYonChanged);
//
start
listening
locaYon
watcher.Start();
Windows
Phone
Programming,
Pasi
Manninen.
121
122. LocaYon
–
Event
Handlers
• StatusChanged
can
handle
following
situaYons
– GeoPosiYonStatus.Disabled
– GeoPosiYonStatus.IniYalizing
– GeoPosiYonStatus.NoData
– GeoPosiYonStatus.Ready
• PosiYonChanged
will
be
called
when
Service
is
ready
and
receiving
data
– LaYtude,
Longitude
– AlYtude
– Course
– Speed
– HorizontalAccuracy,
VerYcalAccuracy
Windows
Phone
Programming,
Pasi
Manninen.
122
123. LocaYon
in
Windows
Phone
8
• Use
Geolocator
Class
• Remember
add
ID_CAP_LOCATION
to
capabiliYes
• Define
– DesiredAccuracy
(High,
Default)
– MovementThreshold
(meters)
• StatusChanged
and
PosiYonChanged
methods
– Use
Dispatcher.BeginInvoke
to
update
UI
• Remember
ask
end
user,
that
your
app
is
using
LocaYon
(otherwise
failed
in
market
test)
Windows
Phone
Programming,
Pasi
Manninen.
123
124. Example:
Detect
LocaYon
•
•
•
•
Start
and
stop
LocaYon
Service
Detect
service
status
changes
Show
laYtude
and
longitude
Use
locaYon
sensor
simulator
– add
locaYons
– save
locaYons
– load
locaYons
• CapabiliYes
– ID_CAP_LOCATION
Windows
Phone
Programming,
Pasi
Manninen.
124
125. Bing
Maps
in
WP7
• Use
Bing
Maps
Silverlight
Control
to
provide
an
enhanced
mapping
experience
• Map
Control
is
used
similarly
as
in
a
desktop
version
– namespace
is
different:
MicrosoR.Phone.Controls.Map
• Developer
has
to
sign
into
the
Bing
Maps
Account
Center
to
obtain
a
Bing
Maps
Key
• Ge†ng
a
Bing
Maps
Key:
hGp://msdn.microsoR.com/en-‐us/library/ff428642.aspx
Windows
Phone
Programming,
Pasi
Manninen.
125
126. Example:
Maps
•
•
•
•
Basic
UI
with
Map
and
BuGon
Controls
Use
Road
and
Aerial
Mode
Use
Zoom
In
and
Out
Accessing
Map
Control
with
Bing
Maps
Key
private
void
roadModeBuGon_Click(object
sender,
RoutedEventArgs
e)
{
map.Mode
=
new
RoadMode();
}
private
void
aerialBuGon_Click(object
sender,
RoutedEventArgs
e)
{
map.Mode
=
new
AerialMode();
}
private
void
zoomInBuGon_Click(object
sender,
RoutedEventArgs
e)
{
map.ZoomLevel++;
}
private
void
zoomOutBuGon_Click(object
sender,
RoutedEventArgs
e)
{
map.ZoomLevel-‐-‐;
}
Windows
Phone
Programming,
Pasi
Manninen.
<my:Map
Name="map"
CredenYalsProvider=”your
key
here"
/>
126
127. Example:
Show
LocaYon
in
Maps
• UI
with
Map
• Use
GeoCoordinateWatcher
to
get
LocaYon
data
• Create
and
show
default
PushPin
with
Text
protected
override
void
OnNavigatedTo(System.Windows.NavigaYon.NavigaYonEventArgs
e)
{
//
create
a
new
pushpin
void
watcher_PosiYonChanged(object
sender,
devicePin
=
new
Pushpin();
devicePin.Content
=
"My
LocaYon";
GeoPosiYonChangedEventArgs<GeoCoordinate>
e)
{
//
add
pushpin
to
map
//
move
pushpin
to
locaYon
of
the
device
map.Children.Add(devicePin);
devicePin.LocaYon
=
e.PosiYon.LocaYon;
}
//
show
map
where
the
pushpin
are,
zoom
15
map.SetView(e.PosiYon.LocaYon,
15);
}
Windows
Phone
Programming,
Pasi
Manninen.
127
128. Example:
Show
PushPins
in
Map
• …
• Add
Places
class
with
LaYtude,
Longitude
and
Text
variables
• Generate
a
few
Places
with
sample
data
• Add
Places
to
MapLayer
with
Custom
PNG-‐Image
(with
TextBlock)
• Detect
Places
PushPin
Pressed
Event
Windows
Phone
Programming,
Pasi
Manninen.
128
129. Example:
a)
Show
Route
in
Map
• …
• Use
BingMapsDirecYonsTask
to
show
route
and
get
direcYon
informaYon
between
device
locaYon
and
selectedplace
Windows
Phone
Programming,
Pasi
Manninen.
129