Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 582

GIO TRNH

LP TRNH WINDOWS PHONE

Khi: i Hc v Cao ng
Nm 2014

GV Bin son: Trn Duy Thanh


Gio trnh: Lp trnh Windows Phone

MC LC
PHN 1. MODULE 1 ..........................................................................................10
BI 1. GII THIU H IU HNH WINDOWS PHONE........................... 10
I. Lch s pht trin Windows Phone ................................................................... 10
II. Cc tnh nng mi trong Windows Phone 8 ...................................................... 12
III. Gii thiu Windows Phone 8 SDK ................................................................... 16
IV. Bt u vi lp trnh Windows Phone 8 ............................................................ 19
1. To project Windows Phone 8 ....................................................................... 19
V. Vng i ng dng Windows Phone (application life cycle) ............................ 25
1. Cc thut ng ................................................................................................ 25
BI 2. TM HIU NGN NG XAML V CC CONTROL C BN ........ 28
I. Tm hiu ngn ng XAML ............................................................................... 28
1. XAML l g? ................................................................................................. 28
2. Tm tt c php XAML ................................................................................ 28
II. Cc control c bn trong Windows Phone ........................................................ 30
1. Layout controls ............................................................................................. 30
2. Text controls ................................................................................................. 34
3. Selection controls .......................................................................................... 37
4. Button control ............................................................................................... 39
5. Image control ................................................................................................ 39
BI 3. CC CONTROL NNG CAO TRONG WINDOWS PHONE ............. 39
I. List controls...................................................................................................... 39
1. ListBox control ............................................................................................. 39
2. LongListSelector control ............................................................................... 42
II. Menu controls................................................................................................... 43
1. ApplicationBar .............................................................................................. 43
III. Media controls .................................................................................................. 44
1. Image control ................................................................................................ 44
2. MediaElement control ................................................................................... 45

Trung Tm Tin Hc H KHTN-TP.HCM Trang 1


Gio trnh: Lp trnh Windows Phone

IV. MessageBox, Popups ........................................................................................ 46


1. MessageBox .................................................................................................. 46
2. Popups .......................................................................................................... 47
BI 4. CC LOI NG DNG V CHUYN TRANG TRONG WINDOWS
PHONE .................................................................................................................. 49
I. Cc loi ng dng............................................................................................. 49
1. Single page.................................................................................................... 49
II. Pivot ................................................................................................................. 50
III. Panorama.......................................................................................................... 54
1. Chuyn trang trong Windows Phone ............................................................. 56
BI 5. DATA BINDING C BN...................................................................... 58
I. Data binding l g? ........................................................................................... 58
II. Cc thnh phn chnh trong Data Binding......................................................... 59
1. Binding Mode ............................................................................................... 59
III. Cch to data binding trong Windows Phone.................................................... 62
BI 6. LM VIC VI FILE V CCH LU TR FILE ............................. 63
I. c im lu tr file trn Windows Phone ....................................................... 63
II. Lm vic vi Folder ......................................................................................... 64
III. Lm vic vi File ............................................................................................. 65
IV. Lm vic vi th mc ci t............................................................................ 67
V. Cng c Windows Phone Power Tools ............................................................. 68
VI. Serialization v Deserialization ........................................................................ 68
VII. IsolatedStorageSettings .............................................................................. 71
BI 7. TM HIU BRUSH V RESOURCE..................................................... 73
I. Tm hiu Brush ................................................................................................. 73
II. Tm hiu v Resource ....................................................................................... 78
1. Cc loi Resource.......................................................................................... 78
2. Gii thiu Resource ....................................................................................... 78
3. Cc v tr t Resource .................................................................................. 79

Trung Tm Tin Hc H KHTN-TP.HCM Trang 2


Gio trnh: Lp trnh Windows Phone

BI 8. TM HIU SQLITE ................................................................................ 81


I. t vn ........................................................................................................ 81
II. Cc bc ci t, cu hnh ................................................................................ 81
III. Cc thao tc c bn trn SQLite ....................................................................... 85
IV. Cng c SQLite Manager ................................................................................. 87
PHN 2. MODULE 3 ..........................................................................................89
BI 1. a phng tin trong Windows Phone (Multimedia) ............................ 89
I. Camera ............................................................................................................. 89
1. Ch Camera Preview ................................................................................ 90
2. Chp hnh t Camera .................................................................................... 93
3. S dng Camera vi ViewModel .................................................................. 95
4. Thit lp hiu ng m thanh cho Camera..................................................... 103
5. To Camera Focus....................................................................................... 110
II. Video.............................................................................................................. 117
1. S dng MediaElement, MediaPlayerLauncher ........................................... 117
2. Cc thao tc thng dng khi s dng Video .............................................. 120
III. Audio ............................................................................................................. 130
1. Thm m thanh vo ng dng ..................................................................... 130
2. Thit lp chy nn Audio ............................................................................ 133
BI 2. DRAWING ............................................................................................. 153
I. Cc i tng v mu ph bin ...................................................................... 153
1. SolidColorBrush.......................................................................................... 154
2. LinearGradientBrush ................................................................................... 156
3. RadialGradientBrush ................................................................................... 162
4. ImageBrush ................................................................................................. 164
II. Canvas ............................................................................................................ 166
1. c tnh ca Canvas .................................................................................... 166
2. Kt xut hnh nh t Canvas ........................................................................ 168
III. Cc loi i tng Shapes .............................................................................. 169

Trung Tm Tin Hc H KHTN-TP.HCM Trang 3


Gio trnh: Lp trnh Windows Phone

1. Ellipse ......................................................................................................... 169


2. Rectangle .................................................................................................... 170
3. Line............................................................................................................. 171
4. Polyline ....................................................................................................... 172
5. Polygon ....................................................................................................... 173
6. Path ............................................................................................................. 173
IV. Kt lun .......................................................................................................... 174
BI 3. Cm ng chm a im trong Windows Phone (Gestures Multi
Touch) ................................................................................................................ 177
I. Khi nim v Gestures .................................................................................... 178
1. Khi nim.................................................................................................... 178
2. Cch ci t Multi Touch Simulator ............................................................ 178
II. K thut Touching .......................................................................................... 185
1. Gii thiu cc s kin Gestures ................................................................... 185
2. Cch s dng Tap (chm), Double Tap v Hold (chm lu) ........................ 186
3. Drag v drop (ko v th) i tng ............................................................ 193
4. Flicking i tng ....................................................................................... 203
5. Zoom i tng bng k thut Pinch v Stretch .......................................... 205
6. Rotate (Xoay i tng) .............................................................................. 210
III. Kt lun .......................................................................................................... 210
BI 4. Bn v nh v (Maps, Location, v Routing) .................................. 218
I. Cch s dng Maps Task Launchers ............................................................... 219
1. MapsTask .................................................................................................... 220
2. MapsDirectionsTask ................................................................................... 221
3. MapDownloaderTask v MapUpdaterTask ................................................. 223
4. Xc nh v tr hin ti trn bn .............................................................. 224
II. Cch s dng Map Control ............................................................................. 227
1. Gii thiu .................................................................................................... 227
2. Cc thuc tnh ............................................................................................. 228

Trung Tm Tin Hc H KHTN-TP.HCM Trang 4


Gio trnh: Lp trnh Windows Phone

3. Cch s dng............................................................................................... 229


III. Cch to Map overlay ..................................................................................... 241
1. Gii thiu .................................................................................................... 241
2. To nhn a im hin ti .......................................................................... 243
3. Thm Overlay ng trn bn .................................................................. 244
IV. M rng cch to ng i v ch dn ............................................................ 247
V. Kt lun .......................................................................................................... 249
BI 5. Lp trnh ng b v bt ng b trong Windows Phone (Synchronous
& Asynchronous Programming) ........................................................................... 250
I. Khi nim ng b v bt ng b ................................................................. 251
II. Async method................................................................................................. 252
1. Cng nng ca Async .................................................................................. 252
2. Cch vit Async .......................................................................................... 253
3. C ch hot ng ca Async ....................................................................... 258
III. Threads........................................................................................................... 265
1. BackgroundWorker ..................................................................................... 265
2. Task ............................................................................................................ 276
IV. Async v Await .............................................................................................. 285
V. Kt lun .......................................................................................................... 288
BI 6. QUN L CC NG DNG CHY NGM (Background Task).... 298
I. Background tasks ........................................................................................... 299
II. Alarms v Reminder ....................................................................................... 299
1. Alarms ........................................................................................................ 300
2. Reminder .................................................................................................... 304
III. Background Transfer Service ......................................................................... 308
IV. Generic Background Agents ........................................................................... 317
V. Background audio........................................................................................... 322
VI. Kt lun .......................................................................................................... 325

Trung Tm Tin Hc H KHTN-TP.HCM Trang 5


Gio trnh: Lp trnh Windows Phone

BI 7. S DNG LIVE TILES TRONG WINDOWS PHONE 8 (Live Tiles)


376
I. Gii thiu Live Tiles....................................................................................... 377
II. Cch to Live Tiles ......................................................................................... 378
1. To Tiles bng XAML ................................................................................ 379
2. To Tiles bng Code ................................................................................... 381
III. Cc loi Live Tiles ......................................................................................... 382
1. Iconic .......................................................................................................... 383
2. Flip ............................................................................................................. 387
3. Cyclic .......................................................................................................... 390
IV. Cch cp nhp Live Tiles ............................................................................... 393
V. Kt lun .......................................................................................................... 398
BI 8. LOCK SCREEN TRONG WINDOWS PHONE 8 (Lock Screen) ...... 398
I. Lock screen background ................................................................................. 400
1. Cu hnh manifest file ................................................................................. 400
2. Lp trnh thay i lock screen background .................................................. 401
3. X l thng s t mn hnh lock screen settings .......................................... 404
4. Truy sut lock screen settings t ng dng .................................................. 405
II. Lock screen notifications ................................................................................ 405
III. Dynamic Lock screen ..................................................................................... 407
1. Dynamic Lock screen vi images trong app folder ...................................... 407
2. Dynamic Lock screen vi images trn Internet ............................................ 412
3. Dynamic Lock screen vi images t RSS .................................................... 414
IV. Kt lun .......................................................................................................... 425
PHN 3. MODULE 4 ........................................................................................426
BI 1. WEB SERVICE ..................................................................................... 426
I. Cc khi nim ................................................................................................. 427
1. SOAP & WSDL .......................................................................................... 427
II. REST.............................................................................................................. 431

Trung Tm Tin Hc H KHTN-TP.HCM Trang 6


Gio trnh: Lp trnh Windows Phone

III. ASP.Net Web Service .................................................................................... 433


1. Cch to .Net Web Service .......................................................................... 434
2. Cch cu hnh IIS ........................................................................................ 446
IV. Tng tc Windows Phone vi .Net Web Service .......................................... 452
V. Tng tc SQL Server v Hosting min ph Somee.com ................................ 463
VI. Kt lun .......................................................................................................... 491
BI 2. WCF V CLOUD (Windows Communication Foundation v Windows
Azure Mobile Service) ............................................................................................ 492
I. WCF - Windows Communication Foundation ................................................ 493
1. Gii thiu WCF ........................................................................................... 493
2. Cch to WCF ............................................................................................. 499
3. Cc thuc tnh trong WCF ........................................................................... 500
4. Tng tc Windows Phone vi WCF .......................................................... 504
II. Windows Azure Mobile Services.................................................................... 524
III. Kt lun .......................................................................................................... 533
BI 3. S DNG PUSH NOTIFICATIONS ................................................... 494
I. Gii thiu ....................................................................................................... 495
II. Kin trc ca Push Notifications .................................................................... 496
III. Cc loi Push Notifications............................................................................. 497
1. Toast Notifications ...................................................................................... 497
2. Tile Notifications ........................................................................................ 498
3. Raw Notifications ....................................................................................... 499
IV. Cch thc hin Push Notification ................................................................... 500
1. Thc hin Toast Notifications ..................................................................... 500
2. Thc hin Tile Notifications ........................................................................ 516
3. Thc hin Raw Notifications ....................................................................... 530
V. Kt lun .......................................................................................................... 542
BI 4. THAO TC VI MEDIALIBRARY API ............................................ 543
I. Gii thiu lp MediaLibrary ........................................................................... 544

Trung Tm Tin Hc H KHTN-TP.HCM Trang 7


Gio trnh: Lp trnh Windows Phone

II. Constructors ................................................................................................... 544


III. Properties ....................................................................................................... 545
1. Albums ....................................................................................................... 546
2. Artists ......................................................................................................... 546
3. Genres ......................................................................................................... 547
4. IsDisposed................................................................................................... 547
5. MediaSource ............................................................................................... 548
6. Pictures ....................................................................................................... 548
7. Playlists ....................................................................................................... 549
8. RootPictureAlbum ...................................................................................... 549
9. SavedPictures .............................................................................................. 550
10. Songs .......................................................................................................... 550
IV. Methods ......................................................................................................... 553
1. GetPictureFromToken ................................................................................. 553
2. SavePicture ................................................................................................. 553
3. SavePictureToCameraRoll .......................................................................... 554
V. Kt lun .......................................................................................................... 555
BI 5. LP TRNH VI THIT B CM NG (SENSORS) ....................... 558
I. Cc khi nim Sensor ..................................................................................... 559
1. Cm bin in dung .................................................................................... 559
2. Cm bin tim cn ....................................................................................... 560
3. Cm bin nh sng ...................................................................................... 561
4. Cm bin nh .............................................................................................. 562
5. Gia tc k .................................................................................................... 562
6. Con quay hi chuyn ................................................................................... 563
7. La bn s ..................................................................................................... 564
8. Cm bin vn tay......................................................................................... 565
II. Lp trnh Sensors ph bin trong Windows Phone .......................................... 567
1. Orientation Cm bin xoay mn hnh ....................................................... 567

Trung Tm Tin Hc H KHTN-TP.HCM Trang 8


Gio trnh: Lp trnh Windows Phone

2. Accelerometer Cm bin gia tc k .......................................................... 572


3. Compass Cm bin la bn s .................................................................... 578
4. Gyroscope Cm bin con quay hi chuyn ............................................... 580
III. Kt lun .......................................................................................................... 582
BI 6. S DNG CLIPBOARD V CONTACTS - CALENDAR RESOURCE
584
I. Clipboard API ................................................................................................ 585
II. Contacts ......................................................................................................... 586
1. Khi nim People Hub ................................................................................ 586
2. Truy vn Contact ......................................................................................... 587
3. Thm mi Contact ....................................................................................... 593
III. Xa Contact.................................................................................................... 594
IV. Calendar ......................................................................................................... 595
1. Truy vn Calendar ....................................................................................... 595
2. To mi cuc hn ........................................................................................ 598
V. Kt lun .......................................................................................................... 598
BI 7. PUBLISH APP TO WINDOWS STORE ............................................. 601

Trung Tm Tin Hc H KHTN-TP.HCM Trang 9


Gio trnh: Lp trnh Windows Phone

PHN 1. MODULE 1
BI 1. GII THIU H IU HNH WINDOWS PHONE

I. Lch s pht trin Windows Phone


Windows Phone c Microsoft pht trin thay th cho h iu hnh di ng
Windows Mobile trc y. Windows Phone bt u t phin bn th 7 (khi ra mt,
Microsoft gi n l Windows Phone 7, cn hin gi n ln n 7.5). c bit, do pht
trin trong thi gian ngn nn Windows Phone rt hn ch trong vic tng thch ngc
vi cc nn tng Windows Mobile trc . Mt l do na Microsoft khng quan tm
nhiu n nn tng c l v mn hnh cm ng bng ngn tay ngy cng ph bin hn
trn in thoi v Windows Mobile vn thit k cho bt stylus tr nn rt li thi.
Windows bt u c ra mt chnh thc vo thng 2/2010 trin lm Mobile
World Congress din ra Barcelona, Ty Ban Nha. n thng 10 cng nm, CEO Steve
Ballmer ca Microsoft ra mt 10 thit b Windows Phone u tin n t HTC, Dell,
Samsung, LG. Vi tun sau, my bt u c bn ra M v Chu u. Thng 5 cng
nm, Microsoft tuyn b hp tc vi mt s nh sn xut khc l Acer, Fujitsu v ZTE.
Mt ct mc quan trng ca Windows Phone l s hp tc gia Microsoft vi
Nokia sau khi hng in thoi Phn Lan ny quyt nh khng cn tp trung vo in thoi
Symbian na. Kt qu ca s hp tc ny l dng Nokia Lumia ra i s kin Nokia
World 2011. n CES 2012, Nokia tip tc ra mt hai my Lumia mi na (mnh s
cp phn sau). Vic tch hp cc dch v ca Microsoft (Bing, Bing Maps, Windows
Phone Marketplace,) ln thit b Nokia c cho l s to nn li th cnh tranh cho
WIndows Phone vi hai i th ln hin thi l iOS v Android.
Lch s cc phin bn pht trin ca Windows Phone:
7.0.7004: phin bn u tin ca Windows Phone 7
7.0.7008: nng cp v ci thin mt vi im
7.0.7390: bn cp nht vi tn m NoDo, h tr mng CDMA, copy v paste,
tc chy ng dng nhanh hn, tch hp Facebook su hn
7.0.7392: sa cc li lin quan n chng nhn bo mt
7.0.7403: bn tin nng cp chun b bc sang mt t nng cp ln
7.10.7720: y l Windows Phone 7.5 vi tn m Mango, c gii thiu
2/2011. Cc tnh nng mi c thm vo nh Internet Explorer 9 h tr ha

Trung Tm Tin Hc H KHTN-TP.HCM Trang 10


Gio trnh: Lp trnh Windows Phone

v chun web tt hn, Twitter tch hp vo People Hub, chy a nhim cho cc
ng dng bn th ba bng cch tm ngng chng
7.10.7740: sa li Microsoft Exchange Server 2003 v cnh bo hp th thoi
7.10.8107: h tr kt ni LTE, sa li bn phm b bin mt v nhiu vn
khc
7.10.8112: bn cho Lumia 900 v HTC Titan II ca nh mng AT&T
7.10.8773: cn gi l Windows Phone 7.5 Refresh vi tn m Tango. Nhiu tnh
nng mi xat hin nh MMS tt hn, biu tng cho vic d v tr, xut v
qun l danh b v SIM, h tr in thoi gi r vi 256MB RAM v xung nhp
CPU chm
7.10.8779: sa li, ci thin v nng cp
Nu bn do quanh mt vi ni c Windows Phone, chc hn bn s c nghe
n cm t "Windows Phone Gen 1" (WP th h th nht) v "Windows Phone Gen 2"
(WP th h th hai). Vy chng l g? l mt cch phn bit hai th h Windows Phone
c v mi m ngi ta thng gi cho tin, thay v phi k chi tit v phn cng.
Cc smartphone Gen 1 l cc my ra mt thi im nm 2010. Cc SoC (system-
on-chip, c th tm hiu l vi x l CPU v b x l ha GPU tch hp chung trong mt
con chip) trm nhng thit b ny thng l Snapdragon QSD8250 do Qualcomm sn xut
vi xung nhp 1GHz. Mt s Windows Phone Gen 1 l HTC HD7, Trophy, Surround,
Mozart, Samsung Omnia 7, Focus, LG Optimus 7 E900.

Vi cc my Gen 2 l cc my mi ra sau ny, tc t nm 2011. Cc my Windows


Phone Gen 2 s dng cc SoC a dng hn rt nhiu so vi Gen 1. Mt s my Gen 2 bn

Trung Tm Tin Hc H KHTN-TP.HCM Trang 11


Gio trnh: Lp trnh Windows Phone

c th tm gp trn th trng l HTC Titan, Titan II, cc dng Nokia Lumia 900, Lumia
800, Lumia 710, Lumia 610, Samsung Focus S, Omnia M, Omnia W, Acer Allegro,
Fujitsu-Toshiba IS12T. C th trong thi gian ti chng ta s thy thm cc mu my Gen
2 xut hin.
Tt nhin, cc my Gen 2 mnh hn Gen 1 kh nhiu, ngoi tr cc dng my gi
r chy phin bn Tango. Mc d c cng xung nhp CPU nh th nhng cu trc khc,
GPU cng khc khin hiu sut ca cc thit b Gen 2 tt hn Gen 1. Tuy nhin, cc my
Windows Phone, d cho cu hnh mnh hay yu th u chy kh mt m, khng vn
g v tc thc thi nh mt s h iu hnh i th. Khc bit gia Gen 1 v Gen 2 cc
tc v thng thng l khng ng k.

II. Cc tnh nng mi trong Windows Phone 8


H iu hnh dnh cho thit b di ng mi nht ca Microsoft c nh gi l
c nhng ci tin vt bc so vi Windows Phone 7 nh h tr
chip ln n 64 nhn, m rng dung lng qua th nh ngoi hay
mn hnh HD.
Nn tng ny c ra mt ti hi ngh Windows Phone
Summit va din ra vo ngy 20/6 M.
Mt trong nhng thay i ln trn Windows Phone 8 l
mn hnh khi ng c nhiu Live Tile hn v cho php ngi
dng iu chnh kch c ty theo mc quan trng ca ng
dng. Nhng in thoi hin chy Windows Phone 7 (Nokia
Lumia 800, HTC Titan II...) s khng th nng cp ln bn 8
nhng s c ci bn 7.8 c mn hnh khi ng mi.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 12


Gio trnh: Lp trnh Windows Phone

Windows Phone 8 s h tr nhiu phn gii mn hnh t 800 x 480 pixel cho
ti 1280 x 720 pixel (720p) v kh nng m rng dung lng qua th nh.

Ging Windows 8, Windows Phone 8 tch hp sn trnh duyt Internet Explorer


10 ha hn mang n hiu nng tt v ti u ha cho JavaScript v HTML5. Khng nhng
th, IE 10 cn c trang b cng c Phishing Protection gip cnh bo, ngn chn nhng
website khng an ton cha nhiu m c.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 13


Gio trnh: Lp trnh Windows Phone

Windows Phone 8 l h iu hnh sn sng cho doanh nghip vi lot cng c cho
admin d dng qun l thit b ca nhn vin. Ngoi ra, n cn tng cng bo mt gip
trnh r r d liu.

Windows Phone 8 b sung nhiu tnh nng cho camera nh Smart Group Shot bt
nhiu tm cng lc chn bc hnh p nht hay chp ngh thut panorama, t gi

Trung Tm Tin Hc H KHTN-TP.HCM Trang 14


Gio trnh: Lp trnh Windows Phone

Vic h tr cng ngh NFC s cho php ngi dng chuyn d liu ln (phim,
nh, nhc) gia cc thit b chy Windows Phone 8 hay vi laptop mt cch d dng.

Microsoft loi b Bing Maps v thay th bng cng c bn ca Nokia trn


Windows Phone 8 cho php ch ng chi tit (turn-by-turn) v chy c ch offline
gip nh v khng cn c mng Internet.

Vi vic tch hp cng ngh Direct X trn Windows Phone 8, Microsoft ha hn


s em n cho smartphone nhng tr chi 3D vi ha tt hn.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 15


Gio trnh: Lp trnh Windows Phone

Mobile Wallet Hub c tnh nng kh ging Passbook trn iOS 6, s dng giao tip
NFC thc hin cc giao dch bng th tn dng ca ngi dng cng nh lu tr thng
tin th tn dng, phiu gim gi, th thnh vin...

Microsoft cho bit, h iu hnh mi c th chy c tt c ng dng Windows


Phone 7. Ngoi ra, do c pht trin t cng mt li vi h iu hnh Windows 8 nn khi
ng dng c to ra, nh pht trin c th chuyn i n hot ng trn c 2 h iu
hnh.

III. Gii thiu Windows Phone 8 SDK

Trung Tm Tin Hc H KHTN-TP.HCM Trang 16


Gio trnh: Lp trnh Windows Phone

Yu cu h thng
H iu hnh h tr: Windows 8, Windows 8 Pro
Windows 8 64-bit (x64) client versions
Microsoft Visual Stuido 2012

Hardware:
4 GB of free hard disk space
4 GB RAM
64-bit (x64) CPU
Windows Phone 8 Emulator:
Windows 8 Pro hoc cc phin bn cao hn.
B x l c h tr Second Level Address Translation (SLAT)
C th ci c trn my khng h tr Hyper-V v SLAT nhng bn khng
th chy my o c(Phone Emulator)
Bt u ci t download 2 ci phn mm sau v:
Link: WP8 SDK http://developer.windowsphone.com/en-us/downloadsdk
Link Visual studio 2012
Sau khi ti v ta c 2 file iso

To a o ci t file iso
Sau click vo a chn file vs_professional.exe ci t.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 17


Gio trnh: Lp trnh Windows Phone

Cc bn tch vo I agree ri next.

Thch ci ci no th tch vo, m c tch ht cho n chc, sau install.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 18


Gio trnh: Lp trnh Windows Phone

Ri tip theo ci SDK WP 8. Lm tng t nh trn t bc Mount file iso


n o.

Cc bn Install i khong tm 7-8 pht l xong.


IV. Bt u vi lp trnh Windows Phone 8
1. To project Windows Phone 8

M Visual Studio 2012, chn menu


File -> New Project to project mi

Chn kiu project Windows Phone -> Windows Phone App

Trung Tm Tin Hc H KHTN-TP.HCM Trang 19


Gio trnh: Lp trnh Windows Phone

Chn kiu loi ng dng Windows Phone 8.0

Cc ca s lm vic

1: Toolbox
2: Solution Explorer

Trung Tm Tin Hc H KHTN-TP.HCM Trang 20


Gio trnh: Lp trnh Windows Phone

3: Emulator Designer
4: XAML Designer
5: Properties
Cu trc th mc ca project

AppManifest.xml: danh sch cc resource c thm vo khi ci


t ng dng
WMAppManifest.xml: m t chi tit ng dng bao gm tn ng
dng, trang khi to, biu tng, cc tng thch phn cng.

o The Assets folder: cha


hnh nh ca biu tng ng
dng, cc tile, cc hnh khi
ng ng dng.
o The Resources folder: cho
php ng dng a ngn ng.
o The App class : Cha cc x
l chung ca ng dng.
o The LocalizedStrings class:
lp truy cp n th mc
Resources.

Khi chy ng dng

Trung Tm Tin Hc H KHTN-TP.HCM Trang 21


Gio trnh: Lp trnh Windows Phone

Mc nh, ng dng s chy trn emulator.


Bn c th chy ng dng trn thit b tht thng qua kt ni cng
USB
S dng emulator
Emulator Windows Phone 8 h tr 3 phn gii:
WVGA- 800 480pixels. C thm ty chn RAM 512MB.
WXGA- 1280 768pixels.
720p- 1280 720pixels.

Cc cng c khc
Accelerometer tab

Trung Tm Tin Hc H KHTN-TP.HCM Trang 22


Gio trnh: Lp trnh Windows Phone

Location tab

Screenshot tab

Trung Tm Tin Hc H KHTN-TP.HCM Trang 23


Gio trnh: Lp trnh Windows Phone

Network tab

ng k thit b tht kim th ng dng


Thc hin theo cc bc sau:
ng k 1 ti khon lp trnh vin ti website
http://dev.windowsphone.com
Kt ni in thoi vi Wifi hoc 3G
M in thoi v m kha mn hnh.
Kim tra ngy gi trn in thoi.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 24


Gio trnh: Lp trnh Windows Phone

Kt ni in thoi vi my tnh thng qua USB.


Trn my tnh,, tm kim Windows Phone Developer Registration
v chy ng dng tm c

Click the Register button

ng nhp vo ti khon Windows Live ID


Kim tra li trng thi chc chn in thoi ng k thnh cng

V. Vng i ng dng Windows Phone (application life cycle)


1. Cc thut ng

Trung Tm Tin Hc H KHTN-TP.HCM Trang 25


Gio trnh: Lp trnh Windows Phone

Nhng hnh nh sau y minh ha vng i ca mt ng dng Windows Phone.

M ng dng (Application launching)


S kin c gi khi mt ng dng c gi bi ngi s dng t danh sch
cc ng dng c ci t hoc t mt Tile vo Start menu hoc c th m t mt
ng dng khc
ng dng ang chy
Sau khi m ng dng, ng dng s chy cho n khi ngi dng iu hng
qua mt ng dng khc. Bn khng nn cung cp bt k chc nng no ngi
dng c th thot ng dng. ng dng cng s thot khi trng thi ang chy khi
mn hnh lockscreen xut hin, tr khi bn v hiu ha ch lockscreen trong ng
dng.
S kin Deactivated
S kin c gi khi ngi dng iu hng ra khi ng dng (nhn phm
Start hoc m mt ng dng khc). S kin cng c gi khi lockscreen xut hin.
Dormant

Trung Tm Tin Hc H KHTN-TP.HCM Trang 26


Gio trnh: Lp trnh Windows Phone

Sau khi s kin Deactivated c gi, ng dng s i vo trng thi dormant.


Trong qu trnh ny, tt c cc tin trnh u dng li, nhng ng dng vn c lu
trong b nh my. Nu ng dng c gi tr li t trng thi ny, d liu v trng
thi ng dng c lu trc s c restore li cho ngi dng.
Tombstoned
Khi c nhiu ng dng trong trng thi dormant, chim qu nhiu b nh
my, lm cho my tr nn chm, khi , h iu hnh s t ly li b nh ca nhng
ng dng nm trng thi dormant lu nht. Khi , ng dng s chuyn sang
trng thi tombstoned.
Mt ng dng trng thi tombstoned ngha l n b chm dt, tuy nhin,
nhng thng tin v trng thi chuyn trang v cc trng thi khc c lu trong qu
trnh deactived vn c lu tr. Thit b c th lu d liu ti a 5 ng dng trng
thi tombstoned.
S kin Activated
S kin ny c gi khi ngi dng m li ng dng t trng thi dormant
hay tombstoned. Lc ny, ta phi kim tra xem ng dng c m li t trng thi
no. Nu trng thi dormant, trng thi ca ng dng c v s t ng load
li cho ngi dng. Ngc li, nu ng dng trng thi tombstoned, ta phi dng
cc state dictionary load li trng thi ng dng.
S kin Closing
S kin ny c gi khi ngi dng nhn phm Back cho n khi thot khi
ng dng. Lc ny, ng dng s tt hon ton v khng c trng thi no c lu.
Lc ny, ta cn x l lu cc d liu sau cng ca ngi dng trnh tnh trng
mt d liu.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 27


Gio trnh: Lp trnh Windows Phone

BI 2. TM HIU NGN NG XAML V CC CONTROL C BN

I. Tm hiu ngn ng XAML


1. XAML l g?

XAML l mt ngn ng nh du khai bo nh XML , n c s dng trong cc


mu lp trnh ca .NET n gin ha vic to ra giao din ngi dng.
Bn c th to cc yu t giao din ngi dng cho ng dung , sau tch ring
phn logic runtime trong code behind ca file .cs, tham gia vo cc khai bo
XAML thng qua partial class.XAML i din cho tp hp cc i tng c
nh ngha c bit t assembly.
T XAML tch bit c 2 phn thit k giao din v lp trnh logic thng
qua tool h tr nh du m t ngn ng nh du no lm c.
Khi c hin th nh dng text , file XAML l cc file XML c ui m rng
l .xaml , cc tp tin xaml ny c th c m ha ging xml v d nh m ha
UTF-8 l in hnh.
V d sau y cho bn thy c cch to 1 nt nh 1 phn ca giao din ngi
dng nhng n ko phi y gi l giao din

<Button Content="XAML" Height="23" HorizontalAlign="Left"


Margin="6" Name="btnNew" VerticalAlign="Top"
Width="75" Height="38" Click="btnNew_Click" />

2. Tm tt c php XAML

Object Element & Property Syntax

Mt Object Element thng khai bo l phin bn (instantce) ca 1 kiu (1 class).


Kiu ny c nh ngha trong assembly cung cp 1 kiu (1 class) tng ng vi
cc Object Element trong XAML.
<[Tn Object Element] [Tn Thuc tnh = "Gi tr"] />

Vd:
<Stackpanel Orientation="Horizontal"

<Button Content="XAML" Height="23" HorizontalAlign="Left"


Margin="6" Name="btnNew" VerticalAlign="Top"
Width="75" Height="38" Click="btnNew_Click" />
</Stackpanel>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 28


Gio trnh: Lp trnh Windows Phone

trn ch r 2 Object Element <Button/> nm trong parent l <StackPanel/>.


mi element s nh x n class tng ng c nh ngha trong
Assemply.Lc bn chn "<" bn ang ch nh XAML to 1 phin bn ca
class.Mi phin bn ca element class c to s gi n contructor mc nh
nm trong class trong qu trnh phn tch v ti XAML.
Property Element Syntax
- i vi vi thuc tnh ca Object Element , khai bo c php Property Syntax
l khng th bi v gi tr ca thuc tnh khng nm trong phm vi "chui gi
tr" thay vo ta phi khai bo Property Element Syntax
Vd:

<Label Content="Title" Margin="6">


<Label.Backgound>
<SolidColorBrush Color="Olive" />
</Label.Background>
</Label>

Collection Syntax

XAML l ngn ng ti u ha kh nng nh du cc nh pht trin d c


hn.Mt trong cc im ti u ha l nu 1 thuc tnh c bit c kiu l Collection.Trong
cc Item ca Collection bn c th nh du nh child element vo trong gi tr ca
thuc tnh c bit v tr thnh 1 phn ca collection.
- Trong trng ny 1 tp cc child object element nh l 1 gi tr ca c gn
cho thuc tnh kiu collection.
Vd:

<Label Content="Title" Margin="6">


<Label.Backgound>
<LinearGradientBrush>
<LinearGradientBrush.GradientStop>
<GradientStop Offset="0.1" Color="Blue" />
<GradientStop Offset="1.1" Color="Red"/>
</LinearGradientBrush.GradientStop>
</LinearGradientBrush>
</Label.Background>
</Label>
Attached Property Syntax( thuc tnh nh km):
Mt s thuc tnh element cha c nh km vo element con
Vd:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 29


Gio trnh: Lp trnh Windows Phone

<Grid>
<Button Grid.Row="1"/>
</Grid>

II. Cc control c bn trong Windows Phone


1. Layout controls

Layout controls l nhng controls k tha t Panel, dng cha v sp xp cc


i tng con nm trong n. C 3 loi Layout controls chnh
Grid
Grid s nh ra cc dng v cc ct, t v tr ca cc control bn trong grid
s c xc nh nm no (dng my, ct my). s dng Grid, ta phi
Khai bo cc dng ca Grid

<Grid x:Name="LayoutRoot" >


<Grid.RowDefinitions>
<RowDefinition Height="150"/>
<RowDefinition Height="100"/>
<RowDefinition Height="200"/>
</Grid.RowDefinitions>
</Grid>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 30


Gio trnh: Lp trnh Windows Phone

Khai bo cc ct ca Grid
<Grid x:Name="LayoutRoot" >
<Grid.RowDefinitions>
<RowDefinition Height="150"/>
<RowDefinition Height="100"/>
<RowDefinition Height="200"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="170"/>
<ColumnDefinition Width="160"/>
</Grid.ColumnDefinitions>
</Grid>

t cc controls vo cc theo mun


<Grid x:Name="LayoutRoot" >
<Grid.RowDefinitions>
<RowDefinition Height="150"/>
<RowDefinition Height="100"/>
<RowDefinition Height="200"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="170"/>
<ColumnDefinition Width="160"/>
</Grid.ColumnDefinitions>
<Button Width="130" Height="100" Content="Button1"/>
<Button Grid.Column="1" Grid.Row="1" Width="130"
Height="100" Content="Button2"/>
<Button Grid.Column="2" Grid.Row="2" Width="130"
Height="100" Content="Button3"/>
</Grid>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 31


Gio trnh: Lp trnh Windows Phone

Stack Panel
StackPanel n gin l mt panel m cc control con nm trong n s c
sp xp trn mt hng dc hoc mt hng ngang. Bn c th dng thuc
tnh Orientation xc nh chiu sp xp ca cc control. Gi tr mc nh
ca thuc tnh Orientation l Vertical (chiu dc).
V d sau s nh ngha mt StackPanel v sp xp cc control ca n theo
chiu dc.
<StackPanel Margin="20">
<Rectangle Fill="Red" Width="50" Height="50" Margin="5" />
<Rectangle Fill="Blue" Width="50" Height="50" Margin="5" />
<Rectangle Fill="Green" Width="50" Height="50" Margin="5" />
<Rectangle Fill="Purple" Width="50" Height="50" Margin="5" />
</StackPanel>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 32


Gio trnh: Lp trnh Windows Phone

Canvas
Canvas s xc nh mt khu vc m cc control con nm trong n s c
xc nh v tr bng cch xc nh khong cch ca control n l tri v l
trn ca canvas. Canvas c s dng khi bn cn to nhng control m
khng mun thay i v tr ca n.
V d ta mun to mt hnh ch nht c khong cch n l tri l 30px, l
trn l 200px.
<Canvas Background="Transparent">
<Rectangle Canvas.Left="30" Canvas.Top="200"
Fill="red" Width="200" Height="200" />
</Canvas>

Border

Trung Tm Tin Hc H KHTN-TP.HCM Trang 33


Gio trnh: Lp trnh Windows Phone

Border khng phi l mt layout control tht s. Border thng c dng


to khung cho Grid hoc StackPanel
<Border BorderThickness="8,4,2,1" Width="300" Height="300">
<Border.BorderBrush>
<LinearGradientBrush EndPoint="0.5,1"
StartPoint="0.5,0">
<GradientStop Color="Red" Offset="0"/>
<GradientStop Color="Blue" Offset="1"/>
</LinearGradientBrush>
</Border.BorderBrush>
<Grid x:Name="ContentPanel" >
</Grid>
</Border>

Scrollviewer
Khi bn cn hin th mt ni dung di, bn c th dng scrollviewer cha
ni dung . ScrollViewer cung cp kh nng cun vn bn khi n vt qu
kch thc quy nh.
s dng scrollviewer, bn khai bo nh sau
<ScrollViewer Height="350">
<TextBlock TextWrapping="Wrap">
[ni dung di]
</TextBlock>
</ScrollViewer>

2. Text controls

TextBlock
Ging nh Label control trong Windows Form, TextBlock dng hin th
chui c tc dng ch c.
s dng textblock, bn khai bo theo c php sau

Trung Tm Tin Hc H KHTN-TP.HCM Trang 34


Gio trnh: Lp trnh Windows Phone

<TextBlock Text="TextBlock"/>

Dng thnh phn <Run/> th hin nhiu chui vi nh dng khc nhau

<TextBlock FontFamily="Arial">
<Run FontFamily="Courier New">
Courier New
</Run>
<LineBreak/>
<Run FontFamily ="Time New Roman">
Time New Roman
</Run>
<LineBreak/>
<Run FontFamily="Verdana">
Verdana
</Run>
</TextBlock>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 35


Gio trnh: Lp trnh Windows Phone

TextBox
Dng hin th v nhn d liu input t ngi dng.
s dng textbox, bn khai bo vi c php sau

<TextBox Height="72" Text="TextBox"/>

Thuc tnh InputScope dng h tr ngi dng nhp liu

InputScope = Url

InputScope = Number

Trung Tm Tin Hc H KHTN-TP.HCM Trang 36


Gio trnh: Lp trnh Windows Phone

InputScope = Text

PasswordBox
Tng t nh TextBox, nhng PasswordBox n cc k t do ngi dng
nhp
Dng thuc tnh Password get hoc set k t cho passwordbox

<PasswordBox Height="72" Password="abc" Width="310"/>

3. Selection controls

CheckBox
Dng th hin cho nhng la chn mang hai gi tr ng sai

<CheckBox Height="72" IsChecked="true"


Content="Bn c thch Windows Phone"/>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 37


Gio trnh: Lp trnh Windows Phone

RadioButton
Dng chn 1 hay nhiu la chn thuc cng nhm vi nhau

<RadioButton Name="radioButton1" Content="Nam" GroupName="GioiTinh"/>

<RadioButton Name="radioButton2" Content="N" GroupName="GioiTinh"/>

Slider
Dng thay i gi tr cn bin thin

<Slider Name="slider1" VerticalAlignment="Top" Width="450"/>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 38


Gio trnh: Lp trnh Windows Phone

4. Button control

L control thng dng nht dng tng tc vi ngi dng

<Button Content="Button" Height="72" HorizontalAlignment="Left"


Name="button1" VerticalAlignment="Top" Width="160" />

5. Image control

Dng th hin hnh nh trong ng dng

<Image Source="logoWindowsPhone.jpg" Width="200"


Stretch="Fill" Height="200" />

BI 3. CC CONTROL NNG CAO TRONG WINDOWS PHONE

I. List controls
1. ListBox control

Khi nim
Dng hin th d liu c dng danh sch.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 39


Gio trnh: Lp trnh Windows Phone

Cch khai bo S dng


Ta khai bo ListBox vi c php sau:

<ListBox>
<ListBoxItem>
</ListBoxItem>
<ListBoxItem>
</ListBoxItem>
</ListBox>

khai bo cc ListBoxItem, ta c th khai bo trc tip trn XAML

VD: Khai bo cc Item t ngay trn XAML


<ListBox>
<ListBoxItem>
<TextBlock Text="Nguyn Hu Ti"/>
</ListBoxItem>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 40


Gio trnh: Lp trnh Windows Phone

<ListBoxItem>
<TextBlock Text=" Th Thy Nhung"/>
</ListBoxItem>
<ListBoxItem>
<TextBlock Text="Dng Thy Trang"/>
</ListBoxItem>
</ListBox>

- Hoc ta c th load cc Item t mt ngun d liu thng qua data


binding

//Code XAML

<ListBox Name="MyListBox">

<ListBox.ItemTemplate>

<DataTemplate>

<TextBlock Text="{Binding}"/>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

//Code behind
public List<string> Items =
new List<string>
{
"Nguyn Hu Ti",
" Th Thy Nhung",
"Dng Thy Trang",

Trung Tm Tin Hc H KHTN-TP.HCM Trang 41


Gio trnh: Lp trnh Windows Phone

};
public MainPage()
{
InitializeComponent();
MyListBox.ItemsSource = Items;
}

- Cc Item trong ListBox c th c kt hp t nhiu thnh phn.

<ListBox Height="523">
<ListBoxItem>
<StackPanel Orientation="Horizontal">
<Image Source="/Assets/4.png"/>
<StackPanel Width="370">
<TextBlock Text="H tn: Nguyn Hu Ti"/>
<TextBlock Text="Tui: 30"
<TextBlock Text="Cng ty: FPT"
</StackPanel>
</StackPanel>
</ListBoxItem>
</ListBox>

2. LongListSelector control

Khi nim
Ging ListBox, LongListSelector cng dng th hin cc d liu dng danh
sch. Ngoi ra, LongListSelector cn cung cp mt s tnh nng cao cp nh:
H tr load d liu theo nh cu, ta c th load nhng d liu cn thit cho
ngi dng, trnh trng hp phi load qu nhiu d liu, lm chm ng dng.
H tr GroupList (nhm danh sch), d liu s c hin th theo dng
nhm, h tr chuyn t nhm ny sang nhm khc mt cch d dng.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 42


Gio trnh: Lp trnh Windows Phone

Cch khai bo S dng


binding cc item trong LongListSelector ta khai bo code nh sau

<phone:LongListSelector x:Name="longlistselector1">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Data}"/>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</ phone:LongListSelector>
phn code behind s khai bo nhu Commented [cc1]: Trang 35

II. Menu controls


1. ApplicationBar

Khi nim
ApplicationBar l control t cui mn hnh truy cp nhanh n mt s
chc nng lin quan n trang hin ti.
Bn c th thm 2 loi thnh phn cho ApplicationBar:
Icons: s lun phi c v lun hin th (tr khi ApplicationBar trng thi
thu nh), v ti a ch c 4 icon c khai bo trn cng 1 ApplicationBar.
Menu: l nhng text n gin, c hin th khi ApplicationBar hin th, s
lng menu s khng b gii hn nh icon.
ApplicationBar khng ging nh cc control khc. n khng phi l mt thnh
phn ca trang. Trn thc t, khi bn khai bo, n s nm bn ngoi Grid chnh. Mt iu
quan trng l, n s khng c h tr binding, bn phi s dng th vin ca hng th
3.
Cch khai bo S dng
khai bo mt ApplicationBar, bn khai bo code XAML nh sau

<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/Assets/AppBar/ad
d.png"
Text="add" />
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text="settings"/>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 43


Gio trnh: Lp trnh Windows Phone

</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

III. Media controls


1. Image control

Khi nim
Image control dng th hin hnh nh trong ng dng. Khi s dng image
control, ta cn khai bo kch thc ca image v s dng thuc tnh Stretch nh kiu
hin th ca image trong trng hp kch thc nh dng ln hn hay nh hn kch thc
ca image. Cc gi tr ca thuc tnh Stretch nh:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 44


Gio trnh: Lp trnh Windows Phone

Fill : hnh s c co gin p ng kch thc inh, khng quan tm


n t l.
None : gi nguyn kch thc cng nh t l ca hnh
The Uniform : co gin hnh ti a theo kch thc nh nhng vn m
bo c t l v vn nm lt trong khung hnh
The UniformToFill : co gin hnh ti a theo kch thc nh, vn m
bo c t l nhng khng m bo vic hnh c b mt khng.

Cch khai bo S dng


khai bo mt Image control, ta khai bo vi c php sau

<Image Source= "/Assets/4.png"


Height="200" Width="250" />

2. MediaElement control

Khi ng dng cn chi cc loi file media nh video hay music, ta c th


dng MediaElenment control.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 45


Gio trnh: Lp trnh Windows Phone

khai bo mt MediaEleement, ta khai bo nh sau

<MediaElement Name="MediaWindow
Source="Assets/hm_helix_twist_320x240.wmv"/>

Tuy nhin, control khng h tr cc button iu khin khi chi media.


V d ta xy dng Play, Pause v Forward khi chi media

<StackPanel Orientation="Horizontal" HorizontalAlignment="Center"


>

<Button Name="btnPlay" Click="btnPlay_Click" Content="Play"/


>

<Button Name="btnPause" Click="btnPause_Click" Content="Paus


e"/> <Button Name="btnForward" Click="btnForward_Click" C
ontent="Forward"/> </StackPanel>
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
MediaWindow.Play();
}
private void btnPause_Click(object sender, RoutedEventArgs e)
{
MediaWindow.Pause();
}
private void btnForward_Click(object sender, RoutedEventArgs e)
{
TimeSpan current = MediaWindow.Position;
MediaWindow.Position = current.Add(new TimeSpan(0, 0, 1)
); }
Lu : ta phi i i thuc tnh Build Action ca file video thnh
Resource

IV. MessageBox, Popups


1. MessageBox

MessageBox cho php ng dng a ra nhng thng bo cho ngi dng


di dng panel nm ln mn hnh hin ti.
Vi MessageBox, ta ch c th tng tc vi ngi dng bng nhng cu
thng bo v cc nt nhn n gin nh Yes, No, Cancel
MessageBox c gi t code behind vi cu lnh nh sau

Trung Tm Tin Hc H KHTN-TP.HCM Trang 46


Gio trnh: Lp trnh Windows Phone

MessageBox.Show("Xin cho ngi dng!");

Nu MessageBox c 2 nt nhn OK Cancel, ta dng bin kiu


MessageBoxResult nhn kt qu

MessageBoxResult result =

MessageBox.Show("Bn c lu d liu khng!", "Cu hi"


, MessageBoxButton.OKCancel);

if (result == MessageBoxResult.OK)

{}

2. Popups

Tng t MessageBox, nhng popup cho php ta thay i giao din v nhn
d liu nhp t ngi dng.
Ta c th nh dng cc popup trn code XAML v gi popup t code behind

<Popup x:Name="MyPopup" VerticalOffset="150


HorizontalOffset="120">
<Popup.Child>
<Border BorderBrush="Red" BorderThickness="3">
<TextBlock Margin="5" Text="Text for my popup
Foreground="White"/>
</Border>
</Popup.Child>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 47


Gio trnh: Lp trnh Windows Phone

</Popup>

n hay hin popup, ta dng thuc tnh IsOpen


IsOpen="True : hin popup
IsOpen="False: n popup

Trung Tm Tin Hc H KHTN-TP.HCM Trang 48


Gio trnh: Lp trnh Windows Phone

BI 4. CC LOI NG DNG V CHUYN TRANG TRONG


WINDOWS PHONE

I. Cc loi ng dng
1. Single page

y l loi ng dng c bn nht ca Windows Phone. ng dng bao gm


nhng trang ring l vi nhau. Ta c th di chuyn gia cc trang thng qua lp
NavigationService.

to ng dng dng single page, ta chn template mc nh khi tao mi project


Windows Phone

Trung Tm Tin Hc H KHTN-TP.HCM Trang 49


Gio trnh: Lp trnh Windows Phone

II. Pivot
Mt trong nhng loi ng dng ph bin nht trong Windows Phone l ng
dng dng Pivot. Bn cht ca ng dng kiu pivot l s dng control gi l pivot. Pivot
control to ra ng dng kiu tab
Pivot control l mt container cha mt hay nhiu PivotItem control.
Ta c th di chuyn gia cc trang trong pivot bng cc cch nh
Panning
Flick
Tap on header

Trung Tm Tin Hc H KHTN-TP.HCM Trang 50


Gio trnh: Lp trnh Windows Phone

Ta c th s dng pivot control lc cc b d liu ln hoc hin th nhiu


b d liu khc nhau.
to mt ng dng dng pivot, ta c th dng mt trong cc cch sau
Chn template Windows Phone Pivot App khi to mi ng dng Windows
Phone

Trung Tm Tin Hc H KHTN-TP.HCM Trang 51


Gio trnh: Lp trnh Windows Phone

Chn template mc nh ri ko pivot control t toolbox vo

Thm mt trang dng pivot vo ng dng c ang c

Cu trc mt pivot control

Trung Tm Tin Hc H KHTN-TP.HCM Trang 52


Gio trnh: Lp trnh Windows Phone

Cch khai bo 1 pivot control

<phone:Pivot Title="MY APPLICATION">


<!--Pivot item one-->
<phone:PivotItem Header="first">
</phone:PivotItem>
<!--Pivot item two-->
<phone:PivotItem Header="second">
</phone:PivotItem>
</phone:Pivot>
Cc lu khi thit k trang Pivot
Rt ngn s trang pivot (ti a 4 trang)
Cc trang pivot nn hin th cng loi d liu
Rt ngn tiu t 1 n 2 t
Khng th thay i chiu cao ca header
Khng nn dng cc control nh slider, Toogle Button, hay map trong
trang pivot

Trung Tm Tin Hc H KHTN-TP.HCM Trang 53


Gio trnh: Lp trnh Windows Phone

III. Panorama
ng dng panorama s dng panorama control, cho php tao ra ng dng gm
nhiu mn hnh tri di theo chiu ngang

to ra ng dng dng panorama, ta c th dng mt trong nhng cch sau:


Chn template dng Windows Phone Panorama App khi to mi project
Windows Phone

Ko th panorama control t toolbox vo giao din

Trung Tm Tin Hc H KHTN-TP.HCM Trang 54


Gio trnh: Lp trnh Windows Phone

Thm mi mt trang c dng Windows Phone Panorama Page

Cu trc ca mt panorama control

Trung Tm Tin Hc H KHTN-TP.HCM Trang 55


Gio trnh: Lp trnh Windows Phone

Cch khai bo panorama control

<phone:Panorama x:Name="MyPanorama">
<phone:Panorama.Background>
<SolidColorBrush Color="White"/>
</phone:Panorama.Background>
<!--Panorama item 1-->
<phone:PanoramaItem>
</phone:PanoramaItem>
<!--Panorama item 2-->
<phone:PanoramaItem>
</phone:PanoramaItem>
</phone:Panorama>

1. Chuyn trang trong Windows Phone

Trung Tm Tin Hc H KHTN-TP.HCM Trang 56


Gio trnh: Lp trnh Windows Phone

Chuyn trang gia cc page


di chuyn t page ny qua page khc, ta s dng phng thc Navigate()
trong lp NavigationService.
NavigationService.Navigate(new Uri("/Pages/Page2.xaml",
UriKind.Relative));
Thuc tnh UriKind cho ta bit ng dn ca trang cn chuyn n thuc
ng dn tng i hay ng dn tuyt i.
Cc s kin quan trng khi lm vic vi chuyn trang
OnNavigatedTo() : s kin navigate t trang khc n trang hin ti
OnNavigatedFrom(): s kin navigate t trang hin ti n trang khc
Loaded: s kin khi page load hon tt.

Truyn tham s gia cc page


Tng t cch truyn tham s trn web
VD: Truyn gi tr ID t page1 sang page2 khi chuyn trang t page1 qua page2
Trn page 1:
NavigationService.Navigate(new Uri("/Page2.xaml?ID=2",UriKind.Relative));

Trn page 2: nhn tham s

protected override void OnNavigatedTo(NavigationEventArgs e)


{
base.OnNavigatedTo();
if (NavigationContext.QueryString.ContainsKey("ID"))
{
int ketqua = int.Parse(NavigationContext
.QueryString["ID"]);
}
}
Lp NavigationContext cung cp thuc tnh kiu collection tn l QueryString,
cha ton b tham s c truyn n di dng.
Hoc c th dng cch sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 57


Gio trnh: Lp trnh Windows Phone

protected override void OnNavigatedTo(NavigationEventArgs e)


{
base.OnNavigatedTo();
string parameter = string.Empty;
if (NavigationContext.QueryString.
TryGetValue("parameter", out parameter))
{
//do something with the parameter
}
}

S dng k t & truyn nhiu tham s cng lc

NavigationService.Navigate(
new Uri("/page1.xaml?ID=2&Ten=abv", UriKind.Relative));
S dng string format

string stringVariable = "This is a test string";


NavigationService.Navigate(new Uri(
string.Format("/Page1.xaml?parameter={0}",stringVariable),
UriKind.Relative));

Lm vic vi Navigation BackStack


BackStack cha danh sch cc trang m ngi dng di chuyn n trong
qu trnh s dng app.
Khi ngi dng nhn phm Back, trang cui cng c lu trong BackStack
s c ly ra.
tr v trang trc , dng phng thc GoBack() trong lp
NavigationService.
xa BackStack, s dng phng thc RemoveBackStackEntry().

BI 5. DATA BINDING C BN

I. Data binding l g?

Trung Tm Tin Hc H KHTN-TP.HCM Trang 58


Gio trnh: Lp trnh Windows Phone

Data Binding l k thut dng to gn kt gia phn giao din (UI) v d liu
thng qua phn business logic. Nh Data Binding, UI c th t ng cp nht li hin
th cc thay i trong d liu.Ngoi ra, Data Binding trong Windows Phone cn h tr cc
chiu khc nhau, ngha l cc thay i c th cp nht t UI vo d liu.

II. Cc thnh phn chnh trong Data Binding


Mt Binding bao gm 4 thnh phn chnh l: binding target, target property,
binding source v mt path (ng dn) n gi tr cn thit trong binding source, thng
thng path ny l mt source property.
V d bn mun gn property Name ca mt i tng Person cho property
Text ca mt TextBox. Khi :
Binding target: TextBox
Target property: property Text ca TextBox
Binding source: i tng Person
Path: ng dn nproperty Name ca i tng Person.
M hnh Data Binding ca WPF theo hnh minh ha sau:

Cn lu l target property phi l mt dependency property. a s cc property


ca lp UIElement u l cc dependency property. i vi binding source, bn c th s
dng bt k i tng .NET no, chng hn nh cc i tng trong ADO.NET, XML hay
cc control trong Windows Phone.

1. Binding Mode

Binding mode s ch ra hng m d liu s c cp nht. Bao gm 5 gi tr


t enum BindingMode l:

Name Description

Trung Tm Tin Hc H KHTN-TP.HCM Trang 59


Gio trnh: Lp trnh Windows Phone

OneWay Cp nht target property theo source property

Cp nht hai chiu gia target property v source


TwoWay property.

Khi to target property t source property. Sau vic


OneTime cp nht d liu s khng c thc hin.

Ging OneWay nhng theo hng ngc li: cp nht t


OneWayToSource target property sang source property.

Hng binding da trn target property. Vi target


property m ngi dng c th thay i gi tr (nh
Default TextBox.Text) th n l TwoWay, cn li l OneWay

V d

Gi s ti mun cp nht ni dung ca mt Label theo gi tr c nhp vo


TextBox. Ca s minh ha cho v d ny cn hai control chnh l textBox1 v label1:

<StackPanel>
<TextBox x:Name="textBox1">Sample Text</TextBox>
<Label x:Name="label1"/>
</StackPanel>

Bn cht ca vic to binding bao gm 2 bc:


To mt i tng System.Windows.Data.Binding v thit lp cc gi tr cn
thit.
Gi phng thc instance FrameworkElement.SetBinding() ca target
binding. FrameworkElement c tha k t UIElement v l lp cha ca cc
control trong Windows Phone. Phng thc ny c tham s u tin l mt
dependency property.
Ta to mt binding vi source binding l textBox1, target property l
TextBox.Text, souce binding l label1 v source property l Label.Content.
Binding binding = new Binding();
binding.Source = textBox1; // or binding.ElementName = "textBox1";
binding.Path = new PropertyPath("Text");
binding.Mode = BindingMode.OneWay;

Thay v phi to binding trong code-behind, bn c th to trong XAML theo cch


thng thng sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 60


Gio trnh: Lp trnh Windows Phone

<StackPanel>
<TextBox x:Name="textBox1">Sample Text</TextBox>
<Label x:Name="label1">
<Label.Content>
<Binding ElementName="textBox1" Path="Text" Mode="OneWay"/>
</Label.Content>
</Label>
</StackPanel>

Tuy nhin, XAML cn h tr mt dng c php gn hn vi cng chc nng nh


on m trn:

<StackPanel>
<TextBox x:Name="textBox1">Sample Text</TextBox>
<Label x:Name="label1"
Content="{Binding ElementName=textBox1, Path=Text, Mode=OneWay}" />
</StackPanel>

Update Source Trigger

Vi Binding Mode l TwoWay hoc OneWayToSource, bn c th xc nh thi


im m binding source s c cp nht li thng qua property
Binding.UpdateSourceTrigger. Enum UpdateSourceTrigger gm 4 gi tr:

Member name Description

a s cc dependency property s c dng gi tr


Default PropertyChanged, cn vi property Text s c gi tr l LostFocus.

PropertyChanged Cp nht binding source khi binding target property thay i.

LostFocus Cp nht binding source khi binding target mt focus.

Cp nht binding source ch khi bn gi phng


Explicit thc UpdateSource.

V d sau s t ng cp nht property Text ca hai TextBox vi nhau ngay khi


property ny b thay i:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 61


Gio trnh: Lp trnh Windows Phone

<StackPanel>
<TextBox x:Name="textBox1">Sample Text</TextBox>
<TextBox x:Name="textBox2"
Text="{Binding ElementName=textBox1, Path=Text, Mode=TwoWay, Update
SourceTrigger=PropertyChanged}" />
</StackPanel>

III. Cch to data binding trong Windows Phone


Windows Phone h tr ta cc loi binding nh sau:
Binding control to control:
V d binding mt TextBlock vi mt TextBox, ta lm nh sau
<TextBox Height="200" Width="400"
Text="Hm nay hc Data binding" x:Name="textBox1" />
<TextBlock x:Name="textBlock1"
Text="{Binding ElementName=textBox1, Path=Text, Mode=OneTime}" />

Binding control to object: y l cch binding thng dng nht, dng


hin th d liu bn di ln giao din
V d ta c lp Person nh sau

public class Person


{
public string Name { get; set; }
public string SurName { get; set; }
}

Ta cn binding ln giao din XAML nh sau

<StackPanel x:Name ="Author1">


<TextBlock Text="Name"/>
<TextBlock Text="{Binding Path=Name}"/>
<TextBlock Text="Surname"/>
<TextBlock Text="{Binding Path=Surname}"/>
</StackPanel>

Ta s c hm MainPage nh sau

public MainPage()
{
InitializeComponent();
Person person = new Person();

Trung Tm Tin Hc H KHTN-TP.HCM Trang 62


Gio trnh: Lp trnh Windows Phone

person.Name = "An Khuong";


person.SurName = "Nguyen";
Author.DataContext = person;
}

Binding ListBox vi List Object


V d ta c khai bo ListBox nh sau

<ListBox x:Name="lstNguoiDung" Height="523">


<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Source="{Binding ImgUrl}" VerticalAlignment="Top"/>
<StackPanel Width="370" Margin="10,0,0,0">
<TextBlock Text="{Binding Name}"></TextBlock>
<TextBlock Text="{Binding Age}"></TextBlock>
<TextBlock Text="{Binding Company}"></TextBlock>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

V class Employee nh sau

public class Employee


{
public string Name { get; set; }
public int Age { get; set; }
public string ImgUrl { get; set; }
public string Company { get; set; }
}

Ta s c code x l nh sau

List<Person> ListPerson = new List<Person>();


public MainPage()
{
InitializeComponent();
Listperson = Person.GetData();
PersonList.ItemsSource = ListPerson;
}
BI 6. LM VIC VI FILE V CCH LU TR FILE

I. c im lu tr file trn Windows Phone

Trung Tm Tin Hc H KHTN-TP.HCM Trang 63


Gio trnh: Lp trnh Windows Phone

Trn Windows Phone, chng ta vn c th to file v th mc ging nh cc h thng


khc. Tuy nhin, cch lu tr file trn Windows Phone c mt c im kh c bit m
Microsoft gi l isolated storage, tc l, mi ng dng c cp cho mt vng nh v ch
c truy cp n vng nh m khng th truy cp n vng nh ca ng dng khc.
Hn th na, ngi dng cng khng th thy c nhng file hay th mc . Lu tr
cc b l mt trong nhng tnh nng c cung cp c 2 b API lm vic. Phng php
c s dng lp IsolatedStorageFile, trong khi phng php mi s dng lp LocalFolder.

II. Lm vic vi Folder


Lp StorageFolder i din cho mt th mc c lu tr trong b nh. Ta c th
truy xut n th mc gc ca ng dng bng cch truy xut n lp
ApplicationData.Current.LocalFolder.

Lp Storage Folder cha cc phng thc x l bt ng b

CreateFolderAsync(): to th mc mi trong th mc hin ti


GetFolderAsync(): truy xut n 1 th mc con trong th mc hin ti.
GetFoldersAsync() ly danh sch th mc con trong th mc hin ti.
DeleteAsync() xa th mc hin ti
RenameAsync() i tn th mc hin ti

on code v d sau m t cch to mt th mc trong th mc gc

private async void OnCreateFolderClicked(object sender, RoutedEventArgs e)


{
await ApplicationData.Current.LocalFolder.CreateFolderAsync("myFolder
");
}

Tht khng may, Windows Storage API khng cung cp mt phng thc no
kim tra xem 1 th mc no c tn ti hay khng. V cch tt nht khc phc chuyn
ny l ta dng cu trc try...catch th truy xut n th mc mun kim tra v ta bt li
FileNotFoundException vng ra nu file khng tn ti. on code sau m t gii php trn:

private async void OnOpenFileClicked(object sender, RoutedEventArgs e)


{
StorageFolder folder;
try
{

Trung Tm Tin Hc H KHTN-TP.HCM Trang 64


Gio trnh: Lp trnh Windows Phone

folder = await
ApplicationData.Current.LocalFolder.GetFolderAsync("myFolder")
;
}
catch (FileNotFoundException exc)
{
folder = null;
}
if (folder == null)
{
MessageBox.Show("The folder doesn't exist");
}
}

III. Lm vic vi File


File-tp tin, c khai bo bi lp StorageFile, lp ny cng c nhng phng thc
tng t lp StorageFolder nh:

DeleteAsync(): xa file
RenameAsync(): i tn file
CopyAsync(): copy file t th mc ny n th mc khc.
MoveAsync() di chuyn file t th mc ny n th mc khc.
lm vic vi file, ta phi bt u t lp StorageFolder c cp phn trn,
ta s s dng 2 phng thc ca lp StorageFolder l phng thc GetFileAsync()
truy xut n 1 file no hoc phng thc CreateFileAsync() to mi mt file.
Lm sao to v ghi file
Nh cp trn, bc u tin to mt file l s dng phng thc
CreateFile() trn mt i tng StorageFolder. on code sau m t vic to mt file mi
gi l file.txt trong th mc gc:
private async void OnCreateFileClicked(object sender, RoutedEventArgs e
)
{
StorageFile file = await
ApplicationData.Current.LocalFolder.CreateFileAsync("file.txt",
CreationCollisionOption.ReplaceExisting);
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 65


Gio trnh: Lp trnh Windows Phone

Bn cng c th truyn vo mt tham s ty chn l CreateionCollisionOption khi


to file, vi ty chn ny, ta s chn nhng cch x l nu file mun to tn ti. Trong
v d trn, ty chn l ReplacExisting, tc l ghi nu file tn ti.
By gi, bn c mt kt ni n file cn thao tc nh vo i tng StorageFile.
V bn c th bt u lm vic vi n bng cch s dng phng thc OpenAsync()
m file. Phng thc ny s tr v mt file stream, t y, bn c th c ghi file.
on code sau m t vic ghi 1 on text vo file
private async void OnCreateFileClicked(object sender, RoutedEventArgs e
)
{
StorageFile file = await
ApplicationData.Current.LocalFolder.CreateFileAsync("file.txt",
CreationCollisionOption.ReplaceExisting);
IRandomAccessStream randomAccessStream = await
file.OpenAsync(FileAccessMode.ReadWrite);
using (DataWriter writer = new
DataWriter(randomAccessStream.GetOutputStreamAt(0)))
{
writer.WriteString("Sample text");
await writer.StoreAsync();
}
}

Trong on code trn ta s dng lp DataWriter, y l mt lp trong Windows


Runtime dng ghi d liu vo file mt cch d dng. n gin l, chng ta s to mi
mt i tng DataWriter, ta s truyn vo file stream ca file cn ghi d liu bng phng
thc GetOutputStreamAt() . Lp DataWriter cung cp nhiu phng thc khc nhau
ghi nhiu loi d liu khc nhau, v d WriteDouble() ghi s, WriteDateTime() ghi
ngy, WriteBytes() ghi d liu nh phn. Cui cng ta s dng phng thc
StoreAsync() hoc FlushAsync() kt thc thao tc ghi file.
Lu : Cu lnh using c th c dng vi nhng lp h tr interface Idisposable.
Chng thng dng kha cc ti nguyn cho n khi cc thao tc hon tt. Trong v d
trn, cho n khi thao tc ghi file c hon tt th khng c thao tc no khc c th truy
xut n file.
Lm sao c file

Trung Tm Tin Hc H KHTN-TP.HCM Trang 66


Gio trnh: Lp trnh Windows Phone

Thao tc c file cng khng khc nhiu so vi thao tc ghi file. Trong trng hp
ny chng cn ly file stream bng cch s dng OpenFile() nh trn. S khc bit l ,
thay v chng ta dng lp DataWriter, chng ta s dng lp DataReader. Xem on code
v d sau
private async void OnReadFileClicked(object sender, RoutedEventArgs e)
{
StorageFile file = await
ApplicationData.Current.LocalFolder.GetFileAsync("file.txt");
IRandomAccessStream randomAccessStream = await
file.OpenAsync(FileAccessMode.Read);
using (DataReader reader = new
DataReader(randomAccessStream.GetInputStreamAt(0)))
{
uint bytesLoaded = await reader.LoadAsync((uint)
randomAccessStream.Size);
string readString = reader.ReadString(bytesLoaded);
MessageBox.Show(readString);
}
}

Trong v d trn, thay v chng ta dng phng thc CreateFileAsync(0, chng ta s


dng phng thc GetFileAsync() truy xut n file cn thao tc.
Ging DataWriter, lp DataReader cng cung cp nhiu phng thc khc nhau
c nhiu loi d liu khc nhau nh ReadDouble(), ReadDateTime(), v ReadBytes().

IV. Lm vic vi th mc ci t
Lu tr cc b ch cho php chng ta ghi d liu cng ng dng, nhng trong mt
vi trng hp, chng ta cn thm vo phn mm ca chng ta mt vi file to sn chy
ng dng.
Windows Runtimes cung cp mt API truy cp n th mc cha cc file ci t
ca ng dng, cng l ni cha cc file trong th mc project trong Visual Studio. l
lp Package.Current.InstalledLocation, l mt class trong namespace
Windows.ApplicationModel.
Lp InstalledLocation cng l mt StorageFolder, ging nh folder lu tr trong b
nh thit b. ta c th s dng cc phng thc ging nh lm vic vi lp StorageFolder.
Tuy nhin bn khng th ghi d liu bi v n l th mc ch c.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 67


Gio trnh: Lp trnh Windows Phone

on code sau m t vic copy file t th mc ci t vo th mc gc ca thit b


private async void OnCopyFileClicked(object sender, RoutedEventArgs e)
{
StorageFile file = await
Package.Current.InstalledLocation.GetFileAsync("file.xml");
await file.CopyAsync(ApplicationData.Current.LocalFolder);
}
V. Cng c Windows Phone Power Tools
Mt nhu cu thit yu ca lp trnh vin khi lm vic vi file v folder l lm sao
thy c cc file v th mc m mnh to ra, cc lp trnh vin khng th n gin truy
xut n cc file v th mc bng cch m trnh exploree trong Windows.
Cch tt nht xem th mc lu tr ca ng dng l s dng mt cng c t hng
th 3 trn trang CodePlex l cng c Windows Phone Power Tools, cng c s cung
cp cho ta mt giao din thy cc th mc v file trong th mc lu tr ca ng dng.
Ta c th ti cng c ti trang web http://wptools.codeplex.com/ . Sau khi ci t ng
dng, bn c th kt ni n thit b hoc emulator. Sau chn mc isolated storage, bn
s thy danh sch cc ng dng m mnh ci t trong qu trnh lp trnh. Ging nh cc
trnh duyt file khc, bn c th m rng hay thu gn cy th mc ca tng ng dng. Bn
cng c th lu file v b nh trn PC, copy mt file t PC v b nh ca ng dng v
thm ch xa cc file trong .

VI. Serialization v Deserialization

Trung Tm Tin Hc H KHTN-TP.HCM Trang 68


Gio trnh: Lp trnh Windows Phone

Serialization l cch n gin nht lu tr d liu ca ng dng trong lu tr cc


b. l qu trnh chuyn i mt i tng phc tp thnh dng text n gin m c th
c lu tr trn file s dng nh dng XML hay JSON. Deserialization l qu trnh ngc
li, chuyn i t kiu text n gin sang kiu i tng phc tp s dng trong ng
dng.

Trong ng dng Windows Phone, k thut serialization thng dng mi khi d liu
c thay i (khi thm, xa , sa d liu), li ch ca n l gim thiu nguy c mt d
liu ca ngi dng khi c s c xy ra khi lu d liu, v d nh ng dng b treo hoc b
ngng t ngt.

Deserialization, tri li, c dng khi ng dng chy ln u tin. Serialization rt


d s dng, tuy nhin, nu ng dng phi lm vic vi d liu ln hoc nhng d liu quan
h phc tp th bn cn phi s dng mt h c s d liu no thay th.

Trong v d sau, gi s ng dng cn thao tc vi lp HocVien

public class HocVien


{
public string Ho { get; set; }
public string Ten { get; set; }
}

Chng ta s to mt danh sch hc vin

List<HocVien> ListHocVien = new List<HocVien>


{
new HocVien
{
Ho = "Nguyn",
Ten = "Lm"
},
new HocVien
{
Ho = "Trn",
Ten = "Dng"
}
};

Serialization

Trung Tm Tin Hc H KHTN-TP.HCM Trang 69


Gio trnh: Lp trnh Windows Phone

serialize d liu, ta dng phng php lu tr file c cp trn. Chng


ta s dng phng thc CreateFile() to file, xem on code v d bn di

private async void OnSerializeClicked(object sender, RoutedEventArgs e)


{
DataContractSerializer serializer = new
DataContractSerializer(typeof(List<HocVien>));
StorageFile file = await
ApplicationData.Current.LocalFolder.CreateFileAsync("HocVien.xml");
IRandomAccessStream randomAccessStream = await
file.OpenAsync(FileAccessMode.ReadWrite);
using (Stream stream = randomAccessStream.AsStreamForWrite())
{
serializer.WriteObject(stream, ListHocVien);
await stream.FlushAsync();
}
}

Lp DataContractSerializer (thuc namespace System.Runtime.Serialization) s


qun l qu trnh serialize. Khi to mt i tng mi, chng ta cn xc nh loi d liu
chng ta cn serialize, trong trng hp ny l List<HocVien>. Tip theo ta s to file
tin hnh ghi d liu. Qu trnh serialize s c thc hin khi ta gi phng thc
WriteObject() ca lp DataContractSerializer, phng thc i hi truyn vo 2 tham s
l file stream ghi d liu v danh sch i tng cn serialize. Nu chng ta kim tra
file HocVien.xml bng cng c Windows Power Tools, ta s thy file c ni dung nh sau

<ArrayOfHocVien xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/Storage.Classes">
<HocVien>
<Ho>Nguyn</Ho>
<Ten>Lm</Ten>
</HocVien>
<HocVien>
<Ho>Trn</Ho>
<Ten>Dng</Ten>
</HocVien>
</ArrayOfHocVien>

Deserialization

Trung Tm Tin Hc H KHTN-TP.HCM Trang 70


Gio trnh: Lp trnh Windows Phone

Qu trnh deserialization th cng tng t, chng ta vn dng StorageFile c ni


dung file cn deserialization, sau s dng lp DataContractSerializer tin hnh
deserialize. Xem on code v d sau:

private async void OnDeserializeClicked(object sender, RoutedEventArgs


e)
{
StorageFile file = await
ApplicationData.Current.LocalFolder.GetFileAsync("HocVien.xml");
DataContractSerializer serializer = new
DataContractSerializer(typeof(List<HocVien>));
IRandomAccessStream randomAccessStream = await
file.OpenAsync(FileAccessMode.Read);
using (Stream stream = randomAccessStream.AsStreamForRead())
{
List<HocVien> people = serializer.ReadObject(stream) as
List<HocVien>;
}
}

Lu : V d trn s dng lp DataContractSerializer, s dng nh dng XML, nu


bn mun dng nh dng JSON, ta thay bng lp DataContractJsonSerializer v s dng
hon ton tng t.

VII. IsolatedStorageSettings

Mt trong nhng nhu cu khi lp trnh trn di ng l lu tr nhng cu hnh. Nhiu


ng dng cung cp mt trang cu hnh ngi dng thay i cc ty chn.

gip lp trnh vin p ng nhu cu , b SDK cung cp 1 lp gi l


IsolatedStorageSettings, n cung cp mt i tng gi l ApplicationSettings c dng
dictionary (key-value) ta lu nhng cu hnh.

Lu : Lp IsolatedStorageSettings l mt phn trong b APIs h tr lu tr trn


Windows Phone 7. Trong b API ca Windows Runtime vn cung cp cho ta phng php
lu tr cu hnh, tuy nhin, n khng c h tr trn Windows Phone.

s dng ApplicationSettings rt d dng, n c kiu d liu l


Dictionary<string,object> v c th c dng lu bt c loai i tng no.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 71


Gio trnh: Lp trnh Windows Phone

on code sau gm 2 phng thc m t vic lu mt cu hnh v cch gi li cu


hnh

private void OnSaveSettingsClicked(object sender, RoutedEventArgs e)


{
IsolatedStorageSettings settings =
IsolatedStorageSettings.ApplicationSettings;
settings.Add("ten", "Lm");
settings.Save();
}
private void OnReadSettingsClicked(object sender, RoutedEventArgs e)
{
IsolatedStorageSettings settings =
IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("ten"))
{
MessageBox.Show(settings["ten"].ToString());
}
}

Lu : bn cht ca vic lu cu hnh ny l lu tr trn 1 file XML v s dng k


thut serialization v deserialization lu v c d liu.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 72


Gio trnh: Lp trnh Windows Phone

BI 7. TM HIU BRUSH V RESOURCE

I. Tm hiu Brush

Brush l mt cng c gip ta nh ngha mu cho cc control. Brush h tr ta v mu


n sc v kt hp nhiu mu vi nhau theo kiu Gradient. S sau m t cc loi brush
h tr trong Windows Phone

Hnh sau y m t tng loi Brush

nh ngha mt Brush, ta c th nh ngha trc tip trn code XAML hoc nh


ngha trong code behind.

nh ngha mt ColorBrush bng code XAML

Trung Tm Tin Hc H KHTN-TP.HCM Trang 73


Gio trnh: Lp trnh Windows Phone

<Button Content="Button" >


<Button.Background>
<SolidColorBrush Color="Red">
</SolidColorBrush>
</Button.Background>
</Button>

nh ngha mt ColorBrush bng code behind

Color cr = new Color();


cr.B = cr.R = cr.G = 122;
cr.A = 255;
SolidColorBrush br = new SolidColorBrush(cr);
button1.Background = br;

nh ngha mt LinearGradientBrush bng code XAML

<Button Content= "Windows Phone" >


<Button.Background>
<LinearGradientBrush>
<GradientStop Color="Red" Offset="0.0"/>
<GradientStop Color="Blue" Offset="0.5"/>
<GradientStop Color="White" Offset="1.0"/>
</LinearGradientBrush>
</Button.Background>
</Button>

nh ngha mt LinearGradientBrush bng code behind

Trung Tm Tin Hc H KHTN-TP.HCM Trang 74


Gio trnh: Lp trnh Windows Phone

LinearGradientBrush br
= new LinearGradientBrush();
GradientStop gs1 = new GradientStop();
gs1.Color = Colors.Red;
gs1.Offset = 0;
GradientStop gs2 = new GradientStop();
gs2.Color = Colors.White;
gs2.Offset = 1.0;
br.GradientStops.Add(gs1);
br.GradientStops.Add(gs2);
button1.Background = br;

nh ngha mt RadialGradientBrush bng code XAML

<Button x:Name="button1" Content="Windows Phone">


<Button.Background>
<RadialGradientBrush GradientOrigin="0.75,0.25">
<GradientStop Color="Yellow" Offset="0.0"/>
<GradientStop Color="Orange" Offset="0.5"/>
<GradientStop Color="Blue" Offset="1.0"/>
</RadialGradientBrush>
</Button.Background>
</Button>

nh ngha mt RadialGradientBrush bng code behind

Trung Tm Tin Hc H KHTN-TP.HCM Trang 75


Gio trnh: Lp trnh Windows Phone

RadialGradientBrush br = new RadialGradientBrush();


br.GradientOrigin = new Point(0.75, 0.25);
GradientStop gs1 = new GradientStop();
gs1.Color = Colors.Yellow;
gs1.Offset = 0;
GradientStop gs2 = new GradientStop();
gs2.Color = Colors.Orange;
gs2.Offset = 0.5;
GradientStop gs3 = new GradientStop();
gs3.Color = Colors.Blue;
gs3.Offset = 1.0;
br.GradientStops.Add(gs1);
br.GradientStops.Add(gs2);
br.GradientStops.Add(gs3);
button1.Background = br;

Lu : Khi s dng Gradient ta cn lu cc im sau

Mi setter s i din cho mt mu. Nu ta mun s dng bao nhiu mu trong


mt Gradient s dng by nhiu setter.
S dng thuc tnh Offset nh tri di ca tng mu. Hai hnh bn di
s m t cch s dng thuc tnh Offset khi s dng LinearGradient v
RadialGradient

Trung Tm Tin Hc H KHTN-TP.HCM Trang 76


Gio trnh: Lp trnh Windows Phone

Ta cng cn lu cc thuc tnh nh GradientOrigin, Center, RadiusX,


RadiusY. Hnh sau y m t cch s dng ca tng thuc tnh

nh ngha mt ImageBrush bng code XAML

Trung Tm Tin Hc H KHTN-TP.HCM Trang 77


Gio trnh: Lp trnh Windows Phone

<ImageBrush
ImageSource="Assets\\childrens.PNG">
</ImageBrush>
nh ngha mt ImageBrush bng code behind

using System.Windows.Media.Imaging;
ImageBrush br = new ImageBrush();
br.ImageSource = new BitmapImage
(
new Uri(
"/Assets/children.jpg",
UriKind.Relative)
);

II. Tm hiu v Resource

Trong qu trnh xy dng ng dng, chc chn ta s khng trnh khi yu cu lm


th no ng dng ca ta mang mt style thng nht, v d nhng mu ch, kiu ch,
font ch trn cc trang phi ng nht vi nhau. Ngoi ra, ta cn phi lm vic vi mt s
control i hi phi nh dng trc mu d liu m control s hin th, v d nh
ListBox hay LongListSelector. Hn th na, ta cn tch bit gia code nh dng cc
control v code khai bo cch control source ca ang c trong sng v d chnh sa
hn, c th ti s dng c nhiu ln. gii quyt cc vn trn, ta cn s dng cc
style v resource c cung cp trong Windows Phone.

1. Cc loi Resource Commented [cc2]: bnbvvb

2. Gii thiu Resource

Resource s c chia thnh 2 nhm chnh l Style v DataTemplate.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 78


Gio trnh: Lp trnh Windows Phone

Ta s dng Style nh dng, trang tr cho cc control, cn DataTemplate dng


nh ngha mu d liu cho cc list control.

Style: nh ngha mt style, ta khai bo c php XAML nh sau

<Style x:Key="CustomText" TargetType="TextBlock">


<Setter Property="FontSize" Value="24"/>
<Setter Property="FontWeight" Value="Bold"/>
</Style>

Thuc tnh x:Key dng nh danh cho style


Thuc tnh TargetType dng loi control s c p dng

Lu : nu thuc tnh x:Key khng c khai bo th tt c cc control cng loi


vi TargetType s c p dng style.

Mt th <Setter/> s khai bo cho mt thuc tnh ca control


p dng 1 style cho 1 control ta khai bo thuc tnh Style ca control
nh sau
Style="{StaticResource <tn ca style>} "

VD: Gn style c tn CustomText c khai bo bn trn cho 1 TextBlock


control: <TextBlock Style="{StaticResource CustomText}"/>

DataTemplate: nh dng DataTemplate, ta cng nh dng ging nh


khi nh dng ItemTemplate cho cc control.

VD: nh ngha mt DataTemplate

<DataTemplate x:Key="ListBoxTemplate">
<StackPanel>
<TextBlock Text="Name"/>
<TextBlock Text="{Binding Path=Name}"/>
<TextBlock Text="Surname"/>
<TextBlock Text="{Binding Path=Surname}"/>
</StackPanel>
</DataTemplate>

- Thuc tnh x:Key dng nh danh cho DataTemplate.

3. Cc v tr t Resource

Ta s c 3 cch t

Trung Tm Tin Hc H KHTN-TP.HCM Trang 79


Gio trnh: Lp trnh Windows Phone

Page Resource
c khai trong mt trang XAML v ch c s dng trong trang .
c nh ngha trong cp th

<phone:PhoneApplicationPage.Resources>
<!-- nh ngha cc Resource ti y -->
</phone:PhoneApplicationPage.Resources>

Application Resource
c khai trong mt trang App.xaml v ch c s dng trong ton ng
dng.
c nh ngha trong cp th

<Application.Resources>

</Application.Resources>

ResourceDictionary
c khai bo trong mt file xml ring l
Tn file phi c kt thc bng .xaml
Cc Resource c nh ngha trong cp th

<?xml version="1.0" encoding="utf-8" ?>


<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006
/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/20
06/xaml">
<!--nh ngha cc Resource ti y -->
</ResourceDictionary>

s dng, ta phi add vo Application Resource nh sau

<Application.Resources>
<ResourceDictionary>
<local:LocalizedStrings xmlns:local="clr-
namespace:Demo_Brush_Resource" x:Key="LocalizedStrings"/>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Assets/Resources/Style
.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources

Trung Tm Tin Hc H KHTN-TP.HCM Trang 80


Gio trnh: Lp trnh Windows Phone

BI 8. TM HIU SQLITE

I. t vn

Khi xy dng ng dng, vic lu tr d liu l mt yu cu thit yu. Trong nhng


bi trc, ta tm hiu cc cch lu tr trn file, tuy nhin, vic lu tr trn file c nhiu
khuyt im, ta khng th lu tr nu ta cn thao tc trn nhiu bng d liu phc tp, hn
th na, ta cng khng th truy vn d liu trn file. t c nhng yu cu trn, ta s
phi dng mt h c s d liu no . Trong Windows Phone, ta c th dng SQL CE
lu tr d liu, tuy nhin, n khng th p ng yu cu cross-platform (chy trn nhiu
nn tn khc nhau), thay vo , ta nn dng SQLite lu tr d liu.

II. Cc bc ci t, cu hnh

c th s dng SQLite, ta cn phi thc hin mt s thao tc ci t cng nh cu


hnh trong Visual Studio nh sau

Bc 1: Ci gi SQLite for Windows Phone trong Visual Studio. Trong


Visual Studio, ta vo menu Tools -> Extensions and Updates. Trong ca s hin ra, ta
chn tab Online ct bn phi, v ta search theo t kha SQLite for Windows Phone.
Sau khi tm c, ta nhn Download

Trung Tm Tin Hc H KHTN-TP.HCM Trang 81


Gio trnh: Lp trnh Windows Phone

Bc 2: Download project SQLite-net-wp8 t Github. y l mt project


C++, ta vo link sau download https://github.com/peterhuene/sqlite-net-wp8. Sau
khi down v, ta c file zip, ta tin hnh gii nn.
Bc 3: Sau khi gii nn, ta tin hnh add project trn vo Solution hin ti.
Ta click phi vo Solution, chn Add -> Existing project, sau chn n file Sqlite
trong th mc va gii nn.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 82


Gio trnh: Lp trnh Windows Phone

Bc 4: Thm References ca project chnh n project SQLite-net-wp8 va


thm vo
Click phi vo th mc References -> Add Reference...

Trung Tm Tin Hc H KHTN-TP.HCM Trang 83


Gio trnh: Lp trnh Windows Phone

Chn tab Solution v tick vo project Sqlite va thm vo

Bc 5: Thm gi Sqlite-net t NuGet


Chn menu Tools -> NuGet Package Manager -> Manage NuGet Package
for Solution...

Trung Tm Tin Hc H KHTN-TP.HCM Trang 84


Gio trnh: Lp trnh Windows Phone

Sau khi add Sqlite-net, 2 file Sqlite.cs v SqliteAsync.cs s c thm vo


project
Bc 6: Cp quyn cho ng dng s dng Sqlite
Click phi vo project chn Properties
Chn Tab Build.
Chn All Configurations ti Configuration
Chn All Platforms ti Platform
Thm USE_WP8_NATIVE_SQLITE ti Conditional compilation
symbols

III. Cc thao tc c bn trn SQLite


Gi s ta cn lu tr thng tin ca nhn vin.
Ta c lp nhn vin nh sau
public class NhanVien
{
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int Id { get; set; }
public string Ten { get; set; }
public string Ho { get; set; }
}

To c s d liu trong file App.xaml.cs:

Ti y, ta kim tra nu file csdl khng tn ti, ta tin hnh to file csdl

Trung Tm Tin Hc H KHTN-TP.HCM Trang 85


Gio trnh: Lp trnh Windows Phone

Copy on code sau vo phng thc khi to ca lp App trong file App.xaml.cs
string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.Loc
alFolder.Path, "db.sqlite");
if (!FileExists("db.sqlite").Result)
{
using (var db = new SQLiteConnection(dbPath))
{
db.CreateTable<NhanVien>();
}
}

Thm phng thc kim tra s tn ti ca csdl trong lp App.xaml.cs


private async Task<bool> FileExists(string fileName)
{
var result = false;
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalF
older.GetFileAsync(fileName);
result = true;
}
catch { }
return result;
}

Ta to 3 button Thm, Xa, Sa thc hin thao tc vi csdl


<StackPanel >
<Button Name="btnInsert" Click="BtnInsert_OnClick" Content ="Insert"
>
</Button>

<Button Click="BtnUpdate_OnClick" Name="btnUpdate" Content="Update"


>
</Button>

<Button Name="btnDelete" Click="BtnDelete_OnClick" Content="Delete"


>
</Button>
</StackPanel>

Code x l button Insert


private void BtnInsert_OnClick(object sender, RoutedEventArgs e)
{
using (var db = new SQLiteConnection(dbPath))
{
db.Insert(new NhanVien() { Ten = "Nhut", Ho = "Le" });
}
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 86


Gio trnh: Lp trnh Windows Phone

Code x l button Delete


private void BtnDelete_OnClick(object sender, RoutedEventArgs e)
{
using (var db = new SQLiteConnection(dbPath))
{
var existing = db.Query<NhanVien>("select * from NhanVien").F
irstOrDefault();
if (existing != null)
{
db.Delete(existing);
}
}
}

Code x l button Update


private void BtnUpdate_OnClick(object sender, RoutedEventArgs e)
{
using (var db = new SQLiteConnection(dbPath))
{
var existing =
db.Query<NhanVien>("select * from NhanVien").FirstOrDefault();
if (existing != null)
{
existing.Ten = "Huy";
db.Update(existing);
}
}
}

IV. Cng c SQLite Manager


Nh ta bit, khi lm vic trn SQLite, hin ti Visual Studio khng h tr cng
c ta qun l. SQLite Manager cung cp kh nng c file sqlite qun l c s d
liu. Ta c th dng cng c ny kim tra nhng thay i trong d liu. SQLite
Manager l mt add-on trong Firefox. Ta tm kim v ci t n nh mt add on bnh
thng

Trung Tm Tin Hc H KHTN-TP.HCM Trang 87


Gio trnh: Lp trnh Windows Phone

Mun kim tra file SQLite:

Ta dng Windows Power Tool ly file sqlite t in thoi,


M SQLite Manager ln v chn Open file

Trung Tm Tin Hc H KHTN-TP.HCM Trang 88


Gio trnh: Lp trnh Windows Phone

PHN 2. MODULE 3
BI 1. a phng tin trong Windows Phone
(Multimedia)

Windows Phone h tr hng lot cc a phng tin nh: Camera, Photo, Video,
Audio Multimedia l mt phn khng th thiu ca ngi s dng thit b di ng.
Ni dung ca phn ny s cp ti nhng phn sau:

I. Camera ..................................................................................................89
1. Ch Camera Preview .................................................................................... 90
2. Chp hnh t Camera ........................................................................................ 93
3. S dng Camera vi ViewModel ...................................................................... 95
4. Thit lp hiu ng m thanh cho Camera ...................................................... 103
5. To Camera Focus ........................................................................................... 110
II. Video ...................................................................................................117
1. S dng MediaElement, MediaPlayerLauncher ............................................ 117
2. Cc thao tc thng dng khi s dng Video ................................................ 120
a. Play (m)........................................................................................................ 120
b. Stop (dng) .................................................................................................... 121
c. Pause (tm dng) ............................................................................................ 122
d. Mute (tt ting) ............................................................................................... 122
e. Seek (dch chuyn) ......................................................................................... 123
f. Quay video v Audio ...................................................................................... 124
III. Audio ...................................................................................................130
1. Thm m thanh vo ng dng ........................................................................ 130
2. Thit lp chy nn Audio................................................................................. 133

I. Camera

Trung Tm Tin Hc H KHTN-TP.HCM Trang 89


Gio trnh: Lp trnh Windows Phone

i vi thit b di ng th chc nng Camera l mt trong nhng tin ch v


cng c o v quan trng. Thng qua Camera ta c th ghi li nhng khong khc ng
nh trong cuc sng, ta c th quay phim, chp hnh v nhng tnh nng m rng khc.
Gio trnh s trnh by nhng tnh nng quan trng v cn thit.
1. Ch Camera Preview

Ch Camera Preview cho php chng ta xem trc khung cnh, c th chp
c mt bc nh th ta phi khi to PhotoCamera v cung cp
ID_CAP_ISV_CAMERA trong WMAppManifest.xml Capabilities.
ch ny ta cn quan tm ti 2 lp th vin PhotoCamera (nm trong th
vin Microsoft.Devices) v VideoBrush (nm trong th vin System.Windows.Media),
lp PhotoCamera s c gn source t VideoBrush.
Thng thi ta s khi to trong OnNavigatedTo v thu hi b nh trong
OnNavigatedFrom, bn ch l i vi tng tc phn cng th phi c thit b tht
kim tra, nu nh dng Emulator th bn ch c thy cc hnh vung chy xung quay
mn hnh khi bn s dng Camera.
Bn lm theo cc hng dn c th di y khi to c Camera xut hin
ln trn ng dng ca bn:

Bc 1: To mt Project tn l : LearnMultimedia
Bc 2: Thit lp ID_CAP_ISV_CAMERA

Bn double click vo tp tin WMAppManifest.xml, Visual Studio s hin th mn


hnh nh bn di, bn vo mc Capabilities ri checked vo ID_CAP_ISV_CAMERA:

Bc 3: Thit k giao din chnh ca phn mm nh sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 90


Gio trnh: Lp trnh Windows Phone

<phone:PhoneApplicationPage

x:Class="LearnMultimedia.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Landscape" Orientation="Landscape"

shell:SystemTray.IsVisible="True">

<Grid x:Name="LayoutRoot" Background="Transparent">

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

<RowDefinition Height="*"/>

</Grid.RowDefinitions>

<MediaElement x:Name="VideoPlayer"

Width="800"

Height="480"

Stretch="Fill" />

</Grid>

</phone:PhoneApplicationPage>

Bn quan st v thy rng ng dng ch c mt control MediaElement, y ta


thit lp Stretch = Fill Camera khi quay khung cnh s c trn y mn hnh.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 91


Gio trnh: Lp trnh Windows Phone

Bc 4: Tin hnh vit coding khi to cc i tng lin quan c th s


dng c Camera, ch l phi using 2 th vin:

using Microsoft.Devices;

using System.Windows.Media;

khi to ta nn vit trong hm OnNavigatedTo v khi hm ny sy ra tc l


ng dng bt u vo Foreground Lifetime (mi ti ngun sn sng chy ng dng):

private PhotoCamera _camera;

private VideoBrush _videoBrush;

protected override void OnNavigatedTo(NavigationEventArgs e)

base.OnNavigatedTo(e);

_camera = new PhotoCamera(CameraType.Primary);

_camera.Initialized += _camera_Initialized;

_videoBrush = new VideoBrush();

_videoBrush.SetSource(_camera);

trn ta dng CameraType.Primary tc l s dng camera mt sau in thoi, cn


nu chuyn qua CameraType.FrontFacing s dng camera mt trc in thoi, ta
cng c th ty bin bng m lnh.
Khi to i tng _videoBrush v gi hm SetSource thit lp VideoBrush ti
Camera.
Bn hm _camera_Initialized c gn cho s kin _camera.Initialized, hm
ny do ta nh ngha bt u kch hot chc nng Camera trong my tnh, hm
ny vit nh sau:

void _camera_Initialized(object sender, CameraOperationCompletedEventArgs e)


{
if (e.Succeeded) //kim tra kch hot thnh cng

Trung Tm Tin Hc H KHTN-TP.HCM Trang 92


Gio trnh: Lp trnh Windows Phone

{
var resolution = new Size(2048, 1536);
if (_camera.AvailableResolutions.Contains(resolution))
{
_camera.Resolution = resolution;
}
Dispatcher.BeginInvoke(() =>
{
this.LayoutRoot.Background = _videoBrush;
});
}
}
_Camera.AvailableResolutions tr v tp cc phn gii m thit b tht h tr,
thng cc phn gii c th l: 640 x 480, 1280 x 960, 2048 x 1536, 3264 x
2448
on coding trn ngha rng nu nh Camera c h tr phn gii 2048 x
1536 th s dng phn gii ny lun, cn khng th ly theo i tng _videoBrush.
Ta khng nn vic hin th VideoBrush Main Thread (Tin trnh chnh), ta
tao mt tin trnh con lm cng vic ny thng qua lnh: Dispatcher.BeginInvoke()

Bc 5: G b khi to i tng sau khi khng cn s dng

protected override void OnNavigatedFrom(NavigationEventArgs e)


{
_videoBrush = null;
_camera.Initialized -= _camera_Initialized;
_camera = null;
base.OnNavigatedFrom(e);
}
2. Chp hnh t Camera

Khi Camera ang kch hot th ta c th chp c hnh t Camera thng qua cc
bc di y (Ta tip tc vi project va to trn):

Bc 1: Thit lp ID_CAP_MEDIALIB_PHOTO capability

Trung Tm Tin Hc H KHTN-TP.HCM Trang 93


Gio trnh: Lp trnh Windows Phone

Bc 2: Thit lp s kin ngi s dng bm nt chp hnh trn thit b v s


kin kim tra hnh nh sn sng c chp hay cha, Nt bm chp hnh
trn thit b in thoi c vit trong s kin static ca lp CameraButtons,
ta sa li hm OnNavigatedTo nh sau:

protected override void OnNavigatedTo(NavigationEventArgs e)


{
base.OnNavigatedTo(e);
_camera = new PhotoCamera(CameraType.Primary);
_camera.Initialized += _camera_Initialized;

_camera.CaptureImageAvailable += _camera_CaptureImageAvailable;
CameraButtons.ShutterKeyPressed += CameraButtons_ShutterKeyPressed;

_videoBrush = new VideoBrush();


_videoBrush.SetSource(_camera);
}

bc ny, khi ngi s dng bm nt chp hnh trn thit b th chng trnh
s t ng gi s kin CameraButtons_ShutterKeyPressed (do ta nh ngha):
void CameraButtons_ShutterKeyPressed(object sender, EventArgs e)
{
try
{
_camera.CaptureImage();
}
catch (InvalidOperationException ex)
{
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(ex.Message);
});

Trong s kin ny ta gi phng thc CaptureImage() ra lnh cho Camera


chp hnh.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 94


Gio trnh: Lp trnh Windows Phone

Khi phng thc ny c gi, camera s tin hnh chp v nu nh chp thnh
cng th s kin _camera_CaptureImageAvailable (do ta nh ngha) s t ng c
triu gi:
void _camera_CaptureImageAvailable(object sender, ContentReadyEventArgs e)
{
string path = "picture" +
DateTime.Now.ToString("YYYYMMDDHHMMSSmmmm") + ".jpg";
MediaLibrary library = new MediaLibrary();
library.SavePictureToCameraRoll(path, e.ImageStream);
}

Hm trn cho php lu hnh nh vo CameraRoll, hnh c Camera chp s lu


trong e.ImageStream. s dng c MediaLibrary th ta phi dng thm th vin:
using Microsoft.Xna.Framework.Media;

Nh vy ta chp c 1 hnh t Camera, bn c th vo Camera Roll xem


kt qu.
3. S dng Camera vi ViewModel

gim thiu thi gian coding, ngi ta s dng Camera ViewModel v binding
ti trang ng dng, bn lm theo cc bc di y:

Bc 1: To Project tn l LearnMultimedia_ViewModel
Bc 2: Thit lp ID_CAP_ISV_CAMERA v
ID_CAP_MEDIALIB_PHOTO, double click vo WMAppManifest.xml/ vo
Capabilities

Bc 3: Thit k MainPage nh sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 95


Gio trnh: Lp trnh Windows Phone

Ch l Binding Preview, th Preview l thuc tnh c khai bo trong lp


CameraViewModel

<phone:PhoneApplicationPage

x:Class="LearnMultimedia_ViewModel.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Landscape" Orientation="Landscape"

shell:SystemTray.IsVisible="False">

<Grid x:Name="LayoutRoot" Background="{Binding Preview}"/>

</phone:PhoneApplicationPage>

Bc 4: To i tng ViewModel khi to Camera, chp hnh


Bc 4.1: To th mc ViewModels cho ng dng
- Bm chut phi vo Project
- Chn Add/ New Folder/ nhp tn th mc ng yu cu
- Xem hnh bn di:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 96


Gio trnh: Lp trnh Windows Phone

Quan st cu trc project s c thm th mc ViewModels:

Bc 4.2: To mt lp tn l BaseViewModel (d nhin bn c th t ty


) trong th mc ViewModels vi ni dung nh sau (nh thm using
System.ComponentModel):

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.ComponentModel;

namespace LearnMultimedia_ViewModel.ViewModels

Trung Tm Tin Hc H KHTN-TP.HCM Trang 97


Gio trnh: Lp trnh Windows Phone

public class BaseViewModel : INotifyPropertyChanged

public void NotifyPropertyChanged(string propertyName)

if (PropertyChanged != null)

PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

public event PropertyChangedEventHandler PropertyChanged;

Bc 4.3: To thm mt lp CameraViewModel k tha t


BaseViewModel trong th mc ViewModels:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

//thm cc th vin sau:

using Microsoft.Devices;

using System.Windows.Media;

using Microsoft.Xna.Framework.Media;

using System.Windows;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 98


Gio trnh: Lp trnh Windows Phone

namespace LearnMultimedia_ViewModel.ViewModels

public class CameraViewModel : BaseViewModel, IDisposable

private PhotoCamera _camera;

private string _captureName;

private VideoBrush _tempBrush;

private VideoBrush _preview;

//Properties ny c Binding trong bc 3

public VideoBrush Preview

get

return _preview;

private set

_preview = value;

NotifyPropertyChanged("Preview");

//hm khi to cc thng s cho Camera

//N c khi to trong hm ca OnNavigatedTo Page s dng

public CameraViewModel()

_camera = new PhotoCamera(CameraType.Primary);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 99


Gio trnh: Lp trnh Windows Phone

_camera.Initialized += camera_Initialized;

_camera.CaptureImageAvailable += camera_CaptureImageAvailable;

_tempBrush = new VideoBrush();

_tempBrush.SetSource(_camera);

//hm hy b cc thng s khi to trc

//N c gi trong hm OnNavigatedFrom ca trang s dng n

public void Dispose()

_camera.Initialized -= camera_Initialized;

_camera.CaptureImageAvailable -= camera_CaptureImageAvailable;

_camera.Dispose();

_camera = null;

_tempBrush = null;

this.Preview = null;

//hm khi to Camera

void camera_Initialized(object sender, CameraOperationCompletedEventArgs e)

if (e.Succeeded)

Deployment.Current.Dispatcher.BeginInvoke(() =>

this.Preview = _tempBrush;

});

Trung Tm Tin Hc H KHTN-TP.HCM Trang 100


Gio trnh: Lp trnh Windows Phone

//hm gi chp hnh, khi gi hm chp th truyn tn hnh mun lu

public void Capture(string fileName)

_captureName = fileName;

try

_camera.CaptureImage();

// ignore images taken too close together

catch (InvalidOperationException) { }

//hm lu hnh c chp vo CameraRoll, ti tn file c ly t hm Capture

void camera_CaptureImageAvailable(object sender, ContentReadyEventArgs e)

MediaLibrary library = new MediaLibrary();

library.SavePictureToCameraRoll(_captureName, e.ImageStream);

Khi ta vit theo cch ny th bt k ng dng no cng c th k tha v s dng


li mt cch nhanh chng.
Bc 4.4: Hiu chnh coding trong MainPage.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 101


Gio trnh: Lp trnh Windows Phone

using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using LearnMultimedia_ViewModel.Resources;
//thm cc th vin sau
using Microsoft.Devices;
using LearnMultimedia_ViewModel.ViewModels;

namespace LearnMultimedia_ViewModel
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private CameraViewModel _vm;
//Tin hnh Binding trong hm ny
protected override void
OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
_vm = new CameraViewModel();
this.LayoutRoot.DataContext = _vm;//Thuc tnh Preview c gn cho
Background ca Grid ri
CameraButtons.ShutterKeyPressed += CameraButtons_ShutterKeyPressed;
}
//NSD bm nt chp hnh
void CameraButtons_ShutterKeyPressed(object sender, System.EventArgs e)
{
string captureName = "picture" +
DateTime.Now.ToString("yyyyMMddhhmmssfff") + ".jpg";
_vm.Capture(captureName);
}
//hy b khi khng s dng
protected override void
OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
this.LayoutRoot.DataContext = null;
_vm.Dispose();
_vm = null;
CameraButtons.ShutterKeyPressed -= CameraButtons_ShutterKeyPressed;
base.OnNavigatedFrom(e);
}
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 102


Gio trnh: Lp trnh Windows Phone

Nh vy bn lm xong ng dng chp hnh bng k thut s dng ViewModel,


mi bt u th bn cm thy n kh v rc ri nhng thc ra n rt tin li, gim thiu
c thi gian coding rt nhiu. Gi s rng tt c cc ng dng ca bn u c
CameraViewModel th v cng n gin, bn ch cn lm bc 4.4 l xong,
CameraViewModel tr thnh 1 th vin c lp.

4. Thit lp hiu ng m thanh cho Camera

Chc nng chp hnh nn c thm hiu ng m thanh cho ngi s dng bit
rng thao tc h thc hin xong hay cha, ng thi cng gip phn mm thm sinh
ng, cc sound bn c th ly t trang: https://soundcloud.com hoc trong th mc
C:\Windows\Media, cc bc chi tit (Tip tc vi bi trn):

Bc 1: Ta tin hnh a 2 file wav vo ng dng nh hnh di y:

Ch l bn to thm th mc Sounds nm bn trong th mc Assets, chp 2 file


m thanh .wav vo th mc Sounds.

Bc 2: To thm 1 lp tn l SoundEffects nm bn trong th mc


ViewModels:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 103


Gio trnh: Lp trnh Windows Phone

Lp SoundEffects ta phi dng cc th vin sau:

using Microsoft.Xna.Framework;

using Microsoft.Xna.Framework.Audio;

using System.Windows.Resources;

using System.Windows;

c th pht m thanh t mt sound file, ta lm cc bc n gin nh sau:

//Bc 1: Ly Stream Resource sound file

StreamResourceInfo resource = Application.GetResourceStream(

new Uri("Assets/Sounds/Windows Critical Stop.wav", UriKind.Relative));

//Bc 2: ly i tng SoundEffect

var effect = SoundEffect.FromStream(resource.Stream);

//Bc 3: Gi hm Update gi thng ip ti XNA framework

FrameworkDispatcher.Update();

//Bc 4: Gi phng thc Play m sound

effect.Play();

Da vo on coding trn th ta c th vit m lnh cho SoundEffects nh sau:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Xna.Framework;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 104


Gio trnh: Lp trnh Windows Phone

using Microsoft.Xna.Framework.Audio;
using System.Windows.Resources;
using System.Windows;

namespace LearnMultimedia_ViewModel.ViewModels
{
//To enum c 2 trng thi l bm chp v b li
public enum EffectTypes { Click, Error };

public class SoundEffects : Dictionary<EffectTypes, SoundEffect>


{
/// <summary>
/// Constructor cho php khi to 2 SoundEffect
/// </summary>
public SoundEffects()
{

this.Add(EffectTypes.Click,
LoadSoundEffect("Windows Navigation Start.wav"));
this.Add(EffectTypes.Error,
LoadSoundEffect("Windows Critical Stop.wav"));
}
/// <summary>
/// Hm c 1 tn ng dn sound file v tr v mt i tng SoundEffect
/// </summary>
/// <param name="fileName">ng dn file</param>
/// <returns>Tr v SoundEffect</returns>
private SoundEffect LoadSoundEffect(string fileName)
{
string path = "Assets/Sounds/" + fileName;
StreamResourceInfo resource = Application.GetResourceStream(
new Uri(path, UriKind.Relative));
return SoundEffect.FromStream(resource.Stream);
}
/// <summary>
/// Phng thc m sound no da vo enum EffectTypes
/// </summary>
/// <param name="effectType"></param>
public void Play(EffectTypes effectType)
{
var effect = this[effectType];
if (effect != null)
{
FrameworkDispatcher.Update();
effect.Play();

Trung Tm Tin Hc H KHTN-TP.HCM Trang 105


Gio trnh: Lp trnh Windows Phone

}
}
}

Bc 3: Tin hnh s dng lp SoundEffects trong CameraViewModel

Ta s s dng SoundEffects trong 2 trng hp, l lc ngi s dng bm nt


Chp th kch hot Windows Navigation Start.wav, nu ngi s dng bm nt chp lin
tc (trong khi camera cha x l kp) th kch hot Windows Critical Stop.wav.
Nh vy mt cu hi t ra l lm sao ta bit c Camera ang x l chp hnh
cha hon tt? ta bit c iu ny v Camera c h tr cho chng ta thm 2 s kin
CaptureStarted v CaptureCompleted, thng qua 2 s kin ny ta s bit c khi no
Camera bt u cng on chp hnh v khi no kt thc qu trnh chp hnh.
Sau y l lp CameraViewModel c chnh sa:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Microsoft.Devices;

using System.Windows.Media;

using Microsoft.Xna.Framework.Media;

using System.Windows;

namespace LearnMultimedia_ViewModel.ViewModels

Trung Tm Tin Hc H KHTN-TP.HCM Trang 106


Gio trnh: Lp trnh Windows Phone

public class CameraViewModel : BaseViewModel, IDisposable

private PhotoCamera _camera;

private string _captureName;

private VideoBrush _tempBrush;

private VideoBrush _preview;

//khai bo thm bin i tng SoundEffects kch hot ng Sound File

private SoundEffects _effects;

//c nh du l Camera ang x l

private bool _isCapturing;

public VideoBrush Preview

get

return _preview;

private set

_preview = value;

NotifyPropertyChanged("Preview");

public CameraViewModel()

_camera = new PhotoCamera(CameraType.Primary);

_camera.Initialized += camera_Initialized;

_camera.CaptureImageAvailable += camera_CaptureImageAvailable;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 107


Gio trnh: Lp trnh Windows Phone

_tempBrush = new VideoBrush();

_tempBrush.SetSource(_camera);

//khi to i tng SoundEffects

_effects = new SoundEffects();

//gn thm s kin lng nghe khi no Camera bt u chp hnh

_camera.CaptureStarted += _camera_CaptureStarted;

//gn thm s kin lng nghe khi no Camera chp hnh xong

_camera.CaptureCompleted += _camera_CaptureCompleted;

public void Dispose()

_camera.Initialized -= camera_Initialized;

_camera.CaptureImageAvailable -= camera_CaptureImageAvailable;

//hy lnh ng ky cc s kin

_camera.CaptureStarted -= _camera_CaptureStarted;

_camera.CaptureCompleted -= _camera_CaptureCompleted;

_camera.Dispose();

_camera = null;

_tempBrush = null;

this.Preview = null;

_effects = null;

//nh du cho c _isCapturing=false khi hon thnh xong qu trnh chp hnh

void _camera_CaptureCompleted(object sender, CameraOperationCompletedEventArgs


e)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 108


Gio trnh: Lp trnh Windows Phone

_isCapturing = false;

//bt u chp th cho _isCapturing =true

void _camera_CaptureStarted(object sender, EventArgs e)

_isCapturing = true;

void camera_Initialized(object sender, CameraOperationCompletedEventArgs e)

if (e.Succeeded)

Deployment.Current.Dispatcher.BeginInvoke(() =>

this.Preview = _tempBrush;

});

else

//nu tht bi th pht nhc bo li

_effects.Play(EffectTypes.Error);

public void Capture(string fileName)

if (!_isCapturing)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 109


Gio trnh: Lp trnh Windows Phone

_captureName = fileName;

_camera.CaptureImage();

//bt u bm nt chp hnh th pht nhc chp hnh

_effects.Play(EffectTypes.Click);

else

//nu ang chp cha xong m bm nt chp lin tc th bo li

_effects.Play(EffectTypes.Error);

void camera_CaptureImageAvailable(object sender, ContentReadyEventArgs e)

MediaLibrary library = new MediaLibrary();

library.SavePictureToCameraRoll(_captureName, e.ImageStream);

Nh vy bn hon thnh xong cch s dng camera chp hnh nh, cch
a m thanh vo trong qu trnh chp, chc nng ny rt hay bn c th p dng vo
nhiu trng hp khc nhau khi lm d n.

5. To Camera Focus

Thng th Camera h tr chng ta chc nng Focus vo mt i tng hay mt


vng no trong qu trnh chng s dng.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 110


Gio trnh: Lp trnh Windows Phone

Ta s dng thuc tnh IsFocusSupported, IsFocusAtPointSupported ca


PhotoCamera kim tra xem camera c h tr Focus hay khng. Dng phng thc
Focus() v FocusAtPoint() thit lp focus. Khi qu trnh Focus hon thnh th n s
t ng xut hin s kin AutoFocusCompleted, dng s kin ny ta x l nhiu kt
qu.
Trong phn ny gio trnh s hng dn cc bn 2 cch Focus l: Nhn na
phm chp, v nhn ngn tay vo v tr bt k trn mn hnh thit lp Focus cho Camera.
Tip tc vi Project trn, ta tin hnh thit lp Camera Focus theo cc bc sau:

Bc 1: To th mc Images nm bn trong th mc Assets, to th mc


Converters nm cng cp vi th mc Assets.
Bc 2: To khung hnh v Focus, ta nn dng hnh trong sut (.png), bn
nn cho kch thc va phi, tt nht l theo kch thc chun focus l 48x48,
lu vo Assets/Images/focus_bracket.png.

Bc 3: To lp BoolToVisibilityConverter nm bn trong th mc
Converters t ng thit lp cho khung focus bracket hin th hay n ng
thi im.

using System;

using System.Collections.Generic;

using System.Linq;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 111


Gio trnh: Lp trnh Windows Phone

using System.Text;

using System.Threading.Tasks;

using System.Windows.Data;

using System.Windows;

namespace LearnMultimedia_ViewModel.Converters

public class BoolToVisibilityConverter : IValueConverter

public object Convert(object value, Type targetType,

object parameter, System.Globalization.CultureInfo culture)

return (bool)value ? Visibility.Visible : Visibility.Collapsed;

public object ConvertBack(object value, Type targetType,

object parameter, System.Globalization.CultureInfo culture)

return ((Visibility)value) == Visibility.Visible;

Bc 4: Thay i giao din, c th thay layout t Grid thnh Canvas ta c


th d dng di chuyn hnh Focus theo ta ty thch:

<phone:PhoneApplicationPage

Trung Tm Tin Hc H KHTN-TP.HCM Trang 112


Gio trnh: Lp trnh Windows Phone

x:Class="LearnMultimedia_ViewModel.CameraFocusPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

xmlns:converters="clr-namespace:LearnMultimedia_ViewModel.Converters"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Landscape" Orientation="Landscape"

shell:SystemTray.IsVisible="False">

<phone:PhoneApplicationPage.Resources>

<converters:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />

</phone:PhoneApplicationPage.Resources>

<Canvas x:Name="LayoutRoot" Background="{Binding Preview}"


Tap="LayoutRoot_Tap_1">

<Canvas.Children>

<Image Name="FocusBrackets" Height="150" Width="200" Stretch="Fill"

Source="/Assets/Images/focus_bracket.png"

Visibility="{Binding IsFocusing,Converter={StaticResource
BoolToVisibilityConverter}}">

</Image>

</Canvas.Children>

</Canvas>

</phone:PhoneApplicationPage>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 113


Gio trnh: Lp trnh Windows Phone

Bc 5: Tin hnh chnh sa lp CameraViewModel h tr t ng Focus


Bc 5.1: Thm thuc tnh IsFocusing cho CameraViewModel

private bool _isFocusing = false;

public bool IsFocusing

get

return _isFocusing;

set

_isFocusing = value;

NotifyPropertyChanged("IsFocusing");

Bc 5.2: Thm s kin AutoFocusCompleted

public CameraViewModel()

_camera.AutoFocusCompleted += _camera_AutoFocusCompleted;

public void Dispose()

_camera.AutoFocusCompleted -= _camera_AutoFocusCompleted;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 114


Gio trnh: Lp trnh Windows Phone

void _camera_AutoFocusCompleted(object sender, CameraOperationCompletedEventArgs


e)

Deployment.Current.Dispatcher.BeginInvoke(() =>

this.IsFocusing = false;

});

Bc 5.3: Thm hm Focus hin th Focus bracket khi ngi s dng


bm na phm chp:

public void Focus()

if ((_camera.IsFocusSupported) && (!_isCapturing))

Deployment.Current.Dispatcher.BeginInvoke(() =>

this.IsFocusing = true;

});

_camera.Focus();

Bc 5.4: Thm hm FocusAtPoint khi ngi s dng nhn ngn tay trn
mn hnh:

public void FocusAtPoint(double x, double y)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 115


Gio trnh: Lp trnh Windows Phone

if ((_camera.IsFocusAtPointSupported) && (!_isCapturing))

Deployment.Current.Dispatcher.BeginInvoke(() =>

this.IsFocusing = true;

});

_camera.FocusAtPoint(x, y);

Bc 6: Thm s kin bm na nt chp v s kin chm ln mn hnh chnh:

protected override void


OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{

CameraButtons.ShutterKeyHalfPressed += CameraButtons_ShutterKeyHalfPressed;
}
protected override void OnNavigatedFrom
(System.Windows.Navigation.NavigationEventArgs e)
{

CameraButtons.ShutterKeyHalfPressed -= CameraButtons_ShutterKeyHalfPressed;
base.OnNavigatedFrom(e);
}
void CameraButtons_ShutterKeyHalfPressed(object sender, EventArgs e)
{
// place "focus brackets" graphic at screen center.
Canvas.SetLeft(this.FocusBrackets,
LayoutRoot.ActualWidth / 2 - (this.FocusBrackets.ActualWidth / 2));
Canvas.SetTop(this.FocusBrackets,
LayoutRoot.ActualHeight / 2 - (this.FocusBrackets.ActualHeight / 2));
_vm.Focus();
}

private void LayoutRoot_Tap_1(object sender,


System.Windows.Input.GestureEventArgs e)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 116


Gio trnh: Lp trnh Windows Phone

{
if (!_vm.IsFocusing)
{
System.Windows.Point point = e.GetPosition(this.LayoutRoot);
double x = point.X / this.LayoutRoot.ActualWidth;
double y = point.Y / this.LayoutRoot.ActualHeight;
Dispatcher.BeginInvoke(() =>
{
Canvas.SetLeft(this.FocusBrackets, point.X - (this.FocusBrackets.ActualWidth
/ 2));
Canvas.SetTop(this.FocusBrackets, point.Y - (this.FocusBrackets.ActualHeight
/ 2));
});
_vm.FocusAtPoint(x, y);
}
}

Nh vy bn bit cch to Focus khi s dng Camera, trung tm c source


code mu ti link sau: http://goo.gl/WLZwMV

II. Video
Trong phn ny gio trnh s hng dn cch s dng control MediaElement,
MediaPlayerLauncher, cc thao tc khi s dng Video (m, dng, tm dng, tt ting, di
chuyn, quay video).
Cc nh dng Media c h tr trong Windows Phone:

1. S dng MediaElement, MediaPlayerLauncher

MediaElement:
MediaElement l mt Windows Phone Control cho php chng ta xem Video
v Audio.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 117


Gio trnh: Lp trnh Windows Phone

S dng control ny rt n gin, ta ch cn thit lp source media l c th s


dng.

<phone:PhoneApplicationPage
x:Class="LearnMediaElement.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Landscape" Orientation="Landscape"
shell:SystemTray.IsVisible="True">
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<MediaElement x:Name="mymedia"
Source="/Assets/videos/ARCastMDISilverlightGridComputing_ch9.wmv"/>
</Grid>
</phone:PhoneApplicationPage>

Cu hnh thng s trn ca s Properties:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 118


Gio trnh: Lp trnh Windows Phone

Khi chy video:

MediaPlayerLauncher:
MediaPlayerLauncher l control rt hu dng, n mc nh c s dng trong
Windows Phone.
private void btnLaucher_Click(object sender, RoutedEventArgs e)

MediaPlayerLauncher player = new MediaPlayerLauncher();

player.Media = new
Uri("Assets/videos/ARCastMDISilverlightGridComputing_ch9.wmv", UriKind.Relative);

player.Location = MediaLocationType.Install;

player.Show();

Mn hnh sau khi chy thnh cng:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 119


Gio trnh: Lp trnh Windows Phone

Ch rng ta s dng MediaLocationType.Data khi media files c lu tr


trong isolated storage. dng MediaLocationType.Install khi media files l mt phn
ca ng dng. Media files c lu tr trong .xap file v c ci t trc tip vo
ng dng. Ta cng c th m video t internet.

2. Cc thao tc thng dng khi s dng Video

Phn ny s ni cc chc nng ca control MediaElement m ta thng s


dng, mediaPlayer c s dng di y l tn ca MediaElement trong ng dng
ca bn.
Play (m)
Phng thc Play cho php chy mt media file, nhng ch trc khi n
c kch hot th bn cn kim tra thit b c ang chy nn media file no khc hay
khng, ta cn xc nhn cho php chy media nu khng n s bo li.
private void btnPlay_Click(object sender, RoutedEventArgs e)

if (this.CanPlay())

mediaPlayer.Play();

private bool CanPlay()

Trung Tm Tin Hc H KHTN-TP.HCM Trang 120


Gio trnh: Lp trnh Windows Phone

bool canPlay = false;

FrameworkDispatcher.Update();

if (MediaPlayer.GameHasControl)

canPlay = true;

else

if (MessageBox.Show

("Is it ok to stop currently playing music and play our animal sounds?"

, "Can play our sounds?", MessageBoxButton.OKCancel) ==


MessageBoxResult.OK)

canPlay = true;

MediaPlayer.Pause();

else

canPlay = false;

return canPlay;

Stop (dng)
ngng m media, ta gi phng thc Stop nh di y:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 121


Gio trnh: Lp trnh Windows Phone

private void btnStop_Click(object sender, RoutedEventArgs e)

mediaPlayer.Stop();

mediaPlayer.Position = System.TimeSpan.FromSeconds(0);

lblStatus.Text = "Stopped";

Pause (tm dng)


tm dng ta cn kim tra media ang m c cho php tm ngng hay khng
sau mi gi phng thc Pause()
private void btnPause_Click(object sender, RoutedEventArgs e)

if (mediaPlayer.CanPause)

mediaPlayer.Pause();

lblStatus.Text = "Paused";

else

lblStatus.Text = "Can not be Paused. Please try again!";

Mute (tt ting)


Trong qu trnh ang m media, i khi ta cn tt ting v nhng l do khc
nhau, v d nh ang nghe nhc m c ng nghip ti trao i cng vic, hay c
nhng ting ng khc ta cn ch lng nghe th chc nng tt ting cng hu dng.
tt ting ta cho IsMuted=true, m li ting ta cho IsMuted=false:
private void btnMute_Click(object sender, RoutedEventArgs e)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 122


Gio trnh: Lp trnh Windows Phone

if (lblSoundStatus.Text.Equals("Sound On",

StringComparison.CurrentCultureIgnoreCase))

lblSoundStatus.Text = "Sound Off";

mediaPlayer.IsMuted = true;

else

lblSoundStatus.Text = "Sound On";

mediaPlayer.IsMuted = false;

Seek (dch chuyn)


Khi ang m media th chc nng dch chuyn ti v tr bt k xem l rt
hay v quan trng, lm c iu ny ta lm nh sau:
Gi s trong giao din ta c Slider cho php ko di chuyn thi gian m
nh sau:
<Slider Height="84" HorizontalAlignment="Left"

Margin="13,423,0,0" Name="mediaTimeline"

VerticalAlignment="Top" Width="443"

ValueChanged="mediaTimeline_ValueChanged"

Maximum="1" LargeChange="0.1" />

S kin x l thay i thi gian pht, ta cn kim tra xem media cho php dch
chuyn:

private void mediaTimeline_ValueChanged(object sender,

Trung Tm Tin Hc H KHTN-TP.HCM Trang 123


Gio trnh: Lp trnh Windows Phone

RoutedPropertyChangedEventArgs<double> e)

if (mediaPlayer.CanSeek)

TimeSpan duration = mediaPlayer.NaturalDuration.TimeSpan;

int newPosition = (int)(duration.TotalSeconds * mediaTimeline.Value);

mediaPlayer.Position = new TimeSpan(0, 0, newPosition);

Quay video v Audio


Chc nng quay Video l mt trong nhng chc nng quan trng v thng
xuyn c s dng nht. bit cch quay c video ta to Project tn
LearnRecordVideo v thit lp Capabilities nh hnh chp di y:

MainPage.XAML n gin nh sau:

<phone:PhoneApplicationPage x:Name="mainpage"

x:Class="LearnRecordVideo.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Trung Tm Tin Hc H KHTN-TP.HCM Trang 124


Gio trnh: Lp trnh Windows Phone

xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Landscape" Orientation="Landscape"

shell:SystemTray.IsVisible="True" >

<Grid x:Name="LayoutRoot" Background="Transparent" Margin="0,-28,0,28">

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

<RowDefinition Height="*"/>

</Grid.RowDefinitions>

<TextBlock Name="lblTitle"></TextBlock>

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="10"

Width="800" Height="480">

<MediaElement x:Name="VideoPlayer" Stretch="Fill"

MediaEnded="VideoPlayer_MediaEnded" Width="800" Height="480" />

</Grid>

</phone:PhoneApplicationPage>

Sau ta tin hnh vit coding behind cho ng dng, trc tin ta cn s dng
cc th vin di y h tr quay video vi m thanh i km:
using System.Windows.Media;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 125


Gio trnh: Lp trnh Windows Phone

using System.IO;

using System.IO.IsolatedStorage;

using Microsoft.Xna.Framework.Media;

Gio trnh lit k cc hm s vit trong ng dng nh di y chng ta d


dng tng qut ha cch thc lp trnh cho phn ny:
public partial class MainPage : PhoneApplicationPage
{
private const string path = "capture.mp4";
private enum CaptureState { Preview, Record, Playback };
private CaptureSource _captureSource;
private VideoBrush _videoBrush;
private FileSink _fileSink;
private CaptureState _captureState;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
}
void MainPage_Tap(object sender, GestureEventArgs e) { }
void VideoPlayer_MediaEnded(object sender, RoutedEventArgs e) { }
private void RunStateMethod() { }
private void Preview() { }
private void Record() { }
private void Playback() { }
}

Coding trn c th c gi gn li trong 3 bc di y:

Bc 1: Ch xem trc

Trung Tm Tin Hc H KHTN-TP.HCM Trang 126


Gio trnh: Lp trnh Windows Phone

quay Video v Audio ta s dng i tng CaptureSource trong th vin


System.Windows.Media, sau ta cn gn AudioCaptureDevice v
VideoCaptureDevice cho i tng ny. Thng th khi khi to ta nn trong hm
OnNavigatedTo, cn khi hy khng s dng th ta trong OnNavigatedFrom.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
//to i tng CaptureSource
_captureSource = new CaptureSource();
// create CaptureSource with default audio and video
//Thit lp thuc tnh mc nh quay video v m thanh
_captureSource.VideoCaptureDevice
=CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
_captureSource.AudioCaptureDevice
=CaptureDeviceConfiguration.GetDefaultAudioCaptureDevice();
//to VideoBrush s dng i tng CaptureSource nh l source
_videoBrush = new VideoBrush();
_fileSink = new FileSink();
//lu ng dn ghi m
_fileSink.IsolatedStorageFileName = path;
//s kin chm ngn tay nn mn hnh chnh
this.Tap += new
EventHandler<System.Windows.Input.GestureEventArgs>(Mainpage_Tap);
//cho enum l Preview ch xem trc khi mi khi ng ng dng
_captureState = CaptureState.Preview;
//dng a tin trnh kch hot cc phng thc: Xem trc, quay, pht li
Deployment.Current.Dispatcher.BeginInvoke(()=>
{
RunStateMethod();
}
);
}
private void RunStateMethod() {

Trung Tm Tin Hc H KHTN-TP.HCM Trang 127


Gio trnh: Lp trnh Windows Phone

// display the state


lblTitle.Text = _captureState.ToString();
// run the appropriate method
switch (_captureState) {
case CaptureState.Preview: { Preview(); break; }
case CaptureState.Record: { Record(); break; }
case CaptureState.Playback: { Playback(); break; }
}
}
private void Preview()
{
VideoPlayer.Stop();
VideoPlayer.Source = null;
// stop any previous captures
_captureSource.Stop();
_videoBrush.SetSource(_captureSource);
// assign the VideoBrush to the background and start the capture
//this.ContentPanel.Background = _videoBrush;
recordvideo.Background = _videoBrush;
_captureSource.Start();
}

Sau khi khng cn s dng th ta phi hy trong hm OnNavigatedFrom nh


sau:
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
this.Tap -= new
EventHandler<System.Windows.Input.GestureEventArgs>(Mainpage_Tap);
_captureSource = null;
_videoBrush = null;
_fileSink = null;
base.OnNavigatedFrom(e);
}

Bc 2: Ch quay

Trung Tm Tin Hc H KHTN-TP.HCM Trang 128


Gio trnh: Lp trnh Windows Phone

ch quay ny ta s dng i tng FileSink lu d liu cho


CaptureSource, cc bc chi tit nh sau:
Bc 2.1: Ngng i tng CaptureSource bng phng thc Stop c th
s dng c FileSink.
Bc 2.2: To mt file trong isolated storage, ch ui l .mp4 ri ng
file ny.
Bc 2.3: To FileSink v thit lp thuc tnh CaptureSource ca FileSink
ti i tng CaptureSource ang ch Stop
Bc 2.4: Gi phng thc Start bng u ghi video v audio vo isolated
Storage

private void Record()

_captureSource.Stop();

using (IsolatedStorageFile store =

IsolatedStorageFile.GetUserStoreForApplication())

store.CreateFile(path).Close();

_fileSink.CaptureSource = _captureSource;

_captureSource.Start();

Bc 3: Ch pht li

S dng i tng MediaElement pht li video v audio c lu tr


trong Isolated Storage, c th:
Bc 3.1: u tin ta cn ngng vic ghi video v audio bng cch gi hm
Stop()
Bc 3.2: Kim tra tra s tn ti ca file c thnh
IsolatedStorageFileStream
Bc 3.3: Gn IsolatedStorageFileStream cho MediaElement
Bc 3.4: Gi phng thc Play() ca i tng MediaElement

Trung Tm Tin Hc H KHTN-TP.HCM Trang 129


Gio trnh: Lp trnh Windows Phone

private void Playback()

_captureSource.Stop();

IsolatedStorageFile store =IsolatedStorageFile.GetUserStoreForApplication();

if (store.FileExists(path))

IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(path,

FileMode.Open, FileAccess.Read, store);

VideoPlayer.SetSource(isoStream);

VideoPlayer.MediaEnded += new
RoutedEventHandler(VideoPlayer_MediaEnded);

VideoPlayer.Play();

III. Audio
Chc nng Audio gip ta x l vi file m thanh Audio mt cch uyn chuyn,
trong gii hn ca gio trnh s trnh by cch chn m thanh vo ng dng, cch thit
lp chy nn Audio cng nh chc nng ghi m v c audio.
1. Thm m thanh vo ng dng

phn trc bn dng MediaElement m Video, nhng ta cng c th


dng n m v to Audio file trong ng dng.
Ta to mt project tn LearnAudio nh hnh di y:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 130


Gio trnh: Lp trnh Windows Phone

Project ta a mt sound file vi nh dng wma vo th mc sound.

Giao din n gin nh sau:


<phone:PhoneApplicationPage

x:Class="LearnAudio.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Portrait" Orientation="Portrait"

shell:SystemTray.IsVisible="True">

<Grid x:Name="LayoutRoot" Background="Transparent">

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 131


Gio trnh: Lp trnh Windows Phone

<RowDefinition Height="*"/>

</Grid.RowDefinitions>

<MediaElement x:Name="mymedia" Height="100"

VerticalAlignment="Bottom" Margin="176,0,204,69"

Source="/Assets/sound/BachCPE_SonataAmin_1.wma" AutoPlay="False"/>

<Button x:Name="btnPlay" Content="Play" HorizontalAlignment="Left"


Margin="127,144,0,0" Grid.Row="1" VerticalAlignment="Top" Click="btnPlay_Click"/>

</Grid>

</phone:PhoneApplicationPage>

Nh AutoPlay=False n khng t ng m khi chy ng dng.


ng thi s dng 2 th vin:
using Microsoft.Xna.Framework.Media;

using Microsoft.Xna.Framework;

Trc khi m c Audio ta phi kim tra xem thi im hin ti cho php
m hay khng, nu khng cho php thng bo li.
private void btnPlay_Click(object sender, RoutedEventArgs e)

if (CanPlay()) {

mymedia.Stop();

mymedia.Source = new
System.Uri("Assets/sound/BachCPE_SonataAmin_1.wma", System.UriKind.Relative);

mymedia.Play();

private bool CanPlay()

Trung Tm Tin Hc H KHTN-TP.HCM Trang 132


Gio trnh: Lp trnh Windows Phone

bool canPlay = false;

FrameworkDispatcher.Update();

if (MediaPlayer.GameHasControl)

canPlay = true;

else

if (MessageBox.Show("Is it ok to stop currently playing music?", "Can stop


music?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)

canPlay = true;

MediaPlayer.Pause();

else {

canPlay = false;

return canPlay;

2. Thit lp chy nn Audio

thit lp cho php Audio chy nn (cho d ng dng ca bn khng trong


ch foreground th n cng t ng play audio) th gii php t ra l ta to Windows
Phone Audio Playback Agent ri tham chiu ti Main App project.
Windows Phone APIs h tr 2 loi chy nn Audio, c 2 loi ny u s dng
th vin Microsoft.Phone.BackgroundAudio:
AudioPlayerAgent:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 133


Gio trnh: Lp trnh Windows Phone

Khi dng Agent ny play Audio th n c th chy nn Audio thm ch khi


ng dng ca chng ta khng vng i Foreground, mt s hm thng dng:

OnPlayStateChanged: Hm ny t ng kim tra s thay i trng thi


play, bao gm: buffering, playing, track ready, track ended, v shutdown.
OnUserAction: Hm ny s c triu gi khi ngi s dng tin hnh
nhng thao tc no trong Applications audio playlist vng i Foreground
(dng controls provider hoc Universal Volume Control)
OnError: Hm ny s c triu gi khi c li sy ra trong qu trnh audio
playback.

Kin trc AudioPlayerAgent

AudioStreamingAgent:

Khi dng Agent ny s to ra stream audio trong ng dng thng qua


MediaStreamSource, lp ny cung cp mt s hm sau:

OnBeginStreaming: Hm ny s c triu gi khi ta bt u Audio


Streaming

Trung Tm Tin Hc H KHTN-TP.HCM Trang 134


Gio trnh: Lp trnh Windows Phone

OnCancel: Hm ny s c triu gi khi Audio Stream b hy.

Kin trc AudioStreamingAgent

hiu r hn, gio trnh s hng dn chi tit tng bc to ra mt ng dng


c th chy nn Audio nh sau:

Bc 1: To ng dng Audio Background (gi s tn


MainApp_AudioBackground)

Trong th mc Assets to thm mt th mc Audio v thm mt vi sound file


vo.
Trong bi ny gio trnh a 3 file mp3 vo thc mc Sound, v ch l tt
c cc file ny ta phi chnh thuc tnh Copy to Output Directory=Copy If Newer
Ta xem hnh minh ha di y:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 135


Gio trnh: Lp trnh Windows Phone

Hiu chnh XAML trong MainPage.xaml nh sau:


<phone:PhoneApplicationPage

x:Class="MainApp_AudioBackground.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Portrait" Orientation="Portrait"

mc:Ignorable="d"

shell:SystemTray.IsVisible="True">

Trung Tm Tin Hc H KHTN-TP.HCM Trang 136


Gio trnh: Lp trnh Windows Phone

<!--LayoutRoot is the root grid where all page content is placed-->

<Grid x:Name="LayoutRoot" Background="Transparent">

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

<RowDefinition Height="*"/>

</Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->

<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">

<TextBlock x:Name="ApplicationTitle" Text="BACKGROUND AUDIO


PLAYER" Style="{StaticResource PhoneTextNormalStyle}"/>

<TextBlock x:Name="PageTitle" Text="play a song" Margin="9,-7,0,0"


Style="{StaticResource PhoneTextTitle1Style}"/>

</StackPanel>

<!--ContentPanel - place additional content here-->

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

<StackPanel Orientation="Horizontal" Width="420" Margin="18,40,18,0"


VerticalAlignment="Top">

<Button Content="prev" x:Name="prevButton" Height="140" Width="140"


Click="prevButton_Click" />

<Button Content="play" x:Name="playButton" Height="140" Width="140"


Click="playButton_Click" />

<Button Content="next" x:Name="nextButton" Height="140" Width="140"


Click="nextButton_Click" />

</StackPanel>

<TextBlock x:Name="txtCurrentTrack" Height="75" HorizontalAlignment="Left"


Margin="12,193,0,0" VerticalAlignment="Top" Width="438" TextWrapping="Wrap" />

Trung Tm Tin Hc H KHTN-TP.HCM Trang 137


Gio trnh: Lp trnh Windows Phone

</Grid>

</Grid>

</phone:PhoneApplicationPage>

T on XAML trn ta s c giao din chnh nh sau:

Ch ta cng phi cho php ID_CAP_MEDIALIB_AUDIO,


ID_CAP_MEDIALIB_PLAYBACK

Bc 2: Tin hnh hiu chnh Source coding ca MainPage.xaml.cs:


Bc 2.1: Thm th vin BackGroundAudio cho Mainpage.xaml.cs:

using Microsoft.Phone.BackgroundAudio;

Bc 2.2: Vit cc s kin cho Button v trc, m nhc, v sau:

private void prevButton_Click(object sender, RoutedEventArgs e)

BackgroundAudioPlayer.Instance.SkipPrevious();

private void playButton_Click(object sender, RoutedEventArgs e)

if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState)

BackgroundAudioPlayer.Instance.Pause();

Trung Tm Tin Hc H KHTN-TP.HCM Trang 138


Gio trnh: Lp trnh Windows Phone

else

BackgroundAudioPlayer.Instance.Play();

private void nextButton_Click(object sender, RoutedEventArgs e)

BackgroundAudioPlayer.Instance.SkipNext();

Bc 2.3: Tin hnh ng k s kin lng nghe s thay i trng thi m


nhc, trong Constructor ca MainPage ta sa li nh sau:

public MainPage()
{
InitializeComponent();
BackgroundAudioPlayer.Instance.PlayStateChanged += new
EventHandler(Instance_PlayStateChanged);
}
void Instance_PlayStateChanged(object sender, EventArgs e)
{
switch (BackgroundAudioPlayer.Instance.PlayerState)
{
case PlayState.Playing:
playButton.Content = "pause";
break;
case PlayState.Paused:
case PlayState.Stopped:
playButton.Content = "play";
break;
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 139


Gio trnh: Lp trnh Windows Phone

if (null != BackgroundAudioPlayer.Instance.Track)
{
txtCurrentTrack.Text = BackgroundAudioPlayer.Instance.Track.Title +
" by " + BackgroundAudioPlayer.Instance.Track.Artist;
}
}

Bc 2.4: V ng dng ca ta chy dng Audio Background nn phi x l


trng hp m li ng dng th phi tr li trng thi trc nh sau:

protected override void OnNavigatedTo(NavigationEventArgs e)

base.OnNavigatedTo(e);

if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState)

playButton.Content = "pause";

txtCurrentTrack.Text = BackgroundAudioPlayer.Instance.Track.Title +

" by " +

BackgroundAudioPlayer.Instance.Track.Artist;

else

playButton.Content = "play";

txtCurrentTrack.Text = "";

Bc 3: Tin hnh hiu chnh Source coding ca App.xaml.cs:


Bc 3.1: Thm cc th vin sau cho lp App:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 140


Gio trnh: Lp trnh Windows Phone

using System.IO.IsolatedStorage;

using System.Windows.Resources;

Bc 3.2: Bi v BackgroundAudioPlayer ch c th m c file t Isolated


storage hoc t remote URI nn ta vit lnh copy ton b audio files t th
mc ci t ti isolated storage:

private void CopyToIsolatedStorage()

using (IsolatedStorageFile storage =


IsolatedStorageFile.GetUserStoreForApplication())

string[] files = new string[] { "KhucThuyDu-TuanNgoc.mp3",


"RiengMotRocTroi-TuanNgoc.mp3", "TuThoAuNgamNgui-TuanNgoc.mp3" };

foreach (var _fileName in files)

if (!storage.FileExists(_fileName))

string _filePath = "Assets/Sound/" + _fileName;

StreamResourceInfo resource = Application.GetResourceStream(new


Uri(_filePath, UriKind.Relative));

using (IsolatedStorageFileStream file = storage.CreateFile(_fileName))

int chunkSize = 4096;

byte[] bytes = new byte[chunkSize];

int byteCount;

while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)

file.Write(bytes, 0, byteCount);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 141


Gio trnh: Lp trnh Windows Phone

Sau ta gi hm CopyToIsolatedStorage() dng cui cng trong


constructor App():
public App()

CopyToIsolatedStorage();

Bc 4: To Project Audio Playback Agent


Bm chut phi vo Project MainApp_AudioBackground/ chn Add/ New
Project:

Ca s to Project hin th ln ta chn loi Windows Phone Audio Playback


Agent, t tn project l MyAudioPlaybackAgent:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 142


Gio trnh: Lp trnh Windows Phone

Mn hnh sau khi thm Project mi:

Bc 5: Ta tin hnh tham chiu t MainApp_AudioBackground ti


MyAudioPlaybackAgent bng cch bm chut phi vo project chnh ri chn
add Reference:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 143


Gio trnh: Lp trnh Windows Phone

Sau khi chn Add Referenceth mn hnh Reference Manager hin th ra


nh di y, ta chn mc Project v tick vo ng MyAudioPlaybackAgent:

Bm Ok ta s c kt qu nh hnh di y:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 144


Gio trnh: Lp trnh Windows Phone

Ta quan st l lp AudioPlayer s t ng c pht sinh ra, by gi ta tin


hnh hiu chnh soure code ca n ng dng c th chy nn Audio c.

Bc 6: Thc hin Audio Player Agent

Ta tin hnh hiu chnh lp AudioPlayer nh sau:

Bc 6.1: Thm th vin sau vo lp:

using System.Collections.Generic;

Bc 6.2: Tin hnh khi to mt s bin kim sot v tr sound file ang
play cng nh danh sch lu tr cc sound file, y gio trnh a 2 loi
sound file : T isolated storage v remote URI:

// What's the current track?

static int currentTrackNumber = 0;

// A playlist made up of AudioTrack items.

private static List<AudioTrack> _playList = new List<AudioTrack>

new AudioTrack(new Uri("KhucThuyDu-TuanNgoc.mp3", UriKind.Relative),

"Nhc Trnh",

Trung Tm Tin Hc H KHTN-TP.HCM Trang 145


Gio trnh: Lp trnh Windows Phone

"Tun Ngc",

"Nhc trnh hay nht",

null),

new AudioTrack(new Uri("RiengMotRocTroi-TuanNgoc.mp3", UriKind.Relative),

"Nhc Trnh",

"Tun Ngc",

"Nhc trnh Vol3",

null),

new AudioTrack(new Uri("TuThoAuNgamNgui-TuanNgoc.mp3",


UriKind.Relative),

"Nhc Trnh",

"Tun Ngc",

"Nhc trnh Vol4",

null),

// A remote URI

new AudioTrack(new Uri("http://traffic.libsyn.com/wpradio/WPRadio_29.mp3",


UriKind.Absolute),

"Episode 29",

"Windows Phone Radio",

"Windows Phone Radio Podcast",

null)

};

Bc 6.3: Tin hnh thm 3 hm tr v u, v sau, m sound file:

private void PlayNextTrack(BackgroundAudioPlayer player)


{
if (++currentTrackNumber >= _playList.Count)
{

Trung Tm Tin Hc H KHTN-TP.HCM Trang 146


Gio trnh: Lp trnh Windows Phone

currentTrackNumber = 0;
}
PlayTrack(player);
}

private void PlayPreviousTrack(BackgroundAudioPlayer player)


{
if (--currentTrackNumber < 0)
{
currentTrackNumber = _playList.Count - 1;
}

PlayTrack(player);
}

private void PlayTrack(BackgroundAudioPlayer player)


{
if ((player.Track == null) || (player.Track.Title !=
_playList[currentTrackNumber].Title))
{
// If it's a new track, set the track
player.Track = _playList[currentTrackNumber];
}
// Play it
if ((player.Track != null) && (player.PlayerState != PlayState.Playing))
{
player.Play();
}
}

Bc 6.4: Tin hnh hiu chnh PlayState.TrackEnded trong hm


OnPlayStateChanged:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 147


Gio trnh: Lp trnh Windows Phone

protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack


track, PlayState playState)

switch (playState)

case PlayState.TrackEnded:

//player.Track = GetPreviousTrack();

PlayNextTrack(player);

break;

case PlayState.TrackReady:

player.Play();

break;

NotifyComplete();

Bc 6.5: tin hnh hiu chnh OnUserAction

protected override void OnUserAction(BackgroundAudioPlayer player, AudioTrack track,


UserAction action, object param)
{
switch (action)
{
case UserAction.Play:
PlayTrack(player);
break;
case UserAction.Stop:
player.Stop();
break;
case UserAction.Pause:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 148


Gio trnh: Lp trnh Windows Phone

player.Pause();
break;
case UserAction.FastForward:
player.FastForward();
break;
case UserAction.Rewind:
player.Rewind();
break;
case UserAction.Seek:
player.Position = (TimeSpan)param;
break;
case UserAction.SkipNext:
PlayNextTrack(player);
break;
case UserAction.SkipPrevious:
PlayPreviousTrack(player);
break;
}
NotifyComplete();
}

Nh vy ta hon thnh xong cc bc to ng dng c th chy c Audio


Background, bn ch cn lm ng cc bc nh trn l c th chy c.
Bn c th ti source code mu y: http://goo.gl/znB0Vo

Trung Tm Tin Hc H KHTN-TP.HCM Trang 149


Gio trnh: Lp trnh Windows Phone

BI 2. DRAWING
Windows Phone h tr hng lot cc lp th vin cho php v nhng hnh nh,
ng nt khc nhau: Ellipse, Line, Path, Polygon, Polyline, Rectangle, Shape;
cng vi cc loi i tng v mu p mt. Bng vic kt hp nhiu tnh nng khc
nhau gip lp trnh vin c th to ra cc ng dng Drawing uyn chuyn.
Ni dung ca phn ny s cp ti nhng phn sau:

I. Cc i tng v mu ph bin ...........................................................153


1. SolidColorBrush .............................................................................................. 154
2. LinearGradientBrush ...................................................................................... 156
3. RadialGradientBrush ...................................................................................... 162
4. ImageBrush ...................................................................................................... 164
II. Canvas .................................................................................................166
1. c tnh ca Canvas ........................................................................................ 166
2. Kt xut hnh nh t Canvas .......................................................................... 168
III. Cc loi i tng Shapes ...................................................................169
1. Ellipse ............................................................................................................... 169
2. Rectangle .......................................................................................................... 170
3. Line ................................................................................................................... 171
4. Polyline ............................................................................................................. 172
5. Polygon ............................................................................................................. 173
6. Path................................................................................................................... 173
IV. Kt lun ...............................................................................................174

I. Cc i tng v mu ph bin
Windows Phone cung cp hng lot cng c Brush gip lp trnh vin thit k
ng dng c th pha trn cc bng mu mt cch c sc, cc Brush ny cho php ta
t mu ch Design hoc Runtime. Cc brush c cung cp bao gm :

Khoa Cng Ngh Thng Tin Trang 153/617


Gio trnh: Lp trnh Windows Phone

SolidColorBrush, LinearGradientBrush, RadialGradientBrush, ImageBrush mi


loi c nhng cng dng khc nhau:

M hnh k tha trong Bush

Tt c cc Brush u nm trong th vin System.Windows.Media

So snh bng mu khi s dng Brush

Sau y ta s i vo tng loi Brush c th:


1. SolidColorBrush

Cng c Brush ny cho php ta t 1 mu ng nht, ta c th dng cc cch t


mu sau: S dng mu c nh sn, s dng k hiu thp lc phn, s dng cc gi
tr ARGB. Ta c th t mu trong XAML hoc coding behind.

Khoa Cng Ngh Thng Tin Trang 154/617


Gio trnh: Lp trnh Windows Phone

S dng mu c nh sn:
Trong XAML:

<Rectangle Width="50" Height="50" Fill="Blue" />

Trong Coding behind:


Rectangle myPredefinedBrushRectangle = new Rectangle();
myPredefinedBrushRectangle.Width = 50;
myPredefinedBrushRectangle.Height = 50;
myPredefinedBrushRectangle.Fill = Brushes.Blue;

S dng k hiu thp lc phn:


Trong XAML:
<!-- Note that the first two characters "FF" of the 8-digit

value is the alpha which controls the transparency of

the color. Therefore, to make a completely transparent

color (invisible), use "00" for those digits (e.g. #000000FF). -->

<Rectangle Width="50" Height="50" Fill="#FF0000FF" />

S dng cc gi tr ARGB:
Trong XAML:

<Rectangle Width="50" Height="50">

<Rectangle.Fill>

<SolidColorBrush>

<SolidColorBrush.Color>

<!-- Describes the brush's color using

RGB values. Each value has a range of 0-255.

R is for red, G is for green, and B is for blue.

A is for alpha which controls transparency of the

color. Therefore, to make a completely transparent

color (invisible), use a value of 0 for Alpha. -->

<Color A="255" R="0" G="0" B="255" />

Khoa Cng Ngh Thng Tin Trang 155/617


Gio trnh: Lp trnh Windows Phone

</SolidColorBrush.Color>

</SolidColorBrush>

</Rectangle.Fill>

</Rectangle>

Trong Coding behind:


Rectangle myRgbRectangle = new Rectangle();

myRgbRectangle.Width = 50;

myRgbRectangle.Height = 50;

SolidColorBrush mySolidColorBrush = new SolidColorBrush();

// Describes the brush's color using RGB values.

// Each value has a range of 0-255.

mySolidColorBrush.Color = Color.FromArgb(255, 0, 0, 255);

myRgbRectangle.Fill = mySolidColorBrush;

2. LinearGradientBrush

Brush ny cho php phi mu tuyn tin, ta c ty chnh phi mu gip giao
din thm c sc v p mt.
iu quan trng cn ch l s nh v ta ca i tng khi s dng Brush
ny nh th no? Ta cn bit rng n s khng quan tm ti kch thc ca i tng,
mc nh gc tri trn cng c ta l (0,0) v gc phi di cng c ta l (1,1).
Tc l cho d i tng c kch thc khc nhau th u c nh v ta v mu l (0,0)
v (1,1).
V d nu bn c 1 Button c kch thc l WIDTH=100, HEIGHT =50 v 1
TextBox c kch thc l WIDTH=200, HEIGHT=80 th s nh v ta v mu
l hon ton ging nhau, chng u ly gc tri trn cng l (0,0) v gc phi di
cng l (1,1).

Khoa Cng Ngh Thng Tin Trang 156/617


Gio trnh: Lp trnh Windows Phone

Hnh nh v ta v mu

phi nhiu mu trong Brush ny ta dng Gradient Stop, hnh di y l


minh ha cho s phi mu ny:

Ta s xem qua 3 v d di y bit c cch s dng bng mu ny:


V d 1: Phi hp mu theo hiu ng cho

v c hnh trn ta s phi phi hp cc loi mu tng ng, i vi lp


trnh vin th ta phi bit c c cch dng XAML v Coding behind. Quan st k th
ta phi to mt loi mu tng hp chuyn i t mu vng (yellow) ti mu (red)
ti mu xanh m (blue) ti mu xanh l cy (lime green).

Khoa Cng Ngh Thng Tin Trang 157/617


Gio trnh: Lp trnh Windows Phone

Cch to trong XAML


<!-- This rectangle is painted with a diagonal linear gradient. -->

<Rectangle Width="200" Height="100">

<Rectangle.Fill>

<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">

<GradientStop Color="Yellow" Offset="0.0" />

<GradientStop Color="Red" Offset="0.25" />

<GradientStop Color="Blue" Offset="0.75" />

<GradientStop Color="LimeGreen" Offset="1.0" />

</LinearGradientBrush>

</Rectangle.Fill>

</Rectangle>

Cch to trong coding behind


Rectangle diagonalFillRectangle = new Rectangle();

diagonalFillRectangle.Width = 200;

diagonalFillRectangle.Height = 100;

// Create a diagonal linear gradient with four stops.

LinearGradientBrush myLinearGradientBrush =

new LinearGradientBrush();

myLinearGradientBrush.StartPoint = new Point(0,0);

myLinearGradientBrush.EndPoint = new Point(1,1);

myLinearGradientBrush.GradientStops.Add(

new GradientStop(Colors.Yellow, 0.0));

myLinearGradientBrush.GradientStops.Add(

new GradientStop(Colors.Red, 0.25));

myLinearGradientBrush.GradientStops.Add(

Khoa Cng Ngh Thng Tin Trang 158/617


Gio trnh: Lp trnh Windows Phone

new GradientStop(Colors.Blue, 0.75));

myLinearGradientBrush.GradientStops.Add(

new GradientStop(Colors.LimeGreen, 1.0));

// Use the brush to paint the rectangle.

diagonalFillRectangle.Fill = myLinearGradientBrush;

V d 2: Phi hp mu theo hiu ng ngang

Cch to trong XAML


<!-- This rectangle is painted with a horizontal linear gradient. -->

<Rectangle Width="200" Height="100">

<Rectangle.Fill>

<LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">

<GradientStop Color="Yellow" Offset="0.0" />

<GradientStop Color="Red" Offset="0.25" />

<GradientStop Color="Blue" Offset="0.75" />

<GradientStop Color="LimeGreen" Offset="1.0" />

</LinearGradientBrush>

</Rectangle.Fill>

</Rectangle>

Cch to trong Coding behind

Rectangle horizontalFillRectangle = new Rectangle();

horizontalFillRectangle.Width = 200;

Khoa Cng Ngh Thng Tin Trang 159/617


Gio trnh: Lp trnh Windows Phone

horizontalFillRectangle.Height = 100;

// Create a horizontal linear gradient with four stops.

LinearGradientBrush myHorizontalGradient =

new LinearGradientBrush();

myHorizontalGradient.StartPoint = new Point(0,0.5);

myHorizontalGradient.EndPoint = new Point(1,0.5);

myHorizontalGradient.GradientStops.Add(

new GradientStop(Colors.Yellow, 0.0));

myHorizontalGradient.GradientStops.Add(

new GradientStop(Colors.Red, 0.25));

myHorizontalGradient.GradientStops.Add(

new GradientStop(Colors.Blue, 0.75));

myHorizontalGradient.GradientStops.Add(

new GradientStop(Colors.LimeGreen, 1.0));

// Use the brush to paint the rectangle.

horizontalFillRectangle.Fill = myHorizontalGradient;

V d 3: Phi hp mu theo hiu ng dc

Cch to trong XAML


<!-- This rectangle is painted with a vertical gradient. -->

<Rectangle Width="200" Height="100">

Khoa Cng Ngh Thng Tin Trang 160/617


Gio trnh: Lp trnh Windows Phone

<Rectangle.Fill>

<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">

<GradientStop Color="Yellow" Offset="0.0" />

<GradientStop Color="Red" Offset="0.25" />

<GradientStop Color="Blue" Offset="0.75" />

<GradientStop Color="LimeGreen" Offset="1.0" />

</LinearGradientBrush>

</Rectangle.Fill>

</Rectangle>

Cch to trong Coding behind


Rectangle verticalFillRectangle = new Rectangle();

verticalFillRectangle.Width = 200;

verticalFillRectangle.Height = 100;

// Create a vertical linear gradient with four stops.

LinearGradientBrush myVerticalGradient =

new LinearGradientBrush();

myVerticalGradient.StartPoint = new Point(0.5,0);

myVerticalGradient.EndPoint = new Point(0.5,1);

myVerticalGradient.GradientStops.Add(

new GradientStop(Colors.Yellow, 0.0));

myVerticalGradient.GradientStops.Add(

new GradientStop(Colors.Red, 0.25));

myVerticalGradient.GradientStops.Add(

new GradientStop(Colors.Blue, 0.75));

myVerticalGradient.GradientStops.Add(

new GradientStop(Colors.LimeGreen, 1.0));

Khoa Cng Ngh Thng Tin Trang 161/617


Gio trnh: Lp trnh Windows Phone

// Use the brush to paint the rectangle.

verticalFillRectangle.Fill = myVerticalGradient;

3. RadialGradientBrush

RadialGradientBrush c tnh nng tng t nh LinearGradientBrush. Tuy


nhin Linear Gradient c 1 im u v 1 im cui xc nh hng Gradient, cn
Radial Gradient c bn trong c mt vng trn lm tiu im.

V d v hnh di y ta lm nh sau:

Cch to trong XAML


<!-- This rectangle is painted with a radial gradient. -->

<Rectangle Width="200" Height="100">

<Rectangle.Fill>

<RadialGradientBrush

GradientOrigin="0.5,0.5"

Center="0.5,0.5" RadiusX="0.5" RadiusY="0.5">

<RadialGradientBrush.GradientStops>

Khoa Cng Ngh Thng Tin Trang 162/617


Gio trnh: Lp trnh Windows Phone

<GradientStop Color="Yellow" Offset="0" />

<GradientStop Color="Red" Offset="0.25" />

<GradientStop Color="Blue" Offset="0.75" />

<GradientStop Color="LimeGreen" Offset="1" />

</RadialGradientBrush.GradientStops>

</RadialGradientBrush>

</Rectangle.Fill>

</Rectangle>

Cch to trong Coding behind


RadialGradientBrush radialGradient = new RadialGradientBrush();

// Set the GradientOrigin to the center of the area being painted.

radialGradient.GradientOrigin = new Point(0.5, 0.5);

// Set the gradient center to the center of the area being painted.

radialGradient.Center = new Point(0.5, 0.5);

// Set the radius of the gradient circle so that it extends to

// the edges of the area being painted.

radialGradient.RadiusX = 0.5;

radialGradient.RadiusY = 0.5;

// Create four gradient stops.

radialGradient.GradientStops.Add(new GradientStop(Colors.Yellow, 0.0));

radialGradient.GradientStops.Add(new GradientStop(Colors.Red, 0.25));

radialGradient.GradientStops.Add(new GradientStop(Colors.Blue, 0.75));

Khoa Cng Ngh Thng Tin Trang 163/617


Gio trnh: Lp trnh Windows Phone

radialGradient.GradientStops.Add(new GradientStop(Colors.LimeGreen, 1.0));

// Freeze the brush (make it unmodifiable) for performance benefits.

radialGradient.Freeze();

// Create a rectangle and paint it with the

// RadialGradientBrush.

Rectangle aRectangle = new Rectangle();

aRectangle.Width = 200;

aRectangle.Height = 100;

aRectangle.Fill = radialGradient;

Nh vy thay i tiu im ta c th thay i gi tr trong GradientOrigin.

4. ImageBrush

Dng ImageBrush hin th hnh nh ln UIElement.

S dng ImageResource thit lp hnh nh cho ImageBrush. Mc nh hnh


nh s hin th y khung cha, ta c th hiu chnh thuc tnh Stretch qua
TileBrush, Uniform hoc UniformToFill.
Nu ta thit lp Viewport v TileMode properties cho ImageBrush th ta c th
to ra nhng mu lp li nh hnh trn.

Khoa Cng Ngh Thng Tin Trang 164/617


Gio trnh: Lp trnh Windows Phone

Cch to trong XAML


<Button

Foreground="White" FontWeight="Bold"

FontSize="16pt" FontFamily="Verdana"

Content="Berries"

Padding="20"

HorizontalAlignment="Left">

<Button.Background>

<!-- The ImageBrush's Viewport and TileMode

are set to produce a pattern from the

image. -->

<ImageBrush

Viewport="0,0,0.5,0.5"

TileMode="FlipXY"

ImageSource="sampleImages\berries.jpg" />

</Button.Background>

</Button>

Cch to trong Coding behind


// Create a button.

Button berriesButton = new Button();

berriesButton.Foreground = Brushes.White;

berriesButton.FontWeight = FontWeights.Bold;

FontSizeConverter sizeConverter = new FontSizeConverter();

berriesButton.FontSize = (Double)sizeConverter.ConvertFromString("16pt");

berriesButton.FontFamily = new FontFamily("Verdana");

berriesButton.Content = "Berries";

Khoa Cng Ngh Thng Tin Trang 165/617


Gio trnh: Lp trnh Windows Phone

berriesButton.Padding = new Thickness(20.0);

berriesButton.HorizontalAlignment = HorizontalAlignment.Left;

// Create an ImageBrush.

ImageBrush berriesBrush = new ImageBrush();

berriesBrush.ImageSource =

new BitmapImage( new Uri(@"sampleImages\berries.jpg", UriKind.Relative) );

// Set the ImageBrush's Viewport and TileMode

// so that it produces a pattern from

// the image.

berriesBrush.Viewport = new Rect(0,0,0.5,0.5);

berriesBrush.TileMode = TileMode.FlipXY;

// Use the brush to paint the button's background.

berriesButton.Background = berriesBrush;

II. Canvas
1. c tnh ca Canvas

Canvas l mt loi panel cho php ta nh v cc i tng trong n theo ta


ty thch.

Khoa Cng Ngh Thng Tin Trang 166/617


Gio trnh: Lp trnh Windows Phone

<Canvas Background="Transparent">

<Rectangle Canvas.Left="30" Canvas.Top="200"

Fill="red" Width="200" Height="200" />

</Canvas>

Nh vy ta mun thay i v tr th dng attach property syntax hoc vit bng


coding behind thng qua h SetLeft, SetTop, V d di chuyn i tng bt k nm
bn trong Canvas ta lm nh sau:
// Create the Canvas

myParentCanvas = new Canvas();

myParentCanvas.Width = 400;

myParentCanvas.Height = 400;

// Define child Canvas elements

myCanvas1 = new Canvas();

Khoa Cng Ngh Thng Tin Trang 167/617


Gio trnh: Lp trnh Windows Phone

myCanvas1.Background = Brushes.Red;

myCanvas1.Height = 200;

myCanvas1.Width = 200;

Canvas.SetTop(myCanvas1, 200);

Canvas.SetLeft(myCanvas1, 30);

2. Kt xut hnh nh t Canvas

Ta c th kt xut hnh nh t Canvas thng qua cch sau:


<Canvas x:Name="drawCanvas"

Background="White" Margin="0,0,0,60">

</Canvas>

using Microsoft.Xna.Framework.Media;

using System.Windows.Media.Imaging;

using System.IO;

using System.Windows.Media;

private void Save_Click(object sender, RoutedEventArgs e)

MediaLibrary library = new MediaLibrary();

WriteableBitmap bitMap = new WriteableBitmap(drawCanvas, null);

MemoryStream ms = new MemoryStream();

Extensions.SaveJpeg(bitMap, ms, bitMap.PixelWidth,

bitMap.PixelHeight, 0, 100);

ms.Seek(0, SeekOrigin.Begin);

library.SavePicture(string.Format("Images\\{0}.jpg",

Guid.NewGuid()), ms);

Khoa Cng Ngh Thng Tin Trang 168/617


Gio trnh: Lp trnh Windows Phone

III. Cc loi i tng Shapes


Windows Phone cung cp mt tp hp cc lp c th v c cc biu tng,
hnh nh ln giao din, cc lp ny bao gm: Ellipse, Rectangle, Line, Polyline,
Polygon, Path. Tng ng vi mi lp s c cc im hin th khc nhau, tt c cc
lp ny c th kt hp c vi SolidColorBrush, LinearGradientBrush,
RadialGradientBrush v ImageBrush.
s dng c cc lp ny th trong ng dng bn phi s dng 2 th vin sau:
using System.Windows.Shapes;

using System.Windows.Media;

1. Ellipse

to mt Ellipse n gin th ta thit lp cc thng s : Width, Height, Fill.


V d di y cho php v mt Ellipse c mu Xanh (blue) chiu rng =300 v chiu
cao =300.
<Ellipse Fill="Blue"

Height="300"

Width="300"/>

Ta c th to Ellipse bng coding behind nh sau:


Ellipse ellipse = new Ellipse();

ellipse.Fill = new SolidColorBrush(Colors.Blue);

ellipse.Width = 300;

ellipse.Height = 300;

mycanvas.Children.Add(ellipse);

Ta c th di chuyn ellipse bng coding behind nh sau:


ellipse.RenderTransform = new TranslateTransform()
{
X=100,
Y=50
};

Khoa Cng Ngh Thng Tin Trang 169/617


Gio trnh: Lp trnh Windows Phone

Hnh minh ha

2. Rectangle

Rectangle cho php v khung hnh ch nht vi cc gc cnh, bo gc, mu ng


vin v dy ca ng vin, mu nn:

<Rectangle Fill="Yellow"

Height="275"

Width="350"

Stroke="Red"

StrokeThickness="15"

RadiusX="40"

RadiusY="30"/>

Khoa Cng Ngh Thng Tin Trang 170/617


Gio trnh: Lp trnh Windows Phone

Fill: T mu nn
Height: Chiu cao
Width: Chiu rng
Stroke: Mu ng vin
StrokeThichness: dy ng vin.
RadiusX: Bo gc theo trc X, gi tr ln nht ca n l Width/2.
RadiusY: Bo gc theo trc Y, gi tr ln nht ca n l Height/2.

XAML code trn s tng ng vi coding behind di y:

Rectangle rect = new Rectangle();

rect.Fill=new SolidColorBrush(Colors.Yellow);

rect.Width=350;

rect.Height=275;

rect.Stroke=new SolidColorBrush(Colors.Red);

rect.StrokeThickness=15;

rect.RadiusX=40.0;

rect.RadiusY=30.0;

3. Line

Line cho php v mt ng thng theo ta X1,Y1 ni vi X2,Y2:


<Line Fill="Yellow"

Stroke="Red"

StrokeThickness="5"

X1="0" Y1="10"

X2="100" Y2="200"

/>

Tng t ta c th to Line trong coding behind:

Khoa Cng Ngh Thng Tin Trang 171/617


Gio trnh: Lp trnh Windows Phone

Line line = new Line();

line.Fill=new SolidColorBrush(Colors.Yellow);

line.Stroke=new SolidColorBrush(Colors.Red);

line.StrokeThickness=5;

line.X1=0.0;

line.Y1=10.0;

line.X2=100.0;

line.Y2=200.0;

4. Polyline

Polyline cho php v cc ng Line lin tip nhau nhng khng to thnh mt
vng khp kn.
<Canvas>

<Polyline Points="50,25 0,100 100,100 50,25"

Stroke="Red" StrokeThickness="10"

Fill="Yellow"

Canvas.Left="75" Canvas.Top="50" />

</Canvas>

Ta cng c th chuyn qua coding behind nh sau:


Polyline polyline=new Polyline();

polyline.Points.Add(new Point(50.0,25.0));

polyline.Points.Add(new Point(0.0,100.0));

polyline.Points.Add(new Point(100.0,100.0));

polyline.Points.Add(new Point(50.0,25.0));

polyline.Stroke=new SolidColorBrush(Colors.Red);

polyline.StrokeThickness=10.0;

polyline.Fill = new SolidColorBrush(Colors.Yellow);

Khoa Cng Ngh Thng Tin Trang 172/617


Gio trnh: Lp trnh Windows Phone

5. Polygon

Polyline cho php v cc ng Line lin tip nhau v to thnh mt vng khp
kn.
<Polygon Points="50,25 0,100 100,100 50,25"

Stroke="Red" StrokeThickness="10"

Fill="Yellow"

Canvas.Left="75" Canvas.Top="50" />

Ta cng c th chuyn qua coding behind nh sau:


Polygon polygon = new Polygon();

polygon.Points.Add(new Point(50.0, 25.0));

polygon.Points.Add(new Point(0.0, 100.0));

polygon.Points.Add(new Point(100.0, 100.0));

polygon.Points.Add(new Point(50.0, 25.0));

polygon.Stroke = new SolidColorBrush(Colors.Red);

polygon.StrokeThickness = 10.0;

polygon.Fill = new SolidColorBrush(Colors.Yellow);

6. Path

Path cho php v cc i tng Shape mt cch linh ng, di y l mt s v


d v cch s dng Path trong XAML code.
<Canvas>

<Path Fill="Gold" Stroke="Black" StrokeThickness="1">

<Path.Data>

<EllipseGeometry Center="50,50" RadiusX="50" RadiusY="50" />

</Path.Data>

</Path>

</Canvas>

Khoa Cng Ngh Thng Tin Trang 173/617


Gio trnh: Lp trnh Windows Phone

<Canvas>

<Path Stroke="DarkGoldenRod" StrokeThickness="3"

Data="M 100,200 C 100,25 400,350 400,175 H 280"/>

</Canvas>

IV. Kt lun
Windows phone h tr nhiu i tng ha cho php lp trnh vin
Drawing, trong cc ng dng Game chng ta s dng rt nhiu. Vic p dng cc i
tng ha thnh tho cng c th gip ch rt nhiu trong qu trnh pht trin cc ng
dng thng thng. Cc i tng Brush khng ch p dng cho Shape m cc c th p
dng cho cc UIELement khc chng hn nh Button, TextBox, TextBlock..

Khoa Cng Ngh Thng Tin Trang 174/617


Gio trnh: Lp trnh Windows Phone

BI 3. Cm ng chm a im trong Windows Phone


(Gestures Multi Touch)
Windows Phone h tr tnh nng chm a im gip ngi s dng c nhng
tri nghim v cng th v. Trong phn ny gio trnh s trnh by v Gesture v cc k
thut Touching thng s dng trong phn mm Windows Phone.
Ni dung ca phn ny s cp ti nhng phn sau:
I. Khi nim v Gestures ....................................................................... 178
1. Khi nim ....................................................................................................... 178
2. Cch ci t Multi Touch Simulator ............................................................. 178
II. K thut Touching ............................................................................. 185
1. Gii thiu cc s kin Gestures ..................................................................... 185
2. Cch s dng Tap (chm), Double Tap v Hold (chm lu) ....................... 186
3. Drag v drop (ko v th) i tng ............................................................. 193
4. Flicking i tng .......................................................................................... 203
5. Zoom i tng bng k thut Pinch v Stretch .......................................... 205
6. Rotate (Xoay i tng) ................................................................................ 210
III. Kt lun ............................................................................................. 210

Trung Tm Tin Hc H KHTN-TP.HCM Trang 177/617


Gio trnh: Lp trnh Windows Phone

I. Khi nim v Gestures


1. Khi nim

Gestures c hiu l cch m ngi s dng dng cc c ch tng tc ln


mn hnh thit b in thoi, v d: Ngi s dng chm ngn tay ln mn hnh (Tap),
chm 2 ln lin tc (Double Tap), chm v nm ko i tng (Touch v Hold), di
chuyn i tng theo mt hng (Pan), di chuyn trang, ni dung n vng khc
(Flick), phng to thu nh i tng (Pinch v Stretch), thay i hng i tng (Twist).

Hnh minh ha Gestures

2. Cch ci t Multi Touch Simulator

Hin nay cc k s xy dng c mt s th vin cho php kim tra Multi


touch trong Windows Phone Emulator l th vin Multitouch Vista, di y l cc
bc ci t, cu hnh v s dng th vin ny:

Bc 1: Ti Multitouch vista ti link di y (tp tin MultiTouchVista_-


_second_release_-_refresh_2.zip):

http://multitouchvista.codeplex.com/releases/view/28979

Bc 2: Gii nn tp tin c ti v Bc 1, vo th mc:


MultiTouchVista_-_second_release_-_refresh_2\Driver\x64

Trong th mc ny c tp tin Install driver.cmd, Ta s dng command line


administrator ci chy tp tin ny.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 178/617


Gio trnh: Lp trnh Windows Phone

Di y l mn hnh Administrator: Command Prompt

Ta chuyn lnh u c ti th mc x64 nh trn. Ch l ty vo phin bn


h iu hnh cng nh chip mainboard m ta chn driver cho ph hp:

Sau g lnh cho php ci t driver c cu hnh trong Install


driver.cmd.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 179/617


Gio trnh: Lp trnh Windows Phone

Sau khi nhn enter th mn hnh thng bo ci t driver s xut hin di y:

Ta bm Install ci t Driver, sau khi ci t xong ta kim tra Properties ca


Windows:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 180/617


Gio trnh: Lp trnh Windows Phone

Nu c thng s nh mn hnh trn l ta ci driver thnh cng. Nu nh


khng c th ta tip tc cu hnh nh sau:
- Vo control panel / chn Device Manager

- Mn hnh Device Manager hin th ln/ ta bm chut phi vo Universal Software


HID device / chn Disable:

- Sau khi chn Disable th mn hnh yu cu xc nhn hin th ra nh bn di, ta


chn Yes:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 181/617


Gio trnh: Lp trnh Windows Phone

- Sau khi Disable xong th ta li Enable tr li, nh vy l hon tt qu trnh ci


t

Bc 3: Kch hot dch v Multitouch:

Ta vo th mc ci t Multitouch Vista/ Bm chn


Multitouch.Service.Console.exe nh hnh bn di y:

Sau khi kch hot th cc con tr chut hin th ra nh bn di, ta cm bao


nhiu chut vo my vi tnh th s c tng im nh mu :

Trung Tm Tin Hc H KHTN-TP.HCM Trang 182/617


Gio trnh: Lp trnh Windows Phone

Bc 4: Cu hnh Multitouch Vista, Ta khi ng


Multitouch.Configuration.WPF.exe

Mn hnh Multitouch configuration hin th ra nh bn di, ta chn


MultipleMice ri bm vo nt Configure device:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 183/617


Gio trnh: Lp trnh Windows Phone

Mn hnh di y xut hin, ta checked vo Block native windows mouse


input. ri bm nt OK, lc ny dch v s v hiu ha biu tng Mouse ca
Windows n ch cn xut hin cc im nh mu i din cho cc con chut c
gn vo my vi tnh. By gi ta c th s dng nhiu chut trn cng 1 my tnh ri.

- Ta c th m Paint ln kim tra nh sau (2 ngi mi ngi 1 chut t v


hnh ring):

Trung Tm Tin Hc H KHTN-TP.HCM Trang 184/617


Gio trnh: Lp trnh Windows Phone

II. K thut Touching


c th s dng thnh tho k thut Touching, gio trnh cung cp c s l
thuyt v nhng v d thc t di y. Hc vin cn nm k v thc hin li.
1. Gii thiu cc s kin Gestures

xy dng ng dng cho php ngi s dng tng tc c vi cc i


tng trn mn hnh m s dng touching, ng thi mun bit c cc loi hnh ng
m ngi s dng tng tc trn mn hnh th ta cn khm ph Gestures cng cc thao
tc c h tr trong thit b Windows Phone mobile. Di y l mt s m t cho cc
s kin Gestures:

Gesture M t Trng hp s dng


Thng s dng cho s kin click ca
S kin ny xy ra khi ngi s dng
Button, chn 1 phn t trong list control,
Tap dng 1 ngn tay chm ln mn hnh ri
thit lp focus cho cc Input Control:
nh ra
Textbox, check box
Thng c s dng cho mc ch
S kin ny xy ra khi ngi s dng
phng to ni dung chng hn nh phng
Double-Tap dng 1 ngn tay chm 2 ln lin tc ln
to ch, hnh nh, bn . Sau thu nh
mn hnh tht nhanh.
ni dung li bng cch lp li double-tap
Thng c s dng cho mc ch hin
S kin ny xy ra khi ngi s dng th Context Menu cho mt i tng c
Tap-And-Hold nhn mi 1 ngn tay trn mn hnh m th no . V d hin th Context menu
li khng nh ra xem chi tit Danh b, xa danh b, m
website mt tab mi
S kin nay xy ra khi ngi s dng
chm ln mn hnh thit b v Thng c s dng di chuyn (ko)
Drag hay Pan
drag(ko) ngn tay trn mn hnh n i tng t v tr ny n v tr khc.
bt k hng no nhng khng nh ra.
S kin ny xy ra khi ngi s dng
Thng c s dng xa 1 i tng
chm ngn tay ln mn hnh thit b v
Flick khi mn hnh, quay (xoay) trang, hiu
ko mt phn ngn tay ln bt k ch
ng trnh din Photo slide show.
no trn mn hnh
S kin xy ra khi ngi s dng dng
nhiu ngn tay chm ln mn hnh thit
Thng c s dng phng to v thu
Pinch b v di chuyn cc ngn tay ny ra xa
nh i tng trn mn hnh.
nhau (zoom in) hoc xch li gn nhau
(zoom out)
Ta c th dng Multitouch simulator demo cho cc ng dng Multitouch, tuy
nhin khi kch hot chng th s lm tiu tn ti nguyn my tnh lm cho my tnh chy
chm do b nh phi lm vic ht cng sut, c gng s dng thit b tht.
lp trnh Gestures, ta c cc cch sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 185/617


Gio trnh: Lp trnh Windows Phone

S dng trc tip cc s kin Gestures c h tr sn trong cc lp UIElement.


Cc lp ny h tr sn Single Touch (Tap, Double Tap, Hold) v Multi Touch
(ManipulationStarted, ManipulationDelta, ManipulationCompleted).
S dng lp Touch, thng qua lp ny ta cng bit c cc hnh ng ca ngi
s dng trn mn hnh in thoi.
S dng GestureListener c cung cp trong Windows Phone Toolkit.

2. Cch s dng Tap (chm), Double Tap v Hold (chm lu)

Ta bit tt c cc control trong Windows Phone u k tha t UIElement


(System.Window.UIElement) v n c cung cp hng lot cc s kin sau:

Events Event Arguments M t


S kin ny xy ra khi ngi s dng
chm ngn tay vo b mt ca
UIElement ri nh ra.
Tap GestureEventArgs GestureEventArgs cung cp thng tin
v v tr m ngn tay chm vo v cc
thng tin khc lin quan ti
UIElement
S kin ny xy ra khi ngi s dng
DoubleTap GestureEventArgs chm ngn tay 2 ln lin tip vo
UIElement
S kin ny xy ra khi ngi s dng
Hold GestureEventArgs
nhn vo UIElement m khng nh ra
Xy ra khi ngi s dng nhn mt
hoc nhiu ngn tay vo UIElement.
ManipulationStartedEventArgs cung
ManipulationStarted ManipulationStartedEventArgs
cp thng tin ca i tng to ra s
kin, im xut pht cng nh ta
ca i tng
S kin xy ra khi ngi s dng tip
tc di chuyn cc ngn tay n v tr
khc m khng nh tay ra, s kin ny
s xut hin mt hoc nhiu ln trong
qu trnh thc thi.
ManipulationDelta ManipulationDeltaEventArgs ManipulationDeltaEventArgs cung
cp cc thng tin m tc v ang sy
ra: Bao gm c nhng thay i tch
ly, nhng thay i gn y nht, tc
thay i v k c s thay i sy ra
do qun tnh.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 186/617


Gio trnh: Lp trnh Windows Phone

Events Event Arguments M t


S kin ny xy ra khi ngi s dng
nh tay ra.
ManipulationCompletedEventArgs
ManipulationCompleted ManipulationCompletedEventArgs
cung cp cc thng tin v tng cng
qu trnh chuyn i, tng tc ca
s thay i v k c qun tnh.

minh ha cho cc l thuyt trn, ta s lm bi demo nh vi m t sau:

Hin th mc nh 1 hnh trn c mu vng khi khi ng chng trnh


i thnh mu khi chm 1 ngn tay vo hnh trn
Sao chp thm 1 hnh trn khi chm lin tc 2 ln vo hnh trn gc
To mt Popup menu khi nhn v gi ngn tay vo hnh trn.
To Project tn LearnSingleTouch_Circle nh hnh bn di:

trn ta c s dng gi Windows Phone Toolkit, sau y l MainPage.xaml:

<phone:PhoneApplicationPage
x:Class="LearnSingleTouch_Circle.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

Trung Tm Tin Hc H KHTN-TP.HCM Trang 187/617


Gio trnh: Lp trnh Windows Phone

mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<toolkit:WrapPanel x:Name="mypanel" HorizontalAlignment="Left" Height="768"
VerticalAlignment="Top" Width="480">
<Popup Name="menuEllipse" IsOpen="False">
<ListBox Name="listMenuItems"
Background="White"
Foreground="Black"
BorderBrush="Gray"
BorderThickness="5"
SelectionChanged="listMenuItems_SelectionChanged"
Width="150"
Height="150">
<ListBoxItem Name="itemColorChange" Content="i mu" Padding="10" />
<ListBoxItem Name="itemNew" Content="Thm hnh trn" Padding="10" />
<ListBoxItem Name="itemDelete" Content="Xa hnh trn" Padding="10"/>
</ListBox>
</Popup>
</toolkit:WrapPanel>
</phone:PhoneApplicationPage>

Tin hnh vit coding behind nh sau:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 188/617


Gio trnh: Lp trnh Windows Phone

using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using LearnSingleTouch_Circle.Resources;

using System.Windows.Input;
using System.Windows.Shapes;
using System.Windows.Media;

namespace LearnSingleTouch_Circle
{
public partial class MainPage : PhoneApplicationPage
{

//to bin lu tr ta m ngi s dng chm trn mn hnh


//da vo ta ny ta hin th Popup menu ng v tr
Point lastTouchedPoint = new Point(0, 0);
// Constructor
public MainPage()
{
InitializeComponent();
//gn s kin ngi s dng chm trn mn hnh
Touch.FrameReported += Touch_FrameReported;
}
void Touch_FrameReported(object sender, TouchFrameEventArgs e)
{
//tr v tp cc ta m ngi s dng chm trn mn hnh
TouchPointCollection touchPoints = e.GetTouchPoints(this);
if (touchPoints.Count > 0)
{
//ly ta u tin ra, v trong trng hp ny ta lm 1 ngn tay ch vo
lastTouchedPoint = touchPoints[0].Position;
}
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 189/617


Gio trnh: Lp trnh Windows Phone

protected override void OnNavigatedTo(NavigationEventArgs e)


{
base.OnNavigatedTo(e);
//mc nh khi khi ng xong th gi hm to 1 hnh trn bt k
AddNewEllipse();
}
public void AddNewEllipse()
{
Ellipse myEllipse = new Ellipse();
myEllipse.Width = myEllipse.Height = 100;
myEllipse.Fill = GetNextColor();
mypanel.Children.Add(myEllipse);
AttachEventHandlers(myEllipse);
}
//hm gn s kin ng cho hnh trn
private void AttachEventHandlers(Ellipse targetEllipse)
{
targetEllipse.Tap += myEllipse_Tap;
targetEllipse.DoubleTap += myEllipse_DoubleTap;
targetEllipse.Hold+= myEllipse_Hold;
}
//hm xa b s kin cho hnh trn -
private void RemoveEventHandlers(Ellipse targetEllipse)
{
targetEllipse.Tap -= myEllipse_Tap;
targetEllipse.DoubleTap -= myEllipse_DoubleTap;
targetEllipse.Hold-=myEllipse_Hold;
}
//hm x l nhn lu trn hnh trn
void myEllipse_Hold(object sender, System.Windows.Input.GestureEventArgs e)
{
Ellipse sourceEllipse = (Ellipse)sender;
//if the point touched is near the right edge of the screen, adjust the
//HorizontalOffset for the context menu to ensure that it is displayed

Trung Tm Tin Hc H KHTN-TP.HCM Trang 190/617


Gio trnh: Lp trnh Windows Phone

//within the bounds of the screen


if ((lastTouchedPoint.X + listMenuItems.Width) > this.ActualWidth)
lastTouchedPoint.X = this.ActualWidth - listMenuItems.Width;
//if the point touched is near the bottom edge of the screen, adjust the
//VerticalOffset for the context menu to ensure that it is displayed
//within the bounds of the screen
if ((lastTouchedPoint.Y + listMenuItems.Height) > this.ActualHeight)
lastTouchedPoint.Y = this.ActualHeight - listMenuItems.Height;
menuEllipse.HorizontalOffset = lastTouchedPoint.X;
menuEllipse.VerticalOffset = lastTouchedPoint.Y;
menuEllipse.IsOpen = true;
//set the Tag of the context menu to the selected ellipse
//so that on menu item selection, the action that is taken
//against the shape that triggered the event
menuEllipse.Tag = sourceEllipse;
}
//hm s l nhn 2 ln lin tc ln hnh trn
void myEllipse_DoubleTap(object sender,
System.Windows.Input.GestureEventArgs e)
{
AddNewEllipse();
}
//hm x l nhn 1 ln ln hnh trn
void myEllipse_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
if (menuEllipse.IsOpen)
{
//if the context menu is open but the user taps
//outside of the menu, then close it
menuEllipse.IsOpen = false;
}
Ellipse sourceEllipse = (Ellipse)sender;
sourceEllipse.Fill = GetNextColor();
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 191/617


Gio trnh: Lp trnh Windows Phone

private Random _random = new Random();


//hm ly mu ngu nhin
public SolidColorBrush GetNextColor()
{
Color newColor = new Color();
newColor.A = (byte)255;
newColor.R = (byte)_random.Next(0, 256);
newColor.G = (byte)_random.Next(0, 256);
newColor.B = (byte)_random.Next(0, 256);
return new SolidColorBrush(newColor);
}
//hm x l ngi s dng chn cc item trong Popup menu
private void listMenuItems_SelectionChanged(object sender,
SelectionChangedEventArgs e)
{
if (e.AddedItems.Count <= 0) return;
Ellipse sourceEllipse = menuEllipse.Tag as Ellipse;
menuEllipse.Tag = null;
menuEllipse.IsOpen = false;

int index = listMenuItems.SelectedIndex;


switch (index)
{
case 0:
sourceEllipse.Fill = GetNextColor();
break;
case 1:
AddNewEllipse();
break;
case 2:
RemoveEventHandlers(sourceEllipse);
mypanel.Children.Remove(sourceEllipse);
break;
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 192/617


Gio trnh: Lp trnh Windows Phone

//reset the state of the listbox so that the selected item


//no longer appears to be selected on the next display of the menu
listMenuItems.ClearValue(ListBox.SelectedItemProperty);
}
}
}

3. Drag v drop (ko v th) i tng

c th ko th i tng ti bt k v tr no ta s dng GestureService trong


th vin Windows Phone toolkit, th vin ny cha GestureListener, DragStarted,
DragDelta, DragCompleted, v s kin Flick.

Sau y l m t cc s kin trong GestureListener Service:

Hnh minh ha v Drag v Drop i tng

Trung Tm Tin Hc H KHTN-TP.HCM Trang 193/617


Gio trnh: Lp trnh Windows Phone

Events Event Arguments M t


GestureBegin, Thng qua s kin ny ta ly c ta
GestureCompleted, GestureEventArgs x,y ni m ngi s dng chm ln
Tap, DoubleTap, Hold b mt UIElement
Ging nh GestureEventArgs, n xc
DragStartedGestureEventAr
DragStarted nh c hng i tng bt u
gs
c ko i trn mn hnh
Ging nh Arguments
DragStartedGestureEventArgs, n xc
DragDelta DragDeltaGestureEventArgs nh c khong cch m i tng
c di chuyn (theo chiu dc v
chiu ngang)
DragCompletedGestureEven Ging nh Argument
DragCompleted
tArgs DragDeltaGestureEventArgs
Ging nh GestureEventArgs, n xc
nh gc , hng v vn tc theo
Flick FlickGestureEventArgs
chiu ng chiu ngang khi ngi s
dng trt ngn tay trn mn hnh.
Ging nh GestureEventArgs, n ly
PinchStartedGestureEventAr
PinchStarted c gc v hng ngn tay m
gs
ngi s dng thao tc trn mn hnh
Tng t GestureEventArgs, n ly
c t l khong cch t c th
PinchDelta PinchGestureEventArgs
xc nh l Zoom in hay Zoom out hay
Rotation
PinchCompleted PinchGestureEventArgs Kt thc qu trnh Pinch
Ta s lm v d v ko th i tng ty trn mn hnh nh sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 194/617


Gio trnh: Lp trnh Windows Phone

To mt project tn: LearnSingleTouch_DragCircle


Thit k giao din tng t nh bi trn, nhng c thm Gestures Service:

<phone:PhoneApplicationPage

x:Class="LearnSingleTouch_DragCircle.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:phone="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Portrait" Orientation="Portrait"

shell:SystemTray.IsVisible="True">

<toolkit:WrapPanel x:Name="mypanel"

Grid.Row="1"

Grid.ColumnSpan="3">

<toolkit:GestureService.GestureListener>

<toolkit:GestureListener

Tap="GestureListener_Tap"

DoubleTap="GestureListener_DoubleTap"

Hold="GestureListener_Hold"

Flick="GestureListener_Flick"

Trung Tm Tin Hc H KHTN-TP.HCM Trang 195/617


Gio trnh: Lp trnh Windows Phone

DragStarted="GestureListener_DragStarted"

DragDelta="GestureListener_DragDelta"

DragCompleted="GestureListener_DragCompleted" />

</toolkit:GestureService.GestureListener>

<Popup Name="menuEllipse" IsOpen="False">

<ListBox Name="listMenuItems"

Background="White"

Foreground="Black"

BorderBrush="Gray"

BorderThickness="5"

SelectionChanged="listMenuItems_SelectionChanged"

Width="150"

Height="150">

<ListBoxItem Name="itemColorChange" Content="i mu" Padding="10"


/>

<ListBoxItem Name="itemNew" Content="Thm hnh trn" Padding="10"


/>

<ListBoxItem Name="itemDelete" Content="Xa hnh trn"


Padding="10"/>

</ListBox>

</Popup>

<TextBlock Name="coordinatesText" Grid.Row="1" Margin="10,709,-156,-


686" />

<Button Content="Reset" Tap="Button_Tap" HorizontalAlignment="Left"


Height="72" VerticalAlignment="Top" Width="120" Margin="191,706,-191,-706"/>

</toolkit:WrapPanel>

</phone:PhoneApplicationPage>

Tin hnh coding nh sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 196/617


Gio trnh: Lp trnh Windows Phone

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using LearnSingleTouch_DragCircle.Resources;

using System.Windows.Shapes;
using System.Windows.Media;
namespace LearnSingleTouch_DragCircle
{
public partial class MainPage : PhoneApplicationPage
{
//to bin lu tr ta m ngi s dng chm trn mn hnh
//da vo ta ny ta hin th Popup menu ng v tr
Point lastTouchedPoint = new Point(0, 0);
bool ellipseInDragMode=false;
// Constructor
public MainPage()
{
InitializeComponent();
//gn s kin ngi s dng chm trn mn hnh
System.Windows.Input.Touch.FrameReported += Touch_FrameReported;
}
void Touch_FrameReported(object sender,
System.Windows.Input.TouchFrameEventArgs e)
{
//tr v tp cc ta m ngi s dng chm trn mn hnh
System.Windows.Input.TouchPointCollection touchPoints =
e.GetTouchPoints(this);
if (touchPoints.Count > 0)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 197/617


Gio trnh: Lp trnh Windows Phone

{
//ly ta u tin ra, v trong trng hp ny ta lm 1 ngn tay ch vo
lastTouchedPoint = touchPoints[0].Position;
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
//mc nh khi khi ng xong th gi hm to 1 hnh trn bt k
AddNewEllipse();
}
private void GestureListener_Tap(object sender, GestureEventArgs e)
{
if (e.OriginalSource.GetType().Equals(typeof(Ellipse)))
{
if (menuEllipse.IsOpen)
{
//if the context menu is open but the user taps
//outside of the menu, then close it
menuEllipse.IsOpen = false;
}
Ellipse sourceEllipse = (Ellipse)e.OriginalSource;
sourceEllipse.Fill = GetNextColor();
}
}
private void GestureListener_DoubleTap(object sender, GestureEventArgs e)
{
if (e.OriginalSource.GetType().Equals(typeof(Ellipse)))
{
AddNewEllipse();
}
}
private void GestureListener_Hold(object sender, GestureEventArgs e)
{

Trung Tm Tin Hc H KHTN-TP.HCM Trang 198/617


Gio trnh: Lp trnh Windows Phone

if (!ellipseInDragMode &&
e.OriginalSource.GetType().Equals(typeof(Ellipse)))
{
Ellipse sourceEllipse = (Ellipse)e.OriginalSource;
//if the point touched is near the right edge of the screen, adjust the
//HorizontalOffset for the context menu to ensure that it is displayed
//within the bounds of the screen
if ((lastTouchedPoint.X + listMenuItems.Width) > this.ActualWidth)
lastTouchedPoint.X = this.ActualWidth - listMenuItems.Width;
//if the point touched is near the bottom edge of the screen, adjust the
//VerticalOffset for the context menu to ensure that it is displayed
//within the bounds of the screen
if ((lastTouchedPoint.Y + listMenuItems.Height) > this.ActualHeight)
lastTouchedPoint.Y = this.ActualHeight - listMenuItems.Height;
menuEllipse.HorizontalOffset = lastTouchedPoint.X;
menuEllipse.VerticalOffset = lastTouchedPoint.Y;
menuEllipse.IsOpen = true;
//set the Tag of the context menu to the selected ellipse
//so that on menu item selection, the action that is taken
//against the shape that triggered the event
menuEllipse.Tag = sourceEllipse;
}
}

private void GestureListener_Flick(object sender, FlickGestureEventArgs e)


{

}
private void GestureListener_DragStarted(object sender,
DragStartedGestureEventArgs e)
{
//kim tra ng l ang chn di chuyn i tng Ellipse
if (e.OriginalSource.GetType().Equals(typeof(Ellipse)))
{
ellipseInDragMode = true;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 199/617


Gio trnh: Lp trnh Windows Phone

//ly chnh xc i tng ang chn


Ellipse targetEllipse = (Ellipse)e.OriginalSource;
//thit lp ton b cc i tng nm bn trong panel c Zindex =0 n
nm bn doi
mypanel.Children.ToList().ForEach(c =>
c.SetValue(Canvas.ZIndexProperty, 0));
//thit lp i tng ang Drag c zindex =1 n lun nm bn trn
targetEllipse.SetValue(Canvas.ZIndexProperty, 1);
//i mu vin ca i tng ang di chuyn thnh mu vng d phn
bit
targetEllipse.Stroke = new SolidColorBrush(Colors.Yellow);
}
}

private void GestureListener_DragDelta(object sender,


DragDeltaGestureEventArgs e)
{
if (e.OriginalSource.GetType().Equals(typeof(Ellipse)))
{
//tin hnh thay i ta ca i tng da vo
DragDeltaGestureEventArgs
Ellipse targetEllipse = (Ellipse)e.OriginalSource;
TranslateTransform transform = targetEllipse.RenderTransform as
TranslateTransform;
transform.X += e.HorizontalChange;//thay i theo chiu x
transform.Y += e.VerticalChange;//thay i theo chiu y
Point lastPosition = e.GetPosition(null);
coordinatesText.Text = string.Format("X:{0}, Y:{1}",
lastPosition.X,
lastPosition.Y);
}
}
private void GestureListener_DragCompleted(object sender,
DragCompletedGestureEventArgs e)
{
if (e.OriginalSource.GetType().Equals(typeof(Ellipse)))

Trung Tm Tin Hc H KHTN-TP.HCM Trang 200/617


Gio trnh: Lp trnh Windows Phone

{
//sau khi hon thnh (nh ngn tay ra)
ellipseInDragMode = false;
Ellipse targetEllipse = (Ellipse)e.OriginalSource;
//reset the border to the default color
targetEllipse.Stroke = new SolidColorBrush(Colors.Gray);
}
}
public void AddNewEllipse()
{
Ellipse myEllipse = new Ellipse();
myEllipse.Width = myEllipse.Height = 100;
myEllipse.Fill = GetNextColor();
myEllipse.Stroke = new SolidColorBrush(Colors.Gray);
myEllipse.HorizontalAlignment = HorizontalAlignment.Left;
myEllipse.VerticalAlignment = VerticalAlignment.Top;
myEllipse.RenderTransform=new TranslateTransform()
{
X=0,
Y=0
};
mypanel.Children.Add(myEllipse);
AttachEventHandlers(myEllipse);
}
//hm gn s kin ng cho hnh trn
private void AttachEventHandlers(Ellipse targetEllipse)
{
targetEllipse.Hold += myEllipse_Hold;
}
//hm xa b s kin cho hnh trn - gi trong OnNavigateFrom
private void RemoveEventHandlers(Ellipse targetEllipse)
{
targetEllipse.Hold -= myEllipse_Hold;
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 201/617


Gio trnh: Lp trnh Windows Phone

//hm x l nhn lu trn hnh trn


void myEllipse_Hold(object sender, System.Windows.Input.GestureEventArgs e)
{
Ellipse sourceEllipse = (Ellipse)sender;
//if the point touched is near the right edge of the screen, adjust the
//HorizontalOffset for the context menu to ensure that it is displayed
//within the bounds of the screen
if ((lastTouchedPoint.X + listMenuItems.Width) > this.ActualWidth)
lastTouchedPoint.X = this.ActualWidth - listMenuItems.Width;
//if the point touched is near the bottom edge of the screen, adjust the
//VerticalOffset for the context menu to ensure that it is displayed
//within the bounds of the screen
if ((lastTouchedPoint.Y + listMenuItems.Height) > this.ActualHeight)
lastTouchedPoint.Y = this.ActualHeight - listMenuItems.Height;
menuEllipse.HorizontalOffset = lastTouchedPoint.X;
menuEllipse.VerticalOffset = lastTouchedPoint.Y;
menuEllipse.IsOpen = true;
//set the Tag of the context menu to the selected ellipse
//so that on menu item selection, the action that is taken
//against the shape that triggered the event
menuEllipse.Tag = sourceEllipse;
}
private Random _random = new Random();
//hm ly mu ngu nhin
public SolidColorBrush GetNextColor()
{
Color newColor = new Color();
newColor.A = (byte)255;
newColor.R = (byte)_random.Next(0, 256);
newColor.G = (byte)_random.Next(0, 256);
newColor.B = (byte)_random.Next(0, 256);
return new SolidColorBrush(newColor);
}
//hm x l ngi s dng chn cc item trong Popup menu

Trung Tm Tin Hc H KHTN-TP.HCM Trang 202/617


Gio trnh: Lp trnh Windows Phone

private void listMenuItems_SelectionChanged(object sender,


SelectionChangedEventArgs e)
{
if (e.AddedItems.Count <= 0) return;
Ellipse sourceEllipse = menuEllipse.Tag as Ellipse;
menuEllipse.Tag = null;
menuEllipse.IsOpen = false;
int index = listMenuItems.SelectedIndex;
switch (index)
{
case 0:
sourceEllipse.Fill = GetNextColor();
break;
case 1:
AddNewEllipse();
break;
case 2:
RemoveEventHandlers(sourceEllipse);
mypanel.Children.Remove(sourceEllipse);
break;
}
//reset the state of the listbox so that the selected item
//no longer appears to be selected on the next display of the menu
listMenuItems.ClearValue(ListBox.SelectedItemProperty);
}
private void Button_Tap(object sender,
System.Windows.Input.GestureEventArgs e)
{
mypanel.Children.Clear();
AddNewEllipse();
coordinatesText.Text = "X:0, Y:0";
}
}
}

4. Flicking i tng

Trung Tm Tin Hc H KHTN-TP.HCM Trang 203/617


Gio trnh: Lp trnh Windows Phone

Flicking l g? Tng t nh Drag v Drop nhng khc nhau ch: Ngi s


dng ko i tng ri nh ra th i tng vn tip tc di chuyn ti ch.

Chc nng ny kh th v, ta c th xc nh c hng di chuyn ca ngn


tay v tc c ca n quyt nh ti s phn ca i tng. V d ta mun khi ngi
s dng Flick i tng vi tc cao v theo hng dc th xa i tng khi mn
hnh chng hn. Ta sa s kin Flick bi trn nh sau:
private void GestureListener_Flick(object sender, FlickGestureEventArgs e)

if (e.OriginalSource.GetType().Equals(typeof(Ellipse)) &&

e.Direction == System.Windows.Controls.Orientation.Vertical &&

(e.VerticalVelocity < -3000))

Ellipse targetEllipse = (Ellipse)e.OriginalSource;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 204/617


Gio trnh: Lp trnh Windows Phone

RemoveEventHandlers(targetEllipse);

mypanel.Children.Remove(targetEllipse);

Nh vy ta c th Drag, Drop, Flick i tng, source code mu:


http://goo.gl/owyRCY

5. Zoom i tng bng k thut Pinch v Stretch

K thut ny rt c a chung trong cc phn mm mobile, ngi s dng


thng xem mt hnh nh (hoc ni dung bt k) h mun phng to thu nh hnh nh
hay i tng mt cch d dng, sau y l cch lp trnh cho php zoom in, zoom out:
Ta s S dng GestureService gn GestureListener cho i tng, sau
tin hnh vit lnh cho cc s kin PinchStarted, PinchDelta, v PinchCompleted.
To project vi tn Learn_PinchImage di y:

trn ta tham chiu ti th vin Windows Phone Toolkit, nhng ch l khng


cn khai bo namespace cho n v ta dng k thut vit s kin ng, giao din rt n
gin ch cn c 1 hnh nh nh sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 205/617


Gio trnh: Lp trnh Windows Phone

Khi ngi s dng dng 2 hoc nhiu ngn tay c th phng ta hoc thu nh
tm hnh bng cch tng khong cch cc ngn tay hoc gim khong cch cc ngon tay
trn mn hnh. Sinh vin nn b sung thm chc nng Drag v Drop, Flick hc mc
trn.

Di y l XAML code:

<phone:PhoneApplicationPage

x:Class="Learn_PinchImage.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

Trung Tm Tin Hc H KHTN-TP.HCM Trang 206/617


Gio trnh: Lp trnh Windows Phone

SupportedOrientations="Portrait" Orientation="Portrait"

shell:SystemTray.IsVisible="True">

<Grid x:Name="LayoutRoot" Background="Transparent">

<Grid.RowDefinitions>

<RowDefinition />

<RowDefinition Height="Auto" />

</Grid.RowDefinitions>

<Image Name="myPhoto"

Source="Assets\thanhdieu.jpg"

Height="300" Width="400">

<Image.RenderTransform>

<ScaleTransform x:Name="photoTransform" />

</Image.RenderTransform>

</Image>

<TextBlock Name="photoScaleText" Grid.Row="1" />

</Grid>

</phone:PhoneApplicationPage>

X l source code behind n gin nh sau:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Navigation;

using Microsoft.Phone.Controls;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 207/617


Gio trnh: Lp trnh Windows Phone

using Microsoft.Phone.Shell;

using Learn_PinchImage.Resources;

namespace Learn_PinchImage

public partial class MainPage : PhoneApplicationPage

// Constructor

public MainPage()

InitializeComponent();

// Sample code to localize the ApplicationBar

//BuildLocalizedApplicationBar();

init();

//gn s kin ng

public void init()

GestureListener listener = GestureService.GetGestureListener(myPhoto);

listener.PinchStarted += new

EventHandler<PinchStartedGestureEventArgs>(GestureListener_PinchStarted);

listener.PinchDelta += new
EventHandler<PinchGestureEventArgs>(GestureListener_PinchDelta);

listener.PinchCompleted += new

EventHandler<PinchGestureEventArgs>(GestureListener_PinchCompleted);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 208/617


Gio trnh: Lp trnh Windows Phone

photoScaleText.Text = string.Format("Size: {0}X{1}",

myPhoto.Width, myPhoto.Height);

private double imageScale = 1;

void GestureListener_PinchStarted(object sender, PinchStartedGestureEventArgs e)

//get the current photo's scale value

imageScale = photoTransform.ScaleX;

//get the two touch points

Point touchPointA = e.GetPosition(myPhoto, 0);

Point touchPointB = e.GetPosition(myPhoto, 1);

//set the photo center x and y axis to the center of the

//corresponding axis between the two touch points

photoTransform.CenterX = touchPointA.X + (touchPointB.X - touchPointA.X) / 2;

photoTransform.CenterY = touchPointA.Y + (touchPointB.Y - touchPointA.Y) / 2;

void GestureListener_PinchDelta(object sender, PinchGestureEventArgs e)

//scale the photo as the pinch gesture changes

photoTransform.ScaleX = imageScale * e.DistanceRatio;

photoTransform.ScaleY = photoTransform.ScaleX;

photoScaleText.Text = string.Format("Size: {0}X{1}, Scale:{2} - Pinch In Progress",

myPhoto.Width, myPhoto.Height, Math.Round(photoTransform.ScaleX, 2));

void GestureListener_PinchCompleted(object sender, PinchGestureEventArgs e)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 209/617


Gio trnh: Lp trnh Windows Phone

photoScaleText.Text = string.Format("Size: {0}X{1}, Scale:{2} - Pinch Completed",

myPhoto.Width, myPhoto.Height, Math.Round(photoTransform.ScaleX, 2));

Nh vy l ta c th Zoom in, zoom out hnh nh.

6. Rotate (Xoay i tng)

xoay c i tng trn mn hnh ta cng s dng Pinch event, tuy nhin
nn kt hp vi Drag, Drop, Zoom in zoom out.
lm c u ny ta s s dng CompositeTransform kt hp c cc
trng thi ca i tng li vi nhau. Cc thuc tnh ta c th thit lp cho
CompositeTransform:
CenterX
CenterY
Rotation
ScaleX
ScaleY
SkewX
SkewY
TranslateX
TranslateY

III. Kt lun
Nh vy ta nm r c k thut touching, multi touching. Vic p dng vo
d n mt cch kho lo s gip chng ta ci thin c tc cng nh gip giao din

Trung Tm Tin Hc H KHTN-TP.HCM Trang 210/617


Gio trnh: Lp trnh Windows Phone

thm p mt. c bit trong nhng ng dng nh trnh din hnh nh hay game di
chuyn i tng. Ta c th p dng k thut ny rt nhiu vo cc d n khc nhau.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 211/617


Gio trnh: Lp trnh Windows Phone

BI 4. Bn v nh v
(Maps, Location, v Routing)
i vi ngi s dng Smart Phone th chc nng xem bn , tm kim ng
i, a im th n l mt trong nhng tin ch khng th thiu, nm bt c tnh hnh
ny Windows Phone tch hp Maps Control, Maps Task Launcher, hay chc nng Map
Overlay gip ngi s dng c th ty bin c bn , chc nng Routes v Directions.
Ni dung ca phn ny s cp ti nhng phn sau:
I. Cch s dng Maps Task Launchers ..................................................219
1. MapsTask ......................................................................................................... 220
2. MapsDirectionsTask ........................................................................................ 221
3. MapDownloaderTask v MapUpdaterTask ................................................... 223
4. Xc nh v tr hin ti trn bn ................................................................. 224
II. Cch s dng Map Control .................................................................227
1. Gii thiu .......................................................................................................... 227
2. Cc thuc tnh .................................................................................................. 228
3. Cch s dng.................................................................................................... 229
III. Cch to Map overlay .........................................................................241
1. Gii thiu .......................................................................................................... 241
2. To nhn a im hin ti .............................................................................. 243
3. Thm Overlay ng trn bn ..................................................................... 244
IV. M rng cch to ng i v ch dn ................................................247
V. Kt lun ...............................................................................................249

Trung Tm Tin Hc H KHTN-TP.HCM Trang 218/617


Gio trnh: Lp trnh Windows Phone

I. Cch s dng Maps Task Launchers


Kin trc v MAPs trong Windows Phone

Nu ta cn tm ng i hay cn bit ta ang ng u th c th s dng Maps


Task Launchers, n l ng dng c built in Windows Phone device. Tin ch cung
cp cc lp v cc hm gip lp trnh vin d dng lp trnh cng nh hiu chnh cc
thng s. Thng khi s dng Maps th trong ng dng ca chng ta s using cc th
vin sau:

using Microsoft.Phone.Tasks;

using System.Threading.Tasks;

using System.Device.Location;

using Windows.Devices.Geolocation;

ng thi ta cng cn thit lp ID_CAP_MAP, ID_CAP_LOCATION trong


Manifest v phi bt tnh nng Location Service trong thit b mobile ln
(Settings/System/Location/ bt Turn On).

Trung Tm Tin Hc H KHTN-TP.HCM Trang 219/617


Gio trnh: Lp trnh Windows Phone

1. MapsTask

Tin ch ny cho php ta tm kim nhng a im xung quanh Search Text (a


im tm kim). Nu a im tm kim khng c cung cp th v tr hin ti ca thit
b s c s dng lm a im trung tm tm kim.
Ta c th cu hnh MapsTask thng qua 3 thuc tnh: Center, SearchTerm,
ZoomLevel trong ta bt buc phi truyn thng s cho Center hoc SearchTerm hoc
c 2 nu khng n s sinh ra li InvalidOperationException.
Thuc tnh M t
L a im c nh du l trung tm tm kim (Center Point),
Maps s tm kim lan ta t Center Point ny. Nu nh ta khng
Center
thit lp gi tr cho n th chng trnh s ly a im hin ti ca
thit b lm Center Point.
T kha tm kim trn bn , n s tm kim t Center Point.
SearchTerm Nu Center Point khng c th n s ly a im hin ti ca thit
b.
Thuc tnh kiu s Double, cho php phng to thu nh bn , ch
ZoomLevel
n c gi tr t 1 ti 21.

V d tm kim xem mt a im u trn bn :

public void TimKiem(string searchTerm)


{
try
{
MapsTask mapTask = new MapsTask();
mapTask.ZoomLevel = 15;
mapTask.SearchTerm = searchTerm;
mapTask.Show();
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show("Location is disabled.");
}
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 220/617


Gio trnh: Lp trnh Windows Phone

Nh trn ta thy Center Point khng c thit lp nn n s ly a im hin


ti ca thit b lm Center Point.
Ta c th thit lp Center Point bng cch truyn v (latitude) v kinh
(longitude) cho GeoCoordinate ri gn vo cho thuc tnh Center:

public void TimKiem(string searchTerm)


{
try
{
MapsTask mapTask = new MapsTask();
double latitude=27.345;
double longitude = 99.05;
mapTask.Center = new GeoCoordinate(latitude, longitude);
mapTask.ZoomLevel = 15;
mapTask.SearchTerm = searchTerm;
mapTask.Show();
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show("Location is disabled.");
}
}

Ch l Maps Task Launchers n khng nm trong ng dng ca chng ta, m


n l mt ng dng c lp nn khi gi mapTask.Show() th mt ng dng Maps hon
ton mi c to ra v ng dng ca ta khng cn nm trong vng i Foreground Life
na.
2. MapsDirectionsTask

Tin ch ny cho ta tm ng i t im u ti im cui, n c 2 thuc tnh l


Start v End. C 2 thuc tnh Start, End u thuc kiu d liu LabeledMapLocation.

Di y l thng tin thuc tnh ca MapsDirectionsTask:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 221/617


Gio trnh: Lp trnh Windows Phone

Thuc tnh M t
Start a im xut pht: C kiu LabeledMapLocation
End a im ch cn tm ti : C kiu LabeledMapLocation

Di y l bng thng tin thuc tnh ca LabeledMapLocation:

Thuc tnh M t
a ch bt u hoc kt thc. Nu thuc tnh Location m khng
Label
c thit lp th n s ly Label ny lm gi tr tm kim.
Thuc tnh lu tr geographic coordinate tm kim. Nu thuc
tnh ny khng c thit lp th n s ly thuc Label tm kim.
Location Thng th nu nh n l Start th ta nn ly mc nh l Ta
hin ti ca thit b tin hnh tm ng i t ni ta ang ng
ti v tr no (End).

V d di y cho php ta tm ng i t 1 v tr A ti mt v tr B:

private async void btnSearch_Click(object sender, RoutedEventArgs e)

MapsDirectionsTask mapsDic = new MapsDirectionsTask();

LabeledMapLocation start = new LabeledMapLocation();

start.Label = txtStart.Text;

LabeledMapLocation end=new LabeledMapLocation();

end.Label = txtEnd.Text;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 222/617


Gio trnh: Lp trnh Windows Phone

mapsDic.Start = start; // im bt u

mapsDic.End = end; // im kt thc

mapsDic.Show();

Sau khi bm vo nt Tm ng i th phn mm s tin hnh gi lnh trn, ta c


kt qu:

mn hnh trn ta c th chn chi tit hng i, thi gian i, s km i.. rt hu


ch cho qu trnh tm ng i.
Ch l nu nh thuc tnh End ca MapsDirectionsTask khng c thit lp
th h thng c th ly a ch hin ti ca thit b, cn nu c 2 thuc tnh Start v End
u khng thit lp th s sinh ra li: InvalidOperationException.
3. MapDownloaderTask v MapUpdaterTask

Trung Tm Tin Hc H KHTN-TP.HCM Trang 223/617


Gio trnh: Lp trnh Windows Phone

Windows Phone cung cp 2 Task n gin d s dng gip ngi dng c th


ti bn cng nh cp nhp mi.

Cch s dng n gin nh sau:

private void btnDownload_Click(object sender, RoutedEventArgs e)

MapDownloaderTask mapDownloaderTask = new MapDownloaderTask();

mapDownloaderTask.Show();

private void btnUpdate_Click(object sender, RoutedEventArgs e)

MapUpdaterTask mapUpdaterTask = new MapUpdaterTask();

mapUpdaterTask.Show();

4. Xc nh v tr hin ti trn bn

c th xc nh c v tr hin ti ca ta trn bn th cch vit nh sau:

Bc 1: To Project
Giao din n gin nh sau:

<Grid x:Name="LayoutRoot" Background="Transparent">

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

<RowDefinition Height="*"/>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 224/617


Gio trnh: Lp trnh Windows Phone

</Grid.RowDefinitions>

<Button x:Name="btnWhereAmI" Content="Where Am I 1"


HorizontalAlignment="Left" Margin="45,432,0,0" Grid.Row="1"
VerticalAlignment="Top" Click="btnWhereAmI_Click"/>

</Grid>

Bc 2: Thit lp ID_CAP_MAPS, ID_CAP_LOCATION v bt tnh nng


location trong thit b tht.
Bc 3: Coding:

Gi hm GetGeopositionAsync ca i tng Geolocator ly Geoposition


hin ti, da vo i tng ny m ta c th ly ra V v Kinh t to i tng
GeoCoordinate.
using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Navigation;

using Microsoft.Phone.Controls;

using Microsoft.Phone.Shell;

using LearnWhereAmI.Resources;

using Windows.Devices.Geolocation;

using System.Device.Location;

using Microsoft.Phone.Tasks;

using System.Windows.Threading;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 225/617


Gio trnh: Lp trnh Windows Phone

using System.Threading.Tasks;

namespace LearnWhereAmI

public partial class MainPage : PhoneApplicationPage

// Constructor

public MainPage()

InitializeComponent();

//hm tr v v tr hin ti ca ta trn bn

private async Task<GeoCoordinate> GetCurrentCoordinate()

Geolocator locator = new Geolocator();

locator.DesiredAccuracy = PositionAccuracy.High;

Geoposition position = await locator.GetGeopositionAsync();

GeoCoordinate coordinate =

new GeoCoordinate(position.Coordinate.Latitude,

position.Coordinate.Longitude);

return coordinate;

private async void btnWhereAmI_Click(object sender, RoutedEventArgs e)

try

Trung Tm Tin Hc H KHTN-TP.HCM Trang 226/617


Gio trnh: Lp trnh Windows Phone

GeoCoordinate coordinate = await GetCurrentCoordinate();

MapsTask mapTask = new MapsTask();

mapTask.ZoomLevel = 15; // phng to 15 ln

//Truyn vo Center hin th v tr ca ta trn bn

mapTask.Center = coordinate;

mapTask.Show(); // hin th bn

catch (UnauthorizedAccessException ex)

MessageBox.Show("Location is disabled.");

II. Cch s dng Map Control


1. Gii thiu

Map Control ging nh 1 component, n nm trong th vin


Microsoft.Phone.Maps.Controls, thng qua control ny ta c th nh km n mt phn
trong ng dng ca mnh, n khc vi MapTask launcher. S dng Map control rt n
gin v v cng tin li.
V d hnh nh cch s dng Map control:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 227/617


Gio trnh: Lp trnh Windows Phone

hnh trn th ng dng c th cha bn nm bn trong, cho php ngi s


dng cu hnh cc thng s.
2. Cc thuc tnh

Map control c rt nhiu thuc tnh hu ch, thng qua cc thuc tnh ny m lp
trnh vin c th ty chnh chc nng. Khi ta ko th Map control vo th n t ng pht
sinh namespace nh sau:
xmlns:mapControls="clr-
namespace:Microsoft.Phone.Maps.Controls;assembly=Microsoft.Phone.Maps"

Thuc tnh M t
Dng thit lp MapCartographicMode cho Map control,
c 4 ch xem bn :
MapCartographicMode.Aerial;
CartographicMode
MapCartographicMode.Hybrid;
MapCartographicMode.Road;
MapCartographicMode.Terrain;
Center Thit lp ta trung tm cho Map control
ColorMode Thit lp mu cho bn , c 2 loi:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 228/617


Gio trnh: Lp trnh Windows Phone

Thuc tnh M t
MapColorMode.Dark;
MapColorMode.Light
Thit lp hng nhn cho bn bng cch xoay bn theo
Heading
cc hng ty , gi tr truyn vo l s thc (t 0 ti 360)
LandmarksEnabled Thit lp land mark.
Thit lp MapLayer cho php hiu chnh bn bng cch
Layers
gn cc hnh nh ty ln bn
MapElements Thit lp Map elements trong Map control
PedestrianFeaturesEnabled Thit lp nhng c tnh cho ngi i b trn bn
Pitch Thit lp xoay bn nm ngang ging mt sn
TileSources Thit lp Tile source cho map control
TransformCenter Thit lp trung tm cho bn c Transformed
UniqueId ID ca Map control
WatermarkMode Thit lp watermark cho map control
ZoomLevel Phong to thu nh bn

3. Cch s dng

Chng ta s hc cch s dng Map control thng qua nhng chc nng sau:
Ly ta hin ti (Current Coordinate)
Phng to thu nh bn (Zoom)
Xoay bn (Pitch)
Quay bn (Heading)
Cp nht mi ta hin ti (Update location)
Thit lp mu cho bn (ColorMode)
Thit lp ch hin th bn (CartographicMode)
Bc 1: To project tn LearnMapControl
Bc 2: Thit lp location service cho thit b, ng thi cu hnh
ID_CAP_LOCATION v ID_CAP_MAP cho ng dng
Bc 3: Thit k giao din nh di y (XAML):

Trung Tm Tin Hc H KHTN-TP.HCM Trang 229/617


Gio trnh: Lp trnh Windows Phone

<phone:PhoneApplicationPage

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

xmlns:mapControls="clr-
namespace:Microsoft.Phone.Maps.Controls;assembly=Microsoft.Phone.Maps"

x:Class="LearnMapControl.MainPage"

mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Portrait" Orientation="Portrait"

shell:SystemTray.IsVisible="True">

<phone:PhoneApplicationPage.ApplicationBar>

<shell:ApplicationBar>

<shell:ApplicationBarIconButton x:Name="btnSetting"
IconUri="/Assets/AppBar/feature.settings.png" IsEnabled="True" Text="Settings"
Click="btnSetting_Click"/>

<shell:ApplicationBarIconButton x:Name="btnRefresh"
IconUri="/Assets/AppBar/refresh.png" IsEnabled="True" Text="Refresh"
Click="btnRefresh_Click"/>

</shell:ApplicationBar>

</phone:PhoneApplicationPage.ApplicationBar>

<!--LayoutRoot is the root grid where all page content is placed-->

<Grid x:Name="LayoutRoot" Background="Transparent">

Trung Tm Tin Hc H KHTN-TP.HCM Trang 230/617


Gio trnh: Lp trnh Windows Phone

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

<RowDefinition Height="*"/>

</Grid.RowDefinitions>

<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">

<TextBlock Text="Trung tm tin hc - KHTN" Style="{StaticResource


PhoneTextNormalStyle}" Margin="12,0"/>

<TextBlock Text="Maps Control" Margin="9,-7,0,0" Style="{StaticResource


PhoneTextTitle1Style}"/>

</StackPanel>

<!--ContentPanel - place additional content here-->

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

<Grid.RowDefinitions>

<RowDefinition />

<RowDefinition Height="Auto"/>

</Grid.RowDefinitions>

<mapControls:Map x:Name="theMap" >

</mapControls:Map>

<Grid Grid.Row="1" Visibility="Visible" x:Name="settingsPanel">

<Grid.RowDefinitions>

<RowDefinition/>

<RowDefinition/>

<RowDefinition/>

</Grid.RowDefinitions>

<Grid.ColumnDefinitions>

<ColumnDefinition/>

<ColumnDefinition/>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 231/617


Gio trnh: Lp trnh Windows Phone

</Grid.ColumnDefinitions>

<Slider

Grid.Column="0"

Grid.Row="0"

Maximum="19"

Minimum="1"

ValueChanged="ZoomSliderValueChanged"

x:Name="zoomSlider" />

<Slider

Grid.Column="1"

Maximum="75"

Minimum="0"

ValueChanged="PitchSliderValueChanged"/>

<Slider

Grid.Row="1"

Grid.ColumnSpan="2"

Maximum="360"

Minimum="0"

ValueChanged="HeadingSliderValueChanged"/>

<Button

Click="ToggleColorMode"

Content="Dark"

Grid.Row="2"/>

<Button

Click="CycleMapCartographicMode"

Content="Mode"

Trung Tm Tin Hc H KHTN-TP.HCM Trang 232/617


Gio trnh: Lp trnh Windows Phone

Grid.Column="1"

Grid.Row="2"/>

</Grid>

<TextBlock x:Name="txtwaiting" Foreground="Red"


HorizontalAlignment="Left" Margin="25,268,0,0" TextWrapping="Wrap" Text="ang
ti vui lng ch" VerticalAlignment="Top" Width="407" Canvas.ZIndex="1"
Visibility="Visible"/>

</Grid>

</Grid>

</phone:PhoneApplicationPage>

Bc 4: Tin hnh coding


Bc 4.1: Thm cc th vin sau vo coding behind:

using System.Device.Location;

using Microsoft.Phone.Tasks;

using Windows.Devices.Geolocation;

using System.Threading.Tasks;

using Windows.System;

using Microsoft.Phone.Maps.Controls;

Bc 4.2: Vit lnh tr v ta hin ti ca thit b:

private async Task<GeoCoordinate> GetCurrentCoordinate()

txtwaiting.Visibility = Visibility.Visible;

Geolocator locator = new Geolocator();

locator.DesiredAccuracy = PositionAccuracy.High;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 233/617


Gio trnh: Lp trnh Windows Phone

Geoposition position = await locator.GetGeopositionAsync();

GeoCoordinate coordinate =

new GeoCoordinate(position.Coordinate.Latitude,
position.Coordinate.Longitude);

txtwaiting.Visibility = Visibility.Collapsed;

return coordinate;

Bc 4.3: Gi hm hin th ta hin ti khi khi ng ng dng:

protected async override void OnNavigatedTo(NavigationEventArgs e)


{
base.OnNavigatedTo(e);
try
{
theMap.Center = await GetCurrentCoordinate();
zoomSlider.Value = 15;
}
catch (Exception)
{
MessageBoxResult result = MessageBox.Show("Thit b ca bn cha bt
tnh nng Location Service, c mun bt khng?", "Error",
MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
launchUri();
}
}
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 234/617


Gio trnh: Lp trnh Windows Phone

Bc 4.4: Hin th mn hnh bt tnh nng Location Service.

Ta phi c bc ny bi v rt nhiu thit b khng c bt tnh nng Location


Service nn ng dng chng ta d b li v b tt, do ta nn try catch bt li ri hin
th thng bo cu hnh Location, bc 4.3 ta c gi hm launchUri(), hm ny c vit
nh sau:

private async void launchUri()

await Launcher.LaunchUriAsync(new Uri("ms-settings-location:"));

Trung Tm Tin Hc H KHTN-TP.HCM Trang 235/617


Gio trnh: Lp trnh Windows Phone

Lnh trn cho php ta hin th mn hnh cu hnh Location Service, ta cng cn
bit thm nhng URI cho php cu hnh nhng chc nng thng s dng c lit k
di y:

URI M t
http:[URL] M mt website c t trong URL
mailto:[email address] Email ti..
ms-settings-accounts: M mn hnh setting account
M mn hnh thit lp air plane mode
V d:
ms-settings-airplanemode:
await Launcher.LaunchUriAsync
(new Uri("ms-settings-airplanemode:"));
ms-settings-bluetooth: M mn hnh cu hnh bluetooth
ms-settings-cellular: M mn hnh cu hnh cellular
ms-settings-emailandaccounts: M mn hnh cu hnh email v account
ms-settings-location: M mn hnh thit lp location service
ms-settings-lock: M mn hnh thit lp lock
ms-settings-wifi: M mn hnh thit lp wifi

bc 4.4 ny l ta c th chy ng dng c, khi khi ng ta s thy c v


tr chnh xc ca ta trn bn .

Bc 4.5: T bc 4.4 ta cm in thoi di chuyn n v tr khc (i xa), ta


phi c chc nng cp nhp li ta mi trn bn , lm nh sau (chc nng
c vit cho Actionbar Icon Button): n gin l gi lm hm ly ta hin
ti

private async void btnRefresh_Click(object sender, EventArgs e)

try

((ApplicationBarIconButton)sender).IsEnabled = false;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 236/617


Gio trnh: Lp trnh Windows Phone

GeoCoordinate coordinate = await GetCurrentCoordinate();

theMap.Center = coordinate;

catch (Exception) // I meant to do that.

MessageBoxResult result = MessageBox.Show("Thit b ca bn cha bt


tnh nng Location Service, c mun bt khng?", "Error",
MessageBoxButton.OKCancel);

if (result == MessageBoxResult.OK) {

launchUri();

finally

((ApplicationBarIconButton)sender).IsEnabled = true;

bc 4.5 ta cng bt buc phi try catch v cho php hin th mn hnh thit
lp Location Service nu nh ngi s dng li tt dch v ny ngay sau khi hin th
c ta ln bn trc .

Bc 4.6: Tin hnh lm chc nng phng to thu nh bn :

private void ZoomSliderValueChanged(object


sender,RoutedPropertyChangedEventArgs<double> e)

if (theMap != null)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 237/617


Gio trnh: Lp trnh Windows Phone

theMap.ZoomLevel = e.NewValue;

trn ta dng Slider control nn mi ln ngi s dng di chuyn slider th ta s


ly gi tr hin ti ca slider gn cho ZoomLevel, n chy t 1 ti 21.

Bc 4.7: Tin hnh vit lnh cho php xoay mn hnh ging nh mt sn
(Pitch):

private void PitchSliderValueChanged(object


sender,RoutedPropertyChangedEventArgs<double> e)

if (theMap != null)

theMap.Pitch = e.NewValue;

Ta c th xoay ngang qua t 0 ti 90 .

Bc 4.8: Tin hnh vit lnh cho php quay bn ta c th quan st mi


gc cnh, thng c th quay t 0 ti 360 .

private void HeadingSliderValueChanged(object


sender,RoutedPropertyChangedEventArgs<double> e)

if (theMap != null)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 238/617


Gio trnh: Lp trnh Windows Phone

theMap.Heading = e.NewValue;

Bc 4.9: hin th mu bn (Ti hay sng), da vo ColorMode:

private void ToggleColorMode(object sender, RoutedEventArgs e)

((Button)(sender)).Content = theMap.ColorMode.ToString();

theMap.ColorMode = theMap.ColorMode == MapColorMode.Dark ?


MapColorMode.Light :

MapColorMode.Dark;

Bc 4.10: Ta cng c th cung cp chc nng cho php ngi s dng ty


chn ch hin th bn (c 4 ch ) nh sau:

private void CycleMapCartographicMode(object sender, RoutedEventArgs e)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 239/617


Gio trnh: Lp trnh Windows Phone

switch (theMap.CartographicMode)

case MapCartographicMode.Aerial:

theMap.CartographicMode = MapCartographicMode.Hybrid;

break;

case MapCartographicMode.Hybrid:

theMap.CartographicMode = MapCartographicMode.Road;

break;

case MapCartographicMode.Road:

theMap.CartographicMode = MapCartographicMode.Terrain;

break;

case MapCartographicMode.Terrain:

theMap.CartographicMode = MapCartographicMode.Aerial;

break;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 240/617


Gio trnh: Lp trnh Windows Phone

Bc 4.11: hin th hay n cng c cu hnh do ta thit k th vit lnh nh


sau:

private void btnSetting_Click(object sender, EventArgs e)

settingsPanel.Visibility =

settingsPanel.Visibility == Visibility.Visible ? Visibility.Collapsed

:Visibility.Visible;

Nh vy ti y ta c mt ng dng Bn hon chnh, ta c th thm chc


nng tm kim ng i v cc chc nng khc.

III. Cch to Map overlay


1. Gii thiu

Map overlay l mt trong nhng tin ch v cng th v m Windows Phone em


n nhng tri nghim tuyt vi cho ngi s dng. Ta c th gn nhn cho a im hin
ti, nh du cc v tr trn bn

Trung Tm Tin Hc H KHTN-TP.HCM Trang 241/617


Gio trnh: Lp trnh Windows Phone

By gi ta tin hnh chnh sa ng dng LearnMapControl mc II c th s


dng c tnh nng Overlay nh sau:

Tham chiu ti th vin Windows Phone Toolkit hoc ti trc tip t NuGet
Packages:

Tip n ta chnh sa Map control trong XAML thnh:

<mapControls:Map x:Name="theMap" Tap="theMap_Tap" >

<toolKit:MapExtensions.Children>

<toolKit:UserLocationMarker

Visibility="Collapsed"

x:Name="UserLocationMarker"/>

</toolKit:MapExtensions.Children>

</mapControls:Map>

Nh l phi c:

xmlns:toolKit="clr-namespace:Microsoft.Phone.Maps.Toolkit;assembly=Microsoft.Phone.Controls.Toolkit"

Trung Tm Tin Hc H KHTN-TP.HCM Trang 242/617


Gio trnh: Lp trnh Windows Phone

v :

using System.Windows.Media.Imaging;

using Microsoft.Phone.Maps.Toolkit;

2. To nhn a im hin ti

to nhn cho a im hin ti xut hin trn bn ta cn sa li lnh trong


hm OnNavigateTo nh sau:

protected async override void OnNavigatedTo(NavigationEventArgs e)

base.OnNavigatedTo(e);

try {

theMap.Center = await GetCurrentCoordinate();

zoomSlider.Value = 15;

this.UserLocationMarker =
(UserLocationMarker)this.FindName("UserLocationMarker");

this.UserLocationMarker.GeoCoordinate = theMap.Center;

this.UserLocationMarker.Visibility = System.Windows.Visibility.Visible;

catch (Exception) {

MessageBoxResult result = MessageBox.Show("Thit b ca bn cha bt tnh


nng Location Service, c mun bt khng?", "Error", MessageBoxButton.OKCancel);

if (result == MessageBoxResult.OK)

launchUri();

Trung Tm Tin Hc H KHTN-TP.HCM Trang 243/617


Gio trnh: Lp trnh Windows Phone

3. Thm Overlay ng trn bn

Chc nng Overlay cho php ta nh du cc hnh nh ln bn trn bn ,


lm c chc nng ny ta cn c hnh nh trong sut, trong ng dng ny th ta s dng
1 hnh nh du, bn c th cho php ngi s dng ty chn cc hnh nh khc nhau
nh du.

Ta chn thm 1 hnh nh tn footprint.png nh sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 244/617


Gio trnh: Lp trnh Windows Phone

Ta tin hnh chnh sa source code phn trc:


Khai bo mt instance variable:

private MapLayer layer;

Sau vit lnh cho s kin Tap trn bn :

private void theMap_Tap(object sender, System.Windows.Input.GestureEventArgs e)

// Ly hnh nh t Resource ra

// that comes with the SDK and add it to

// a new MapOverlay

Image image = new Image();

image.Source = new BitmapImage(new Uri("Assets/footprint.png",

UriKind.RelativeOrAbsolute));

// To i tng MapOverlay

MapOverlay overlay = new MapOverlay();

overlay.Content = image; // Thit lp hnh nh cho Overlay

Trung Tm Tin Hc H KHTN-TP.HCM Trang 245/617


Gio trnh: Lp trnh Windows Phone

// get the position that the user tapped

Point point = e.GetPosition(theMap); // Ly ta ngn tay nhn trn bn

// the favs icon is 76 x 76 and we want to

// center it on the point the user tapped

// so we'll shift the point

point.X -= 38;//ty vo hnh nh ta a vo m tr cng i width, height

point.Y -= 38;

// convert the ViewPort point into an actual GeoCoordinate value

// Chuyn ta trn thit b thnh ta thc t GeoCoordinate

GeoCoordinate coordinate =
theMap.ConvertViewportPointToGeoCoordinate(point);

// Thit lp GeoCoordinate ny cho Overlay trn

overlay.GeoCoordinate = coordinate;

// the one and only layer that we

// add all of the overlays to

if (layer == null)

layer = new MapLayer(); // cp php b nh cho MapLayer

theMap.Layers.Add(layer);//a Layer vo bn trc

layer.Add(overlay);// a overlay vo Layer sau.

on coding trn cho php chng ta gn cc hnh nh ln trn bn , ch l


ch cn 1 Layer (MapLayer), ta c th to nhiu MapOverlay vo trong 1 Layer, tng
ng vi 1 MapOverlay s l 1 hnh nh c th no .

Trung Tm Tin Hc H KHTN-TP.HCM Trang 246/617


Gio trnh: Lp trnh Windows Phone

IV. M rng cch to ng i v ch dn


Thng qua MapsDirectionsTask phn u th ta cng c th s dng tm
ng i cng nh cch ch dn ng i. Tuy nhin ta cng c th ci tin chc nng
ny. Ta s dng GeocodeQuery v RouteQuery c sn trong
Microsoft.Phone.Maps.Services.

MapsDirectionsTask c th ch h tr 1 ng i (cch i), nu nh ta mun c


nhiu cch ti cng 1 a im th lm nh th no?

Ta s dng th vin:

using Microsoft.Phone.Maps.Services;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 247/617


Gio trnh: Lp trnh Windows Phone

Ta dng GeocodeQuery tin hnh truy vn thng tin:

private void btnSearch_Click(object sender, RoutedEventArgs e)


{
GeocodeQuery codeQuery = new GeocodeQuery();
codeQuery.SearchTerm = txtSearchText.Text;
codeQuery.GeoCoordinate = currentLocation;
codeQuery.QueryCompleted += codeQuery_QueryCompleted;
codeQuery.QueryAsync();
}
List<GeoCoordinate> locations = new List<GeoCoordinate>();
void codeQuery_QueryCompleted(object sender,
QueryCompletedEventArgs<IList<MapLocation>> e)
{
foreach (var result in e.Result)
{
MapAddress address = result.Information.Address;
string addressText = string.Format("{0} {1}, {2}",
address.HouseNumber, address.Street, address.City);
GeoCoordinate coordinate = result.GeoCoordinate;

//X l theo addressText


//x l theo Coordinate
locations.Add(coordinate);
}
}

Ta c th ly ch dn tng GeoCoordinate nh sau:

RouteQuery routeQuery = new RouteQuery();

routeQuery.Waypoints = locations;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 248/617


Gio trnh: Lp trnh Windows Phone

routeQuery.QueryCompleted += routeQuery_QueryCompleted;

routeQuery.QueryAsync();

void routeQuery_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e)

Route route = e.Result;

foreach(RouteLeg leg in route.Legs)

foreach (RouteManeuver maneuver in leg.Maneuvers)

//X l maneuver.InstructionText;

//X l maneuver.LengthInMeters;

//X l maneuver.StartGeoCoordinate;

V. Kt lun
Nh vy bn v nh v gip lp trnh vin chng ta c nhng tri nghim
th v, n l mt trong nhng tin ch khng th thiu c i vi bt k mt thit b
SmartPhone no. Vic nm r kin trc cng nh cch thc lp trnh vi bn v nh
v s em li nhng li ch to ln c v kinh t ln thi gian.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 249/617


Gio trnh: Lp trnh Windows Phone

BI 5. Lp trnh ng b v bt ng b trong Windows Phone


(Synchronous & Asynchronous Programming)

trnh Nt tht c chai v tng kh nng p ng ca phn mm th ta nn s


dng k thut lp trnh bt ng b, tuy nhin khng phi ai cng c th hiu v trin khai
c k thut ny (kh vit, kh g li, kh bo tr). Gio trnh s trnh by chi tit k
thut lp trnh bt ng b, cng nh a ra mt s v d c th gip chng ta th d
dng nm bt v thc hin c.

Ni dung ca phn ny s cp ti nhng phn sau:


I) Khi nim ng b v bt ng b ..................................................251
II) Async method ....................................................................................252
1) Cng nng ca Async ...................................................................................... 252
2) Cch vit Async................................................................................................ 253
3) C ch hot ng ca Async............................................................................ 258
III) Threads ..............................................................................................265
1) BackgroundWorker ......................................................................................... 265
2) Task .................................................................................................................. 276
a) To mt Task ................................................................................................. 277
b) Thc hin Task lin tip ................................................................................. 279
c) Nhn kt qu tr v t Task ............................................................................ 281
d) Ch thc thi mt hoc nhiu Task .................................................................. 283
IV) Async v Await ..................................................................................285
V) Kt lun ..............................................................................................288

Trung Tm Tin Hc H KHTN-TP.HCM Trang 250/617


Gio trnh: Lp trnh Windows Phone

I. Khi nim ng b v bt ng b
Synchronous (ng b): L khi nim ni ln tnh nguyn tc, n i hi cc d
liu, v cc tin trnh c lin quan phi c kt ni, lin h theo mt trnh t thc hin
c nh, khng bao gi thay i. Trong mt chui cc hm ca mt quy trnh c n tc v,
nu chng l ng b th trnh t thc hin cc hm s khng bao gi thay i. Hm 1
c thit lp c gi v chy trc hm 2 th hm 2 bt buc phi ch hm 1 kt
thc mi c php bt u.

Asynchronous (bt ng b): L mt khi nim c th ni l ngc li vi


Synchronous. N ni ln s thiu cht ch, tnh lin kt yu, qun l v cng kh khn
(Kh vit code, kh sa code, kh bo tr) tuy nhin li uyn chuyn v kh nng ty bin
cao. Trong mt chui cc hm ca mt quy trnh c n tc v, nu n l bt ng b th c
ngha l cho d hm 2 c gi sau hm 1 nhng khng ai m bo c rng hm 1 s
phi kt thc trc hm 2 v hm 2 bt buc ch c chy khi hm 1 kt thc.

Trong lp trnh bt ng b th Windows Phone c rt nhiu phng php thc


hin, chng hn nh: S dng Tasks, Thread Safety, Concurrent Data Structures, UI
Threading, WPF Dispatcher, WinRT Dispatcher, UI Timers, async v await hay Parallel
Programming.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 251/617


Gio trnh: Lp trnh Windows Phone

Gio trnh s trnh by c ng nhng k thut x l bt ng b ph bin nht


hin nay kt hp vi nhng v d c th gip hc vin c th vn dng c ngay.

II. Async method


1. Cng nng ca Async

Lp trnh bt ng b l rt cn thit trong cc ng dng mobile c bit l trong


cc thao tc ly d liu t web, tng tc file, quay phim, chp nh nhng thao tc ny
thng hay b chm v tr hon do n thng lm ng dng c cm gic nh b treo.
Bng di y cho ta bit cc ng dng m Async c th ci thin tc :

Loi ng dng APIs c cha async method


Web access
HttpClient, SyndicationClient
(Truy sut Web)
Working with files StorageFile, StreamWriter, StreamReader, XmlReader

Trung Tm Tin Hc H KHTN-TP.HCM Trang 252/617


Gio trnh: Lp trnh Windows Phone

Loi ng dng APIs c cha async method


(Tng tc tp tin)
Working with images
MediaCapture, BitmapEncoder, BitmapDecoder
(Tng tc hnh nh)
WCF programming
Synchronous v Asynchronous Operations
(Lp trnh WCF)

Ta cn ch l khi phi lm mt tc v no m n c kh nng chim nhiu


thi gian v b treo giao din th ta nn dng k thut lp trnh khng ng b.

2. Cch vit Async

T kha async v await l linh hn ca lp trnh bt ng b. Khi s dng 2 t


kha ny th ta c th dng cc ti nguyn trong .NET Framework hoc Windows
Runtime to mt phng thc bt ng b mt cch d dng. Phng thc bt ng
b m ta nh ngha bng cch s dng async v await c xem nh l async methods.

V d HttpClient:

To mt project tn AsyncFirstExample:

Ch l th vin System.Net.Http khng c built-in trong Windows Phone, ta cn


ti t Nuge Packages v.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 253/617


Gio trnh: Lp trnh Windows Phone

Ta thit k XAML vi 2 control n gin nh sau:

<Button x:Name="StartButton" Content="Start" HorizontalAlignment="Left"


Margin="115,38,0,0" VerticalAlignment="Top" Click="StartButton_Click"/>

<TextBlock x:Name="resultsTextBox" HorizontalAlignment="Left" Margin="61,96,0,0"


Grid.Row="1" TextWrapping="Wrap" VerticalAlignment="Top" Width="342" Height="129"/>

ti System.Net.Http t NuGet Packages: Ta bm chut phi vo Reference/


chn Manage NuGet Packages

Mn hnh Manage NuGet Packages hin th ln ta tm t kha HttpClient, Ta


chn kt qu nh bn di Microsoft HTTP client Libraries.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 254/617


Gio trnh: Lp trnh Windows Phone

Source code nh sau:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Navigation;

using Microsoft.Phone.Controls;

using Microsoft.Phone.Shell;

using AsyncFirstExample.Resources;

using System.Net.Http;

using System.Threading.Tasks;

namespace AsyncFirstExample

public partial class MainPage : PhoneApplicationPage

// Constructor

public MainPage()

InitializeComponent();

private async void StartButton_Click(object sender, RoutedEventArgs e)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 255/617


Gio trnh: Lp trnh Windows Phone

Task<int> contentLengthTask = AccessTheWebAsync(); ;

int contentLength = await contentLengthTask;

resultsTextBox.Text +=

String.Format("\r\nLength of the downloaded string: {0}.\r\n",

contentLength);

// Three things to note in the signature:

// - The method has an async modifier.

// - The return type is Task or Task<T>. (See "Return Types" section.)

// Here, it is Task<int> because the return statement returns an integer.

// - The method name ends in "Async."

async Task<int> AccessTheWebAsync()

// You need to add a reference to System.Net.Http to declare client.

HttpClient client = new HttpClient();

// GetStringAsync returns a Task<string>. That means that when you await the

// task you'll get a string (urlContents).

Task<string> getStringTask =
client.GetStringAsync("http://duythanhcse.wordpress.com/");

// You can do work here that doesn't rely on the string from GetStringAsync.

DoIndependentWork();

// The await operator suspends AccessTheWebAsync.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 256/617


Gio trnh: Lp trnh Windows Phone

// - AccessTheWebAsync can't continue until getStringTask is complete.

// - Meanwhile, control returns to the caller of AccessTheWebAsync.

// - Control resumes here when getStringTask is complete.

// - The await operator then retrieves the string result from getStringTask.

string urlContents = await getStringTask;

// The return statement specifies an integer result.

// Any methods that are awaiting AccessTheWebAsync retrieve the length value.

return urlContents.Length;

void DoIndependentWork()

resultsTextBox.Text += "Working . . . . . . .\r\n";

Ch l nu hm AccessTheWebAsync khng lm g c gia qu trnh gi


GetStringAsync v ch n hon thnh th ta c th vit n gin nh sau:

string urlContents =await client.GetStringAsync("http://duythanhcse.wordpress.com/");

Ta quan st v nhn xt v d trn nh sau:


Phng thc c s dng t kha async
Tn ca mt phng thc bt ng b c vit theo lut c ni Async ng
sau hm, v d GetStringAsync, AccessTheWebAsync.
Kiu d liu tr v (Return Type), c 3 loi:
Task c lnh tr v kiu d liu Task<TResult>, v d async Task<int>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 257/617


Gio trnh: Lp trnh Windows Phone

Task khng c lnh tr v d liu, v d async Task DoSomething()


void nu ta vit s kin bt ng b, v d async void
StartButton_Click
Mt phng thc thng c t nht mt biu thc await, ni m n nh du
phng thc khng th tip tc thc hin cho ti khi hm bt ng b c
thc hin xong. Ngha l ngay ti thi im ny phng thc s b kha li
v n tr quyn iu khin cho phng thc c gi.
3. C ch hot ng ca Async

iu quan trng nht l ta phi hiu c c ch hot ng ca phng thc bt


ng b n xy ra nh th no, hnh di y s minh ha v c ch ny:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 258/617


Gio trnh: Lp trnh Windows Phone

Cc bc tin trnh bt ng b trong v d trn thc hin nh sau:


Bc 1: S kin StartButton c gi v ch hm bt ng b
AccessTheWebAsync thc thi
Bc 2: Hm AccessTheWebAsync to mt i tng HttpClient v gi phng
thc bt ng b GetStringAsync ti ni dung ca website v.
Bc 3: V hm GetStringAsync phi c thi gian tng i ti ht ni dung
website v, nn trnh b treo ti nguyn, hm GetStringAsync s tr quyn
iu khin li cho AccessTheWebAsync (yields control).

Hm GetStringAsync s tr v 1 Task<string>, v c lu tr vo bin


getStringTask.

Bc 4: Bi v getStringTask cha c s dng await nn hm


AccessTheWebAsync tip tc gi cc lnh bn di, c th l gi hm ng b
DoIndependentWork.
Bc 5: Hm DoIndependentWork l mt hm ng b nn cc lnh bn trong
n s c thc thi sau tr li quyn iu khin cho hm gi n.
Bc 6: Lc ny string urlContents = await getStringTask; s c thc thi, sau
khi thc hin xong n s tr v hm StartButton_Click (Ta thy k l ng khng?
Theo suy ngh thng thng th sau khi gi hm trn n phi gi lnh return
urlContents.Length; Nhng n li khng gi.
Bc 7: T bc sau khi qua bc 7 n s gi lnh

int contentLength = await contentLengthTask;

Khi gi lnh ny xong n s quay li hm AccessTheWebAsync gi lnh


return urlContents.Length.

Bc 8: Kt thc

Sau khi bc 7 thc hin return urlContents.Length, chng trnh quay li


StartButton_Click kt thc tin trnh.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 259/617


Gio trnh: Lp trnh Windows Phone

r hn ta xem thm v d th 2:

Cng dng cc th vin v Nuge Packages nh v d 1.

<Button x:Name="StartButton" Content="Start" HorizontalAlignment="Left"


Margin="115,38,0,0" VerticalAlignment="Top" Click="startButton_Click"/>

<TextBlock x:Name="resultsTextBox" HorizontalAlignment="Left"


Margin="61,96,0,0" Grid.Row="1" TextWrapping="Wrap" VerticalAlignment="Top"
Width="342" Height="129"/>

private async void startButton_Click(object sender, RoutedEventArgs e)

// ONE

Task<int> getLengthTask = AccessTheWebAsync();

// FOUR

int contentLength = await getLengthTask;

// SIX

resultsTextBox.Text +=

String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);

async Task<int> AccessTheWebAsync()

// TWO

HttpClient client = new HttpClient();

Task<string> getStringTask =

client.GetStringAsync("http://msdn.microsoft.com");

Trung Tm Tin Hc H KHTN-TP.HCM Trang 260/617


Gio trnh: Lp trnh Windows Phone

// THREE

string urlContents = await getStringTask;

// FIVE

return urlContents.Length;

Cc nh du ONE, TWO, THREE, FOUR l i din cho cc bc thi thi cc


hm bt ng b, di y l tm tt bc chy:

ONE: Vo hm startButton_Click.

Gi lnh bt ng b AccessTheWebAsync.

TWO: Vo lnh bt ng b AccessTheWebAsync.

Gi hm bt ng b HttpClient.GetStringAsync.

THREE: Quay tr li AccessTheWebAsync.

Task getStringTask c thc thi.

Ch getStringTask & tr v 1 Task<int> ti hm startButton_Click.

FOUR: Quay tr li startButton_Click.

Task getLengthTask c thc thi.

Ch getLengthTask -- no caller to return to.

FIVE: Tip tc Quay li AccessTheWebAsync.

Task getStringTask va thc thi xong

X l tr v kt qu.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 261/617


Gio trnh: Lp trnh Windows Phone

Kt thc hm AccessTheWebAsync.

SIX: Quay tr li startButton_Click.

Task getLengthTask hon thnh.

Kt qu t AccessTheWebAsync c lu tr trong contentLength.

Hin th contentLength kt thc.

Length of the downloaded string: 33946.

Chi tit cc bc nh sau:


Bc ONE v TWO:

u tin ta hin th dng thng bo qu trnh x l: startButton_Click gi hm bt


ng b AccessTheWebAsync, v AccessTheWebAsync gi hm bt ng b
GetStringAsync(String) ca HttpClient. Hnh di y m t chi tit cho bc ONE v
TWO:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 262/617


Gio trnh: Lp trnh Windows Phone

Bc THREE:

Chng trnh s quay tr li AccessTheWebAsync gi task getStringTask

Bc FOUR:

Khi ti dng lnh await n s quay li hm startButton_click.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 263/617


Gio trnh: Lp trnh Windows Phone

Bc FIVE:

Trong hm startButton_click, khi gp await n li tr v AccessTheWebAsync,


lc ny Task getStringTask thc thi xong, n x v tr v kt qu chiu di ca chui,
kt thc hm AccessTheWebAsync.

Bc SIX:
Quay tr v bin lu tr kt qu contentLength, xut kt qu v kt thc chng
trnh.
int contentLength = await getLengthTask;

SIX: Back in startButton_Click.

Task getLengthTask is finished.

Result from AccessTheWebAsync is stored in contentLength.

About to display contentLength and exit.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 264/617


Gio trnh: Lp trnh Windows Phone

III. Threads
K thut lp trnh bt ng b khng cn thit phi dng a tin trnh v chng
khng chy trn tin trnh ring, tuy nhin giao din vn khng b treo trong qu trnh cc
phng thc bt ng b ang x l cha xong (long time).

vit a tin trnh ta c th dng BackgroundWorker hoc Task.Run tin


hnh cp nht giao din trong thi gian thc. V d nh cp nht Progressbar.

1. BackgroundWorker

BackgroundWorker l mt lp cho php ta vit a tin trnh cp nht giao din


thi gian thc, nm trong th vin using System.ComponentModel;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 265/617


Gio trnh: Lp trnh Windows Phone

Di y l bng thuc tnh v cc phng thc thng s dng:

Thuc tnh / Phng thc/


M t
S kin

WorkerSupportsCancellation H tr cho php hy tin trnh cp nht


CancellationPending Kim tra xem c ang hy hay khng
IsBusy Kim tra xem c ang bn x l hay khng
WorkerReportsProgress
Cho php cp nht, s dng ProgressChanged

RunWorkerAsync Kch hot Worker


CancelAsync Hy Worker
Report, thng bo kt qu ti s kin
ReportProgress
ProgressChanged
S kin x l tin trnh cp nht giao din, ch l
khng c cp nht giao din trong s kin, ch
DoWork
c cp nhp giao din trong s kin
ProgressChanged
ProgressChanged S kin cp nht giao din
RunWorkerCompleted S kin nh du l tin trnh thc thi xong
DoWorkEventArgs Parameter ca DoWork
RunWorkerCompletedEventArgs Parameter ca RunWorkerCompleted
ProgressChangedEventArgs Parameter ca ProgressChanged

V d v cch s dng BackgroundWorker n gin nh sau:

Ta c XAML :

<phone:PhoneApplicationPage

x:Class="Learn_BackgroundWorker.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

Trung Tm Tin Hc H KHTN-TP.HCM Trang 266/617


Gio trnh: Lp trnh Windows Phone

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Portrait" Orientation="Portrait"

shell:SystemTray.IsVisible="True">

<Grid x:Name="LayoutRoot" Background="Transparent">

<StackPanel>

<StackPanel Orientation="Horizontal"

HorizontalAlignment="Left" VerticalAlignment="Top"

Margin="10" >

<Button x:Name="buttonStart" Content="Start" Click="buttonStart_Click"

Width="200" />

<Button x:Name="buttonCancel" Content="Cancel"


Click="buttonCancel_Click"

Width="200" />

</StackPanel>

<StackPanel Margin="10,50,0,0" Orientation="Horizontal">

<TextBlock Text="Progress: " />

<TextBlock x:Name="tbProgress" />

</StackPanel>

</StackPanel>

</Grid>

</phone:PhoneApplicationPage>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 267/617


Gio trnh: Lp trnh Windows Phone

Source code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Navigation;

using Microsoft.Phone.Controls;

using Microsoft.Phone.Shell;

using Learn_BackgroundWorker.Resources;

using System.ComponentModel;

namespace Learn_BackgroundWorker

public partial class MainPage : PhoneApplicationPage

private BackgroundWorker bw = new BackgroundWorker();

// Constructor

public MainPage()

InitializeComponent();

//h tr cho php hy

bw.WorkerSupportsCancellation = true;

//h tr cho php cp nht

Trung Tm Tin Hc H KHTN-TP.HCM Trang 268/617


Gio trnh: Lp trnh Windows Phone

bw.WorkerReportsProgress = true;

//s kin kch hot bt u chy BackgroundWorker

bw.DoWork += bw_DoWork;

//S kin cp nht

bw.ProgressChanged += bw_ProgressChanged;

//s kin nh du l xong

bw.RunWorkerCompleted += bw_RunWorkerCompleted;

// Sample code to localize the ApplicationBar

//BuildLocalizedApplicationBar();

private void buttonStart_Click(object sender, RoutedEventArgs e)

//Nu khng bn

if (bw.IsBusy != true)

//gi lnh kch hot BackgroundWorker

bw.RunWorkerAsync();

private void buttonCancel_Click(object sender, RoutedEventArgs e)

//Nu cho php hy

if (bw.WorkerSupportsCancellation == true)

//gi lnh hy

Trung Tm Tin Hc H KHTN-TP.HCM Trang 269/617


Gio trnh: Lp trnh Windows Phone

bw.CancelAsync();

//S kin chy Background

//Khng cp nht giao din trong ny m truyn qua

//bw_ProgressChanged bng lnh ReportProgress

private void bw_DoWork(object sender, DoWorkEventArgs e)

BackgroundWorker worker = sender as BackgroundWorker;

for (int i = 1; i <= 10; i++)

if ((worker.CancellationPending == true))

e.Cancel = true;

break;

else

// Perform a time consuming operation and report progress.

System.Threading.Thread.Sleep(500);

worker.ReportProgress(i * 10);

//s kin cp nht giao din

private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 270/617


Gio trnh: Lp trnh Windows Phone

this.tbProgress.Text = (e.ProgressPercentage.ToString() + "%");

//s kin nh du hon thnh.

private void bw_RunWorkerCompleted(object sender,


RunWorkerCompletedEventArgs e)

if (e.Cancelled == true)

this.tbProgress.Text = "Canceled!";

else if (!(e.Error == null))

this.tbProgress.Text = ("Error: " + e.Error.Message);

else

this.tbProgress.Text = "Done!";

V d cp nht giao din thi gian thc c i s truyn vo:

XAML nh sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 271/617


Gio trnh: Lp trnh Windows Phone

Giao din cho php cp nht Button ng v hin th % tin trnh c thc
hin:

<phone:PhoneApplicationPage

x:Class="Learn_BackgroundWorker.Page1"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

Trung Tm Tin Hc H KHTN-TP.HCM Trang 272/617


Gio trnh: Lp trnh Windows Phone

SupportedOrientations="Portrait" Orientation="Portrait"

mc:Ignorable="d"

shell:SystemTray.IsVisible="True">

<StackPanel HorizontalAlignment="Left" Height="768" VerticalAlignment="Top"


Width="480">

<StackPanel Height="88" Orientation="Horizontal" Margin="0,0,10,0">

<TextBlock TextWrapping="Wrap" Text="Input N:"


VerticalAlignment="Center"/>

<TextBox x:Name="txtN" TextWrapping="Wrap" Width="181"/>

<Button x:Name="btnOK" Content="OK" Click="btnOK_Click"/>

<Button x:Name="btnCancel" Content="Cancel" Click="btnCancel_Click"/>

</StackPanel>

<StackPanel Height="50" >

<TextBlock Height="50" x:Name="txtProgressBar" Foreground="Red"


VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="20"
FontWeight="Bold"/>

</StackPanel>

<ScrollViewer>

<StackPanel x:Name="mystack" Height="667"/>

</ScrollViewer>

</StackPanel>

</phone:PhoneApplicationPage>

Source code x l:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 273/617


Gio trnh: Lp trnh Windows Phone

using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

using System.ComponentModel;

namespace Learn_BackgroundWorker
{
public partial class Page1 : PhoneApplicationPage
{
BackgroundWorker bw = new BackgroundWorker();
public Page1()
{
InitializeComponent();

bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += bw_DoWork;
bw.ProgressChanged += bw_ProgressChanged;
bw.RunWorkerCompleted += bw_RunWorkerCompleted;
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = sender as BackgroundWorker;
Random rd = new Random();
int so = (int)e.Argument;
for (int i = 1; i <= so; i++)
{
if (bw.CancellationPending)
{

Trung Tm Tin Hc H KHTN-TP.HCM Trang 274/617


Gio trnh: Lp trnh Windows Phone

e.Cancel = true;
break;
}
System.Threading.Thread.Sleep(1000);
bw.ReportProgress((int)((i*1.0/so)*100), rd.Next(-100, 100));
}
}
void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
txtProgressBar.Text = e.ProgressPercentage + "%";
Button b = new Button();
b.Content = e.UserState;
b.Height = 100;
mystack.Children.Add(b);
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
txtProgressBar.Text = "Canceled!";
}

else if (!(e.Error == null))


{
txtProgressBar.Text = ("Error: " + e.Error.Message);
}

else
{
txtProgressBar.Text += "-Done!";
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 275/617


Gio trnh: Lp trnh Windows Phone

}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
if (bw.IsBusy == false)
{
mystack.Children.Clear();
int so = 0;
int.TryParse(txtN.Text, out so);
bw.RunWorkerAsync(so);
}
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
if (bw.CancellationPending)
bw.CancelAsync();
}
}
}

2. Task

Task i din cho mt s cng vic cn phi hon thnh. Cc cng vic ny c
th chy trong 1 thread ring hoc c th thc thi mt cch ng b, v kt qu c ch
i tr v thread gi n.

Task l mt lp tru tng, bn c nhiu kim sot hn l vic s dng Thread.

Task cho php bn t chc cng vic mt cch linh hot. V d:

nh ngha cc cng vic tip theo, c lm sau khi 1 task khc kt thc.
Cng vic c th khc khi cng vic trc thc thi thnh cng hay tht
bi.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 276/617


Gio trnh: Lp trnh Windows Phone

Nhn c kt qu tr t mt lung khc.


Kim sot li tt hn.
D dng ch i 1 hay nhiu Task thc thi xong.
Ta dng th vin : using System.Threading.Tasks;

To mt Task

C rt nhiu cch to Task, sau y gio trnh s trnh by mt s cch thng s


dng:

Cch 1: Dng phng thc Run ca lp Task

public void Dosomething()

int s = 0;

for (int i = 0; i < 10; i++)

s += i;

Dispatcher.BeginInvoke(() => { MessageBox.Show("s=" + s); });

private void Button_Click(object sender, RoutedEventArgs e)

Task.Run(() => { Dosomething(); });

Cch 2 : Dng phng thc StartNew:

public void GiaiThua(int n)

int s = 1;

for (int i = 1; i <= 10; i++)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 277/617


Gio trnh: Lp trnh Windows Phone

s *= i;

Dispatcher.BeginInvoke(() => { MessageBox.Show("s=" + s); });

private void Button_Click(object sender, RoutedEventArgs e)

Task.Factory.StartNew(() => GiaiThua(8));

Cch 3: S dng phng thc Start

public async void getDataFromWeb()

string s = "";

HttpClient client = new HttpClient();

Task<string> sTask= client.GetStringAsync("http://duythanhcse.wordpress.com");

s = await sTask;

Dispatcher.BeginInvoke(() => { MessageBox.Show("s=" + s); });

private void Button_Click(object sender, RoutedEventArgs e)

Action actionCall = new Action(getDataFromWeb);

Task t = new Task(actionCall);

t.Start();

V d trn l ta c ni dung t mt website, ta s dng thm th vin using


System.Net.Http, ch l ti th vin ny t NuGet packages.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 278/617


Gio trnh: Lp trnh Windows Phone

Thc hin Task lin tip


Khi s dng Task, Ta c th ch ra 1 cng vic thc hin sau khi mt cng vic
khc hon thnh (tng t nh Background Worker phn trn). Ta s dng
ContinueWith.

Ta dng TextBlock hin th thng tin cho d quan st:

<TextBlock x:Name="txtTrace" HorizontalAlignment="Left" Margin="30,298,0,0"


Grid.Row="1" TextWrapping="Wrap" VerticalAlignment="Top" Height="345" Width="419"/>

X l coding:

private void Button_Click_1(object sender, RoutedEventArgs e)

txtTrace.Text = "";

var t1 = new Task(DoOnFirst);

var t2 = t1.ContinueWith(DoOnSecond);

t1.Start();

public void showInfor(string s)

Dispatcher.BeginInvoke(()=>txtTrace.Text+=s+"\n");

public void DoOnFirst()

string s = "doing some task " + Task.CurrentId;

showInfor(s);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 279/617


Gio trnh: Lp trnh Windows Phone

System.Threading.Thread.Sleep(3000);

public void DoOnSecond(Task t)

string s = "task " + t.Id + " finished";

showInfor(s);

s = "this task id " + Task.CurrentId;

showInfor(s);

s = "do some cleanup";

showInfor(s);

System.Threading.Thread.Sleep(3000);

c bit ta cng c th ch ra iu kin thc hin cng vic tip theo khi cng vic
trc hon thnh. Trong v d di y, Task 3 s thc hin trong trng hp Task 2
thc thi qu lu, bng cch s dng TaskContinuationOptions.

private void Button_Click_1(object sender, RoutedEventArgs e)

txtTrace.Text = "";

var t1 = new Task(DoOnFirst);

var t2 = t1.ContinueWith(DoOnSecond);

var t3 = t2.ContinueWith(DoOnThird, TaskContinuationOptions.LongRunning);

t1.Start();

Trung Tm Tin Hc H KHTN-TP.HCM Trang 280/617


Gio trnh: Lp trnh Windows Phone

Nhn kt qu tr v t Task

nhn c kt qu tr v t Task, Ta s dng class Task<T> vi T l kiu d


liu ca kt qu tr v, sau dng task.Result ly kt qu tr v. Gio trnh s trnh
by mt s cch thng s dng:

Cch 1: Dng Run

public int Fib(int n)

if (n <= 2) return 1;

return Fib(n - 2) + Fib(n - 1);

private void Button_Click_2(object sender, RoutedEventArgs e)

var task = Task.Run(()=>Fib(10));

MessageBox.Show("Fib="+task.Result);

Cch 2: Dng StartNew

public bool isPrime(int n)

if (n <= 1) return false;

for (int i = 2; i <= Math.Sqrt(n); i++)

if (n % i == 0) return false;

return true;

private void Button_Click_2(object sender, RoutedEventArgs e)

int n = 55;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 281/617


Gio trnh: Lp trnh Windows Phone

var task = Task.Factory.StartNew(() => isPrime(n));

if (task.Result == true)

MessageBox.Show(n+" l s nguyn t");

Cch 3: S dng Delegate:

private void Button_Click_3(object sender, RoutedEventArgs e)

var task = Task.Factory.StartNew(delegate

double s = 0.0;

int x=2;

int n=5;

for(int i=1;i<=n;i++)

s+=Math.Pow(x,i)/i;

return s;

});

MessageBox.Show("Kt qu =" + task.Result);

Cch 4: Kt hp chui Task thc hin vi kt qu tr v

private void Button_Click_4(object sender, RoutedEventArgs e)

int[] nums = { 2,19, 17, 21, 4, 13, 8, 12, 7, 3, 5 };

Trung Tm Tin Hc H KHTN-TP.HCM Trang 282/617


Gio trnh: Lp trnh Windows Phone

var f0 = new Task<double>(() => nums.Average());

//t chnh l task f0, t.Result tr v trung bnh cng ca nums

//v t.Result c s dng l mean cho cch tnh lnh chun

var f1 = f0.ContinueWith(t => GetStandardDeviation(nums, t.Result));

f0.Start();

string s="the standard deviation is "+f1.Result;

MessageBox.Show(s);

private static double GetStandardDeviation(int[] values, double mean)

double d = 0.0;

foreach (var n in values)

d += Math.Pow(mean - n, 2);

return Math.Sqrt(d / (values.Length - 1));

Ch thc thi mt hoc nhiu Task

ch i 1 Task hon thnh, ta gi hm Task.Wait.

private void Button_Click_5(object sender, RoutedEventArgs e)

var task = Task.Factory.StartNew(() =>

int n = 5;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 283/617


Gio trnh: Lp trnh Windows Phone

int s = 0;

for (int i = 1; i <= n; i++)

s += i;

return s;

});

task.Wait();

MessageBox.Show("s="+task.Result);

ch i nhiu Task thc thi xong, Ta gi hm Task.WaitAll(Task[]).

public int Func1(int x)

return x * 2;

public void Func2()

Dispatcher.BeginInvoke(() => { MessageBox.Show("Lm ci g !"); });

private void Button_Click_6(object sender, RoutedEventArgs e)

var task1 = Task.Factory.StartNew(() => Func1(6));

var task2 = Task.Factory.StartNew(() => Func2());

Task.WaitAll(task1, task2);

MessageBox.Show("x ca task1="+task1.Result);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 284/617


Gio trnh: Lp trnh Windows Phone

IV. Async v Await


Nu phng thc chng ta s dng async, th phng thc c kh nng:

Phng thc bt ng b c th s dng await to im dng ch thc


hin xong. Ton t await yu cu trnh bin dch ra lnh cho hm bt ng b phi ch
cho ti khi dng awaited x l xong. Trong khi ch i, dng iu khin s tr v ch
gi hm bt ng b.
Phng thc bt ng b c th t n awaited bng phng thc gi n.
V d v Async:

// You can use this code to create either a WPF app or a Windows Store app.

// Either way, the code requires Visual Studio 2012.

// You need a button (StartButton) and a textbox (ResultsTextBox).

// To create this example as a Windows Store app, you must add using

// directives for System.Net.Http and System.Threading.Tasks.

// To create this example as a desktop app, you must add a reference and a

// using directive for System.Net.Http.

private async void StartButton_Click(object sender, RoutedEventArgs e)

// ExampleMethodAsync returns a Task<int> and has an int result.

// A value is assigned to intTask when ExampleMethodAsync reaches

// an await.

try

Task<int> intTask = ExampleMethodAsync();

Trung Tm Tin Hc H KHTN-TP.HCM Trang 285/617


Gio trnh: Lp trnh Windows Phone

// You can do other work here that doesn't require the result from

// ExampleMethodAsync. . . .

ResultsTextBox.Text += "Doing other work before awaiting intTask. . . . .\n";

// Wait for intTask to complete, and then access the int result.

int intResult = await intTask;

// Or you can combine the previous two steps:

//int intResult = await ExampleMethodAsync();

// Process the result (intResult) . . . .

ResultsTextBox.Text += String.Format("Length: {0}\n\n", intResult);

catch (Exception)

// Process the exception. . . .

public async Task<int> ExampleMethodAsync()

var httpClient = new HttpClient();

// The following line activates GetStringAsync, which is an asynchronous method.

Task<string> contentsTask =
httpClient.GetStringAsync("http://msdn.microsoft.com");

Trung Tm Tin Hc H KHTN-TP.HCM Trang 286/617


Gio trnh: Lp trnh Windows Phone

// While the task is active, you can do other work.

ResultsTextBox.Text += "Doing other work before awaiting contentsTask. . . . .\n";

// When you await contentsTask, execution in ExampleMethodAsync is suspended,

// and control returns to the caller, StartButton_Click.

string contents = await contentsTask;

// After contentTask completes, you can calculate the length of the string.

int exampleInt = contents.Length;

//// You can combine the previous sequence into a single statement.

//int exampleInt = (await


httpClient.GetStringAsync("http://msdn.microsoft.com")).Length;

ResultsTextBox.Text += "Preparing to finish ExampleMethodAsync.\n";

// After the following return statement, any method that's awaiting

// ExampleMethodAsync (in this case, StartButton_Click) can get the integer result.

return exampleInt;

// Sample output:

// Doing other work before awaiting contentsTask. . . . .

// Doing other work before awaiting intTask. . . . .

// Preparing to finish ExampleMethodAsync.

// Length: 53292

V d await:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 287/617


Gio trnh: Lp trnh Windows Phone

private async void button1_Click(object sender, EventArgs e)


{
// Call the method that runs asynchronously.
string result = await WaitAsynchronouslyAsync();

// Call the method that runs synchronously.


//string result = await WaitSynchronously ();

// Display the result.


textBox1.Text += result;
}
// The following method runs asynchronously. The UI thread is not
// blocked during the delay. You can move or resize the Form1 window
// while Task.Delay is running.
public async Task<string> WaitAsynchronouslyAsync()
{
await Task.Delay(10000);
return "Finished";
}
// The following method runs synchronously, despite the use of async.
// You cannot move or resize the Form1 window while Thread.Sleep
// is running because the UI thread is blocked.
public async Task<string> WaitSynchronously()
{
// Add a using directive for System.Threading.
Thread.Sleep(10000);
return "Finished";
}

V. Kt lun
Lp trnh ng b v bt ng b trong Windows Phone mang ngha rt to ln.
Thng qua bt ng b ta c th qun l cc tc v khc nhau, s dng
BackgroundWorker cp nht giao din vi thi gian thc. Hu ht cc API c cung
cp trong Windows Phone u s dng k thut bt ng b, nn nm c k thut ny
s gip cho ta d dng khm ph Windows Phone.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 288/617


Gio trnh: Lp trnh Windows Phone

BI 6. QUN L CC NG DNG CHY NGM


(Background Task)
c th tip tc chy ng dng trong khi phn mm khng cn trong Foreground
liftime chng hn nh tip tc m nhc khi tt ng dng, t ng hin th cnh bo v nhc
nh, thng bo cuc gi n, sms n... i vi lp trnh mobile ni chung v lp trnh
Windows Phone ni ring th y l mt trong nhng c tnh khng th thiu.

Ni dung ca phn ny s cp ti nhng phn sau:


I) Background tasks ................................................................................299
II) Alarms v Reminder ...........................................................................299
1) Alarms .............................................................................................................. 300
2) Reminder .......................................................................................................... 304
III) Background Transfer Service .............................................................308
IV) Generic Background Agents................................................................317
V) Background audio ...............................................................................322
VI) Kt lun ...............................................................................................325

Trung Tm Tin Hc H KHTN-TP.HCM Trang 298/617


Gio trnh: Lp trnh Windows Phone

I. Background tasks
Windows Phone xy dng flatform chy nn cho php ngi s dng tng tc
theo 2 kch bn nh sau:

Ngi s dng mun m mt vi ng dng trng thi foreground lifetime


sau m qua ng dng khc th nhng ng dng trc vn c chy ngm, v
d: Ngi s dng ang nghe 1 bi nhc, sau m email ln xem th nhc vn tip
tc chy nn.
Ngi s dng cu hnh mt ng dng chy nn khng l thuc vo nhng
ng dng m h ang thao tc, v d: H cu hnh cnh bo gi gic, cuc hn.
lm c 2 kch bn trn, Windows Phone h tr 4 loi Background task nh sau:

Alarms v reminders: Cho php gi chng trnh 1 ln hoc theo nh k m


khng l thuc vo ng dng m ngi s dng ang thao tc.
Background Transfer Service: Cho php download v upload background
Generic Background Agents: Cho php chy Background khi ng dng khng
cn trong trng thi Foreground lifetime.
Background audio: Cho php m Audio trong Foreground lifetime v tip tc
c m khi khng cn trong Foreground lifetime
Vic cho ng dng va chy foreground lifetime v chy nn thng tng nguy c
v tranh chp ti nguyn phn cng, hiu r hn v cch qun l chng trnh
Background trong Windows Phone ta s i vo chi tit di y.

II. Alarms v Reminder


Alarms v Reminder l 2 flatform cng chung loi UX (User Experience). C 2
trng hp ny u kch hot mt Notification ngi s dng c th la chn cc tc
v c thit k trong ng dng. Notification l mt mn hnh di dng Dialog box c
hin th ti mt thi im c th no , n c th hin th Text, Nt lnh v ngi s dng
c th Dismiss (tt) v Postpone (hon) Notification. Alarm v Reminder n ch khc nhau

Trung Tm Tin Hc H KHTN-TP.HCM Trang 299/617


Gio trnh: Lp trnh Windows Phone

vi vi im nh: Alarm ta c th thit lp Sound khi Notification c kch hot, vi


Reminder ta c th m 1 trang trong ng dng khi ngi s dng chm vo Reminder UI.

1. Alarms

Alarm c xy dng t Windows Phone 7.0, ta phi using


Microsoft.Phone.Scheduler.

Di y l cc bc to mt Alarm:

Bc 1: To mt i tng Alarm
Bc 2: Thit lp cc thuc tnh cho Alarm
Bc 3: a Alarm vo ScheduledActionService

V d cho cc bc trn:

//t tn Alarm l Cafe, n phi l duy nht, nu trc c Alarm no t tn ny


ri th khng c t na

Alarm alarm = new Alarm("Cafe");

//Ni dung Alarm

alarm.Content = "Ngh tra ri! i c ph nh bn!";

//Thi gian bt u kch hot

alarm.BeginTime = DateTime.Now.AddSeconds(5);

alarm.ExpirationTime = DateTime.Now.AddSeconds(10);

//Thit lp Sound cho Alarm

alarm.Sound = new Uri("/Assets/ringout.wav", UriKind.Relative);

//a vo ScheduledActionService

ScheduledActionService.Add(alarm);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 300/617


Gio trnh: Lp trnh Windows Phone

Ta c th dng DateTime.Now.AddHours; DateTime.Now.AddMinutes

Ta cng c th thit lp danh sch cc Alarm, gi s ta c 9 tp tin sound v to ra


9 Alarm, mi ln Alarm c gi th n s m tn sound tng ng:

Source Code:

private void btnAddListAlarm_Click(object sender, RoutedEventArgs e)

for (int i = 1; i < 10; i++)

try

Alarm alarm = new Alarm("ten"+i);

alarm.Content = "Ni dung thng bo th "+i;

alarm.BeginTime = DateTime.Now.AddSeconds(5*i);

alarm.ExpirationTime = DateTime.Now.AddSeconds(10 * i);

string s = string.Format("/Assets/Ring0{0}.wav", i);

alarm.Sound = new Uri(s, UriKind.Relative);

ScheduledActionService.Add(alarm);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 301/617


Gio trnh: Lp trnh Windows Phone

catch (Exception ex)

MessageBox.Show(ex.Message);

Bn ch l Alarm khng l thuc vo ng dng ca ta ang chy (ta tt ng ng


th n vn hot ng). Mt vn sy ra l lm sao hy cc Alarm vo to trc ?

Trc tin ta cn bit cch ly tp cc Alarm c nh ngha trong ng dng:

ScheduledActionService.GetActions<Alarm>();

Khi gi hm trn s tr v mt danh sch cc Alarm c nh ngha.

hy ton b Alarm sy ra trc thi im hin ti v sau thi gian hin ti


(cha sy ra), ta lm nh sau:

private void btnRemoveAlarm_Click(object sender, RoutedEventArgs e)

IEnumerable<Alarm> oldAlarms =
ScheduledActionService.GetActions<Alarm>();

foreach (Alarm alarm in oldAlarms)

ScheduledActionService.Remove(alarm.Name);

Ta c th xa Alarm theo iu kin thi gian, v d:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 302/617


Gio trnh: Lp trnh Windows Phone

private void btnRemoveAlarm_Click(object sender, RoutedEventArgs e)

IEnumerable<Alarm> oldAlarms =
ScheduledActionService.GetActions<Alarm>();

foreach (Alarm alarm in oldAlarms)

if (alarm.ExpirationTime < DateTime.Now)

ScheduledActionService.Remove(alarm.Name);

Trong mt s trng hp ngi s dng s nh ngha hng lot cc Alarm, sau


li tin hnh xa mt vi Alarm c th no . c th xa c bt k mt Alarm no
do ngi s dng quy nh th ta s kim tra theo tn ca Alarm trc khi tin hnh gi
lnh xa ca lp ScheduledActionService, v d bn di l xa Alarm c tn ten1:

private void btnRemoveAlarmByName_Click(object sender, RoutedEventArgs e)

IEnumerable<Alarm> oldAlarms =
ScheduledActionService.GetActions<Alarm>();

foreach (Alarm alarm in oldAlarms)

if(alarm.Name=="ten1")

Trung Tm Tin Hc H KHTN-TP.HCM Trang 303/617


Gio trnh: Lp trnh Windows Phone

ScheduledActionService.Remove(alarm.Name);

2. Reminder

Reminder cho php hin th nhc nh, khi ngi s dng chm vo th m ra mt
trang mi:

Tng t nh Alarm, ta cng phi s dng th vin using


Microsoft.Phone.Scheduler; ta c cc bc sau to 1 Reminder:

Bc 1: To mt i tng Reminder
Bc 2: Thit lp cc thuc tnh cho Reminder
Bc 3: a Alarm vo ScheduledActionService

Trung Tm Tin Hc H KHTN-TP.HCM Trang 304/617


Gio trnh: Lp trnh Windows Phone

Di y l Source code mu to 1 Reminder:

private void btnAddReminder_Click(object sender, RoutedEventArgs e)

{
var uniqueName = Guid.NewGuid().ToString();
//to i tng reminder

Reminder reminder = new Reminder(uniqueName);


//thi gian bt u
reminder.BeginTime = DateTime.Now.AddSeconds(3);
//thi gian kt thc
reminder.ExpirationTime = DateTime.Now.AddSeconds(10);
//tiu
reminder.Title = "M trang mi khng?";
//ni dung hin th

reminder.Content = "Chm vo y m trang mi";


//iu hng ti trang mi

reminder.NavigationUri = new Uri("/newpage.xaml", UriKind.Relative);

try
{
//a vo ScheduledActionService
ScheduledActionService.Add(reminder);
}

catch (InvalidOperationException ex)


{

MessageBox.Show(ex.Message);
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 305/617


Gio trnh: Lp trnh Windows Phone

Khi Reminder hin th ln, ngi s dng c th thit lp thm thng tin.

Tng t nh Alarm, ta c th to danh sch Reminder, xa cc Reminder theo cc


thng s khc nhau.

V d di y cho php to 5 Reminder m 5 hnh khc nhau:

To ng dng c cu trc v ni dung nh hnh trn, T MainPage s to 5


Reminder v cho php m trang newpage.xaml ln, tng ng vi mi Reminder s load
5 hnh khc nhau.

Source Code Mainpage.xaml.cs:

private void btnCreateReminderList_Click(object sender, RoutedEventArgs e)

var oldReminders = ScheduledActionService.GetActions<Reminder>();

foreach (Reminder r in oldReminders)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 306/617


Gio trnh: Lp trnh Windows Phone

ScheduledActionService.Remove(r.Name);

for (int i = 1; i <= 5; i++)

Reminder reminder = new Reminder("reminder"+i);

//thi gian bt u

reminder.BeginTime = DateTime.Now.AddSeconds(3);

//thi gian kt thc

reminder.ExpirationTime = DateTime.Now.AddSeconds(10);

//tiu

reminder.Title = "M trang mi khng?";

//ni dung hin th

reminder.Content = "Chm vo y m trang mi";

//iu hng ti trang mi

string pageUir = string.Format("/newpage.xaml?hinh=hinh{0}.png", i);

reminder.NavigationUri = new Uri(pageUir, UriKind.Relative);

ScheduledActionService.Add(reminder);

Ch t kha hinh ng sau du ? l key truy sut d liu nm trong trang


newpage.xaml.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 307/617


Gio trnh: Lp trnh Windows Phone

trang newpage.xaml.cs ta c ni dung khi ngi s dng nhn vo Reminder


hin th ln nh sau:

protected override void OnNavigatedTo(NavigationEventArgs e)

base.OnNavigatedTo(e);

string hinh=NavigationContext.QueryString["hinh"];

string hinh_path = "/Assets/images/" + hinh;

BitmapImage img=new BitmapImage(new Uri(hinh_path,UriKind.Relative));

myimage.Source = img;

myimage l tn control Image trong giao din ca trang newpage.xaml.

Nh phi s dng thm th vin to using System.Windows.Media.Imaging;


BitmapImage.

III. Background Transfer Service


Khi ti hay upload d liu t website xung ta thng dng HttpWebRequest hay
WebClient, nu nh ni dung qu ln (hnh nh, video c dung lng ln chng hn) th
n s chim rt nhiu thi gian lm cho ng dng b treo, gii quyt vn ny th c
c th s dng Background Transfer Service (Microsoft.Phone.BackgroundTransfer)

C ch lm vic ca BackgroundTransferService ging nh Xbox live, tc l cho


php ti a mi ln request download l 25MB i vi Cell Network v 100MB khi kt
ni WIFI, c th request download hn 100MB th ta phi thit lp Transfer Preferences
ti None. Vi request upload th cho ti a 5MB, mi 1 ng dng cho cho php request
upload ti a 25 ln v ti a l 500 ln cho tt c cc ng dng trong in thoi.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 308/617


Gio trnh: Lp trnh Windows Phone

Cc bc lp trnh vi dch v ny nh sau:

Bc 1: Thm cc th vin sau vo ng dng

using System.IO;

using System.IO.IsolatedStorage;

using Microsoft.Phone.BackgroundTransfer;

Bc 2: To IsolatedStorageFile

private IsolatedStorageFile isf;

public MainPage()

isf = IsolatedStorageFile.GetUserStoreForApplication();

Bc 3: To i tng BackgroundTransferRequest bng cch dng constructor


c 2 i s, i s th nht l Uri mun ti v, i s th 2 l ni lu tr tp tin ti v

Uri remoteFileUri=new Uri(@"http://drthanh.com/abc.wmv",UriKind.Absolute);

Uri localFileUri =new Uri("/shared/transfers/save_abc.wmv", UriKind.Relative);

BackgroundTransferRequest btr;

btr = new BackgroundTransferRequest(remoteFileUri, localFileUri);

Bc 4: Gn i tng btr cho BackgroundTransferService:

BackgroundTransferService.Add(btr);

Bc 5: Gn cc s kin ang ti thi gian thc v s kin kim tra qu trnh ti


cho BackgroundTransferRequest:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 309/617


Gio trnh: Lp trnh Windows Phone

btr.TransferProgressChanged += btr_TransferProgressChanged;

btr.TransferStatusChanged += btr_TransferStatusChanged;

// Match the progress bar to the filesize and current download status.

private void btr_TransferProgressChanged(

object sender, BackgroundTransferEventArgs e) {

//to tiu trnh cp nht Progressbar

Dispatcher.BeginInvoke(() =>

// tng s byte s ti

progressBar.Maximum = btr.TotalBytesToReceive;

//s byte ti xong

progressBar.Value = btr.BytesReceived;

});

private void btr_TransferStatusChanged(object sender,


BackgroundTransferEventArgs e)

// ti hon thnh

if (btr.TransferStatus == TransferStatus.Completed) {

//x l sau khi ti xong

Ta ch l trong qu trnh ti th n t ng lu vo localFileUri, mi ln ta c


BackgroundTransferService.Add(btr); th khi n thc hin s to ra cc localfile v lu tr
vo thit b (nn cu hnh tn file khc nhau, trn l cng tn).

Trung Tm Tin Hc H KHTN-TP.HCM Trang 310/617


Gio trnh: Lp trnh Windows Phone

Bc 6: X l sau khi download xong

truy sut ton tp tin c lu vo thit b sau khi ti xong ta dng cch sau:

public void showallList() {

foreach(BackgroundTransferRequest res in
BackgroundTransferService.Requests)

res.BytesReceived;

res.BytesSent;

res.DownloadLocation;

res.TotalBytesToReceive;

Da vo on coding trn ta c th to danh sch hin th ln giao din cho php


ngi dng la chn tng tp tin m (nn dng tiu trnh m).

Nu nh ch mun ly 1 tp tin u tin m th ta lm nh sau:

btr = BackgroundTransferService.Requests.FirstOrDefault();

if (btr.TransferStatus == TransferStatus.Completed)

Dispatcher.BeginInvoke(() =>

using (IsolatedStorageFileStream file =

isf.OpenFile(btr.DownloadLocation.ToString(),

FileMode.Open, FileAccess.Read))

Trung Tm Tin Hc H KHTN-TP.HCM Trang 311/617


Gio trnh: Lp trnh Windows Phone

mediaElement.SetSource(file);

mediaElement.Play();

});

Source code y di y cho php ti video t internet s dng Background


Transfer Service

Thit k giao din XAML:

<phone:PhoneApplicationPage

x:Class="BackgroundTransferDemo.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Trung Tm Tin Hc H KHTN-TP.HCM Trang 312/617


Gio trnh: Lp trnh Windows Phone

xmlns:phone="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Portrait" Orientation="Portrait"

shell:SystemTray.IsVisible="True">

<Grid x:Name="LayoutRoot" Background="Transparent">

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

<RowDefinition Height="*"/>

</Grid.RowDefinitions>

<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">

<TextBlock Text="BACKGROUND TRANSFER DEMO"


Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>

<TextBlock Text="get video" Margin="9,-7,0,0" Style="{StaticResource


PhoneTextTitle1Style}"/>

</StackPanel>

<StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

<StackPanel Orientation="Horizontal">

<Button x:Name="downloadButton" Content="download" Width="226"


Click="downloadButton_Click"/>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 313/617


Gio trnh: Lp trnh Windows Phone

<Button x:Name="playButton" Content="play" IsEnabled="False"


Width="226" Click="playButton_Click" />

</StackPanel>

<ProgressBar x:Name="progressBar" Minimum="0" Margin="0,12"/>

<Border BorderBrush="{StaticResource PhoneForegroundBrush}"


Height="370">

<MediaElement x:Name="mediaElement" Stretch="Uniform"


MediaOpened="mediaElement_MediaOpened" AutoPlay="False" Margin="0,24" />

</Border>

</StackPanel>

</Grid>

</phone:PhoneApplicationPage>

Source code MainPage.xaml.cs:

using System;

using System.IO;

using System.IO.IsolatedStorage;

using System.Linq;

using System.Windows;

using System.Windows.Navigation;

using Microsoft.Phone.BackgroundTransfer;

using Microsoft.Phone.Controls;

namespace BackgroundTransferDemo

public partial class MainPage : PhoneApplicationPage

private static readonly Uri remoteFileUri =

Trung Tm Tin Hc H KHTN-TP.HCM Trang 314/617


Gio trnh: Lp trnh Windows Phone

new Uri(@"http://media.ch9.ms/ch9/4b58/de9f7501-2a51-4875-8b2f-
9f4d014b4b58/IWP22PtorrBkgrndAgnt_ch9.wmv",

UriKind.Absolute);

private static readonly Uri localFileUri =

new Uri("/shared/transfers/movie.wmv", UriKind.Relative);

private IsolatedStorageFile isf;

private BackgroundTransferRequest btr;

public MainPage()

InitializeComponent();

isf = IsolatedStorageFile.GetUserStoreForApplication();

private void downloadButton_Click(object sender, RoutedEventArgs e)

{ btr = new BackgroundTransferRequest(remoteFileUri, localFileUri);

BackgroundTransferService.Add(btr);

btr.TransferProgressChanged += btr_TransferProgressChanged;

btr.TransferStatusChanged += btr_TransferStatusChanged;

downloadButton.IsEnabled = false;

protected override void OnNavigatedTo(NavigationEventArgs e)

btr = BackgroundTransferService.Requests.FirstOrDefault();

if (btr == null) {

downloadButton.IsEnabled = true;

return;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 315/617


Gio trnh: Lp trnh Windows Phone

downloadButton.IsEnabled = false;

btr.TransferProgressChanged += btr_TransferProgressChanged;

btr.TransferStatusChanged += btr_TransferStatusChanged;

if (btr.TransferStatus == TransferStatus.Completed) {

UpdateUi();

// Match the progress bar to the filesize and current download status.

private void btr_TransferProgressChanged(

object sender, BackgroundTransferEventArgs e) {

Dispatcher.BeginInvoke(() =>

progressBar.Maximum = btr.TotalBytesToReceive;

progressBar.Value = btr.BytesReceived;

});

private void btr_TransferStatusChanged(object sender,


BackgroundTransferEventArgs e)

if (btr.TransferStatus == TransferStatus.Completed) {

UpdateUi();

private void UpdateUi()

Trung Tm Tin Hc H KHTN-TP.HCM Trang 316/617


Gio trnh: Lp trnh Windows Phone

Dispatcher.BeginInvoke(() =>

progressBar.Value = btr.BytesReceived;

using (IsolatedStorageFileStream file =

isf.OpenFile(btr.DownloadLocation.ToString(),

FileMode.Open, FileAccess.Read)) {

mediaElement.SetSource(file);

});

private void mediaElement_MediaOpened(object sender, RoutedEventArgs e)


{

playButton.IsEnabled = true;

private void playButton_Click(object sender, RoutedEventArgs e)

mediaElement.Play();

IV. Generic Background Agents


Generic Background Agents (GBA) Cho php chy Background khi ng dng
khng cn trong trng thi Foreground lifetime, Windows phone h tr 2 loi GBA:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 317/617


Gio trnh: Lp trnh Windows Phone

Periodic (PeriodicTask class): Cho php chy Background trong thi gian
ngn, thi gian ti a chy l 25 giy, chy trong khong 30 pht (n cng c th co
gin trong on t 20 ti 40 pht ty vo ti nguyn thit b).
Resource-intensive (ResourceIntensiveTask class): Cho php chy
Background trong thi gian di v n ch c thc hin khi c mt tp cc iu kin c
xc nhn. ResourceIntensiveTask c th thc thi ti a 10 pht cho mi ln chy khi cc
iu kin sau c tha mn:
in thoi s dng external power
Kt ni internet qua Wi-Fi
Pin ln hn 90 phn trm
Mn hnh thit b ang b kha
Khng c cuc gi no ang thc hin

Mi quan h gia cc Background Agent Component

Cc bc thc hin GBA:


Bc 1. To Main App Project
Bc 2. Thm 1 Project Windows Phone Scheduled Task Agent vo solution,

Trung Tm Tin Hc H KHTN-TP.HCM Trang 318/617


Gio trnh: Lp trnh Windows Phone

Bc 3. T Main App Project va to bc 1 ta tham chiu ti Agent project


bc 2.
Bc 4. Cp nht li Main App Manifest : Thm ExtendedTaskentry to
background agent.
Bc 5. Trong Main Project, gi hm ScheduledActionService.Add ng k
Agent vi h thng.
Bc 6. Gi ScheduledActionService.LaunchForTest kch hot chng trnh
test kh nng chy Agent (c th b qua bc ny).
Bc 7. Trong Agent Project to bc 2, To lp k tha t ScheduledTaskAgent,
Ta phi override hm OnInvoke thc hin cc chc nng chy nn m ta mun.
Ngoi ra ti thi im ny ta c th test nu nh Agent ny l loi periodic
(PeriodicTask class) hocr resource-intensive agent (ResourceIntensiveTask
class). Thng thng h thng t to lp k tha t ScheduledTaskAgent tn l
ScheduledAgent gim ta ri.
Bc 8. Trong Agent m bo rng ta c gi NotifyComplete khi tc v thc hin
xong ( m bo rng phi ch cho tt c cc tc v bt ng b khc hon thnh).
Chi tit cho cc bc trn:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 319/617


Gio trnh: Lp trnh Windows Phone

Hiu chnh WMAppManifest.xml.

<Tasks>

<DefaultTask Name="_default" NavigationPage="MainPage.xaml" />

<ExtendedTask Name="BackgroundTask">

<BackgroundServiceAgent Specifier="ScheduledTaskAgent"
Name="GeoAgent" Source="GeoAgent" Type="GeoAgent.ScheduledAgent" />

</ExtendedTask>

</Tasks>

Tin hnh gi ScheduledActionService.Add v


ScheduledActionService.LaunchForTest

private void StartButton_Click(object sender, RoutedEventArgs e)

PeriodicTask task = new PeriodicTask(agentId);

task.Description = "Timestamped position data";

task.ExpirationTime = DateTime.Now.AddDays(1);

Debug.WriteLine(task.LastExitReason.ToString());

if (ScheduledActionService.Find(agentId) != null)

ScheduledActionService.Remove(agentId);

try

ScheduledActionService.Add(task);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 320/617


Gio trnh: Lp trnh Windows Phone

ScheduledActionService.LaunchForTest(agentId,

TimeSpan.FromSeconds(10));

catch (InvalidOperationException ex)

if (ex.Message.Contains("BNS Error: The action is disabled"))

MessageBox.Show("The user has disabled background agents for this


application.");

if (ex.Message.Contains("BNS Error: The maximum number of


ScheduledActions of this type have already been added."))

// No action required: the system prompts the user when the hard limit of
periodic tasks has been reached.

Debug.WriteLine(ex.Message);

catch (SchedulerServiceException ex)

// No action required: adding a scheduled task can throw a


SchedulerServiceException if the device has just booted and the Scheduled Action
Service hasnt started yet.

Debug.WriteLine(ex.Message);

override hm OnInvoke trong ScheduledAgent:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 321/617


Gio trnh: Lp trnh Windows Phone

protected override void OnInvoke(ScheduledTask task)

// lm ci g

NotifyComplete();

V. Background audio
Phn ny c trnh by s lc trong phn Multimedia, gio trnh s tng quan
li c ch hot ng v cch lp trnh vi Background audio.

Mi quan h gia cc component Background Audio

Trung Tm Tin Hc H KHTN-TP.HCM Trang 322/617


Gio trnh: Lp trnh Windows Phone

M hnh Playing audio tracks vi BackgroundAudioPlayer.

thit lp cho php Audio chy nn (cho d ng dng ca bn khng trong ch


foreground th n cng t ng play audio) th gii php t ra l ta to Windows Phone
Audio Playback Agent ri tham chiu ti Main App project.

Windows Phone APIs h tr 2 loi chy nn Audio, c 2 loi ny u s dng th


vin Microsoft.Phone.BackgroundAudio:

AudioPlayerAgent:
Khi dng Agent ny play Audio th n c th chy nn Audio thm ch khi
ng dng ca chng ta khng vng i Foreground, mt s hm thng dng:

OnPlayStateChanged: Hm ny t ng kim tra s thay i trng thi


play, bao gm: buffering, playing, track ready, track ended, v shutdown.
OnUserAction: Hm ny s c triu gi khi ngi s dng tin hnh
nhng thao tc no trong Applications audio playlist vng i Foreground (dng
controls provider hoc Universal Volume Control)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 323/617


Gio trnh: Lp trnh Windows Phone

OnError: Hm ny s c triu gi khi c li sy ra trong qu trnh audio


playback.

Kin trc AudioPlayerAgent

AudioStreamingAgent:
Khi dng Agent ny s to ra stream audio trong ng dng thng qua.

MediaStreamSource, lp ny cung cp mt s hm sau:

OnBeginStreaming: Hm ny s c triu gi khi ta bt u Audio


Streaming
OnCancel: Hm ny s c triu gi khi Audio Stream b hy.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 324/617


Gio trnh: Lp trnh Windows Phone

Kin trc AudioStreamingAgent

VI. Kt lun
Ta nghin cu nhng background m Windows Phone thng s dng, n h
tr 4 loi Background task nh sau:

Alarms v reminders: Cho php gi chng trnh 1 ln hoc theo nh k m


khng l thuc vo ng dng m ngi s dng ang thao tc.
Background Transfer Service: Cho php download v upload background
Generic Background Agents: Cho php chy Background khi ng dng khng
cn trong trng thi Foreground lifetime.
Background audio: Cho php m Audio trong Foreground lifetime v tip tc
c m khi khng cn trong Foreground lifetime.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 325/617


Gio trnh: Lp trnh Windows Phone

BI 7. S DNG LIVE TILES TRONG WINDOWS PHONE 8


(Live Tiles)
Live Tiles l mt trong nhng tin ch rt hay ca Windows Phone 8, n cung cp
nhng k thut gip ngi s dng tng tc c vi phn mm thm ch phn mm
khng Running. Live Tiles nm mn hnh Start Screen gip ngi s dng c th khi
ng ng dng mt cch nhanh chng cng nh c th xem c cc thng tin tng quan
khc.

Ni dung ca phn ny s cp ti nhng phn sau:


I) Gii thiu Live Tiles ............................................................................377
II) Cch to Live Tiles ..............................................................................378
1) To Tiles bng XAML ..................................................................................... 379
2) To Tiles bng Code ........................................................................................ 381
III) Cc loi Live Tiles ...............................................................................382
1) Iconic ................................................................................................................ 383
2) Flip.................................................................................................................... 387
3) Cyclic ................................................................................................................ 390
IV) Cch cp nhp Live Tiles ....................................................................393
V) Kt lun ...............................................................................................398

Trung Tm Tin Hc H KHTN-TP.HCM Trang 376/617


Gio trnh: Lp trnh Windows Phone

I. Gii thiu Live Tiles


Mt trong nhng th n tng nht khi chng ta ni v nn tng di ng ca
Microsoft chnh l giao din Live Tiles va p c v con mt va tin dng trong s
dng. Live Tiles chnh l mt trong nhng yu t em n s khc bit thc s ca
Windows Phone so vi Android hay iOS.

Live c ngha l trc tip nh l truyn hnh trc tip cn Tiles l nhng vin gch,
tc ch cc cc vung vung hay ch nht trn giao din chnh ca Windows Phone. Nhng
vin gch ny lun chuyn ng v cung cp nhng thng tin mi nht nn c gi l
Live Tiles, ta xem hnh minh ha v Live Tiles bn di:

Thng a ng dng ca mnh ra mn hnh Start Screen lm Live Tiles ta


lm nh sau:

Nhn tht lu vo phn mm c ci t trong in thoi/ chn Pin to Start t


context menu ng cnh hin th ra:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 377/617


Gio trnh: Lp trnh Windows Phone

Ta cn nh l Primary Tiles khng th xa trong qu trnh runtime, cn Second


Tiles th c th thm v xa trong qu trnh Runtime.

Tiles h tr 3 loi kch thc: small, medium, v large size, ngi s dng c th
nhn vo gc phi trn cng neo Tiles, hoc thay i kch thc ca Tiles:

II. Cch to Live Tiles


Ta c th to Live Tiles trong XAML hoc trong Coding behind, gio trnh s trnh
by tng cch to ty vo tng trng hp m lp trnh vin c th ty bin.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 378/617


Gio trnh: Lp trnh Windows Phone

1. To Tiles bng XAML

Tiles hin nay c h tr c 3 loi Template, c 3 loi ny u c thuc tnh Title


v Count. Cc Tile vi biu tng Small ch c hnh i din m khng c Animation.

Flip: H tr Medium v large size tiles gip ta c th flip animation mt cch


ngu nhin theo mt thi gian no . Mt trc ca Tiles hin th thng tin chnh
(primary information) v mt sau hin th cc thng tin b sung (Secondary
information).
Iconic: Hin th cc biu tng hnh nh theo Windows Phone Design
Principles, hnh nh ny gip ta d xem thng tin, nhng biu tng ln c b sung thm
message v 3 dng text ng cnh.
Cycle: Cho php thit lp ti 9 Images v chng c animated vi nhau.
Cch to Tile nhanh nht l ta hiu chnh trc tip trong WMAppManifest.xml bng cch
double click vo file ny, giao din GUI hin th ln cho php ta hiu chnh:

Sau khi cu hnh song, ta m WMAppManifest.xml di dng XML (bm


chut phi vo file ny/ chn View Code) v quan st:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 379/617


Gio trnh: Lp trnh Windows Phone

<PrimaryToken TokenID="LiveTilesToken" TaskName="_default">

<TemplateFlip>

<SmallImageURI IsRelative="true" IsResource="false">

Assets\Tiles\FlipCycleTileSmall.png

</SmallImageURI>

<Count>0</Count>

<BackgroundImageURI IsRelative="true" IsResource="false">

Assets\Tiles\FlipCycleTileMedium.png

</BackgroundImageURI>

<Title>My Title</Title>

<BackContent></BackContent>

<BackBackgroundImageURI IsRelative="true" IsResource="false">

</BackBackgroundImageURI>

<BackTitle></BackTitle>

<LargeBackgroundImageURI IsRelative="true" IsResource="false">

Assets\Tiles\FlipCycleTileLarge.png

</LargeBackgroundImageURI>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 380/617


Gio trnh: Lp trnh Windows Phone

<LargeBackContent />

<LargeBackBackgroundImageURI IsRelative="true" IsResource="false">

</LargeBackBackgroundImageURI>

<DeviceLockImageURI IsRelative="true" IsResource="false">

</DeviceLockImageURI>

<HasLarge>True</HasLarge>

</TemplateFlip>

</PrimaryToken>

Ta cn a thm hnh nh vo c th thc hin c Live Tiles, trong th mc


Assets/Tiles c danh sch cc hnh nh, ta c th thay th chng:

Ch l c c th dng png hoc jpg, nhng nn dng png v n c trong sut


gip Live Tile p mt hn.

2. To Tiles bng Code

Cc template to Live tile nm trong th vin using Microsoft.Phone.Shell;

Di y l mt v d lm Live tile bng coding:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 381/617


Gio trnh: Lp trnh Windows Phone

Mi tile s kt hp vi 1 navigation URI parameter, v navigation URI ny phi


relative path khi ngoi Start Screen ngi s dng nhn chn n s m trang URI ny
ra.

var tileData = new IconicTileData()

Title = "Surf Sites",

SmallIconImage = new Uri("Assets/Tiles/IconicTileSmall.png",


UriKind.Relative),

IconImage = new Uri("Assets/Tiles/IconicTileMediumLarge.png",


UriKind.Relative),

Count = 6

};

Uri uri = new Uri("/SecondPage.xaml", UriKind.Relative);

var tile = ShellTile.ActiveTiles.FirstOrDefault(t =>


t.NavigationUri.Equals(uri));

if (tile == null)

ShellTile.Create(uri, tileData, true);

else

tile.Update(tileData);

};

ShellTile.ActiveTiles.FirstOrDefault dng kim tra xem tile tn ti hay cha,


nu tn ti th cp nht, cn cha th to. Nu ta c gng to mt Tile tn ti th h thng
s thng bo li InvalidOperationException.

III. Cc loi Live Tiles

Trung Tm Tin Hc H KHTN-TP.HCM Trang 382/617


Gio trnh: Lp trnh Windows Phone

Windows Phone h tr mt s dng Template nh Iconic, Flip, Cyclic mi


template c cc c tnh khc nhau, gip ngi s dng d thao tc v giao din p mt.

Cc kch thc hnh nh thng dng.

1. Iconic

Iconic tile dng hin th mt hnh nh trn mt nn do ta quy nh. Tiu s


c hin th bn di Tiles, Message hin th gc phi trn cng, Coun hin th gc
phi di cng, Title ln c hin th gc tri trn cng Tiles (Windows Phone cho ti
a 3 tiu ln). Back color (mu nn) c th c thit lp bng hexadecimal hoc mu
chun.

Ta c th to bng XAML v coding behind:


Cch to bng XAML: Chnh sa trong manifest

<TemplateIconic>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 383/617


Gio trnh: Lp trnh Windows Phone

<SmallImageURI IsRelative="true" IsResource="false">

Assets\Tiles\IconicTileSmall.png

</SmallImageURI>

<Count>6</Count>

<IconImageURI IsRelative="true" IsResource="false">

Assets\Tiles\IconicTileMediumLarge.png

</IconImageURI>

<Title>Title</Title>

<Message>Message</Message>

<BackgroundColor>#5A7594</BackgroundColor>

<HasLarge>True</HasLarge>

<LargeContent1>LargeContent1</LargeContent1>

<LargeContent2>LargeContent2</LargeContent2>

<LargeContent3>LargeContent3</LargeContent3>

<DeviceLockImageURI></DeviceLockImageURI>

</TemplateIconic>

Khi dng XAML th ta phi Pin ng dng ra ngoi Start Screen.

Hnh minh ha y :

Trung Tm Tin Hc H KHTN-TP.HCM Trang 384/617


Gio trnh: Lp trnh Windows Phone

vit bng Coding behind, ta cn to i tng IconicTileData sau gi lnh


ShellTitle.Create()

Uri uri = new Uri("/SecondPage.xaml", UriKind.Relative);

var tileData = new IconicTileData()

Title = "Surf Sites",

SmallIconImage = new Uri("Assets/Tiles/IconicTileSmall.png",


UriKind.Relative),

IconImage = new Uri("Assets/Tiles/IconicTileMediumLarge.png",


UriKind.Relative),

Count = 6,

BackgroundColor = Color.FromArgb(255, 90, 117, 148),

Trung Tm Tin Hc H KHTN-TP.HCM Trang 385/617


Gio trnh: Lp trnh Windows Phone

WideContent1 = "LargeContent1",

WideContent2 = "LargeContent2",

WideContent3 = "LargeContent3",

};

ShellTile.Create(uri, tileData, true);

Ta s dng System.Windows.Media gn mu cho Tile, Color.FromArgb(255,


90, 117, 148) i s u tin lun lun l 255, cc thng s ng sau: RED, GREEN,
BLUE.

XAML Coding behind


Title Title
SmallImageURI SmallIconImage
IconImageURI IconImage
Count Count
Message
BackgroundColor BackgroundColor
LargeContent1 WideContent1
LargeContent2 WideContent2
LargeContent3 WideContent3

Ch l ta cn phi kim tra s tn ti ca Live tile, nu n tn ti m c


gng to th s b li nh cp trn.

ShellTile oldTile= ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri ==


uri);

if (oldTile == null)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 386/617


Gio trnh: Lp trnh Windows Phone

ShellTile.Create(uri, tileData, true);

else

oldTile.Update(tileData);

2. Flip

FLIP cho php TILE thay i lun phin cc trang thng tin, thng thng ta nn
c khong 5 hnh hnh cho Flip template.

1 SmallImageURI (Tile nh khng c flip, nn ch cn 1 hnh)


4 hnh thit lp cho front-and-back (medium v large sizes):
BackgroundImageURI, BackBackgroundImageURI, LargeBackgroundImageURI,
v LargeBackBackgroundImageURI.

Ta c th to Tile ny bng XAML hoc coding:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 387/617


Gio trnh: Lp trnh Windows Phone

<TemplateFlip>

<SmallImageURI IsRelative="true" IsResource="false">

Assets\Tiles\h1XSmall.jpg

</SmallImageURI>

<Count>6</Count>

<BackgroundImageURI IsRelative="true" IsResource="false">

Assets\Tiles\h2XSmall.jpg

</BackgroundImageURI>

<Title>Surf Sites</Title>

<BackContent>Pleasure Point wind 11 to 13 mph</BackContent>

<BackBackgroundImageURI IsRelative="true" IsResource="false">

Assets\Tiles\h3XSmall.jpg

</BackBackgroundImageURI>

<BackTitle>Surf Advisories</BackTitle>

<LargeBackgroundImageURI IsRelative="true" IsResource="false">

Assets\Tiles\h4XSmall.jpg

</LargeBackgroundImageURI>

<LargeBackContent>High surf, poor visibility</LargeBackContent>

<LargeBackBackgroundImageURI IsRelative="true" IsResource="false">

Assets\Tiles\h5XSmall.jpg

</LargeBackBackgroundImageURI>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 388/617


Gio trnh: Lp trnh Windows Phone

<DeviceLockImageURI IsRelative="true"
IsResource="false"></DeviceLockImageURI>

<HasLarge>True</HasLarge>

</TemplateFlip>

Bng coding: Ta cng phi kim tra Tile tn ti hay cha:

Uri uri = new Uri("/SecondPage.xaml", UriKind.Relative);

var tileData = new FlipTileData()

Title = "Surf Sites",

SmallBackgroundImage =

new Uri("Assets/Tiles/h1XSmall.jpg", UriKind.Relative),

BackgroundImage =

new Uri("Assets/Tiles/h2XSmall.jpg", UriKind.Relative),

Count = 6,

BackContent = "Pleasure Point wind 11 to 13 mph",

BackBackgroundImage =

new Uri("Assets/Tiles/h3XSmall.jpg", UriKind.Relative),

BackTitle = "Surf Advisories",

WideBackContent = "High surf, poor visibility",

WideBackgroundImage =

new Uri("Assets/Tiles/h4XSmall.jpg", UriKind.Relative),

WideBackBackgroundImage =

Trung Tm Tin Hc H KHTN-TP.HCM Trang 389/617


Gio trnh: Lp trnh Windows Phone

new Uri("Assets/Tiles/h5XSmall.jpg", UriKind.Relative)

};

ShellTile oldTile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri ==


uri);

if (oldTile == null)

ShellTile.Create(uri, tileData, true);

else {

oldTile.Update(tileData);

3. Cyclic

Template cho php hin th 9 hnh nh lin tip theo chu k. N rt hu dng cho
phn mm v qun l hnh nh, du lch, lc chn sn phm

Ta c th to trong XAML hoc trong coding behind:

<TemplateCycle>

<SmallImageURI IsRelative="true" IsResource="false">

Assets\Tiles\h1XSmall.jpg

Trung Tm Tin Hc H KHTN-TP.HCM Trang 390/617


Gio trnh: Lp trnh Windows Phone

</SmallImageURI>

<Title>Surf Sites</Title>

<Photo01ImageURI IsRelative="true" IsResource="false">

Assets\Tiles\h2XSmall.jpg

</Photo01ImageURI>

<Photo02ImageURI IsRelative="true" IsResource="false">

Assets\Tiles\h3XSmall.jpg

</Photo02ImageURI>

<Photo03ImageURI IsRelative="true" IsResource="false">

Assets\Tiles\h4XSmall.jpg

</Photo03ImageURI>

<Photo04ImageURI IsRelative="true" IsResource="false">

Assets\Tiles\h5XSmall.jpg

</Photo04ImageURI>

<Photo05ImageURI IsRelative="true" IsResource="false">

Assets\Tiles\h6XSmall.jpg

</Photo05ImageURI>

<Photo06ImageURI IsRelative="true" IsResource="false">

Assets\Tiles\h7XSmall.jpg

</Photo06ImageURI>

<Photo07ImageURI IsRelative="true" IsResource="false">

</Photo07ImageURI>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 391/617


Gio trnh: Lp trnh Windows Phone

<Photo08ImageURI IsRelative="true" IsResource="false">

</Photo08ImageURI>

<Photo09ImageURI IsRelative="true" IsResource="false">

</Photo09ImageURI>

<Count>6</Count>

<HasLarge>True</HasLarge>

<DeviceLockImageURI IsRelative="true" IsResource="false">

</DeviceLockImageURI>

</TemplateCycle>

Bng coding behind:

Uri uri = new Uri("/CycleTarget.xaml", UriKind.Relative);

var tileData = new CycleTileData()

Title = "Surf Sites",

SmallBackgroundImage =

new Uri("Assets/Tiles/iStock_000004630599XSmall.jpg", UriKind.Relative),

Count = 6,

CycleImages = new List<Uri>()

new Uri("Assets/Tiles/h1XSmall.jpg", UriKind.Relative),

Trung Tm Tin Hc H KHTN-TP.HCM Trang 392/617


Gio trnh: Lp trnh Windows Phone

new Uri("Assets/Tiles/h2XSmall.jpg", UriKind.Relative),

new Uri("Assets/Tiles/h3XSmall.jpg", UriKind.Relative),

new Uri("Assets/Tiles/h4XSmall.jpg", UriKind.Relative),

new Uri("Assets/Tiles/h5XSmall.jpg", UriKind.Relative),

new Uri("Assets/Tiles/h6XSmall.jpg", UriKind.Relative)

},

};

ShellTile oldTile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri ==


uri);

if (oldTile == null) {

ShellTile.Create(uri, tileData, true);

else

oldTile.Update(tileData);

IV. Cch cp nhp Live Tiles


S tuyt vi ca Live Tiles l cho php chng ta cp nhp c chng. Ta dng
ShellTileSchedule trong Microsoft.Phone.Shell cp nhp Tiles.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 393/617


Gio trnh: Lp trnh Windows Phone

to primary tile, ta to ShellTileSchedule instance, gn RemoteImageUri vi


ng dn hnh nh ngoi c nh, thit lp cc thng s StartTime v cc thng s khc
ri gi phng thc Start:

var tileSchedule = new ShellTileSchedule();

tileSchedule.StartTime = DateTime.Now;

tileSchedule.Recurrence = UpdateRecurrence.Interval;

tileSchedule.Interval = UpdateInterval.EveryHour;

Uri remoteUri = new Uri(@"http://drthanh.com/h1.jpg");

tileSchedule.RemoteImageUri = remoteUri;

tileSchedule.Start();

Ta c th thit lp dng Recurrence:

UpdateRecurrence.Interval;//lp theo chu k

UpdateRecurrence.Onetime // lp 1 ln

y ta c th thit lp Interval:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 394/617


Gio trnh: Lp trnh Windows Phone

UpdateInterval.EveryDay

UpdateInterval.EveryHour

UpdateInterval.EveryMonth

UpdateInterval.EveryWeek

ngng update:

var primaryTile = ShellTile.ActiveTiles.FirstOrDefault();

if (primaryTile != null)

var shellTileSchedule = new ShellTileSchedule(primaryTile, new


FlipTileData());

shellTileSchedule.Start();

shellTileSchedule.Stop();

Updating Secondary Tile:

var secondaryTile = ShellTile.ActiveTiles

.Where(t => t.NavigationUri.Equals(secondaryUri));

var tile = secondaryTile.SingleOrDefault();

if (tile != null)

var tileData = new FlipTileData()

Title = "We're no trouble",

BackContent = "Adopt me!",

Trung Tm Tin Hc H KHTN-TP.HCM Trang 395/617


Gio trnh: Lp trnh Windows Phone

SmallBackgroundImage = smallBunnyUri,

BackgroundImage = mediumBunnyUri,

WideBackgroundImage = largeBunnyUri,

Count = 6,

BackTitle = "Do you haz kibbles?",

WideBackContent = "Pick a fluffball",

BackBackgroundImage = mediumBunnyUri,

WideBackBackgroundImage = largeBunnyUri

};

var tileSchedule = new ShellTileSchedule(tile, tileData);

tileSchedule.StartTime = DateTime.Now;

tileSchedule.Recurrence = UpdateRecurrence.Onetime;

tileSchedule.Start();

Ngoi ra ta cng c th kim tra loi Template Tile c cu hnh trong Manifest:

enum TemplateType

TemplateUnknown,

TemplateFlip,

TemplateIconic,

TemplateCycle

Trung Tm Tin Hc H KHTN-TP.HCM Trang 396/617


Gio trnh: Lp trnh Windows Phone

private TemplateType GetTemplateTypeFromManifest()

TemplateType templateType = TemplateType.TemplateUnknown;

XDocument appManifest = XDocument.Load("WMAppManifest.xml");

if (appManifest != null)

var primaryTokenNode = appManifest.Descendants("PrimaryToken");

if (primaryTokenNode != null)

var templateNode = primaryTokenNode.Descendants().FirstOrDefault();

if (templateNode.Name == "TemplateFlip")

templateType = TemplateType.TemplateFlip;

else if (templateNode.Name == "TemplateIconic")

templateType = TemplateType.TemplateIconic;

else if (templateNode.Name == "TemplateCycle")

templateType = TemplateType.TemplateCycle;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 397/617


Gio trnh: Lp trnh Windows Phone

return templateType;

V. Kt lun
Live Tiles em n nhng tri nghim th v cho ngi s dng, Live Tiles gip
trang tr mn hnh Start Screen p v ng thi cng gip truy sut ti ng dng rt nhanh
gip ngi s dng lun hi lng. Vic Windows Phone cho php ta to cng nh cp nht
trng thi ca Live Tiles cng gip ch rt nhiu trong vic truyn ti thng tin ti ngi
s dng ngay khi ng dng cha c kch hot.

BI 8. LOCK SCREEN TRONG WINDOWS PHONE 8


(Lock Screen)
Lock Screen l mt trong nhng tnh nng tuyt vi ca Windows Phone, lp trnh
vin c th tng tc vi mn hnh Lock Screen: To, chnh sa Lock Screen Image cng
nh thay i cc thng tin, c bit c th i Lock Screen mt cch linh ng thng qua
ly cc hnh nh t Local App, Internet, RSS

Ni dung ca phn ny s cp ti nhng phn sau:


I) Lock screen background .....................................................................400
1) Cu hnh manifest file ...................................................................................... 400
2) Lp trnh thay i lock screen background.................................................... 401
3) X l thng s t mn hnh lock screen settings ............................................ 404
4) Truy sut lock screen settings t ng dng .................................................... 405
II) Lock screen notifications .....................................................................405
III) Dynamic Lock screen ..........................................................................407
1) Dynamic Lock screen vi images trong app folder ........................................ 407
2) Dynamic Lock screen vi images trn Internet .............................................. 412

Trung Tm Tin Hc H KHTN-TP.HCM Trang 398/617


Gio trnh: Lp trnh Windows Phone

3) Dynamic Lock screen vi images t RSS ....................................................... 414


a) Khi nim RSS ............................................................................................... 414
b) Parse RSS ....................................................................................................... 417
c) Ti hnh nh t RSS ....................................................................................... 419
d) Thit lp Lock Screen vi RSS Images ........................................................... 422
e) Thay i lock screen vi RSS Images ............................................................. 423
IV) Kt lun ...............................................................................................425

Trung Tm Tin Hc H KHTN-TP.HCM Trang 399/617


Gio trnh: Lp trnh Windows Phone

I. Lock screen background


Windows Phone 8 cho php ngi s dng dng mt ng dng bt k lm Lock
Screen.

c th a ng dng lm Lock Screen ta cn khia bo app intent trong Manifest


v tin hnh coding thay i hnh nn Lock Screen.

1. Cu hnh manifest file

to hnh nn Lock Screen cho in thoi, trc tin ta cn phi cung cp intent
cho Manifest file:

Bm chut phi vo WMAppManifest.xml/ chn Open With / Source Code (Text


Editor) With Encoding.

Thm tag <Extension> bn trong tag <Extensions>, nu nh chng khng tn


ti th ta c th a on XAML mu di y vo Manifest, ch l bt buc n phi
theo ngay sau tag <Tokens>:

<Extensions>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 400/617


Gio trnh: Lp trnh Windows Phone

<Extension ExtensionName="LockScreen_Background"

ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default"
/>

</Extensions>

2. Lp trnh thay i lock screen background

Sau khi cu hnh xong Manifest phn trc, ta tin hnh vit coding behind
lm Lock Screen nh sau:

private async void LockHelper(string filePathOfTheImage, bool isAppResource)

try

var isProvider =
Windows.Phone.System.UserProfile.LockScreenManager.IsProvidedByCurrentAppl
ication;

if (!isProvider)

// If you're not the provider, this call will prompt the user for permission.

// Calling RequestAccessAsync from a background agent is not allowed.

var op = await
Windows.Phone.System.UserProfile.LockScreenManager.RequestAccessAsync();

// Only do further work if the access was granted.

isProvider = op ==
Windows.Phone.System.UserProfile.LockScreenRequestResult.Granted;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 401/617


Gio trnh: Lp trnh Windows Phone

if (isProvider)

// At this stage, the app is the active lock screen background provider.

// The following code example shows the new URI schema.

// ms-appdata points to the root of the local app data folder.

// ms-appx points to the Local app install folder, to reference resources


bundled in the XAP package.

var schema = isAppResource ? "ms-appx:///" : "ms-appdata:///Local/";

var uri = new Uri(schema + filePathOfTheImage, UriKind.Absolute);

// Set the lock screen background image.

Windows.Phone.System.UserProfile.LockScreen.SetImageUri(uri);

// Get the URI of the lock screen background image.

var currentImage =
Windows.Phone.System.UserProfile.LockScreen.GetImageUri();

System.Diagnostics.Debug.WriteLine("The new lock screen background


image is set to {0}", currentImage.ToString());

else

MessageBox.Show("You said no, so I can't update your background.");

catch (System.Exception ex)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 402/617


Gio trnh: Lp trnh Windows Phone

System.Diagnostics.Debug.WriteLine(ex.ToString());

bt k v tr no ta s gi lnh trn tin hnh lm Lock Screen:

LockHelper("Assets/hinh/h1.jpg", true);

Vi hnh h1.jpg c lu trong Project.

test trn Emulator, sau khi gi lnh trn ta nhn phm F12 kha mn hnh
li, xem mn hnh Lock Screen ta nhn vo ni Start th s xut hin mn hnh kha nh
mong mun.

cp nht hnh Lock Screen khc trong isolated storage ta cn cung cp unique
file name cho mi ln cp nht:

string fileName;

var currentImage = LockScreen.GetImageUri();

if (currentImage.ToString().EndsWith("_A.jpg"))

fileName = "LiveLockBackground_B.jpg";

else

fileName = "LiveLockBackground_A.jpg";

Trung Tm Tin Hc H KHTN-TP.HCM Trang 403/617


Gio trnh: Lp trnh Windows Phone

var lockImage = string.Format("{0}", fileName);

// At this point in the code, write the image to isolated storage.

3. X l thng s t mn hnh lock screen settings

Ta c th a ng dng ra lm mn hnh Lock Screen bng cch dng chc nng


Lock Screen trong Windows Phone (vo Setting chn Lock Screen):

Trong mc Background ta chn ng dng lm mn hnh Lock Screen ri bm


nt Open App.

Sau khi bm Open App th ng dng ca ta s c triu gi, ta nn vit lnh trong
OnNavigatedTo x l:

protected override void OnNavigatedTo(NavigationEventArgs e)

base.OnNavigatedTo(e);

string lockscreenKey = "WallpaperSettings";

Trung Tm Tin Hc H KHTN-TP.HCM Trang 404/617


Gio trnh: Lp trnh Windows Phone

string lockscreenValue = "0";

bool lockscreenValueExists =
NavigationContext.QueryString.TryGetValue(lockscreenKey, out lockscreenValue);

if (lockscreenValueExists)

// Navigate the user to your app's lock screen settings screen here,

// or indicate that the lock screen background image is updating.

4. Truy sut lock screen settings t ng dng

Trong mt s tnh hung ta khng th x l Lock Screen bng coding th c th


vit lnh m mn hnh Lock Screen ca thit b nh sau:

private async void btnGoToSetting_Click(object sender, RoutedEventArgs e)

// Launch URI for the lock screen settings screen.

var op = await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-


settings-lock:"));

II. Lock screen notifications


Windows Phone 8 cho php kha mn hnh v hin th cc thng bo nh email,
message, phone Hnh di y minh ha cho Notification AREA

Trung Tm Tin Hc H KHTN-TP.HCM Trang 405/617


Gio trnh: Lp trnh Windows Phone

Icon, Count v Text ca mn hnh kha c ly trc tip t Default Tile. c


th cung cp chc nng Notification ta cn khai bo App intent trong Manifest ng thi
thm cc Provider trong mn hnh Screen Lock nh hnh bn di:

Ta to mt Icon PNG c kch thc 38x38 v lu vo th mc Assets, sau hiu


chnh li Manifest nh sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 406/617


Gio trnh: Lp trnh Windows Phone

<DeviceLockImageURI IsRelative="true" IsResource="false">


Assets\LockImage.png

</DeviceLockImageURI>

Tip theo ta hiu chnh Extension:

<Extensions>

<Extension ExtensionName="LockScreen_Notification_IconCount"
ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default"
/>

<Extension ExtensionName="LockScreen_Notification_TextField"
ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default"
/>

</Extensions>

III. Dynamic Lock screen


Trong phn ny gio trnh s trnh by cch thc hiu chnh Lock Screen theo cch
Dynamic: C th thay i Lock Screen bng hnh nh trong App folder hoc trn internet.

1. Dynamic Lock screen vi images trong app folder

c th thay i Lock Screen theo mt chu k no th ta s dng Windows


Phone Scheduled Task Agent.

T solution ta add thm mt Project (New Project -> Windows Phone Scheduled
Task Agent.)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 407/617


Gio trnh: Lp trnh Windows Phone

Trong MainPage.xaml.cs ta cn to mt PeriodicTask:

PeriodicTask periodicTask;

string periodicTaskName = "PeriodicAgent";

Di y l m lnh thc hin:

private void StartPeriodicAgent()

// is old task running, remove it

periodicTask = ScheduledActionService.Find(periodicTaskName) as
PeriodicTask;

if (periodicTask != null)

try

Trung Tm Tin Hc H KHTN-TP.HCM Trang 408/617


Gio trnh: Lp trnh Windows Phone

ScheduledActionService.Remove(periodicTaskName);

catch (Exception)

// create a new task

periodicTask = new PeriodicTask(periodicTaskName);

// load description from localized strings

periodicTask.Description = "This is Lockscreen image provider app.";

// set expiration days

periodicTask.ExpirationTime = DateTime.Now.AddDays(14);

try

// add thas to scheduled action service

ScheduledActionService.Add(periodicTask);

// debug, so run in every 30 secs

#if(DEBUG_AGENT)

ScheduledActionService.LaunchForTest(periodicTaskName,
TimeSpan.FromSeconds(30));

System.Diagnostics.Debug.WriteLine("Periodic task is started: " +


periodicTaskName);

#endif

Trung Tm Tin Hc H KHTN-TP.HCM Trang 409/617


Gio trnh: Lp trnh Windows Phone

catch (InvalidOperationException exception)

if (exception.Message.Contains("BNS Error: The action is disabled"))

// load error text from localized strings

MessageBox.Show("Background agents for this application have been


disabled by the user.");

if (exception.Message.Contains("BNS Error: The maximum number of


ScheduledActions of this type have already been added."))

// No user action required. The system prompts the user when the hard
limit of periodic tasks has been reached.

catch (SchedulerServiceException)

// No user action required.

Ch on code trn ta dng ScheduledActionService.LaunchForTest


kim tra tnh nng trong 30 giy v th trn my o.

Trong lp ScheduledAgent.cs ta cn override hm onInvoke tin hnh cp


nht Lock Screen theo nh k. Trong ng dng ny ta th nghim vi 10 hnh nh c
nh s th t lu trong th mc ng dng (mc ch phn tch index hnh nh cho d).

Ta kim tra hnh nh hin ti ang c s dng lm Lock Screen:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 410/617


Gio trnh: Lp trnh Windows Phone

// Get the URI of the lock screen background image.

var currentImage = LockScreen.GetImageUri();

Sau chng ta x l chui c th chuyn qua hnh k tip hay hnh ng trc
tin hnh Lock Screen theo chu k quy nh:

string imgCount =
currentImage.ToString().Substring(currentImage.ToString().IndexOf('_') + 1,
currentImage.ToString().Length - (currentImage.ToString().IndexOf('_') +
1)).Replace(".jpg", "");

if (imgCount != "9")

Imagename = "wallpaper/CustomizedPersonalWalleper_" +
Convert.ToString(Convert.ToUInt32(imgCount) + 1) + ".jpg";

else

Imagename = "wallpaper/CustomizedPersonalWalleper_0.jpg";

Sau phi gi NotifyComplete(); m bo rng tt c cc hm bt ng b


hon thnh, di y l coding y :

protected override void OnInvoke(ScheduledTask task)

// Get the URI of the lock screen background image.

var currentImage = LockScreen.GetImageUri();

string Imagename = string.Empty;

string imgCount =
currentImage.ToString().Substring(currentImage.ToString().IndexOf('_') + 1,
currentImage.ToString().Length - (currentImage.ToString().IndexOf('_') +
1)).Replace(".jpg", "");

if (imgCount != "9")

Trung Tm Tin Hc H KHTN-TP.HCM Trang 411/617


Gio trnh: Lp trnh Windows Phone

Imagename = "wallpaper/CustomizedPersonalWalleper_" +
Convert.ToString(Convert.ToUInt32(imgCount) + 1) + ".jpg";

else

Imagename = "wallpaper/CustomizedPersonalWalleper_0.jpg";

LockScreenChange(Imagename, true);

// If debugging is enabled, launch the agent again in one minute.

// debug, so run in every 30 secs

#if(DEBUG_AGENT)

ScheduledActionService.LaunchForTest(task.Name,
TimeSpan.FromSeconds(30));

System.Diagnostics.Debug.WriteLine("Periodic task is started again: " +


task.Name);

#endif

// Call NotifyComplete to let the system know the agent is done working.

NotifyComplete();

2. Dynamic Lock screen vi images trn Internet

mc trn ta ch thay i Lock Screen trong Local App, by gi ta ly t Internet.


Ta cn ti v v lu vo IsolatedStorage sau dng LockScreen.SetImageUri() thit
lp Lock Screen, v d y v cch ti hnh nh t internet v my v thit lp lm Lock
Screen:

private void DownloadImagefromServer()

WebClient client = new WebClient();

client.OpenReadCompleted += new
OpenReadCompletedEventHandler(client_OpenReadCompleted);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 412/617


Gio trnh: Lp trnh Windows Phone

// give the image url that we need to download and store on IsolatedStorage

client.OpenReadAsync(new Uri("http://ajtroxell.com/wp-
content/uploads/2012/02/wp7_vintage.jpg", UriKind.Absolute));

void client_OpenReadCompleted(object sender,


OpenReadCompletedEventArgs e)

BitmapImage bitmap = new BitmapImage();

bitmap.SetSource(e.Result);

//img.Source = bitmap;

// Create a filename for JPEG file in isolated storage.

String tempJPEG = "DownloadedWalleper.jpg";

// Create virtual store and file stream. Check for duplicate tempJPEG files.

using (IsolatedStorageFile myIsolatedStorage =


IsolatedStorageFile.GetUserStoreForApplication())

if (myIsolatedStorage.FileExists(tempJPEG))

myIsolatedStorage.DeleteFile(tempJPEG);

IsolatedStorageFileStream fileStream =
myIsolatedStorage.CreateFile(tempJPEG);

StreamResourceInfo sri = null;

Uri uri = new Uri(tempJPEG, UriKind.Relative);

sri = Application.GetResourceStream(uri);

//BitmapImage bitmap = new BitmapImage();

Trung Tm Tin Hc H KHTN-TP.HCM Trang 413/617


Gio trnh: Lp trnh Windows Phone

//bitmap.SetSource(sri.Stream);

WriteableBitmap wb = new WriteableBitmap(bitmap);

// Encode WriteableBitmap object to a JPEG stream.

Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0,


85);

//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);

fileStream.Close();

// call function to set downloaded image as lock screen

LockScreenChange("DownloadedWalleper.jpg", false);

3. Dynamic Lock screen vi images t RSS

Khi nim RSS

Trung Tm Tin Hc H KHTN-TP.HCM Trang 414/617


Gio trnh: Lp trnh Windows Phone

RSS l mt nh dng tp tin thuc h XML dng trong vic chia s tin tc Web
(Web syndication) c dng bi nhiu website tin tc v weblog. Ch vit tt (theo ting
Anh) dng ch cc chun sau:

Rich Site Summary (RSS 0.91)


RDF Site Summary (RSS 0.9 and 1.0)
Really Simple Syndication (RSS 2.0.0)
Cng ngh ca RSS cho php ngi dng Internet c th t mua thng tin t cc
websites c cung cp kh nng RSS (RSS feeds); chng thng l cc site c ni dung thay
i v c thm vo thng xuyn, hu ht RSS l min ph.

nh dng RSS cung cp ni dung web v tm lc ni dng web cng vi cc


lin kt n phin bn y ca ni dung tin , v cc siu-d-liu (meta-data) khc.
Thng tin ny c cung cp di dng mt tp tin XML c gi l mt RSS feed,
webfeed, RSS stream, hay RSS channel. Cng vi vic h tr cung cp chia s thng tin,
RSS cho php nhng c gi thng xuyn ca mt website c th theo di cc cp nht
ca site .

Trong Windows Phone 8 ta c th ly hnh nh t RSS lm Lock Screen

Di y l mt v d v RSS n gin:

<rss xmlns:media="http://search.yahoo.com/mrss/"
xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
<channel>
<title>Flickr Photos tagged with nature</title>
<link>
www.flickr.com
</link>
<description>Flickr Photos tagged with nature</description>

<language>en-us</language>
<pubDate>Mon, 10 Dec 2012 01:40:13 -0500</pubDate>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 415/617


Gio trnh: Lp trnh Windows Phone

<lastBuildDate>Mon, 10 Dec 2012 01:40:13 -0500</lastBuildDate>


<generator>http://www.degraeve.com/flickr-rss/</generator>
<webMaster>webmaster@degraeve.com</webMaster>
<item>
<title>mandarin duck in full color</title>
<link>http://www.flickr.com/photos/54419396@N00/45599281</link>
<description>
<img src="http://farm1.static.flickr.com/27/45599281_0e33a17e35.jpg" alt=""
/>
</description>
<pubDate>Thu, 22 Sep 2005 11:42:56 -0400</pubDate>
<guid>
http://farm1.static.flickr.com/27/45599281_0e33a17e35.jpg
</guid>
<media:content
url="http://farm1.static.flickr.com/27/45599281_0e33a17e35.jpg"
type="image/jpeg"/>
<media:title>mandarin duck in full color</media:title>
<media:text type="html">
<img src="http://farm1.static.flickr.com/27/45599281_0e33a17e35.jpg" />
</media:text>
<media:thumbnail
url="http://farm1.static.flickr.com/27/45599281_0e33a17e35.jpg"/>
</item>
<item>
<title>Japanese Maple</title>
<link>
http://www.flickr.com/photos/52317893@N00/263966036
</link>

<description>
<img src="http://farm1.static.flickr.com/103/263966036_ee04032cc8.jpg"

Trung Tm Tin Hc H KHTN-TP.HCM Trang 416/617


Gio trnh: Lp trnh Windows Phone

alt="" />
</description>
<pubDate>Sun, 08 Oct 2006 12:17:38 -0400</pubDate>
<guid>
http://farm1.static.flickr.com/103/263966036_ee04032cc8.jpg
</guid>
<media:content
url="http://farm1.static.flickr.com/103/263966036_ee04032cc8.jpg"
type="image/jpeg"/>
<media:title>Japanese Maple</media:title>
<media:text type="html">
<img src="http://farm1.static.flickr.com/103/263966036_ee04032cc8.jpg" />
</media:text>
<media:thumbnail
url="http://farm1.static.flickr.com/103/263966036_ee04032cc8.jpg"/>
</item>
</channel>
</rss>

Parse RSS
Ta dng WebClient tin hnh Parse RSS, coding nh sau (gi s ta Parse link
RSS sau: http://www.degraeve.com/flickr-
rss/rss.php?tags=nature&tagmode=all&sort=interestingness-desc&num=24)

// Global variable

public int imageCount = 0;

public string[] imgarray;

// pass above url in this method as input argument

Trung Tm Tin Hc H KHTN-TP.HCM Trang 417/617


Gio trnh: Lp trnh Windows Phone

public void DownloadRSS(string rssURL)

WebClient myRSS = new WebClient();

myRSS.DownloadStringCompleted += new
DownloadStringCompletedEventHandler(myRSS_DownloadStringCompleted);

myRSS.DownloadStringAsync(new Uri(rssURL));

void myRSS_DownloadStringCompleted(object sender,


DownloadStringCompletedEventArgs e)

//Check if the Network is available

if
(Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsNetworkA
vailable)

// filter all images from rss located on media:content

XNamespace media = XNamespace.Get("http://search.yahoo.com/mrss/");

imgarray = XElement.Parse(e.Result).Descendants(media + "content")

.Where(m => m.Attribute("type").Value == "image/jpeg")

.Select(m => m.Attribute("url").Value)

.ToArray();

// check that images are there in rss

if (imgarray.Length > 0)

imageCount = 0;

// download images

Trung Tm Tin Hc H KHTN-TP.HCM Trang 418/617


Gio trnh: Lp trnh Windows Phone

DownloadImagefromServer(Convert.ToString(imgarray[0]));

else

MessageBox.Show("No image found in applied RSS link");

else

MessageBox.Show("No network is available..");

Ti hnh nh t RSS
Ta vit coding trong hm DownloadImagefromServer, hnh nh khi ti v t
internet s c lu vo thit b thng qua IsolatedStorage:

// to download image from server

private void DownloadImagefromServer(string imageUrl)

WebClient client = new WebClient();

client.OpenReadCompleted += new
OpenReadCompletedEventHandler(client_OpenReadCompleted);

client.OpenReadAsync(new Uri(imageUrl, UriKind.Absolute));

Trung Tm Tin Hc H KHTN-TP.HCM Trang 419/617


Gio trnh: Lp trnh Windows Phone

void client_OpenReadCompleted(object sender,


OpenReadCompletedEventArgs e)

BitmapImage bitmap = new BitmapImage();

bitmap.SetSource(e.Result);

// Create a filename for JPEG file in isolated storage.

String tempJPEG = "DownloadedWalleper_" +


Convert.ToString(imageCount) + ".jpg";

// Create virtual store and file stream. Check for duplicate tempJPEG files.

using (IsolatedStorageFile myIsolatedStorage =


IsolatedStorageFile.GetUserStoreForApplication())

if (myIsolatedStorage.FileExists(tempJPEG))

myIsolatedStorage.DeleteFile(tempJPEG);

IsolatedStorageFileStream fileStream =
myIsolatedStorage.CreateFile(tempJPEG);

StreamResourceInfo sri = null;

Uri uri = new Uri(tempJPEG, UriKind.Relative);

sri = Application.GetResourceStream(uri);

WriteableBitmap wb = new WriteableBitmap(bitmap);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 420/617


Gio trnh: Lp trnh Windows Phone

// Encode WriteableBitmap object to a JPEG stream.

System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, fileStream,
wb.PixelWidth, wb.PixelHeight, 0, 85);

//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);

fileStream.Close();

System.Diagnostics.Debug.WriteLine("image downloaded: " +


tempJPEG);

if (imageCount == imgarray.Length - 1)

// set first image

LockScreenChange("DownloadedWalleper_0.jpg", false);

// start service

StartPeriodicAgent();

if (imageCount < imgarray.Length - 1)

imageCount++;

// download remaining images

DownloadImagefromServer(Convert.ToString(imgarray[imageCount]));

Trung Tm Tin Hc H KHTN-TP.HCM Trang 421/617


Gio trnh: Lp trnh Windows Phone

Thit lp Lock Screen vi RSS Images


Sau khi ti hnh nh t RSS xung IsolatedStorage ta dng
LockScreen.SetImageUri(uri) thit lp Lock Screen:

private async void LockScreenChange(string filePathOfTheImage, bool


isAppResource)

if (!LockScreenManager.IsProvidedByCurrentApplication)

// If you're not the provider, this call will prompt the user for permission.

// Calling RequestAccessAsync from a background agent is not allowed.

await LockScreenManager.RequestAccessAsync();

// Only do further work if the access is granted.

if (LockScreenManager.IsProvidedByCurrentApplication)

// At this stage, the app is the active lock screen background provider.

// The following code example shows the new URI schema.

// ms-appdata points to the root of the local app data folder.

// ms-appx points to the Local app install folder, to reference resources


bundled in the XAP package

var schema = isAppResource ? "ms-appx:///" : "ms-appdata:///Local/";

var uri = new Uri(schema + filePathOfTheImage, UriKind.Absolute);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 422/617


Gio trnh: Lp trnh Windows Phone

// Set the lock screen background image.

LockScreen.SetImageUri(uri);

// Get the URI of the lock screen background image.

var currentImage = LockScreen.GetImageUri();

System.Diagnostics.Debug.WriteLine("The new lock screen background


image is set to {0}", currentImage.ToString());

MessageBox.Show("Lock screen changed. Click F12 or go to lock


screen.");

else

MessageBox.Show("Background cant be updated as you clicked no!!");

Thay i lock screen vi RSS Images


thay i Lock Screen vi RSS Images ta cng s dng ScheduledTask ( v
d trn l ta ti khong 25 hnh nh, ci ny l gi s c th thay i):

protected override void OnInvoke(ScheduledTask task)


{
if (LockScreenManager.IsProvidedByCurrentApplication)
{
// Get the URI of the lock screen background image.
// NOTE: GetImageUri throws IF the app is not the current application
var currentImage = LockScreen.GetImageUri();
string Imagename = string.Empty;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 423/617


Gio trnh: Lp trnh Windows Phone

string imgCount =
currentImage.ToString().Substring(currentImage.ToString().IndexOf('_') + 1,
currentImage.ToString().Length - (currentImage.ToString().IndexOf('_') +
1)).Replace(".jpg", "");

if (imgCount != "24")
Imagename = "DownloadedWalleper_" +
Convert.ToString(Convert.ToUInt32(imgCount) + 1) + ".jpg";
else
Imagename = "DownloadedWalleper_0.jpg";

LockScreenChange(Imagename, false);
}
else
{
// Do cleanup, since we are no longer the active lock screen provider.
// This could be: delete images, stop the agent, etc...
periodicTask = ScheduledActionService.Find(periodicTaskName) as
PeriodicTask;
if (periodicTask != null)
{
try
{
ScheduledActionService.Remove(periodicTaskName);
}
catch (Exception)
{
}
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 424/617


Gio trnh: Lp trnh Windows Phone

// If debugging is enabled, launch the agent again in one minute.


// debug, so run in every 30 secs
#if(DEBUG_AGENT)
ScheduledActionService.LaunchForTest(task.Name,
TimeSpan.FromSeconds(30));
System.Diagnostics.Debug.WriteLine("Periodic task is started again: " +
task.Name);
#endif

// Call NotifyComplete to let the system know the agent is done working.
NotifyComplete();
}

IV. Kt lun
Windows Phone 8 vi tnh nng h tr lp trnh vi Lock Screen gip lp trnh
vin c thm nhiu ty bin cho ng dng, ta cng c th ti t internet, RSS tin hnh
to hnh Lock Screen cng nh kt hp vi Agent gip ng dng c th thay i hnh nn
theo chu k nh trc.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 425/617


Gio trnh: Lp trnh Windows Phone

PHN 3. MODULE 4
BI 1. WEB SERVICE
Web Service l mt trong nhng cng ngh khng th thiu khi chng ta pht trin
cc ng dng lin quan ti Client Server, c bit l vi cc ng dng Di ng th vic
tng tc ln Server cng ti quan trng. Mi d liu quan trng u c lu tr trn
server, thit b di ng ch l thit b lu tr tm thi v n khng mang tnh bn vng
(c th d b h in thoi do va chm nh, c th d b mt cp, hay b x l yu khng
bng PC..), gio trnh s trnh by cng ngh Web Service lin quan ti cc khi nim v
SOAP, WSDL, REST cng nh cch to .Net Web Service, trin khai v tng tc.

Ni dung ca phn ny s cp ti nhng phn sau:


I) Cc khi nim ......................................................................................427
1) SOAP & WSDL ............................................................................................... 427
2) REST ................................................................................................................ 431
II) ASP.Net Web Service ..........................................................................433
1) Cch to .Net Web Service .............................................................................. 434
2) Cch cu hnh IIS ............................................................................................ 446
3) Tng tc Windows Phone vi .Net Web Service .......................................... 452
III) Tng tc SQL Server v Hosting min ph Somee.com.....................463
IV) Kt lun ...............................................................................................491

Trung Tm Tin Hc H KHTN-TP.HCM Trang 426/617


Gio trnh: Lp trnh Windows Phone

I. Cc khi nim
Web Serivce l mt cng ngh cho php client truy xut thc hin mi tc v
nh mt Web Application. V bn cht, Web service da trn XML v HTTP, trong
XML lm nhim v m ha v gii m d liu v dng SOAP truyn ti. Web Service
khng ph thuc vo platform no, do Ta c th dng Web Service truyn ti d liu
gia cc ng dng hay gia cc platform.

1. SOAP & WSDL

SOAP- Simple Object Access Protocol


SOAP l vit tt ca cm t Simple Object Access Protocol, mt tiu chun ca
W3C. L giao thc s dng XML nh ngha d liu dng thun vn bn (plain text)
thng qua HTTP. SOAP l cch m Web Service s dng truyn ti d liu. V da
trn XML nn SOAP l mt giao thc khng ph thuc platform cng nh bt k ngn ng
lp trnh no.

Mt thng ip SOAP c chia thnh hai phn l header v body. Phn header
ch ra a ch Web Service, host, Content-Type, Content-Length tng t nh mt thng
ip HTTP.

Cc li gi hm tham s truyn hm, d liu tr v t hm, tt c u c chuyn


sang dng XML v c th d dng x l bi tt c cc ngn ng. Mt th mnh khc l
nu cc i tng phn tn xy dng trn m hnh Web services s c th triu gi ln
nhau, v khng l thuc vo ngn ng lp trnh. Hin ti, SOAP c coi l mt s thay
i ln k t khi COM, RMI, CORBA ra i.
Mt client s gi thng ip yu cu ti server v ngay lp tc server s gi nhng
thng ip tr li ti client. C SMTP v HTTP u l nhng giao thc lp ng dng
ca SOAP nhng HTTP c s dng v chp nhn rng ri hn bi ngy nay n c th
lm vic rt tt vi c s h tng Internet.
Cu trc mt thng ip theo dng SOAP
Thng ip theo nh dng SOAP l mt vn bn XML bnh thng bao gm cc
phn t sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 427/617


Gio trnh: Lp trnh Windows Phone

Phn t gc envelop: phn t bao trm ni dung thng ip, khai bo vn


bn XML nh l mt thng ip SOAP.
Phn t u trang header: cha cc thng tin tiu cho trang, phn t
ny khng bt buc khai bo trong vn bn. Header cn c th mang nhng d liu
chng thc, nhng ch k s, thng tin m ha hay ci t cho cc giao dch khc.
Phn t khai bo ni dung chnh trong thng ip body, cha cc thng
tin yu cu v thng tin c phn hi.
Phn t a ra cc thng tin v li -fault, cung cp thng tin li xy ra
trong qu trnh x l thng ip.
Mt SOAP n gin trong body s lu cc thng tin v tn thng ip, tham chiu
ti mt th hin ca dch v, mt hoc nhiu tham s. C 3 kiu thng bo s c a ra
khi truyn thng tin: request message(tham s gi thc thi mt thng ip), respond
message (cc tham s tr v, c s dng khi yu cu c p ng) v cui cng l fault
message (thng bo tnh trng li).
Kiu truyn thng: C 2 kiu truyn thng
Remote procedure call (RPC): cho php gi hm hoc th tc qua mng.
Kiu ny c khai thc bi nhiu dch v Web.
Document: c bit n nh kiu hng thng ip, n cung cp giao tip
mc tru tng thp, kh hiu v yu cu lp trnh vin mt cng sc hn.
Hai kiu truyn thng ny cung cp cc nh dng thng ip, tham s, li gi n
cc API khc nhau nn vic s dng chng ty thuc vo thi gian v s ph hp vi dch
v Web cn xy dng.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 428/617


Gio trnh: Lp trnh Windows Phone

Cu trc d liu: Cung cp nhng nh dng v khi nim c bn ging nh trong


cc ngn ng lp trnh khc nh kiu d liu (int, string, date) hay nhng kiu phc tp
hn nh struct, array, vector nh ngha cu trc d liu SOAP c t trong
namespace SOAP-ENC.
M ha: Gi s service rquester v service provider c pht trin trong Java,
khi m ha SOAP l lm th no chuyn i t cu trc d liu Java sang SOAP XML
v ngc li, bi v nh dng cho Web Service chnh l XML. Bt k mt mi trng
thc thi SOAP no cng phi c mt bng cha thng tin nh x nhm chuyn i t ngn
ng Java sang XML v t XML sang Java bng c gi l SOAPMappingRegistry.
Nu mt kiu d liu c s dng di mt dng m ha th s c mt nh x tn ti
trong b ng k ca mi trng thc thi SOAP .
V d v kt qu tr v ca SOAP:

POST /MathService.asmx HTTP/1.1


Host: localhost
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<HelloWorld xmlns="http://tempuri.org/" />
</soap12:Body>
</soap12:Envelope>

WSDL Web Services Description Language:


WSDL l ngn ng c s dng m t y v Web Service theo chun
XML nh cc phng thc, kiu d liu, da trn XML schema.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 429/617


Gio trnh: Lp trnh Windows Phone

V d mt on nh ngha kiu d liu ca WSDL cho phng thc HelloWorld()


trn:

[]

<wsdl:types>

<s:schema elementFormDefault="qualified"
targetNamespace="http://tempuri.org/">

<s:element name="HelloWorld">

<s:complexType />

</s:element>

<s:element name="HelloWorldResponse">

<s:complexType>

<s:sequence>

<s:element minOccurs="0" maxOccurs="1" name="HelloWorldResult"


type="s:string" />

</s:sequence>

</s:complexType>

</s:element>

</s:schema>

</wsdl:types>

[]

Trong , phn nh ngha cc kiu d liu dng cho request c t tn da


theo tn phng thc HelloWorld:

<s:element name="HelloWorld">

<s:complexType />

Trung Tm Tin Hc H KHTN-TP.HCM Trang 430/617


Gio trnh: Lp trnh Windows Phone

</s:element>

Theo sau l phn nh ngha cc kiu d liu dng response c t tn


HelloWorldResponse:

<s:element name="HelloWorldResponse">

<s:complexType>

<s:sequence>

<s:element minOccurs="0" maxOccurs="1" name="HelloWorldResult"


type="s:string" />

</s:sequence>

</s:complexType>

</s:element>

Vic t tn ny cn thit s dng trong phn nh ngha message pha sau.


Tham kho hng dn v XML Schema v WSDL ti cc link sau:

http://www.w3schools.com/wsdl/default.asp

http://www.w3schools.com/schema/

II. REST
Gio trnh s trnh by li kin thc v REST m cc lp trnh vin chuyn nghip
trc thc hin, hc vin c th tham kho thm trn internet:
REST cung cp web service tht s da trn URI v HTTP.
REST t vit tt l vit tt ca Representational State Transfer, iu ny v c bn
c ngha l tng URL l mt i din ca mt s i tng (object). Bn c th nhn c
cc ni dung ca i tng bng cch s dng mt HTTP GET, xa n, bn c th

Trung Tm Tin Hc H KHTN-TP.HCM Trang 431/617


Gio trnh: Lp trnh Windows Phone

s dng mt POST, PUT, hoc DELETE sa i cc i tng (trong thc t hu ht


cc dch v (service) s dng POST cho vic ny).
REST l mt tp hp cc nguyn tc kin trc v l mt kiu kin trc phn mm
xy dng cc h thng mng (network-enabled system) da trn cc c cu v nh
ngha v truy cp cc ti nguyn, chng hn nh WWW (World Wide Web). Thut ng
REST, c Roy Fielding nh ngha trong lun n ca ng, thng c dng mt cch
kh lng lo m t mt khung lm vic chuyn ti d liu qua mt giao thc chng
hn nh HTTP m khng phi b sung cc lp ng ngha hoc qun l phin lm vic.
REST nh ngha mt s phn cch nghim ngt ca cc mi lin h gia cc thnh
phn c tham gia vo mt h thng khch-ch (client - server) m n gin ho vic thc
hin cc yu cu. REST cng phn u n gin ho ng ngha truyn thng trong mt
h thng mng lm tng kh nng m rng v ci thin hiu nng. REST lin quan n
yu cu t qun, gia cc thnh phn tham gia trong mt trao i thng ip m ng cc
yu cu phi gm ton b cc thng tin m mt my khch hoc my ch yu cu
hiu c ng cnh ca yu cu. Trong mt h thng da trn REST, bn s dng cc tp
hp ti thiu cc yu cu kh d trao i cc kiu phng tin truyn thng chun.
Nh Roy Fielding m t, mt trong cc nguyn tc hn ch ni dung ca REST
l ch n c th khai thc cc cng ngh, chun, giao thc hin hnh lin quan n Web,
chng hn nh HTTP. S trng mong ny v cc cng ngh v giao thc hin hnh lm
cho REST d hc hn v s dng n gin hn phn ln cc chun thng bo da trn
Web khc, v cc chi ph ph b sung i hi t hn, cho php vic trao i thng tin hiu
qu.
Mt hi thoi da trn REST, theo Fielding, hot ng trong cc hi thoi phi trng
thi, bng cch y to cho n mt b xc tin ch yu cho cc cng ngh da trn thu bao,
chng hn nh RSS, RDF, OWL, v Atom, trong ni dung c a vo cho cc khch
hng thu bao trc.
REST nh ngha cc thc th ch yu sau y:
Cc phn t d liu: D liu, cc b nh danh (cc URL v URI), v cc i
din ca d liu chng hn nh ti liu HTML, ti liu XML, v hnh nh.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 432/617


Gio trnh: Lp trnh Windows Phone

Cc thnh phn: Cc my ch ngun chng hn nh Apache http v Cc Dch


v Thng tin Internet Microsoft (IIS), cc cng vo chng hn nh Squid v CGI, cc
proxy chng hn nh Gauntlet v Netscape, v cc i l ngi s dng chng hn nh
cc trnh duyt Web hoc cc thit b lu ng.
Cc u ni: Cc u ni khch hng chng hn nh libwww, cc u ni
my ch chng hn nh NSAPI, cc cache, chng hn nh mt cache trnh duyt, v
mt s khc.
Cc my ch proxy c th c s dng nh l mt phn ca kin trc,
ci thin hiu sut v kh nng m rng. Bt k proxy HTTP tiu chun c th c s
dng.

SOAP REST
Thng ip dng Evenlop Thng ip dng Postcard
Gn lin vi XML Lm vic trn URL v HTML
H tr h thng phn tn H tr point to point
bo mt cao Bo mt thp hn
Theo chun W3C Khng theo chun
L giao thc (protocol) kt ni mng L kiu kin trc (architecture) mng
phc tp. n gin, trc quan.
t tng tc cache H tr b nh cache tt hn
Hightweight tng i nng hn. Lightweight request v reponse
dung lng nh, t tn lu lng
mng.
Yu cu tool pht trin Khng cn tool
Phc tp, tn nhiu thi gian tm hiu D hiu, t tn thi gian tm hiu

III. ASP.Net Web Service


ASP.NET Web Services da trn lp System.Xml.Serialization.XmlSerializer
sp xp d liu vo phn thng tin SOAP hoc ly d liu t ra trong thi gian chy.
Vi metadata, chng to cc nh ngha WSDL v XSD (XML Schema) m t phn thng
tin cha nhng g. Da trn cc WSDL v XSD thun nht gip metadata ca ASP.NET
Web Services c kh nng di ng. Chng m t cu trc d liu theo cch khin cc

Trung Tm Tin Hc H KHTN-TP.HCM Trang 433/617


Gio trnh: Lp trnh Windows Phone

toolkit Web service trn nhiu platform khc v nhiu m hnh lp trnh khc vn c th
hiu c. Trong mt s trng hp cn lin quan rng buc ti nhiu kiu ly ra t mt
Web service. XmlSerializer ch sp xp th t nhng th c m t trong XSD.
XmlSerializer khng sp xp phn ho i tng v h tr hn ch cho cc kiu lu tr.

Mc d cc gii hn ny dng nh khng ng k trc i tng phn phi theo


lp, nhng chng gip m bo thng nht thao tc gia cc phn vi framework Web
service khc - mc ch c bn ca m hnh Web service kt hp lng. Phn h tr cho
thao tc gia cc phn c tng cng vi tp hp phong ph cc thuc tnh tu chn,
cho php bn ch thch kiu d liu iu khin cch thc XmlSerializer sp xp th t.
Kt qu, bn c quyn iu khin rt hu ch qua hnh thc ca XML to ra khi mt i
tng c sp xp th t. Thm vo , mt Web service trn nn ASP.NET c th c
bin i m t cc thng tin ca n theo thut ng XSD literal (nguyn bn) hoc cc
nguyn tc m ho SOAP. XSD literal c t mc nh v sau ny s c tiu chun
ho. Chc nng h tr m ho SOAP c sp xp cho tt c cc phn vi toolkit ang sn
c. iu ny rt c li, nht l khi bn cn phi lin lc vi mt Web service hoc client
tn ti, s dng kiu tin tc xc nh trc.

M hnh ASP.NET Web Services s dng cu trc dch v khng trng thi lm
mc nh. N khng tng quan vi a li gi t cng mt ngi dng. Thm vo , mi
ln mt client vin dn mt Web service ASP.NET, i tng mi s c to phc v
cho yu cu. i tng ny c b i sau khi li gi phng thc hon thnh. duy tr
trng thi gia cc yu cu, bn c th dng cng k thut nh cc trang ASP.NET (VD:
i tng Session v Application) hoc c th t trin khai gii php ring ca mnh.

1. Cch to .Net Web Service

to c Asp.net Web service gio trnh s hng dn t m cch to mt dch


v nh th no, hc vin cn c k hng dn th s c th da vo n trin khai c
cc dch v khc ln hn.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 434/617


Gio trnh: Lp trnh Windows Phone

Gio trnh s trnh by 3 trng hp m lp trnh vin thng s dng khi to


tng tc vi dch v web:

Tng tc Primitive Data


Tng tc Serializable Data
Tng tc SQL Server
Ty tng ng dng m ta c th tng tc Primitive Data (int, long, float, double,
bool, short, byte, string), Serializable Data (cc lp i tng truyn ti trn mng nh lp
sinh vin, lp sn phm, lp nhn vin..), hay tng tc c s d liu (SQL Server l mt
trng hp s dng):

Tng tc Primitive Data

Trong trng hp ny ta s tin hnh vit dch v gii phng trnh bc 2

Bc 1: T mn hnh Visual Studio/ chn File/New/ Project (hoc nhn t


hp phm Ctrl + Shift +N):

Sau khi chn Project nh trn th mn hnh New Project s hin th ra nh


sau:
Bc 2: Chn ASP.NET Empty Web Application

T mn hnh New Project bn Installed Templates ta chn Web/ sau chn


Asp.NET Empty Web Application:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 435/617


Gio trnh: Lp trnh Windows Phone

Mc Name: Nhp tn Project, y ta t tn: DichVu_PTB2


Location: Chn ni lu tr Project
Mc Solution name: t tn cho Solution
Sau ta Bm OK chp nhn to Project, mc nh Project s nh sau:

Ta thy trong Project DichVu_PTB2 c cc thnh phn:


Properties: Thng tin cho ng dng, c lu tr trong tp tin
AssemblyInfo.cs
Reference: Cc th vin m ng dng cn tham chiu ti

Trung Tm Tin Hc H KHTN-TP.HCM Trang 436/617


Gio trnh: Lp trnh Windows Phone

Web.config: File cu hnh cho ng dng web


Bc 3: To Webservice

Ti bc ny ta to mt service tn l MyWebService, bm chut phi vo Project/


chn Add/ chn New Item:

Sau khi chn New Item, mn hnh Add New Item s hin th ra nh bn di:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 437/617


Gio trnh: Lp trnh Windows Phone

Ta chn Web Service v trong mc name nhp vo MyWebService, mc nh phn


m rng l asmx. Ri nhn nt Add to service.

Mn hnh sau khi to MyWebService:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 438/617


Gio trnh: Lp trnh Windows Phone

Lp MyWebService s c to ra ta c 2 tp tin, y ta s coding trong


MyWebService.asmx.cs. Mc nh phng thc HelloWorld mu c to ra, ta c
thuc tnh [WebMethod] trn phng thc, y chnh l cch a hm ra lm Service
cc thit b, ng dng khc c th tng tc ti hm ny.

Bc 4: B sung hm gii phng trnh bc 2

/// <summary>
/// Dch v gii v bin lun phng trnh bc 2 Ax^2+Bx+c=0
/// </summary>
/// <param name="a">h s a</param>
/// <param name="b">h s b</param>
/// <param name="c">h s c</param>
/// <returns>Tr v nghim ca ca phng trnh</returns>
[WebMethod]
public string GiaiPTB2(int a, int b, int c)
{
if (a == 0)
{
if (b == 0)
{
if (c == 0)
{
return "PT v s nghim";
}
else
{
return "PT v nghim";
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 439/617


Gio trnh: Lp trnh Windows Phone

}
else
{
return "x=" + (-c * 1.0 / b);
}
}
else
{
double delta = Math.Pow(b, 2) - 4 * a * c;
if (delta < 0)
{
return "PT v nghim";
}
else if (delta == 0)
{
return "PT c nghip kp x1=x2=" + (-b * 1.0 / (2 * a));
}
else
{
double x1 = (-b - Math.Sqrt(delta)) / (2 * a);
double x2 = (-b + Math.Sqrt(delta)) / (2 * a);
return "X1=" + x1 + "; X2=" + x2;
}
}
}

Tin hnh chy Web Service: Bm chut phi vo MyWebService/ chn View in
Browser ta c kt qu nh sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 440/617


Gio trnh: Lp trnh Windows Phone

Kt qu:

Ta th nghim tng hm, bm vo HelloWord:

Bm vo nt Invoke Ta s c kt qu nh hnh di y:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 441/617


Gio trnh: Lp trnh Windows Phone

Tip tc ta bm vo dch v GiaiPTB2:

Ta nhp cc h s ri nhn nt Invoke:

<string xmlns="http://tempuri.org/">X1=-0.4; X2=1</string>

Tng tc Serializable Data


Ta thng xuyn phi gi nhn i tng qua li trn internet, Web Service cng
h tr ta tnh nng ny, sau y l v d ni tip phn trn:

Ta Bm chut phi vo Project/Add/Class:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 442/617


Gio trnh: Lp trnh Windows Phone

mn hnh Add New Item ta t tn lp l SinhVien ri nhn nt Add:

Ta tin hnh vit coding cho lp SinhVien nh sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 443/617


Gio trnh: Lp trnh Windows Phone

[Serializable]

public class SinhVien

public int MaSV

get;

set;

public string TenSV

get;

set;

lp sinhvien ta phi thm thuc tnh trn lp, l yu cu c th truyn


ti i tng trn internet.

Sau tin hnh vit coding cho Webservice gi danh sch i tng ny v
Client:

[WebMethod]

public List<SinhVien> GetSampleList()

List<SinhVien> ds = new List<SinhVien>();

Trung Tm Tin Hc H KHTN-TP.HCM Trang 444/617


Gio trnh: Lp trnh Windows Phone

ds.Add(new SinhVien() { MaSV=1,TenSV="Nguyn vn to"});

ds.Add(new SinhVien() { MaSV = 2, TenSV = "Dr Thanh" });

ds.Add(new SinhVien() { MaSV = 2, TenSV = "Trn Th N" });

return ds;

Thc hin service:

Kt qu khi ta bm vo hm GetSampleList:

Tng tc SQL Server


Phn ny s c trnh by trong mc s dng Hosting Somee.com min ph.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 445/617


Gio trnh: Lp trnh Windows Phone

2. Cch cu hnh IIS

Bc cu hnh IIS l rt quan trng, mi mt lp trnh vin cn bit cu hnh IIS,


gio trnh s hng dn cch cu hnh nh sau:

Bc 1: Bt c tnh IIS, Turn Windows features on or off trong Control Panel:

Mn hnh Windows Features hin th ra nh di y:

Ta check vo Web Management Tools v World Wide Web Services ri bm OK,


ch mt thi gian cho my tnh thc hin xong.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 446/617


Gio trnh: Lp trnh Windows Phone

Bc 2: Thao tc vi IIS, vo Control Panel click chn Administrative Tools:

Mn hnh Administrative Tools s hin th nh di y:

Ta bm chn Internet Information Service (IIS) Manager hin th ca s


qun l:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 447/617


Gio trnh: Lp trnh Windows Phone

Bc 3: Cu hnh Application Pools:

Khi Ta chy IIS trong ch worker process isolation, Ta c th tch bit nhng
ng dng web v v tr web vo trong nhng nhm c gi l application pool. Mt
application pool l mt nhm ca mt hoc nhiu URLs m c phc v bi mt worker
process.

Bt k mt th mc web hoc th mc o c th c gn tr thnh mt


application pool.

Mi ng dng trong cng mt application pool chia s cng worker process. Bi


v mi worker process iu khin nh l mt instance ring l ca worker process thc thi
, worker process m phc v cho mt application pool c tch ring t worker process
phc v cho ci khc.

Mi worker process ring l cung cp mt tin trnh m khi mt application


c gn n mt application pool, nhng vn trong nhng application pool khc khng

Trung Tm Tin Hc H KHTN-TP.HCM Trang 448/617


Gio trnh: Lp trnh Windows Phone

nh hng n n application . iu ny bo m rng nu mt worker process li, n


khng nh hng n application ang chy trong nhng application pool khc.

Ta chn mc Application Pools, bn mn hnh phi ta bm chut phi chn Add


Application Pool: Cu hnh nh bn di ri nhn nt OK:

Ta c kt qu khi bm OK:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 449/617


Gio trnh: Lp trnh Windows Phone

cu hnh nng cao ta chn pool v bm chn Advanced Settings:

Hiu chnh ri bm nt OK.


Bc 4: To Application thc thi ng dng trn IIS:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 450/617


Gio trnh: Lp trnh Windows Phone

Bm chut phi vo Default Web Site/ chn Add Application..

Mn hnh Add Application s hin th ra nh di y:

Alias: t tn i din cho dch v, y ta t khtn_test


Application pool: Ta bm vo nt Select v chn ng khtn_pool to
trc
Physical path: Tr ti ng dn lu tr dch v m ta coding trn.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 451/617


Gio trnh: Lp trnh Windows Phone

Bm OK chp nhn to Application.

Ta chn khtn_test/ bn mn hnh phi ta chn tab Content View/ bm chut phi
vo MyWebService.asmx/ chn Browse:

Kt qu sau khi thc thi thnh cng:

IV. Tng tc Windows Phone vi .Net Web Service

Trung Tm Tin Hc H KHTN-TP.HCM Trang 452/617


Gio trnh: Lp trnh Windows Phone

Ta thy trn c http://localhost/khtn_test/MyWebService.asmx

Ta ch rng link ny ch c th s dng trong Windows Phone 7.1, cn Windows


Phone 8 th khng c do WP8 c card mng ring.

Do nu ta truy sut localhost coi nh b hiu l ang truy sut trn WP8 u
dn n sai a ch, ta cn cu hnh IP thay th cho localhost th mi thao tc c t WP8
ti Webservice (s trnh by phn sau):

xc nh c IP ta cn m ca s Command line ln v g Ipconfig nh sau:

G t hp phm Windows +R hin th mn hnh Run nh di y:

Ta g vo cmd ri bm nt OK:
Mn hnh command line hin th ln ta g lnh ipconfig:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 453/617


Gio trnh: Lp trnh Windows Phone

Ta tm a ch IP chy Application va ri, dng IP th trong Emulator ca


Windows Phone 8 mi truy sut localhost IIS c.

Gi ta to mt ng dng Windows Phone 8 truy sut ti Web Service ny, ta


ch l khi tng tc Web Service bng localhost n c rt nhiu vn sy ra: FireWall,
Proxy, IP khng phi lc no cng sun s, phi lm nhiu c kinh nghim fix li.

Ta to mt ng dng triu gi dch v Gii phng trnh bc 2 nh sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 454/617


Gio trnh: Lp trnh Windows Phone

Ta to mt project tn: Goi_DichVu_PTB2

Ta tin hnh tham chiu ti dch v to phn trn:


Bm chut phi vo References/ chn Add Service Reference..:

Mn hnh Add Service Reference hin th nh di y, ta sao chp link cu hnh


dch v vo Address ri bm nt GO:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 455/617


Gio trnh: Lp trnh Windows Phone

Khi nhn thy kt qu nh trn l thnh cng, ta bm OK gn tham chiu.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 456/617


Gio trnh: Lp trnh Windows Phone

Ta thy ServiceReferences.ClientConfig s t ng c to ra cng vi cc thng


s cu hnh. Trong mc Service References c ServiceReference1, da vo n ta truy
sut d liu trn server thng qua cc service.

Tip theo ta thit k MainPage.xaml:

<phone:PhoneApplicationPage
x:Class="Goi_DichVu_PTB2.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">

<!--LayoutRoot is the root grid where all page content is placed-->


<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 457/617


Gio trnh: Lp trnh Windows Phone

<Border BorderThickness="5" HorizontalAlignment="Left" Height="366"


Margin="8,22,0,0" Grid.Row="1" VerticalAlignment="Top" Width="462">
<Border.BorderBrush>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Red" Offset="0"/>
<GradientStop Color="Pink" Offset="0.5"/>
<GradientStop Color="Yellow" Offset="1"/>
</LinearGradientBrush>
</Border.BorderBrush>
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="#FF3AA256" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,-5">
<TextBlock Text="Gii phng trnh bc 2" Style="{StaticResource
PhoneTextNormalStyle}" Margin="91,6,58,315" Foreground="#FFF9E62B"
FontSize="22" FontWeight="Bold"/>
<TextBlock HorizontalAlignment="Left" Margin="10,55,0,0"
TextWrapping="Wrap" Text="Nhp a:" VerticalAlignment="Top"/>
<TextBlock HorizontalAlignment="Left" Margin="10,113,0,0"
TextWrapping="Wrap" Text="Nhp b:" VerticalAlignment="Top"/>
<TextBlock HorizontalAlignment="Left" Margin="10,173,0,0"
TextWrapping="Wrap" Text="Nhp c:" VerticalAlignment="Top"/>
<TextBlock HorizontalAlignment="Left" Margin="10,219,0,0"
TextWrapping="Wrap" Text="Kt qu:" VerticalAlignment="Top"/>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 458/617


Gio trnh: Lp trnh Windows Phone

<TextBox x:Name="txta" HorizontalAlignment="Left" Height="72"


Margin="83,32,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="314"
InputScope="Default"/>
<TextBox x:Name="txtb" HorizontalAlignment="Left" Height="72"
Margin="83,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="314"
InputScope="Number"/>
<TextBox x:Name="txtc" HorizontalAlignment="Left" Height="72"
Margin="83,142,0,0" TextWrapping="Wrap" VerticalAlignment="Top"
Width="314" InputScope="Number" AcceptsReturn="True"/>
<TextBox x:Name="txtkq" HorizontalAlignment="Left" Height="72"
Margin="83,198,0,0" TextWrapping="Wrap" VerticalAlignment="Top"
Width="314" InputScope="Default"/>
<Button x:Name="btnGiai" Content="Gii" Margin="10,271,275,10"
Click="btnGiai_Click">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="#FFF7ED0F" Offset="1"/>
</LinearGradientBrush>
</Button.Background>
</Button>
<Button x:Name="btnMoi" Content="Mi" Margin="148,271,137,10"
Click="btnMoi_Click">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="#FFC3FD46" Offset="1"/>
</LinearGradientBrush>
</Button.Background>
</Button>
<Button x:Name="btnThoat" Content="Thot" Margin="275,271,10,10"
Click="btnThoat_Click">

Trung Tm Tin Hc H KHTN-TP.HCM Trang 459/617


Gio trnh: Lp trnh Windows Phone

<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="#FFC7BE09" Offset="1"/>
</LinearGradientBrush>
</Button.Background>
</Button>
</Grid>
</Border>

</Grid>

</phone:PhoneApplicationPage>

Tin hnh coding MainPage.xaml.cs:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Navigation;

using Microsoft.Phone.Controls;

using Microsoft.Phone.Shell;

using Goi_DichVu_PTB2.Resources;

using System.IO.IsolatedStorage;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 460/617


Gio trnh: Lp trnh Windows Phone

namespace Goi_DichVu_PTB2

public partial class MainPage : PhoneApplicationPage

public MainPage()

InitializeComponent();

ServiceReference1.MyWebServiceSoapClient client = null;

private void btnGiai_Click(object sender, RoutedEventArgs e)

int a = 0, b = 0, c = 0;

try

if (client == null)

client = new ServiceReference1.MyWebServiceSoapClient();

a = int.Parse(txta.Text);

b = int.Parse(txtb.Text);

c = int.Parse(txtc.Text);

client.GiaiPTB2Async(a, b, c);

client.GiaiPTB2Completed += client_GiaiPTB2Completed;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 461/617


Gio trnh: Lp trnh Windows Phone

catch (Exception ex)

MessageBox.Show("Li d liu u vo");

void client_GiaiPTB2Completed(object sender,


ServiceReference1.GiaiPTB2CompletedEventArgs e)

string s = e.Result;

txtkq.Text = s;

private void btnMoi_Click(object sender, RoutedEventArgs e)

txta.Text = "";

txtb.Text = "";

txtc.Text = "";

txtkq.Text = "";

txta.Focus();

private void btnThoat_Click(object sender, RoutedEventArgs e)

while (((PhoneApplicationFrame)App.Current.RootVisual).CanGoBack)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 462/617


Gio trnh: Lp trnh Windows Phone

((PhoneApplicationFrame)App.Current.RootVisual).RemoveBackEntry();

IsolatedStorageSettings.ApplicationSettings.Save();

Application.Current.Terminate();

V. Tng tc SQL Server v Hosting min ph Somee.com


Phn ny gio trnh s hng dn cc bn cch s dng Hosting min ph
Somee.com, Hosting ny rt tt n cho ta min ph c Sql Server nn c th dng n lm
cng c Testing rt hiu qu m khng mt ph.

Gio trnh s i tng bc t khu to C s d liu, vit web Service ti khu


ng k ti khon v up d liu ln Hosting.

Ta to mt c s d liu c cu trc nh sau (dbProductManager):

Trung Tm Tin Hc H KHTN-TP.HCM Trang 463/617


Gio trnh: Lp trnh Windows Phone

Cch vit .net Webservice tng tc vi CSDL:


Ta s dng LinQ to SQL vit code cho l v gip cc bn d hiu hn, ta lm
nh sau:

T menu View/ chn Server Explorer m ca s kt ni CSDL nh bn di


y:

Trong mn hnh Server Explorer/ ta chn biu tng kt ni c t vng trn mu


.
Mn hnh kt ni c hin th ra nh di y:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 464/617


Gio trnh: Lp trnh Windows Phone

1. Server name: Nhp tn Server ca my bn vo y, trn kia th my ca tui tn


l drthanh.
2. Chn kiu Authentication, bn chn loi no cng c, trn kia tui
chn Windows Authentication.
3. Chn CSDL, d nhin ta phi chn ng CSDL dbproductmanager.
4. Test connection kim tra xem c kt ni thnh cng hay khng, khi bn test
m n ra ca s sau l OK:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 465/617


Gio trnh: Lp trnh Windows Phone

5. Bm OK chp nhn Kt ni.


Kt qu nh sau:

By gi ta tin hnh dng LinQ to SQL tng tc ti CSDL ny nh sau:


Bm chut phi vo Project website to bc trn/ chn Add New Item:

Trong mn hnh New Item ta chn LINQ to SQL Classes nh hnh di y, t


tn ProductManager.dbml ri nhn nt Add:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 466/617


Gio trnh: Lp trnh Windows Phone

Sau khi bm nt Add, ta c thng tin nh hnh di:

Vng 1: L vng CSDL


Vng 2: L vng ta ko th CSDL vo
Vng 3: L vng ta ko th cc Store Procedure vo
Vng 4: Vng cu trc tp tin, lp m ta lp trnh.
By gi ta tin hnh ko th CSDL vo vng s 1 nh sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 467/617


Gio trnh: Lp trnh Windows Phone

+ phm Ctrl + click chut vo 2 bng Catalog v Product ri ko vo vng s


2, ta c giao din:

bc trn, h thng t pht sinh cc lp, hm (CRUD) cho php chng ta


tng tc ti CSDL mt cch d dng. y n t ng sinh ra
lp ProductManagerDataContext v cc lp tng ng vi mi bng (tc l c 2 lp t
ng c pht sinh: Catalog v Product). Thng qua cc lp ny chng ta c th tng
tc c vi CSDL.

Tip tc to Webservice cung cp cc hm ly d liu, ta cng bm chut phi


vo Project/ chn Add new Item hin th mn hnh di y:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 468/617


Gio trnh: Lp trnh Windows Phone

mn hnh trn ta chn Web Service, t tn cho n (mywebservice) ri nhn nt


Add.
Khi nhn nt Add, mc nh ta c thng tin ca web service nh sau:

Ta tin hnh thm mt s hm s dng cho bi tp ny nh sau:


1- Hm m xem c bao nhiu danh mc trong bng catalog

2- Hm tr v danh sch Catalog

3- Hm tr v thng tin ca 1 Catalog theo Id

Trung Tm Tin Hc H KHTN-TP.HCM Trang 469/617


Gio trnh: Lp trnh Windows Phone

4- Hm tr v danh sch Product

5- Hm tr v danh sch Product theo Catalog Id

6- Hm tr v thng tin ca mt Product theo Id

7- Hm xa Catalog theo ID

8- Hm xa Product theo ID.

9- Xut tng tin ca cc mt hng

Ta ln lt vit cc hm ny nh sau:
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.Services;
6
7 /// <summary>
8 /// Summary description for mywebservice
9 /// </summary>
10 [WebService(Namespace = "http://tranduythanh.com/")]
11 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
12 // To allow this Web Service to be called from script, using
13 ASP.NET AJAX,

14 // [System.Web.Script.Services.ScriptService]

15 public class mywebservice : System.Web.Services.WebService {

16
17 ProductManagerDataContext db = null;

18 public mywebservice () {

19

Trung Tm Tin Hc H KHTN-TP.HCM Trang 470/617


Gio trnh: Lp trnh Windows Phone

20 //Uncomment the following line if using designed components


21 //InitializeComponent();
22 db = new ProductManagerDataContext();
23 }
24
25 [WebMethod]
26 public string HelloWorld() {
27 return "Hello World";
28 }
29 //Hm m xem c bao nhiu danh mc trong bng catalog
30 [WebMethod]
31 public int CountCatalog()
32 {
33 return db.Catalogs.Count();
34 }
35 //2- Hm tr v danh sch Catalog
36 [WebMethod]
37 public List<Catalog> getListCatalog()
38 {
39 List<Catalog> listCate = db.Catalogs.ToList();
40 foreach (Catalog c in listCate)
41 c.Products.Clear();
42 return listCate;
43 }
44 //3- Hm tr v thng tin ca 1 Catalog theo Id
45 [WebMethod]

Trung Tm Tin Hc H KHTN-TP.HCM Trang 471/617


Gio trnh: Lp trnh Windows Phone

46 public Catalog getCatalog(string id)


47 {
48 Catalog c=db.Catalogs.FirstOrDefault(x => x.CateId == id);
49 c.Products.Clear();
50 return c;
51 }
52 //4- Hm tr v danh sch Product
53 [WebMethod]
54 public List<Product> getListProduct()
55 {
56 List<Product> listPro = db.Products.ToList();
57 foreach (Product p in listPro)
58 p.Catalog = null;
59 return listPro;
60 }
61 //5- Hm tr v danh sch Product theo Catalog Id
62 [WebMethod]
63 public List<Product> getListProductByCatalogId(string id)
64 {
65 List<Product> listPro=db.Products.Where(x => x.CateId ==
id).ToList();
66
foreach(Product p in listPro)
67
p.Catalog=null;
68
return listPro;
69
}
70
//6- Hm tr v thng tin ca mt Product theo Id
71

Trung Tm Tin Hc H KHTN-TP.HCM Trang 472/617


Gio trnh: Lp trnh Windows Phone

72 [WebMethod]
73 public Product getProduct(string id)
74 {
75 Product p = db.Products.FirstOrDefault(x => x.ProductId == id);
76 p.Catalog = null;
77 return p;
78 }
79 //7- Hm xa Catalog theo ID
80 [WebMethod]
81 public bool deleteCatalog(string id)
82 {
83 try
84 {
85 Catalog cate = getCatalog(id);
86 db.Catalogs.DeleteOnSubmit(cate);
87 db.SubmitChanges();
88 }
89 catch (Exception ex)
90 {
91 return false;
92 }
93 return true;
94 }
95 //8- Hm xa Product theo ID.
96 [WebMethod]
97 public bool deleteProduct(string id)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 473/617


Gio trnh: Lp trnh Windows Phone

98 {
99 try
100 {
101 Product p = getProduct(id);
102 db.Products.DeleteOnSubmit(p);
103 db.SubmitChanges();
104 }
105 catch (Exception ex)
106 {
107 return false;
108 }
109 return true;
110 }
111 //9- Xut tng tin ca cc mt hng
112 [WebMethod]
113 public double getToTalMoney()
114 {
115 return db.Products.Sum(x => x.TotalMoney).Value;
}
}
Bn ch on code trn ta gn =null nhiu ch l do x l vic Loop trong
thao tc Webservice, nu c s loop (hay quy) th n khng chp nhn. Nu vit bng
Winform hay Webform bnh thng th khng sao (l gii php tm thi)

Ta tin hnh kim tra webservice trn my cc b nh sau (nhn F5 chy):

Trung Tm Tin Hc H KHTN-TP.HCM Trang 474/617


Gio trnh: Lp trnh Windows Phone

Ta thy cc hm c hin th ra y. test th bn ch cn bm vo hm ri


chn Invoke l OK.

V d chn hm CountCatalog v getListCatalog, getListProductByCatalogId:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 475/617


Gio trnh: Lp trnh Windows Phone

Trung Tm Tin Hc H KHTN-TP.HCM Trang 476/617


Gio trnh: Lp trnh Windows Phone

Mc ch ca chng ta l kt ni t Android ti Webservice ny tng tc. Bn


c th cu hnh IIS chy trn my cc b (ta lm ri), gi ta a n ln Internet (trang
Somee) demo thc t, ti v thc t l n nm trn internet. Mobile ch l Client.

Cch thc a CSDL v .net webservice ln somee.com


Bc 1: Vo https://somee.com
Bc 2: Chn Free .Net hosting nh hnh di y:

Bm chn Learn More qua bc 3.

Bc 3: Chn Order mua gi min ph ny:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 477/617


Gio trnh: Lp trnh Windows Phone

Bc 4: Nhp cc thng s cn thit to to ti khon:

Bm Register new user and continue ng k v tip tc vi mn hnh


checkout.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 478/617


Gio trnh: Lp trnh Windows Phone

Bc 5: Chn cc thng s ri bm Continue, mn hnh Create Website s hin


th ra nh bn di, ta nhp cc thng tin ri bm:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 479/617


Gio trnh: Lp trnh Windows Phone

Mn hnh thng bo thnh cng hin th ra di y:

Tip theo ta to CSDL cho trang testdrthanh.somee.com


Bm chn mc Databases bn tay tri trn mn hnh trn:

Mn hnh trn n nt Create c khoanh mu , ta bm vo n. Mn hnh to


CSDL hin th ra, y ta nn t cng tn vi CSDL m ta to my Client d dng
Backup, Restore .

Trung Tm Tin Hc H KHTN-TP.HCM Trang 480/617


Gio trnh: Lp trnh Windows Phone

Sau khi nhp y thng tin, bm chn Create empty database.


Sau khi to thnh cng th ta c mn hnh nh di y:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 481/617


Gio trnh: Lp trnh Windows Phone

Bn dng t mu xanh, chnh l chui kt ni ti CSDL, bn c th copy


paste chui ny dn vo chui kt ni my Local ca bn th khi chy website n s kt
ni ti CSDL trn trang somee ny.

workstation id=dbproductmanager.mssql.somee.com;packet size=4096;user


id=drthanh_SQLLogin_1;pwd=7szjt75abq;data
source=dbproductmanager.mssql.somee.com;persist security info=False;initial
catalog=dbproductmanager

testdrthanh.somee.com chnh l sub domain m n cung cp cho mnh, da vo


y ta ly thng tin.

By gi ta tin hnh a d liu t my Local ln Trang somee, lm nh sau:


1- Backup li CSDL ti my Local ca bn:

Bm chut phi vo CSDL/ chn Tasks/ Chn Backup:

Mn hnh chn Backup hin th ra nh di y, ta tin hnh nhp thng s


ri bm OK:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 482/617


Gio trnh: Lp trnh Windows Phone

Gi bn kim tra a D:/ xem c tp tin ny hay cha, nu c tc l


backup thnh cng.
2- a file Backup ny ln Server somee:

Ta chn Restore database, ri chn Choose File, chn ng tp tin va backup


trn ri bm Upload the file and restore it.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 483/617


Gio trnh: Lp trnh Windows Phone

Ch bo thnh cng l OK:

test coi n c chy c hay khng th ta chn mc New SQL Query mn


hnh trn, n s hin th ra ca s cho php ta nhp cu SQL:

Nh hnh trn th thnh cng.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 484/617


Gio trnh: Lp trnh Windows Phone

3- Tip tc ta a Webservice ln somee Test nh sau:

Dng Win Zip ca h iu hnh Windows, nn li source code v y ln server.


D nhin ta cn sa chui kt ni li. Nh mc trn Ta ni l copy paste chui kt ni :

workstation id=dbproductmanager.mssql.somee.com;packet size=4096;user


id=drthanh_SQLLogin_1;pwd=7szjt75abq;data
source=dbproductmanager.mssql.somee.com;persist security info=False;initial
catalog=dbproductmanager

Thay th cho chui c sn my Local nh sau (d nhin khi bn to th chui n


phi khc v bn phi ly theo chui ca bn):

Trong Project Web Service, m tp tin Web.config v thay th bng chui trn:

Sau tin hnh zip nh sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 485/617


Gio trnh: Lp trnh Windows Phone

hnh trn l ta Ctrl+ A chn ton b tp tin v th mc/sau ta bm chut


phi vo 1 tp tin bt k trong th mc cha source code/ chn Send to / chn
Compressed nh hnh bn trn, n pht sinh ra mt file zip cha ton b source code
trong ny (ta chn tp tin no bm chut phi cng c).
Sau khi c file zip, ta quay li mn hnh somee server a source code ln nh
sau:
1- Chn File Manager/ ca s hin th ln chn nt Upload nh hnh bn di:

Sau khi chn nt Upload th n xut hin cho chng ta nt Choose File a file
t client ln Server/ ta chn ng file zip lc ny ri bm Upload and Unzip archives:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 486/617


Gio trnh: Lp trnh Windows Phone

Sau khi bm Upload and unzip archives th ta c kt qu nh sau:

Bn thy y, ton b source code c a ln server.


By gi ta tin hnh kim tra Webservice c chy hay khng nh sau:
http://testdrthanh.somee.com/mywebservice.asmx :

Trung Tm Tin Hc H KHTN-TP.HCM Trang 487/617


Gio trnh: Lp trnh Windows Phone

Nh vy l thnh cng, bn c th tin hnh kim tra tng Service trong ny.
By gi ta xy dng phn mm Windows Phone tng tc ti:
http://testdrthanh.somee.com/mywebservice.asmx
Lm bi n gin l hin th danh mc sn phm, giao din n gin nh sau:

Cc bc tham chiu Service ging nh bi trn trnh by

Trung Tm Tin Hc H KHTN-TP.HCM Trang 488/617


Gio trnh: Lp trnh Windows Phone

Giao din MainPage.xaml:


<phone:PhoneApplicationPage

x:Class="Test_Service_somee.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:phone="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Portrait" Orientation="Portrait"

shell:SystemTray.IsVisible="True">

<StackPanel HorizontalAlignment="Left" Height="768"


VerticalAlignment="Top" Width="480">

<Button x:Name="btnLoadData" Content="Load Data"


Click="btnLoadData_Click"/>

<ListBox x:Name="mylistbox"></ListBox>

</StackPanel>

<!--LayoutRoot is the root grid where all page content is placed-->

</phone:PhoneApplicationPage>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 489/617


Gio trnh: Lp trnh Windows Phone

Source code Mainpage.xaml.cs:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Navigation;

using Microsoft.Phone.Controls;

using Microsoft.Phone.Shell;

using Test_Service_somee.Resources;

namespace Test_Service_somee

public partial class MainPage : PhoneApplicationPage

// Constructor

public MainPage()

InitializeComponent();

// Sample code to localize the ApplicationBar

//BuildLocalizedApplicationBar();

private void btnLoadData_Click(object sender, RoutedEventArgs e)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 490/617


Gio trnh: Lp trnh Windows Phone

ServiceReference1.mywebserviceSoapClient client = new


ServiceReference1.mywebserviceSoapClient();

client.getListCatalogAsync();

client.getListCatalogCompleted += client_getListCatalogCompleted;

void client_getListCatalogCompleted(object sender,


ServiceReference1.getListCatalogCompletedEventArgs e)

mylistbox.Items.Clear();

foreach (ServiceReference1.Catalog cate in e.Result)

mylistbox.Items.Add(cate.CateName);

VI. Kt lun
Web service l mt trong nhng cng ngh khng th thiu i vi cc phn mm
chuyn bit trong Windows Phone, ta cn nm cc kin thc c bn v SOAP cch to .net
Web service cng nh cch trin khai ln Hosting.

Cn hiu r cch thc tng tc t Windows Phone ln Server. i vi Windows


Phone 8 n hi phc tp do n tch ring card mng nn vic truy sut trn emulator phi
theo IP v cn kim tra Firewall cng nh cc vn khc.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 491/617


Gio trnh: Lp trnh Windows Phone

BI 2. WCF V CLOUD
(Windows Communication Foundation v Windows Azure
Mobile Service)

bi 1 v bi 2 ta nghin cu ASP.NET Web Service, bi ny chng ta tip


tc nghin cu v cc dch v nng cao nh WCF (Windows Communication Foundation)
v Cloud (Windows Azure Service) c h tr trong Windows Phone. Mi mt kin trc
n c nhng sc mnh v tng lp trnh khc nhau, chng u mang li nhng tri
nghim v cng th v khi ta lp trnh vi Windows Phone.

Ni dung ca phn ny s cp ti nhng phn sau:


I) WCF - Windows Communication Foundation ....................................493
1) Gii thiu WCF ................................................................................................ 493
2) Cch to WCF.................................................................................................. 499
3) Cc thuc tnh trong WCF .............................................................................. 500
a) Service Contract ............................................................................................. 500
b) Operation Contract ......................................................................................... 501
c) Data Contract ................................................................................................. 501
d) DataMember................................................................................................... 502
e) Fault Contracts ............................................................................................... 502
4) Tng tc Windows Phone vi WCF ............................................................. 504
II) Windows Azure Mobile Services .........................................................524
III) Kt lun ...............................................................................................533

Trung Tm Tin Hc H KHTN-TP.HCM Trang 492/617


Gio trnh: Lp trnh Windows Phone

I. WCF - Windows Communication Foundation


Cc khi nim v WCF c gio trnh tng hp t cc trang mng chuyn v lp
trnh chuyn su WCF v t MSDN ca Microsoft, ng thi cho d hiu gio trnh s
tm tt li nhng im quan trng ca WCF lp trnh vin c th d dng nm bt cng
nh lp trnh c vi WCF v tng tc Windows Phone vi WCF (ngun
http://forum.aspvn.net/, http://www.bigdata.com.vn/, http://www.c-sharpcorner.com,
http://msdn.microsoft.com, https://www.ibm.com/developerworks/vn/ ).

1. Gii thiu WCF

WCF l g?
WCF l cng ngh nn tng nhm thng nht nhiu m hnh lp trnh giao tip
c h tr trong .NET 2.0 thnh mt m hnh duy nht. Vo thng 11 nm 2005, .NET
2.0 c Microsoft pht hnh trong c cung cp cc hm API ring bit cho cc lin lc
da trn SOAP ti a ho s lm vic gia cc nn tng s dng Web Services, ng
thi .NET 2.0 cn cung cp cc API ti u vic lin lc da trn m nh phn gia cc
ng dng chy trn h thng Windows gi l .NET Remoting, cc API cho cc giao dch
phn tn, v API cho lin lc d b. WCF thng nht cc API ny thnh mt m hnh duy
nht nhm p ng m hnh lp trnh hng dch v.

WCF c th s dng cc bn tin SOAP gia hai tin trnh, do lm cho cc ng


dng da trn WCF c th lm vic vi cc tin trnh khc thng qua vic giao tip s dng
bn tin SOAP. Khi mt tin trnh WCF lin lc vi mt tin trnh khng l WCF, cc bn
tin SOAP c m ho trn c s XML, nhng khi n lin lc vi mt tin trnh WCF
khc, bn tin SOAP c th c ti u ho da trn m ho nh phn.

Ti sao s dng WCF?


Nh phn trn trnh by, .NET 2.0 h tr rt nhiu phng php lin lc gia
cc ng dng khc nhau nhm vo cc mc tiu khc nhau. Cc phng php lin lc ny
kh phc tp v phi mt nhiu thi gian lm ch c cng ngh. Tuy nhin kin thc
thu c t vic trin khai mt phng php t c kh nng dng c khi lm vic vi
phng php khc.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 493/617


Gio trnh: Lp trnh Windows Phone

Vi vic ra i ca WCF, mi phng php lin lc trc kia u c th thc hin


trn WCF. Do vy nh pht trin ch cn lm ch c cng ngh WCF l c th xy dng
cc ng dng mt cch nhanh chng.

WCF l mt m hnh lp trnh cho php nh pht trin xy dng cc gii php dch
v m bo tnh n nh, v bo mt v thm ch l m bo giao dch. N lm n gin
ho vic pht trin cc ng dng ni kt v a ra cho nh pht trin nhng gi tr m c
th h cha nhn ra ngay, l cch tip cn pht trin h thng phn tn thng nht, n
gin, v qun l c.

Do WCF c xy dng trn c s ca .NET Framework 2.0 CLR, n l tp cc


lp cho php cc nh pht trin xy dng cc ng dng hng dch v bng mi trng
lp trnh quen thuc ca h nh VB.NET hay C#.

Kin trc ca WCF


Hnh sau m t cc lp ch yu trong kin trc ca Windows Communication
Foundation

Trung Tm Tin Hc H KHTN-TP.HCM Trang 494/617


Gio trnh: Lp trnh Windows Phone

M t chi tit cho kin trc ca WCF nh sau:


Cc contracts (Cc hip ngh):
Cc contract trong WCF cng ging nh cc hp ng/hip nh m bn k trong
i sng tht. Mt hp ng bn k c th cha cc thng tin nh kiu cng vic bn s
lm, v nhng thng tin m bn mun a ra cho cc bn khc. WCF contract cng cha
cc thng tin tng t nh vy. Contract nh ngha cc c t trong h thng bn tin.Thng
thng c cc loi contract sau:

Contract d liu m t cc tham s cho cc bn tin m mt dch v c th to ra


hay s dng. Cc tham s bn tin c nh ngha bng cc ti liu s dng ngn ng c
t XML Schema (XSD), iu ny cho php cc h thng hiu XML c th x l ti liu d
dng. Cc dch v khi lin lc vi nhau c th khng cn ng vi nhau v cc kiu,
nhng cn ng v contract d liu, ngha l ng v cc tham s v cc kiu tr v.

Contract bn tin nh ngha cc phn c trong bn tin s dng cc giao thc SOAP,
v n cho php iu khin su hn ti cc phn trong bn tin khi c yu cu s chnh xc
nh vy.

Contract dch v c t chi tit cc phng thc ca dch v, v c phn phi


nh l mt giao din trong cc ngn ng lp trnh nh Visual Basic hay Visual C#. C th
hnh dung v contract dch v mt cch gin tip nh sau: y l cc kiu d liu ca cc
bn tin ca ti, y l ni ti cung cp, v y l cc giao thc m ti c th lin lc

Cc chnh sch v cc kt ni (bindings) m t cc iu kin cn c giao tip


vi mt dch v. Cc chnh sch s bao gm c cc yu cu v bo mt v cc iu kin
khc cn phi c khi kt ni vi mt dch v.

Runtime service (Dch v thc thi):


Lp dch v thc thi cha cc hnh x s xy ra trong qu trnh thc hin ca dch
v, ngha l cc hnh x thc thi ca dch v. Ta s thy mt s cc hnh x nh sau:

Throttling behavior: iu khin lung nhm quy nh xem c bao nhiu bn


tin c x l

Trung Tm Tin Hc H KHTN-TP.HCM Trang 495/617


Gio trnh: Lp trnh Windows Phone

Error behavior: Hnh x li quy nh nhng hnh ng khi li xy ra trong h


thng
Metadata behavior: Hnh x vi cc siu d liu quy nh xem lm th no v
khi no th cc siu d liu c a ra bn ngoi dch v
Instance behavior: Hnh x thc th quy nh xem c bao nhiu thc th ca
dch v c chy
Transaction behavior: Hnh x giao dch cho php vic rollback cc giao dch
nu xy ra li
Message inspection: Kim tra bn tin em li cho dch v kh nng kim tra tt
c hay mt s phn ca bn tin
Dispatch behavior: Khi mt bn tin c x l bi nn tng WCF, dch v
Dispatch behavior xc nh xem bn tin c x l nh th no.
Concurrency behavior: Hnh x ng thi xc nh xem vic x l th no vi
vic a lung ca mi dch v hay mi thc th ca dch v. Hnh x ny gip
cho vic iu khin s lng lung c th truy nhp ti mt thc th ca dch
v.
Parameter filtering: Khi mt bn tin c a ti mt dch v, s xy ra mt
s hnh ng da trn ni dung phn u ca bn tin. Phn lc tham s s
thc hin lc cc u bn tin v thc hin cc hnh ng t sn da trn vic
lc u bn tin.
Message (Bn tin):
Lp bn tin l tp hp cc knh. Mi knh l mt thnh phn x l bn tin theo
mt cch no . Mt tp cc knh thng c gi l ngn xp knh. Cc knh lm vic
trn bn tin v trn u ca bn tin. Lp ny khc vi lp thc thi dch v ch yu bi
s khc nhau trong vic x l ni dung bn tin.

C hai knh khc nhau l:

Knh vn chuyn (transport channel)


Knh iu khin (control channel).

Trung Tm Tin Hc H KHTN-TP.HCM Trang 496/617


Gio trnh: Lp trnh Windows Phone

Knh vn chuyn ph trch vic c v ghi cc bn tin t mng (network) hoc t


mt s im giao dch bn ngoi)

Knh iu khin thc hin x l bn tin theo giao thc, thng thng lm vic
bng cch c v ghi thm cc u cho bn tin

Host and activation (Cha v kch hot):


Nhn mt cch tng th th mt dch v thc cht l mt chng trnh. Cng ging
nh cc chng trnh khc, mt dch v cn phi chy trong mt tp thc thi. Dch v ny
thng c gi l dch v t cha.

Cc dch v cn c th c cha, hoc chy trong mt tp thc thi c qun l


bi mt agent bn ngoi nh IIS hay Windows Activation Services (WAS). WAS cho php
WCF c kch hot mt cch t ng khi phn phi ti mt my tnh c chy WAS.

Cc tnh nng ca WCF


WCF c nhiu tnh nng v s c m t chi tit trong ton b kho hc. Mc
ny ch nhm mc ch tho lun mt s tnh nng ca WCF. Danh sch cc tnh nng
y khng phi l danh sch hon chnh, m ch hy vng l danh sch cc tnh nng nh
nht.

Transaction (Giao dch)


Mt giao dch l mt n v ca cng vic. Mt giao dch m bo chc chn rng
mi th din ra trong giao dch thnh cng hay tht bi u l kt qu tng th. V d, nu
mt giao dch cha ba mc cng vic cn thc hin, trong qu trnh thc hin giao dch,
mt trong s cc mc b tht bi, khi c ba mc s l tht bi. Giao dch ch thnh
cng khi c ba mc cng vic u thnh cng. Giao dch thng thy trong cc thao tc
vi c s d liu.

WCF cho php a vo vic x l giao dch nh trn vi cc lin lc. Nh pht
trin c th nhm cc lin lc vi nhau thnh cc giao dch. mc doanh nghip, tnh nng
ny cho php bn thc hin cc cng vic giao dch qua cc nn tng khc nhau.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 497/617


Gio trnh: Lp trnh Windows Phone

Host (Cha)
WCF cho php cc dch v c cha trong mt s ln cc mi trng khc nhau,
nh Windows NT Services, Windows Forms, v ng dng console, cng nh trn IIS
(Internet Information Server) v WAS (Windows Activation Services).

Cha ng dng trn IIS cn c thm cc li im khc l dch v c th nhn cc


u im ca rt nhiu tnh nng c sn trn IIS, v d IIS c th iu khin mt cch t
ng vic bt u hay kt thc mt dch v.

Bo mt
Bo mt l tnh nng khng th thiu trong WCF ni ring v trong lin lc ni
chung. Trong WCF, tt c mi th t cc bn tin ti cc client hay server u phi xc thc
v WCF c tnh nng m bo rng cc bn tin khng b ln trong qu trnh vn chuyn.
WCF bao gm vic m bo tnh ton vn v bo mt ca bn tin.

WCF cn cho php bn tch hp ng dng ca bn vi c s h tng bo mt sn


c, bao gm c cc chun bn ngoi mi trng Windows bng cch s dng cc bn tin
SOAP bo mt.

Cng c pht trin vi WCF:


S dng Visual Studio lp trnh vi WCF

S khc nhau gia Web Service v WCF

WebService WCF

S dng thuc tnh [WebService] trong S dng thuc tnh [ServiceContract] thay
class th.

S dng [WebMethod] vi Method. S dng [OperationContract] vi Method

Ch c th host trn IIS C th host trn IIS, WAS (Windows


Activation Service), trong mt Window
Service hoc t host chnh n.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 498/617


Gio trnh: Lp trnh Windows Phone

2. Cch to WCF

Gio trnh s hng dn cc bn to WCF trn Visual Studio 2010, hc vin c th


to trn Visual studio 2012, 2013 cng tng t:

T Menu File/ chn New/ chn Project (hoc nhn t hp phm Ctrl + Shift +N):

Ca s New Project hin th ln ta chn nh hnh di y:

mc bn tri ta chn WCF template.


Sau chn WCF Service Application
Name: t tn cho Project ri nhn nt OK (ta t KHTN_WcfService).
Kt qu sau khi nhn nt OK:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 499/617


Gio trnh: Lp trnh Windows Phone

Mc nh h thng s to ra 2 tp tin IService1 v Service1 nh hnh trn.


Double click vo file IService1.cs tm hiu v cc Contract trong interface
IService1

y chng ta s tm hiu 3 contract l ServiceContract, OperationContract


v DataContract v DataMember, ngoi ra gio trnh s trnh by thm v Fault
Contracts.

3. Cc thuc tnh trong WCF

Service Contract
L thuc tnh c p dng cho service interface, y l interface IService1, n
miu t nhng hnh ng m client c th thc hin trn Service:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 500/617


Gio trnh: Lp trnh Windows Phone

Operation Contract
L thuc tnh p dng cho cc phng thc trong Service Interface. N dng
nh ngha mt Method trong interface:

Data Contract
Dng nh ngha kiu d liu c truyn n v i ca mt Service. N c
s dng nh ngha mt class v thuc tnh DataMember c dng nh ngha thuc
tnh (Properties).

Trung Tm Tin Hc H KHTN-TP.HCM Trang 501/617


Gio trnh: Lp trnh Windows Phone

DataMember

Nh vy ta cn ch l khi truyn ti cc lp(i tng) qua li trn mng th phi


c thuc tnh DataConstract cho lp v Datamember cho cc Properties.

Fault Contracts
WCF cho php chng ta nh ngha hnh vi s thc thi khi c li xy ra trong WCF.

V d: chng ta to mt service v n c s dng bi client, gi s service ny


to ra mt li ngoi l, nhng lm sao client c thng bo v thng tin li ny? Bi
v mi ln mt Exeption pht sinh trong WCF, n khng th gi thng tin ny ti Client,
nhng bn li mun bit nguyn nhn v sao li sinh ra li, do Fault Contract s gip
chng ta thc hin iu .

So snh Fault vi Exception


Exception l c ch ca .Net cho php chng ta Throw, Catch, hoc Ignore mt
ngoi l khi c li xy ra trong ng dng. Ti mt im no chng s c x l hoc
.Net Runtime s chm dt v tm dng Thread ca chng trnh v nm ra li.

Fault l khi nim ch n c ch li ca SOAP truyn thng tin li t


Service ti Client. WCF cung cp mt class l FaultException x l vn ny.
Mi khi c li, WCF service s serialize thng tin v gi ti Client.
FaultExeption:c dng gi d liu li c kiu xc nh ti Client,
TDetail l kiu tham s lu thng tin li.Hay kho st mt v d c th nh sau.
Hy to mt project nh bi 1, thm vo Interface IService1 on code sau.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 502/617


Gio trnh: Lp trnh Windows Phone

[ServiceContract]

public interface IService1

[OperationContract]

[FaultContract(typeof(FaultInfo))]

string Topup(string Operator, string MobileNumber, double Amount);

[DataContract()]

public class FaultInfo

[DataMember()]

public string Reason = null;

y chng ta dng th FaulContract nh ngha mt FaultContract v nh


ngha ny ch p dng interface. Nu chng ta mun tr v nhiu kiu Fault khc nhau
th chng ta phi dng th FaultContract nhiu ln.

Nu chng ta tr v d liu Fault c kiu xc nh th chng ta phi nh ngha


kiu d liu cho n. y , chng ta nh ngha kiu d liu l FaultInfo lu thng tin
v li c tr v, trong class ny c mt DataMember lReason, lu thng tin l do gy
ra li.

V nh ngha FaultContract, nn trong file Service1.svc.cs chng ta phi trin


khai phng thc Topup c trong Interface IService1 nh sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 503/617


Gio trnh: Lp trnh Windows Phone

public string Topup(string Operator, string MobileNumber, double Amount)

if (Amount >= 100000000)

FaultInfo fi = new FaultInfo();

fi.Reason = "Amount should not greater than 100,000,000.";

throw new FaultException(fi, new FaultReason(fi.Reason));

return "Recharge Successful.";

phng thc trn, chng ta kim tra Amount, nu Amount <= 100 triu th bo
li, mt i tng FaultInfo c to ra v gn vo thng bo li cho thuc tnh Reason.
Cui cng, chng ta nm ra mt ngoi l FaultException ca kiu d liu FaultInfo.

4. Tng tc Windows Phone vi WCF

thc hin WCF ta bm chut phi vo Service1.svc ri chn View in Browser:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 504/617


Gio trnh: Lp trnh Windows Phone

Kt qu :

Ch y khi ta mun tng tc vi WCF qua GUI th phi dng cng c


WcfTestClient.exe ca Microsoft, thng n nm trong th mc:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 505/617


Gio trnh: Lp trnh Windows Phone

Cng c ny cung cp cho chng ta giao din tng tc rt tin li:

Mi u khi khi ng WCF Test Client ln th n trng nh mn hnh bn di,


ta bm chut phi vo My Service Projects/ Chn Add Service:

Mn hnh Add Service s hin th ra nh di y, ta nhp URL kch hot Service:

Sau khi bm OK, ta s c kt qu nh sau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 506/617


Gio trnh: Lp trnh Windows Phone

Mun chy Dch v no th ta Double click vo hm , v d mun chy GetData


th ta double click vo hm ny ri nhp tham s l 113 ( test) sau bmn nt Invoke
th ta c kt qu nh hnh trn.

Windows Phone tng tc c vi WCF th tng t nh ASP.NET Web


service ta cng cn cu hnh IIS ( hng dn bi 1-2) hoc WAS. k tha kin thc
hc t bi 1 v bi 2 (WAS s hng dn ngay sau phn ny), hc vin c th cu hnh
WCF trn IIS. Ch l i vi Windows Phone 8 ta phi dng a ch IP truy sut. Bn
cn xem li bi 1 v bi 2 cu hnh c IIS, gio trnh s hin th lun kt qu cu hnh:

Bm chut phi vo Default Web Site, chn Add Application:

Hiu chnh cc thng s ri nhn nt OK, sau ta cn tm a ch IP chy WCF


cu hnh ny, y gio trnh c kt qu:

http://169.254.80.80/khtn_testwcf/Service1.svc :

Trung Tm Tin Hc H KHTN-TP.HCM Trang 507/617


Gio trnh: Lp trnh Windows Phone

Tip theo ta to mt Project Windows Phone 8 test WCF trn nh sau:

Giao din n gin nh sau (MainPage.xaml):

<phone:PhoneApplicationPage

x:Class="Test_Wcf.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:phone="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d"

Trung Tm Tin Hc H KHTN-TP.HCM Trang 508/617


Gio trnh: Lp trnh Windows Phone

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Portrait" Orientation="Portrait"

shell:SystemTray.IsVisible="True">

<StackPanel HorizontalAlignment="Left" Height="768"


VerticalAlignment="Top" Width="480">

<TextBlock TextWrapping="Wrap" Text="Nhp Data:"/>

<TextBox x:Name="txtData" Height="72" TextWrapping="Wrap"/>

<TextBlock x:Name="txtResult" TextWrapping="Wrap"


HorizontalAlignment="Center"/>

<Button x:Name="btnGetData" Content="Get Data"


Click="btnGetData_Click"/>

</StackPanel>

</phone:PhoneApplicationPage>

Tip theo tham chiu ti dch v WCF:

Mn hnh Add Service Reference hin th ra nh di y:


Mc Address: Nhp vo URL ca WCF ri nhn nt GO:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 509/617


Gio trnh: Lp trnh Windows Phone

Ta quan st trong mc Services, kt qu s c hin th ra y, ta tin hnh chn


Service1/ Iservice1 th mc Operations s lit k ton b cc dch v c cung cp.

Bm OK thm tham chiu Service.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 510/617


Gio trnh: Lp trnh Windows Phone

Sau khi bm OK, Dch v s c tham chiu vo Mobile Project nh hnh bn


trn. kim tra cc cu hnh ta c th vo file ServiceReferences.ClientConfig quan
st.

Tin hnh coding cho MainPage.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Test_Wcf.Resources;

namespace Test_Wcf
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();

// Sample code to localize the ApplicationBar


//BuildLocalizedApplicationBar();
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 511/617


Gio trnh: Lp trnh Windows Phone

private void btnGetData_Click(object sender, RoutedEventArgs e)


{
//to i tng service client:
ServiceReference1.Service1Client client =
new ServiceReference1.Service1Client();
int data=int.Parse(txtData.Text);
//triu gi hm bt ng b GetDataAsync
//ta ch rng cc dch v c to ra trong WCF khi tham chiu trong
Windows Phone
//n s t ng pht sinh ra cc hm bt ng b tng ng
client.GetDataAsync(data);
//gi dch v completed kim tra s hon tt ca giao dch cng nh ly
kt qu
client.GetDataCompleted += client_GetDataCompleted;
}

void client_GetDataCompleted(object sender,


ServiceReference1.GetDataCompletedEventArgs e)
{
// kt qu c lu tr cho bin e
//ch l ty thuc vo kiu d liu tr v ca dch v do ta vit
//trong WCF m e s c cc kiu khc nhau ng vi kiu ta tr v.
txtResult.Text = e.Result;
}

}
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 512/617


Gio trnh: Lp trnh Windows Phone

Sau khi thc thi ta c kt qu nh sau:

Tip theo gio trnh s hng dn cch to WCF bng WAS


To mt Project Windows Form Application tn l KHTN_WCF_WAS:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 513/617


Gio trnh: Lp trnh Windows Phone

To mt Form nh giao din di y:

Tip theo l Project ca ta cn tham chiu ti Service Model nh sau (bm chut
phi vo References/ chn Add Reference):

Mn hnh Add Reference hin ln ta chn tab .Net:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 514/617


Gio trnh: Lp trnh Windows Phone

Tm ti System.ServiceModel ri nhn ni OK.

Tip theo to 1 Interface tn l ITest vo project, c dch v cng 2 s nguyn


nh sau:

Bm chut phi vo Project / chn Add / chn Class..

Trung Tm Tin Hc H KHTN-TP.HCM Trang 515/617


Gio trnh: Lp trnh Windows Phone

Mn hnh Add New Item hin th ln, ta chn Interface:

t tn l ITest ri nhn nt Add.


Tin hnh coding cho Interface ny nh sau:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

namespace KHTN_WCF_WAS

Trung Tm Tin Hc H KHTN-TP.HCM Trang 516/617


Gio trnh: Lp trnh Windows Phone

[ServiceContract]

interface ITest

[OperationContract]

int cong2so(int a, int b);

Tip tc to 1 lp Test implement interface ITest (bc lm tng t nhng ta


chn Class thay v Interface):

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace KHTN_WCF_WAS

public class Test:ITest

public int cong2so(int a, int b)

return a + b;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 517/617


Gio trnh: Lp trnh Windows Phone

Tin hnh Coding cho Form1.cs:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

//thm 2 th vin ny:

using System.ServiceModel;

using System.ServiceModel.Description;

namespace KHTN_WCF_WAS

public partial class Form1 : Form

public Form1()

InitializeComponent();

private ServiceHost host;

private void btnStartServer_Click(object sender, EventArgs e)

String add = "http://169.254.80.80/Test";

host = new ServiceHost(typeof(Test), new Uri(add));

Trung Tm Tin Hc H KHTN-TP.HCM Trang 518/617


Gio trnh: Lp trnh Windows Phone

ServiceMetadataBehavior sv = new ServiceMetadataBehavior();

sv.HttpGetEnabled = true;

sv.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;

host.Description.Behaviors.Add(sv);

try

host.Open();

MessageBox.Show(" kch hot Server");

catch (AddressAccessDeniedException ex) {

MessageBox.Show("a ch khng vo c \n"+ex.ToString());

host = null;

catch (AddressAlreadyInUseException)

host = null;

MessageBox.Show("a ch vo ri");

catch (Exception) {

host = null;

MessageBox.Show("Li g ");

Trung Tm Tin Hc H KHTN-TP.HCM Trang 519/617


Gio trnh: Lp trnh Windows Phone

Ch on coding trn ta dng http://169.254.80.80/Test d nhin n l thuc


vo IP trong my tnh ca bn.

Tin hnh bin dch ri thc thi (bm chut phi vo .exe v Run as Administrator):

Bm nt Start Server nu c thng bo nh trn l thnh cng.


Kt qu ta cng c nh sau (khng cn cu hnh IIS m dng c ch WAS):

Trung Tm Tin Hc H KHTN-TP.HCM Trang 520/617


Gio trnh: Lp trnh Windows Phone

By gi ta tin hnh chnh sa Project Mobile Test_Wcf phn trc, gio trnh
mun cung cp thm thng tin l ta c th thm nhiu Service vo cng 1 ng dng Mobile:

T ng dng c ta b sung thm cc nhp s a, s b tin hnh triu gi dch


v cng 2 s c xy dng bng WAS:

thm dch v vo ng dng ta cng lm tng t:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 521/617


Gio trnh: Lp trnh Windows Phone

Vy hin gi Projet Mobile c c thm 2 dch v, ta tin hnh triu gi hm


cng 2 s bng cch coding cho Mainpage.xaml.cs nh sau:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Navigation;

using Microsoft.Phone.Controls;

using Microsoft.Phone.Shell;

using Test_Wcf.Resources;

namespace Test_Wcf

public partial class MainPage : PhoneApplicationPage

{ ..

private void btnCong_Click(object sender, RoutedEventArgs e)

ServiceReference2.TestClient client = new ServiceReference2.TestClient();

int a = int.Parse(txtSoa.Text);

int b = int.Parse(txtSob.Text);

client.cong2soAsync(a, b);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 522/617


Gio trnh: Lp trnh Windows Phone

client.cong2soCompleted += client_cong2soCompleted;

void client_cong2soCompleted(object sender,


ServiceReference2.cong2soCompletedEventArgs e) {

txtKetquaCong.Text = "Kt qu ="+e.Result;

Kt qu sau khi thc thi 2 dch v trong cng 1 ng dng Mobile:

Bn ch l ta vn c th dng cng c WCF client test ca Microsoft kim


tra.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 523/617


Gio trnh: Lp trnh Windows Phone

II. Windows Azure Mobile Services


Cho ti thi im ny th Microsoft cha h tr bn dng th cho quc gia Vit
Nam trn Data Center ca Microsoft, nn vic tr gip cc hc vin nghin cu l tng
i kh khn, di y l kin trc ca Azure service:

Windows Azure Mobile Services (WAMS) l dch v cho php lp trnh vin
tng tc vi c s d liu trn my ch thng qua cc phng thc CRUD (Create, Read,
Update, Delete). ng thi n cn h tr cc dch v khc nh Microsoft Account,
Facebook, Google, v Twitter gip d dng tch hp vi Windows, Apple, v Google push
notification services.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 524/617


Gio trnh: Lp trnh Windows Phone

lm c vi WAMS trc tin ta phi c ti khon Azure, link:


www.windowsazure.com

Trong phn ny gio trnh s trnh by l thuyt v cc phn ca Windows Azure


Mobile Service nh:

Cch to mt Mobile Service


Lm vic vi Data
Lm vic vi Server-Side Scripts: Validation v Access Control
Lm vic vi Authentication Providers
Ta bt u i vo chi tit:

Cch to mt Mobile Service:


Vo trnh duyt www.windowsazure.com bm chn Portal gc phi trn cng
vo Windows Azure Management Portal. Nu cha c ti khon th ta c th ng k FREE
TRAIL (tuy nhin Vit Nam cha c h tr).

Gi s ta c ti khon ri th cung cp Microsoft account ID v password ng


nhp vo portal:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 525/617


Gio trnh: Lp trnh Windows Phone

Ta tm ti mc MOBILE SERVICE nh hnh di y:

Nu cha c mobile Service th ta bm vo nt Create a New MOBILE


SERVICE
Mn hnh New MOBILE SERVICE s hin th ra nh di y:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 526/617


Gio trnh: Lp trnh Windows Phone

Nhp thng tin cho cc mc:


URL: Nhp URL m bn thch, ch l tn ny phi duy nht do h thng
s kim tra xem n c tn ti hay cha, nu tn ti ri th bn phi t tn khc.
DATABASE: c th to trn CSDL c sn hoc to mi nh trn.
SUBSCRIPTION: Chn thng tin c SUBSCRIPTION
REGION: Chn vng quc gia lnh th.

Sau khi nhp thng tin th bm next gc phi di cng mn hnh qua
trang mi.

Mn hnh mi hin th mn hnh thit lp c s d liu v Server nh sau:

NAME: t tn cho c s d liu


SERVER: Chn Server
SERVER LOGIN NAME: Tn Server
SERVER LOGIN PASSWORD: Nhp mt khu ng nhp SERVER
CONFIRM PASSWORD: Nhp li mt khu ng nhp SERVER.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 527/617


Gio trnh: Lp trnh Windows Phone

REGION: Chn vng, quc gia lnh th.


Mun cu hnh nng cao ta checked vo CONFIGURE ADVANCED
DATABASE SETTINGS.
Sau khi cu hnh xong ta bm vo nt Save gc phi di cng lu cu hnh.
Sau khi bm nt Lu th n s tr v mn hnh ban u nh sau:

Sau khi hon tt th h thng s hin th ct STATUS l Ready nh bn di:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 528/617


Gio trnh: Lp trnh Windows Phone

Trong mn hnh Mobile Service c to ra ta c th ty chn cho IOS, Android,


HTML/JavaScript:

Lm vic vi Data
Ta c bng Data Type Mappings

JSON/CLR Data Type T-SQL Type in Azure Table Displayed As


Numeric values (integer, float(53) the highest-precision data type Number
decimal, floating-point)
Boolean Bit Boolean
DateTime DateTimeOffset Date
String nvarchar(max) String

Cch nh ngha Data:

Mi th ta cn tham chiu ti th vin Windows Azure Mobile SDK. Th vin


ny thng n khng c nh km trong th mc ci t m ta dng Manage NuGet
Packages ti v, bm chut phi vo Project chn Manage NuGet Packages ri tm t
kha WindowsAzure.MobileServices ci t.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 529/617


Gio trnh: Lp trnh Windows Phone

public class HoneyDoThis

public int Id

{ get; set; }

public string Instructions

{ get; set; }

public bool DidYouDoIt

{ get; set; }

Ta cn khai bo Serialize cho i tng bng cch s dng namspace


System.Runtime.Serialization v Microsoft.WindowsAzure.MobileServices:

[DataContract]

[DataTable("HoneyDoThis")]

public class HoneyDoThis

[DataMember(Name = "Id")]

public int Id { get; set; }

[DataMember(Name = "Instructions")]

public string Instructions { get; set; }

[DataMember(Name = "DidYouDoIt")]

public bool DidYouDoIt { get; set; }

[IgnoreDataMember]

public string DoNotSaveThis { get; set; }

Chi tit hc vin c th xem thm trong gio trnh Windows Phone 8 Recipes.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 530/617


Gio trnh: Lp trnh Windows Phone

Lm vic vi Server-Side Scripts: Validation v Access Control


kim tra d liu hp l trc khi submit ln server th h thng h tr
Validation v Access control cho cc thao tao Insert, Update, Read v Delete:

Member Code
OK 200
CREATED 201
ACCEPTED 202
NO_CONTENT 204
BAD_REQUEST 400
UNAUTHORIZED 401
FORBIDDEN 403
NOT_FOUND 404
CONFLICT 409
INTERNAL_SERVER_ERROR 500

Insert:
function insert(item, user, request) {

if (item.Approved) {

request.execute();

} else {

request.respond(statusCodes.FORBIDDEN, "This task has not been approved.");

Update:
function update(item, user, request) {

item.Instructions = "Hello from the script."

item.LastUpdate = new Date();

request.execute();

Trung Tm Tin Hc H KHTN-TP.HCM Trang 531/617


Gio trnh: Lp trnh Windows Phone

Delete:
function del(id, user, request) {

if(id % 2 === 0) {

request.respond(statusCodes.OK, "Everything went fine.");

} else {

request.execute();

Read:
function read(query, user, request) {

query.where({ UserId: user.userId, Approved: true});

request.execute();

function read(query, user, request) {

query.where({ UserId: user.userId});

query.where({ Approved: true});

request.execute();

function read(query, user, request) {

query.where({ UserId: user.userId})

.where({ Approved: true});

request.execute();

Trung Tm Tin Hc H KHTN-TP.HCM Trang 532/617


Gio trnh: Lp trnh Windows Phone

Lm vic vi Authentication Providers


nng cao tnh bo mt ca d liu th h thng Windows Azure c nhng cch
thc hin, chi tit hc vin c th xem ti gio trnh Windows Phone 8 Recipes.

III. Kt lun
Nh vy Windows Phone h tr ti a k thut tng tc Service, y l mt
trong ng tnh nng khng th thiu i vi thit b ng, v ta bit rng cc d liu quan
trng iu c lu tr trn Server, Client (thit b ng) ch l cc thit b tm thi. Thng
qua cc service n tng tc d liu trn Server, m bo tnh lin thng v bo mt
cho h thng.

Service c th c xy dng vi cc k thut khc nhau v client c th s dng


bt k ngn ng hay cng c no tng tc ln Server, Mobile ch l mt trong nhng
m hnh ny.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 533/617


Gio trnh: Lp trnh Windows Phone

BI 3. S DNG PUSH NOTIFICATIONS


Microsoft a ra mt knh mnh m cho cc lp trnh vin gi v cp nht thng
tin cho ng dng mobile t dch v web (web service hc trc ), tnh nng ny c
gi l Push Notification Service.

Trc y, mt ng dng mobile s cn phi hi t cc dch v web tng ng


bit c c tn hiu cn c x l hay khng? iu ny lm thit b lun phi m tn
hiu radio thng xuyn, rt hao tn thi lng pin. Gi y, nh vic s dng push
notification (push: y), mt web service c th thng bo nhng cp nht quan trng cho
mt ng dng mobile bt k.

Ni dung ca phn ny s cp ti nhng phn sau:


I) Gii thiu .............................................................................................495
II) Kin trc ca Push Notifications .........................................................496
III) Cc loi Push Notifications ..................................................................497
1) Toast Notifications ........................................................................................... 497
2) Tile Notifications .............................................................................................. 498
3) Raw Notifications ............................................................................................. 499
IV) Cch thc hin Push Notification ........................................................500
1) Thc hin Toast Notifications ......................................................................... 500
2) Thc hin Tile Notifications ............................................................................ 516
3) Thc hin Raw Notifications ........................................................................... 530
V) Kt lun ...............................................................................................542

Trung Tm Tin Hc H KHTN-TP.HCM Trang 494/617


Gio trnh: Lp trnh Windows Phone

I. Gii thiu
Microsoft a ra mt knh mnh m cho cc lp trnh vin gi v cp nht thng
tin cho ng dng mobile t dch v web (web service hc trc ), tnh nng ny c
gi l Push Notification Service.

Trc y, mt ng dng mobile s cn phi hi t cc dch v web tng ng


bit c c tn hiu cn c x l hay khng? iu ny lm thit b lun phi m tn
hiu radio thng xuyn, rt hao tn thi lng pin. Gi y, nh vic s dng push
notification (push: y), mt web service c th thng bo nhng cp nht quan trng cho
mt ng dng mobile bt k.

Khi mt web service c thng tin gi v ng dng, n s gi mt push notification


vo Push Notification Service, ti y tn hiu s c chuyn n ng dng. Ph thuc
vo nh dng ca push notification ny m nhng d liu c gn vo n s c chuyn
nh mt tn hiu th, hay nh mt tile c cp nht trc quan hoc cng c th l mt
toast notification. Nu cm thy cn thit, ng dng c th lin lc vi web service bng
vic s dng chnh giao thc ring ca n.

Push Notification Service s gi mt code tr li li vi web service ca bn


sau khi mt push notification c gi i. Tuy nhin, Push Notification Service khng
cung cp cho bn mt s xc nhn i t u ny n u kia cho push notificaiton ca bn,
tc l n s khng c chuyn t web service ca bn n ng dng.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 495/617


Gio trnh: Lp trnh Windows Phone

Push notifications khng nn cha nhng thng tin c nhn cng nh c th nh


dng.

II. Kin trc ca Push Notifications

Gii thch s lc quy trnh kin trc thc hin:


1. ng dng ca bn s request mt push nofitication URI t Push Client Service
2. Push Client Service s lm vic vi Microsoft Push Notification Service(MPNS),
v sau MPNS s gi v cho Push Client Service mt notification URI.
3. Push Client Service cp pht cho ng dng ca bn notification URI va tr v.
4. Khi c cp pht notification URI th ng dng ca bn c th trc tip
lm vic vi Service ca bn.
5. Khi pha Service c thng tin gi ti ng dng ca bn, th trc tin Service
s gi thng tin ti MPNS thng qua notification URI ca ng dng.
6. Cui cng l thng bo s gi ti ng dng ca bn.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 496/617


Gio trnh: Lp trnh Windows Phone

III. Cc loi Push Notifications


Ty thuc vo nh dng Push Notification m h thng s c cc cch thng bo
hin th tng ng, Windows Phone c 3 loi Push Notification nh : Toast Notifications,
Tile Notifications v Raw Notifications.

1. Toast Notifications

Hin th thng bo trn top ca mn hnh in thoi, ging nh cc thng bo


khi c tin nhn, hay email mi:

Trong trng hp ny th ch c mt dng tiu v 1 dng ni dung c hin


th, Icon s xut hin gc tri bn trn mn hnh. Ch rng Toast Notification ch hin

Trung Tm Tin Hc H KHTN-TP.HCM Trang 497/617


Gio trnh: Lp trnh Windows Phone

th khi ng dng ca bn cha Running cn nu ang running th bn khng th thy n


trn mn hnh in thoi.

2. Tile Notifications

Hin th thng tin pha cc Huc LiveTile ca ng dng (khi ng dng ca bn c


Pin vo Start Screen).

Tile notifications c dng giao tip trc quan cc thng tin nh thi tit,
thng bo khc trn mn hnh. Thng th n s cha c 2 dng d liu v 1 Icon v tile
notifications c th c thay i. thay i hnh nn th tile notification phi cha mt
URI hin th hnh nh mi, hnh nh ny c th local hoc cloud-based.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 498/617


Gio trnh: Lp trnh Windows Phone

V d tip theo v thay i Tile Notifications:

3. Raw Notifications

Thng dng nhn mu tin khi ang chy ng dng. Raw Notifications yu cu
ng dng phi ang trong ch Foreground lifetime.

Ta c bng so snh cc c im ca Push Notifications type:

Must Application Must Application


PN Type Be Running in Tile Be Pinned to Use
Foreground? Start Screen?

Dng cho cc trng hp khn


Toast No No cp v thi gian nhy cm: V
d cnh bo sm chp, bo

Dng cp nht: V d ch
Tile No Yes m s email mi, m ngi
comment trn Facebook

D liu lin tc (Twitter client,


Raw Yes No
stock ticker)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 499/617


Gio trnh: Lp trnh Windows Phone

IV. Cch thc hin Push Notification


Ta cn s dng cc th vin Microsoft.Phone.Notification v
HttpChannelNotification

Trong cc bc thc hin cc loi Push Notification, gio trnh s dng 2 Project
c lp: 1 l Mobile Application, 2 l web/win application gi Notification ti Mobile
Application, sau y l chi tit cc trng hp s dng:

1. Thc hin Toast Notifications

Gio trnh s hng dn chi tit tng bc cch to Toast Notification, hc vin
cn lm theo tng bc c th xy dng c mt ng dng Push Notifications hon
chnh.

Gio trnh hng dn cch gi t Server ti mt client, hc vin cn p dng phn


Webservice vo y c th gi cng 1 lc cho hng lot Client.

Bc 1: Xy dng Server Push Notification bng Windows Form vi giao din


nh sau:

To mt Server Project nh trn

Trung Tm Tin Hc H KHTN-TP.HCM Trang 500/617


Gio trnh: Lp trnh Windows Phone

Giao din ca Form1.cs

M t cho cc control trn Server:

Loi control Tn control M t


TextBox txtPushNotificationURL Nhp URI t Mobile Client to ra
TextBox txtPushNotificationTitle Tiu thng bo ca Toast Notification
TextBox txtPushNotificationText Ni dung thng bo ca Toast Notification
Label lblStatus Trng thi khi kt ni ti URI
Button btnSenNotification Button thc hin lnh gi Notifications ti
Mobile client

Bc 2: Tin hnh coding cho Push Notification Server.

Bc ny ta cn to MPNS XML h thng c th tng tc vi dch v.

<?xml version="1.0" encoding="utf-8"?>

<wp:Notification xmlns:wp="WPNotification">

<wp:Toast>

<wp:Text1>Notification Title</wp:Text1>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 501/617


Gio trnh: Lp trnh Windows Phone

<wp:Text2>Notification Text</wp:Text2>

<wp:Param>Parameter List</wp:Param>

</wp:Toast>

</wp:Notification>

Sau y l coding y cho Server:


Ta cn thit lp X-WindowsPhone-Target l toast v X-NotificationClass l 2;

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

//phi s dng 2 th vin sau

using System.Net;

using System.IO;

namespace PushNotification_Server_WinApp

public partial class Form1 : Form

String ToastPushXML = String.Empty;

String TilePushXML = String.Empty;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 502/617


Gio trnh: Lp trnh Windows Phone

//hm to parma send Push Notification, cu trc phi ging nh bn di:

private void InitParams()

StringBuilder builder = new StringBuilder();

builder.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");

builder.Append("<wp:Notification xmlns:wp=\"WPNotification\">");

builder.Append(" <wp:Tile>");

builder.Append(" <wp:Count>{0}</wp:Count>");

builder.Append(" <wp:Title>{1}</wp:Title>");

builder.Append(" </wp:Tile>");

builder.Append("</wp:Notification>");

TilePushXML = builder.ToString();

builder.Clear();

builder.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");

builder.Append("<wp:Notification xmlns:wp=\"WPNotification\">");

builder.Append(" <wp:Toast>");

builder.Append(" <wp:Text1>{0}</wp:Text1>");

builder.Append(" <wp:Text2>{1}</wp:Text2>");

builder.Append(" </wp:Toast>");

builder.Append("</wp:Notification>");

ToastPushXML = builder.ToString();

public Form1()

InitializeComponent();

Trung Tm Tin Hc H KHTN-TP.HCM Trang 503/617


Gio trnh: Lp trnh Windows Phone

InitParams();

private void btnSenNotification_Click(object sender, EventArgs e)

try

if (txtPushNotificationURL.Text == string.Empty)

MessageBox.Show("Please enter a url");

return;

if (txtPushNotificationTitle.Text == string.Empty ||
txtPushNotificationText.Text == string.Empty)

MessageBox.Show("Please enter text and title to send");

return;

//ly URL: ci ny ta sao chp t Mobile client to ra

string url = txtPushNotificationURL.Text;

HttpWebRequest sendNotificationRequest =
(HttpWebRequest)WebRequest.Create(url);

sendNotificationRequest.Method = "POST";

sendNotificationRequest.Headers = new WebHeaderCollection();

sendNotificationRequest.ContentType = "text/xml";

//to X-WindowsPhone-Target

Trung Tm Tin Hc H KHTN-TP.HCM Trang 504/617


Gio trnh: Lp trnh Windows Phone

sendNotificationRequest.Headers.Add("X-WindowsPhone-Target",
"toast");

//to X-NotificationClass

sendNotificationRequest.Headers.Add("X-NotificationClass", "2");

string str = string.Format(ToastPushXML, txtPushNotificationTitle.Text,


txtPushNotificationText.Text);

byte[] strBytes = new UTF8Encoding().GetBytes(str);

sendNotificationRequest.ContentLength = strBytes.Length;

using (Stream requestStream =


sendNotificationRequest.GetRequestStream())

requestStream.Write(strBytes, 0, strBytes.Length);

HttpWebResponse response =
(HttpWebResponse)sendNotificationRequest.GetResponse();

string notificationStatus = response.Headers["X-NotificationStatus"];

string deviceConnectionStatus = response.Headers["X-


DeviceConnectionStatus"];

lblStatus.Text = "Status: " + notificationStatus + " : " +


deviceConnectionStatus;

catch (Exception ex)

MessageBox.Show(ex.ToString());

Trung Tm Tin Hc H KHTN-TP.HCM Trang 505/617


Gio trnh: Lp trnh Windows Phone

trn ta thy c 2 lp : X-NotificationClass v X-WindowsPhone-Target:

Loi control Tn control M t

TextBox txtPushNotificationURL Nhp URI t Mobile Client to ra

TextBox txtPushNotificationTitle Tiu thng bo ca Toast Notification

TextBox txtPushNotificationText Ni dung thng bo ca Toast Notification

Label lblStatus Trng thi khi kt ni ti URI


Button btnSenNotification Button thc hin lnh gi Notifications ti
Mobile client

Ta ch rng Server s phi nhn c URI t mobile client, ngi s dng c


th nhp cc thng s truyn v cho Client qua c ch Push Notification.

Bc 3: Xy dng Mobile client nhn Push Notification t Server.


Bc 3.1: To mobile client Project vi tn Learn_PushToastNotification:

Ch cn thm ID_CAP_PUSH_NOTIFICATION capabilities cho ng dng

Trung Tm Tin Hc H KHTN-TP.HCM Trang 506/617


Gio trnh: Lp trnh Windows Phone

Bc 3.2: To giao din MainPage nh sau:

<phone:PhoneApplicationPage
x:Class="Learn_PushToastNotification.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button x:Name="btnCreateChannel" Content="Create Channel"
HorizontalAlignment="Left" Margin="274,0,0,0" VerticalAlignment="Top"
Click="btnCreateChannel_Click"/>
<TextBox x:Name="txtURI" HorizontalAlignment="Left" Height="662"
Margin="10,0,-3,0" Grid.Row="1" TextWrapping="Wrap"
VerticalAlignment="Top" Width="473"/>
</Grid>
</phone:PhoneApplicationPage>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 507/617


Gio trnh: Lp trnh Windows Phone

Bc 3.3: Tin hnh coding cho MainPage.xaml.cs:

Sau y gio trnh s hng dn tng bc coding cho Mobile client nhn
Notification t Server thng qua Service nh th no:

Bc 3.3.1: Thm cc th vin sau vo lp MainPage.xaml.cs

using Microsoft.Phone.Notification;

using System.Diagnostics;

Bc 3.3.2: Coding ly c URI channel t server, bc ny s pht


sinh ra URI, ta s copy link ny cung cp cho Server, v c tnh ca Mobile
l kh copy do giao din b gii hn nn coding xut ra mn hnh Ouput
Windows gip ta d dng sao chp:

Uri channelUri;

public Uri ChannelUri

get

return channelUri;

set

channelUri = value;

OnChannelUriChanged(value);

private void OnChannelUriChanged(Uri value)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 508/617


Gio trnh: Lp trnh Windows Phone

Dispatcher.BeginInvoke(() =>

txtURI.Text = "changing uri to " + value.ToString();

});

//khi chy n s xut hin link URI, ta sao chp y

Debug.WriteLine("changing uri to " + value.ToString());

Khi chy thnh cng th ta s thy link bn di xut hin mn hn Output, nu


khng thy mn hnh ny th ta vo View/OutPut:

Bc 3.3.3: Coding cho button Create Channel:

private void btnCreateChannel_Click(object sender, RoutedEventArgs e)

SetupChannel();

Trong SetupChannel ta dng HttpNotificationChannel tm cc Push


Notification

private void SetupChannel()


{
HttpNotificationChannel httpChannel = null;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 509/617


Gio trnh: Lp trnh Windows Phone

string channelName = "DemoChannel";


try
{
//if channel exists, retrieve existing channel
httpChannel = HttpNotificationChannel.Find(channelName);
if (httpChannel != null)
{
//If we cannot get Channel URI, then close the channel and reopen it
if (httpChannel.ChannelUri == null)
{
httpChannel.UnbindToShellToast();
httpChannel.Close();
SetupChannel();
return;
}
else
{
ChannelUri = httpChannel.ChannelUri;
}
BindToShell(httpChannel);
}
else
{
httpChannel = new HttpNotificationChannel(channelName);
httpChannel.ChannelUriUpdated += new

EventHandler<NotificationChannelUriEventArgs>(httpChannel_ChannelUriUpdated
);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 510/617


Gio trnh: Lp trnh Windows Phone

httpChannel.ShellToastNotificationReceived += new

EventHandler<NotificationEventArgs>(httpChannel_ShellToastNotificationReceive
d);
httpChannel.ErrorOccurred += new

EventHandler<NotificationChannelErrorEventArgs>(httpChannel_ExceptionOccurre
d);
httpChannel.Open();
BindToShell(httpChannel);

}
}
catch (Exception ex)
{
Debug.WriteLine("An exception occurred setting up channel: " +
ex.ToString());
}
}
void httpChannel_ShellToastNotificationReceived(object
sender,NotificationEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
txtURI.Text = "Toast Notification Message Received: ";
if (e.Collection != null)
{
Dictionary<string, string> collection =
(Dictionary<string, string>)e.Collection;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 511/617


Gio trnh: Lp trnh Windows Phone

System.Text.StringBuilder messageBuilder = new


System.Text.StringBuilder();
foreach (string elementName in collection.Keys)
{
txtURI.Text += string.Format("Key: {0}, Value: {1}\r\n",
elementName,
collection[elementName]);
}
}
});
}
private static void BindToShell(HttpNotificationChannel httpChannel)
{
//This is a toast notification
try
{
//toast notification binding
if (!httpChannel.IsShellToastBound)
httpChannel.BindToShellToast();
}
catch (Exception ex)
{
Debug.WriteLine("An exception occurred binding to shell " +
ex.ToString());
}
}
void httpChannel_ExceptionOccurred(object
sender,NotificationChannelErrorEventArgs e)
{

Trung Tm Tin Hc H KHTN-TP.HCM Trang 512/617


Gio trnh: Lp trnh Windows Phone

//Display Message on error


Debug.WriteLine(e.Message);
}
void httpChannel_ChannelUriUpdated(object sender,
NotificationChannelUriEventArgs e)
{
//You got the new Uri (or maybe it's updated)
ChannelUri = e.ChannelUri;
}

By gi ta khi chy Mobile client ri bm vo nt Create Channel th h thng s


tr v URI, ta sao chp URI ny qua Server:

Sau khi sao chp URI qua Server ri th ta tin hnh ng ng dng Mobile client
i bi v Toast Notification ch hin th khi m ng dng khng c nm trong Foreground
lifetime.

T server ta bm nt Send Notifications th sau khong mt thi gian do ta nh


trong coding m Mobile client application s c t ng nhn Push Notification t
Server. Chc nng ny rt l tuyt vi nu nh lp trnh vin cn xy dng cc h thng

Trung Tm Tin Hc H KHTN-TP.HCM Trang 513/617


Gio trnh: Lp trnh Windows Phone

c tnh nng cp nhp thng tin lin tc m l thuc vo Server, t Server ta s gi cc


Push Notification v cho client, ta xem kt qu nhn c t Mobile client application:

Push Notification t
Server gi v.

m rng ng dng ca Toast Notification ta c th chnh sa cho php Server


gi cc thng s theo dng Parameter, v d nh l gi thng tin tn ngi, tn cng ty hay
bt k mt thng tin no , di y l coding Server:

Nu Toast Notification mun m thm mi trang mi:

<wp:Param>/StockChart.xaml?companyName=MSFT</wp:Param>

Chi tit:

string ToastPushXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +

"<wp:Notification xmlns:wp=\"WPNotification\">" +

"<wp:Toast>" +

"<wp:Text1>{0}</wp:Text1>" +

"<wp:Text2>{1}</wp:Text2>" +

"<wp:Param>/StockChart.xaml?company=MSFT</wp:Param>" +

"</wp:Toast>" +

"</wp:Notification>";

Trung Tm Tin Hc H KHTN-TP.HCM Trang 514/617


Gio trnh: Lp trnh Windows Phone

Hoc Nu ng dng ch c 1 trang MainPage.xaml duy nht:

<wp:Param>?companyName=MSFT</wp:Param>

Chi tit:

string ToastPushXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +

"<wp:Notification xmlns:wp=\"WPNotification\">" +

"<wp:Toast>" +

"<wp:Text1>{0}</wp:Text1>" +

"<wp:Text2>{1}</wp:Text2>" +

"<wp:Param>?company=MSFT</wp:Param>" +

"</wp:Toast>" +

"</wp:Notification>";

Ta thy c 2 trng hp u dng du ? truyn gi tr Parameter c tn company

Mobile client trong c 2 trng hp th ta u c th ly c thng tin ny


bng cch Override OnNavigatedTo:

protected override void OnNavigatedTo


(System.Windows.Navigation.NavigationEventArgs e)

base.OnNavigatedTo(e);

string strCompany = string.Empty;

string strPriceChange = string.Empty;

if (NavigationContext.QueryString.TryGetValue("company", out strCompany))

txtURI.Text += "\n\nCompany name passed in: " + strCompany;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 515/617


Gio trnh: Lp trnh Windows Phone

2. Thc hin Tile Notifications

Tile notifications c th cp nht hnh nh v Text ca tiles ng dng:

Thng Tile Notifications s dng trong cc trng hp hin th nhng thng tin
gii hn v c tnh cp thit: Thng bo thi tit, thng bo hng la bn hay nhng
thng tin quan trng v nhanh chng khc.

Cc bc xy dng Tile Notification cng tng t nh Toast Notification vi 3


bc c bn nh sau:

Bc 1:To mt ng dng Windows Phone Notification client. ng dng ny


dng thit lp mt notification channel.
Bc 2:To v thc hin mt Windows Forms Application ly URI t
notification channel To bc 1 v submit push notification ti ng dng
Mobile.
Bc 3:Xc nhn qu trnh nhn tile notifications trong Windows Phone
application thnh cng hay khng.
Sau y l chi tit tng bc to Push Notification cho kiu Tile Notification:
Bc 1: To Project Windows Phone Notification client nh hnh di y:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 516/617


Gio trnh: Lp trnh Windows Phone

trn ta chp 7 hnh .png vo Assets/Tiles Push Notification chn lc hnh ra


trong Tile Screen.

Ch phi thit lp ID_CAP_PUSH_NOTIFICATION cho Manifest.


Thit k giao din cho MainPage.xaml:

<phone:PhoneApplicationPage

x:Class="Learn_PushTileNotification.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:phone="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

Trung Tm Tin Hc H KHTN-TP.HCM Trang 517/617


Gio trnh: Lp trnh Windows Phone

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Portrait" Orientation="Portrait"

shell:SystemTray.IsVisible="True">

<Grid x:Name="LayoutRoot" Background="Transparent">

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

<RowDefinition Height="*"/>

</Grid.RowDefinitions>

<Button x:Name="btnCreateChannel" Content="Create Channel"


HorizontalAlignment="Left" Margin="58,41,0,0" VerticalAlignment="Top"
Click="btnCreateChannel_Click"/>

<TextBox x:Name="txtURI" HorizontalAlignment="Left" Height="421"


Margin="10,37,0,0" Grid.Row="1" TextWrapping="Wrap" Text="TextBox"
VerticalAlignment="Top" Width="456"/>

</Grid>

</phone:PhoneApplicationPage>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 518/617


Gio trnh: Lp trnh Windows Phone

Tin hnh coding cho MainPage.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Learn_PushTileNotification.Resources;
using Microsoft.Phone.Notification;
using System.Diagnostics;
namespace Learn_PushTileNotification
{
public partial class MainPage : PhoneApplicationPage
{
Uri channelUri;
public Uri ChannelUri
{
get
{
return channelUri;
}
set
{
channelUri = value;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 519/617


Gio trnh: Lp trnh Windows Phone

OnChannelUriChanged(value);
}
}
private void OnChannelUriChanged(Uri value)
{
Dispatcher.BeginInvoke(() =>
{
txtURI.Text = "changing uri to " + value.ToString();
});
//khi chy n s xut hin link URI, ta sao chp y
Debug.WriteLine("changing uri to " + value.ToString());
}
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private void btnCreateChannel_Click(object sender, RoutedEventArgs e)
{
SetupChannel();
}
private void SetupChannel()
{
HttpNotificationChannel httpChannel = null;
string channelName = "DemoChannel";

Trung Tm Tin Hc H KHTN-TP.HCM Trang 520/617


Gio trnh: Lp trnh Windows Phone

try
{
//if channel exists, retrieve existing channel
httpChannel = HttpNotificationChannel.Find(channelName);
if (httpChannel != null) {
//If we cannot get Channel URI, then close the channel and reopen it
if (httpChannel.ChannelUri == null)
{
httpChannel.UnbindToShellToast();
httpChannel.Close();
SetupChannel();
return;
}
else
{
ChannelUri = httpChannel.ChannelUri;
}
BindToShell(httpChannel);
}
else
{
httpChannel = new HttpNotificationChannel(channelName);
httpChannel.ChannelUriUpdated += new
EventHandler<NotificationChannelUriEventArgs>(httpChannel_ChannelUriUpdated
);
httpChannel.ShellToastNotificationReceived += new
EventHandler<NotificationEventArgs>(httpChannel_ShellToastNotificationReceive
d);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 521/617


Gio trnh: Lp trnh Windows Phone

httpChannel.ErrorOccurred += new
EventHandler<NotificationChannelErrorEventArgs>(httpChannel_ExceptionOccurre
d);
httpChannel.Open();
BindToShell(httpChannel);
}
}
catch (Exception ex)
{
Debug.WriteLine("An exception occurred setting up channel: " +
ex.ToString());
}
}
void httpChannel_ShellToastNotificationReceived(object sender,
NotificationEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
txtURI.Text = "Toast Notification Message Received: ";
if (e.Collection != null)
{
Dictionary<string, string> collection =
(Dictionary<string, string>)e.Collection;
System.Text.StringBuilder messageBuilder = new
System.Text.StringBuilder();
foreach (string elementName in collection.Keys)
{
txtURI.Text += string.Format("Key: {0}, Value: {1}\r\n",
elementName,
collection[elementName]);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 522/617


Gio trnh: Lp trnh Windows Phone

}
}
});
}
private static void BindToShell(HttpNotificationChannel httpChannel)
{
try
{
if (!httpChannel.IsShellTileBound)
httpChannel.BindToShellTile();
}
catch (Exception ex)
{
Debug.WriteLine("An exception occurred binding to shell " +
ex.ToString());
}
}
void httpChannel_ExceptionOccurred(object sender,
NotificationChannelErrorEventArgs e) {
//Display Message on error
Debug.WriteLine(e.Message);
}
void httpChannel_ChannelUriUpdated(object sender,
NotificationChannelUriEventArgs e) {
//You got the new Uri (or maybe it's updated)
ChannelUri = e.ChannelUri;
}
}
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 523/617


Gio trnh: Lp trnh Windows Phone

Bc 2: Xy dng Push Notification Server

Ta dng C# thit k giao din cho Push Notification nh sau:

M t chi tit cho cc control trn giao din:

Loi control Tn control M t


TextBox txtPushNotificationURL Nhp URI t Mobile Client to ra
TextBox txtCount Hin th Count cho Tile
TextBox txtTitle Hin th tiu mt trc cho Tile
TextBox txtBackTitle Hin th tiu mt sau cho Tile
TextBox txtBackContent Hin th ni dung mt sau cho Tile
ListBox listboxBackgroundImage Hin th hnh nn cho mt trc
ListBox listboxBackBackgroundImage Hin th hnh nn cho mt sau
Label lblStatus Trng thi khi kt ni ti URI
Button btnSenNotification Button thc hin lnh gi Notifications ti
Mobile client

Trung Tm Tin Hc H KHTN-TP.HCM Trang 524/617


Gio trnh: Lp trnh Windows Phone

Source code cho Push Notification Server:


Ta cn thit lp X-WindowsPhone-Target l token v X-NotificationClass l 1

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Net;

using System.IO;

namespace PushNotification_Server_WinApp

public partial class Form2 : Form

String TilePushXML = String.Empty;

//hm to parma send Push Notification

private void InitParams()

StringBuilder builder = new StringBuilder();

builder.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");

builder.Append("<wp:Notification xmlns:wp=\"WPNotification\">");

builder.Append(" <wp:Tile>");

builder.Append(" <wp:BackgroundImage>{0}</wp:BackgroundImage>");

Trung Tm Tin Hc H KHTN-TP.HCM Trang 525/617


Gio trnh: Lp trnh Windows Phone

builder.Append(" <wp:Count>{1}</wp:Count>");

builder.Append(" <wp:Title>{2}</wp:Title>");

builder.Append(" <wp:BackTitle>{3}</wp:BackTitle> ");

builder.Append(" <wp:BackContent>{4}</wp:BackContent> ");

builder.Append("
<wp:BackBackgroundImage>{5}</wp:BackBackgroundImage>");

builder.Append(" </wp:Tile>");

builder.Append("</wp:Notification>");

TilePushXML = builder.ToString();

public Form2()

InitializeComponent();

InitParams();

private void btnSenNotification_Click(object sender, EventArgs e)

try

if (txtPushNotificationURL.Text == string.Empty)

MessageBox.Show("Please enter a url");

return;

if (txtCount.Text == string.Empty || txtTitle.Text == string.Empty)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 526/617


Gio trnh: Lp trnh Windows Phone

MessageBox.Show("Please enter Count and title to send");

return;

if (txtBackTitle.Text == string.Empty || txtBackContent.Text ==


string.Empty)

MessageBox.Show("Please enter Back title and back content to send");

return;

if (listboxBackgroundImage.SelectedIndex == -1 ||
listboxBackBackgroundImage.SelectedIndex == -1)

MessageBox.Show("Please choose Backdround Image and Back


Background Image to send");

return;

//ly URL: ci ny ta sao chp t Mobile client to ra

string url = txtPushNotificationURL.Text;

HttpWebRequest sendNotificationRequest =
(HttpWebRequest)WebRequest.Create(url);

sendNotificationRequest.Method = "POST";

sendNotificationRequest.Headers = new WebHeaderCollection();

sendNotificationRequest.ContentType = "text/xml";

//to X-WindowsPhone-Target

sendNotificationRequest.Headers.Add("X-WindowsPhone-Target",
"token");

//to X-NotificationClass

Trung Tm Tin Hc H KHTN-TP.HCM Trang 527/617


Gio trnh: Lp trnh Windows Phone

sendNotificationRequest.Headers.Add("X-NotificationClass", "1");

string str = string.Format(TilePushXML,


listboxBackgroundImage.Text,txtCount.Text, txtTitle.Text, txtBackTitle.Text,
txtBackContent.Text, listboxBackBackgroundImage.Text);

//string str = string.Format(TilePushXML, txtCount.Text, txtTitle.Text);

byte[] strBytes = new UTF8Encoding().GetBytes(str);

sendNotificationRequest.ContentLength = strBytes.Length;

using (Stream requestStream =


sendNotificationRequest.GetRequestStream())

requestStream.Write(strBytes, 0, strBytes.Length);

HttpWebResponse response =
(HttpWebResponse)sendNotificationRequest.GetResponse();

string notificationStatus = response.Headers["X-NotificationStatus"];

string deviceConnectionStatus = response.Headers["X-


DeviceConnectionStatus"];

lblStatus.Text = "Status: " + notificationStatus + " : " +


deviceConnectionStatus;

MessageBox.Show(str);

catch (Exception ex)

MessageBox.Show(ex.ToString());

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 528/617


Gio trnh: Lp trnh Windows Phone

//picBackgroundImage.ImageLocation=listboxBackgroundIamge.Text;

private void listBox2_SelectedIndexChanged(object sender, EventArgs e)

Bc 3: Tin hnh kim tra hot ng ca Push Notification


Khi ng Mobile client application, bm Create Channel to URI:

Ta sao chp URI to ra t Mobile application vo Textbox Push Notification URL:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 529/617


Gio trnh: Lp trnh Windows Phone

Nhp cc thng s ri nhn nt Send Notifications, quan st ng dng Mobile


client mn hnh Tile Screen s c thay i theo thng s nhp t Server. Ch l ng
dng Mobile client ca bn sau khi to Channel xong th nh Pin ra Tile Start Screen, bn
s quan st c kt qu nh trn.

3. Thc hin Raw Notifications

Thng dng nhn mu tin khi ang chy ng dng. Raw Notifications yu cu
ng dng phi ang trong ch Foreground lifetime.

Sau y l cc bc thc hin:


Bc 1: Xy dng Mobile client
To mt Mobile client Project nh sau:

Ch nh thit lp ID_CAP_PUSH_NOTIFICATION cho Manifest. Mc ch


ca bi ny l ly ni dung 1 tp tin gi t Server theo kin trc Push Notification.

Thit k giao din cho MainPage.xaml nh sau:

<phone:PhoneApplicationPage

x:Class="Learn_PushRawNotification.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Trung Tm Tin Hc H KHTN-TP.HCM Trang 530/617


Gio trnh: Lp trnh Windows Phone

xmlns:phone="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Portrait" Orientation="Portrait"

shell:SystemTray.IsVisible="True">

<StackPanel HorizontalAlignment="Left" Height="768"


VerticalAlignment="Top" Width="480">

<Button x:Name="btnCreateChannel" Content="Create Channel"


Click="btnCreateChannel_Click"/>

<TextBox x:Name="txtURI" Height="175" TextWrapping="Wrap"/>

<TextBlock TextWrapping="Wrap" Text="Raw Notification Message


Received:"/>

<TextBox x:Name="txtData" Height="463" TextWrapping="Wrap"/>

</StackPanel>

</phone:PhoneApplicationPage>

Giao din sau khi thc hin:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 531/617


Gio trnh: Lp trnh Windows Phone

Ni dung File c
Push t Server

Tin hnh coding cho MainPage.xaml.cs, c cht t khc vi 2 loi trc:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 532/617


Gio trnh: Lp trnh Windows Phone

using System.Windows.Controls;

using System.Windows.Navigation;

using Microsoft.Phone.Controls;

using Microsoft.Phone.Shell;

using Learn_PushRawNotification.Resources;

using Microsoft.Phone.Notification;

using System.Diagnostics;

namespace Learn_PushRawNotification

public partial class MainPage : PhoneApplicationPage

Uri channelUri;

public Uri ChannelUri

get { return channelUri; }

set

channelUri = value;

OnChannelUriChanged(value);

private void OnChannelUriChanged(Uri value)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 533/617


Gio trnh: Lp trnh Windows Phone

Dispatcher.BeginInvoke(() =>

txtURI.Text = "changing uri to " + value.ToString();

});

Debug.WriteLine("changing uri to " + value.ToString());

// Constructor

public MainPage()

InitializeComponent();

private void btnCreateChannel_Click(object sender, RoutedEventArgs e)

SetupChannel();

private void SetupChannel()

HttpNotificationChannel httpChannel = null;

String channelName = "DemoChannel";

try

//if channel exists, retrieve existing channel

httpChannel = HttpNotificationChannel.Find(channelName);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 534/617


Gio trnh: Lp trnh Windows Phone

if (httpChannel != null)

//If you can't get it, then close and reopen it.

if (httpChannel.ChannelUri == null)

httpChannel.UnbindToShellToast();

httpChannel.Close();

SetupChannel();

return;

else

ChannelUri = httpChannel.ChannelUri;

//wiring up the raw notifications event handler

httpChannel.HttpNotificationReceived += new

EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNotificationReceived);

else

httpChannel = new HttpNotificationChannel(channelName);

httpChannel.ChannelUriUpdated += new

Trung Tm Tin Hc H KHTN-TP.HCM Trang 535/617


Gio trnh: Lp trnh Windows Phone

EventHandler<NotificationChannelUriEventArgs>(httpChannel_ChannelUriUpdated
);

httpChannel.ErrorOccurred += new

EventHandler<NotificationChannelErrorEventArgs>(httpChannel_ExceptionOccurre
d);

//wiring up the raw notifications event handler

httpChannel.HttpNotificationReceived += new

EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNotificationReceived);

httpChannel.Open();

catch (Exception ex)

Debug.WriteLine("An exception setting up channel " + ex.ToString());

void httpChannel_ShellToastNotificationReceived(object sender,


NotificationEventArgs e)

Dispatcher.BeginInvoke(() =>

txtURI.Text = "Toast Notification Message Received: ";

if (e.Collection != null)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 536/617


Gio trnh: Lp trnh Windows Phone

Dictionary<string, string> collection =

(Dictionary<string, string>)e.Collection;

System.Text.StringBuilder messageBuilder = new


System.Text.StringBuilder();

foreach (string elementName in collection.Keys)

txtURI.Text += string.Format("Key: {0}, Value: {1}\r\n",


elementName,

collection[elementName]);

});

void httpChannel_ExceptionOccurred(object sender,


NotificationChannelErrorEventArgs e) {

//Display Message on error

Debug.WriteLine(e.Message);

void httpChannel_ChannelUriUpdated(object sender,


NotificationChannelUriEventArgs e) {

//You got the new Uri (or maybe it's updated)

ChannelUri = e.ChannelUri;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 537/617


Gio trnh: Lp trnh Windows Phone

void httpChannel_HttpNotificationReceived(object sender,


HttpNotificationEventArgs e)

if (e.Notification.Body != null && e.Notification.Headers != null)

System.IO.StreamReader reader = new

System.IO.StreamReader(e.Notification.Body);

Dispatcher.BeginInvoke(() =>

txtData.Text=reader.ReadToEnd();

});

Bc 2: Xy dng Server gi Push Notification


Thit k Form vi giao din di y:

M t chi tit cho tng control

Trung Tm Tin Hc H KHTN-TP.HCM Trang 538/617


Gio trnh: Lp trnh Windows Phone

Loi control Tn control M t


TextBox txtPushNotificationURL Nhp URI t Mobile Client to ra
TextBox txtFileToSend Hin th file mun Push ti Client
Label lblStatus Trng thi khi kt ni ti URI
Button btnSenNotification Button thc hin lnh gi Notifications
ti Mobile client
Button btnBrowser Button hin th OpenFile Dialog cho
php ty chn File bt k gi i
OpenFileDialog openFileDialog1 Dialog hin th chn File

Tin hnh coding nh sau:

Ta cu hnh "X-WindowsPhone-Target" trng v cu hnh "X-


NotificationClass" l 3.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;

namespace PushNotification_Server_WinApp
{
public partial class Form3 : Form
{
public Form3()
{

Trung Tm Tin Hc H KHTN-TP.HCM Trang 539/617


Gio trnh: Lp trnh Windows Phone

InitializeComponent();
}
private void btnSenNotification_Click(object sender, EventArgs e)
{
if (txtPushNotificationURL.Text == string.Empty)
{
MessageBox.Show("Please enter a url");
return;
}
HttpWebRequest sendNotificationRequest =
(HttpWebRequest)WebRequest.Create(txtPushNotificationURL.Text);
sendNotificationRequest.Method = "POST";
sendNotificationRequest.Headers = new WebHeaderCollection();
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "");
sendNotificationRequest.Headers.Add("X-NotificationClass", "3"); //- raw

String str = File.ReadAllText(txtFileToSend.Text);


byte[] strBytes = new UTF8Encoding().GetBytes(str);
sendNotificationRequest.ContentLength = strBytes.Length;
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(strBytes, 0, strBytes.Length);
}
HttpWebResponse response =
(HttpWebResponse)sendNotificationRequest.GetResponse();
string notificationStatus = response.Headers["X-NotificationStatus"];

Trung Tm Tin Hc H KHTN-TP.HCM Trang 540/617


Gio trnh: Lp trnh Windows Phone

string deviceConnectionStatus = response.Headers["X-


DeviceConnectionStatus"];
lblStatus.Text = "Status: " + notificationStatus + " : " +
deviceConnectionStatus;
}
private void btnBrowser_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "*.txt|*.txt";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
txtFileToSend.Text = openFileDialog1.FileName;
}
}
}
}

Bc 3: Kim tra Push Notification


- Khi ng Mobile client v bm vo Create Channel: Tin hnh ly Uri

Trung Tm Tin Hc H KHTN-TP.HCM Trang 541/617


Gio trnh: Lp trnh Windows Phone

- Ti Server ta chn File mun Push ni dung xung client ri bm nt Send


Notifications, kt qu thu c l:

V. Kt lun
Microsoft a ra mt knh mnh m cho cc lp trnh vin gi v cp nht thng
tin cho ng dng mobile t dch v web (web service hc trc ), tnh nng ny c
gi l Push Notification Service.

Windows Phone cung cp 3 loi Push Notification gip lp trnh vin c nhiu
kiu la chn: Toast Notification, Tile Notification v Raw Notification. Mi loi c nhng
tnh nng tuyt vi khc nhau.

Toast Notification v Tile Notification th yu cu ng dng phi ch khng


phi Foreground Lifetime, cn Raw Notification th bt buc ng dng client phi ch
Foreground Lifetime.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 542/617


Gio trnh: Lp trnh Windows Phone

BI 4. THAO TC VI MEDIALIBRARY API


Lp MediaLibrary thuc namespace Microsoft.Xna.Framework.Media, lp
ny cung cp cho lp trnh vin hng lot cc Properties, Method tng tc vi Songs,
Album, RootPictureAlbum, Artists, Pictures, SavedPictures

Ni dung ca phn ny s cp ti nhng phn sau:


I) Gii thiu lp MediaLibrary ...............................................................544
II) Constructors ........................................................................................544
III) Properties ............................................................................................545
1) Albums ............................................................................................................. 546
2) Artists ............................................................................................................... 546
3) Genres .............................................................................................................. 547
4) IsDisposed ........................................................................................................ 547
5) MediaSource .................................................................................................... 548
6) Pictures ............................................................................................................. 548
7) Playlists............................................................................................................. 549
8) RootPictureAlbum ........................................................................................... 549
9) SavedPictures ................................................................................................... 550
10) Songs................................................................................................................. 550
IV) Methods ...............................................................................................553
1) GetPictureFromToken .................................................................................... 553
2) SavePicture ...................................................................................................... 553
3) SavePictureToCameraRoll .............................................................................. 554
V) Kt lun ...............................................................................................555

Trung Tm Tin Hc H KHTN-TP.HCM Trang 543/617


Gio trnh: Lp trnh Windows Phone

I. Gii thiu lp MediaLibrary


MediaLibrary cung cp hng lot cc Properties tr v tp cc Media chng hn
nh: Albums, Artists, Genres, Pictures, Playlists, v Songs. Mt mt Properties tr v mt
tp cc object c th theo dng enumerated v indexed. ng thi n cng cung cp
phng thc lu tr Media vo thit b. Bi v MediaLibrary c implement t interface
IDisposable nn khi s dng th vin ny ta nn trong using block.

V d ly danh sch Songs t thit b v Play 1 Song u tin trong danh sch:

//Thm cc th vin sau


using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
//---------------------------------------------------------
//X l ly danh sch Songs trong MediaLibrary:
using(MediaLibrary library = new MediaLibrary())
{
SongCollection songs = library.Songs;
Song song = songs[0];
MediaPlayer.Play(song);
}

II. Constructors

MediaLibrary cng cp 2 constructor khi to i tng MediaLibrary nh sau:

Constructor M t
MediaLibrary () Khi to i tng MediaLibrary
MediaLibrary (MediaSource) Khi to i tng MediaLibrary, s dng
MediaSource to mi MediaLibrary

Trung Tm Tin Hc H KHTN-TP.HCM Trang 544/617


Gio trnh: Lp trnh Windows Phone

V d to i tng MediaLibrary t MediaSource:

ICollection<MediaSource> mediaSources
=MediaSource.GetAvailableMediaSources();
foreach (MediaSource source in mediaSources)
{
MediaLibrary ml = new MediaLibrary(source);
//ml.Albums.Count
}

III. Properties
MediaLibrary cung cp hng lot cc Properties tr gip c lc cho vic truy
sut thng tin t thit b:

Properties M t
Albums Ly v AlbumCollection, collection ny cha ton b Albums
trong media Library
Artists Ly v ArtistCollection, collection ny cha ton b artists
trong media Library
Genres Ly v GenreCollection, collection ny cha ton b genres
(th loi) trong media Library
IsDisposed Property tr v c kim tra i tc c b Disposed hay khng
MediaSource Ly v MediaSource m c gn vo cho MediaLibrary khi ta
khi to Contructor c i s l MediaSource
Pictures Ly v PictureCollection, collection ny cha ton b Picture
trong media Library
Playlists Ly v PlaylistCollection, collection ny cha ton b playlists
trong media Library
RootPictureAlbum Ly v root PictureAlbum, n cha ton b picture trong media
Library
SavedPictures Tr v tp tt c cc Pictures c lu tr trong media Library
Songs Ly v SongCollection, collection ny cha ton b Songs
trong media Library

Trung Tm Tin Hc H KHTN-TP.HCM Trang 545/617


Gio trnh: Lp trnh Windows Phone

Sau y l chi tit cch s dng tng thuc tnh ca MediaLibrary:

1. Albums

Ly v AlbumCollection, collection ny cha ton b Albums trong media


Library.

using (MediaLibrary library = new MediaLibrary())

AlbumCollection albums= library.Albums;

foreach (Album album in albums)

album.Name;

album.Songs;

album.Artist;

2. Artists

Ly v ArtistCollection, collection ny cha ton b artists trong media Library

using (MediaLibrary library = new MediaLibrary())


{
ArtistCollection artists= library.Artists;
foreach (Artist artist in artists)
{
artist.Name;
artist.Albums;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 546/617


Gio trnh: Lp trnh Windows Phone

artist.Songs;
}
}

3. Genres

Ly v GenreCollection, collection ny cha ton b genres (th loi) trong media


Library

using (MediaLibrary library = new MediaLibrary())


{
GenreCollection genressed= library.Genres;
foreach (Genre genres in genressed)
{
genres.Name;
genres.Albums;
genres.Songs;
}
}

4. IsDisposed

Property tr v c kim tra i tc c b Disposed hay khng

using (MediaLibrary library = new MediaLibrary())


{
if (library.IsDisposed)
{

}
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 547/617


Gio trnh: Lp trnh Windows Phone

5. MediaSource

Ly v MediaSource m c gn vo cho MediaLibrary khi ta khi to


Contructor c i s l MediaSource

ICollection<MediaSource> mediaSources =
MediaSource.GetAvailableMediaSources();

foreach (MediaSource source in mediaSources)

MediaLibrary ml = new MediaLibrary(source);

MediaSource source_assign = ml.MediaSource;

source_assign.Name;

source_assign.MediaSourceType;

6. Pictures

Ly v PictureCollection, collection ny cha ton b Picture trong media Library

using (MediaLibrary library = new MediaLibrary())

PictureCollection pictures = library.Pictures;

foreach (Picture picture in pictures)

picture.Name;

picture.Album;

picture.GetImage;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 548/617


Gio trnh: Lp trnh Windows Phone

7. Playlists

Ly v PlaylistCollection, collection ny cha ton b playlists trong media


Library

using (MediaLibrary library = new MediaLibrary())

PlaylistCollection playlists = library.Playlists;

foreach (Playlist playlist in playlists)

playlist.Name;

playlist.Songs;

playlist.Duration;

8. RootPictureAlbum

Ly v root PictureAlbum, n cha ton b picture trong media Library

using (MediaLibrary library = new MediaLibrary())

PictureAlbum picAlbum= library.RootPictureAlbum;

picAlbum.Name;

picAlbum.Pictures;

picAlbum.Albums;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 549/617


Gio trnh: Lp trnh Windows Phone

9. SavedPictures

Tr v tp tt c cc Pictures c lu tr trong media Library

using (MediaLibrary library = new MediaLibrary())

PictureCollection pictures= library.SavedPictures;

foreach (Picture picture in pictures)

picture.Name;

picture.Album;

picture.GetImage;

10. Songs

Ly v SongCollection, collection ny cha ton b Songs trong media Library

Ta s lm v d v vit chng trnh nghe nhc: Cho php hin th danh sch Songs
trong thit b ln Listbox, chn bi ht no trong ListBox th play bi , giao din nh
sau:

<phone:PhoneApplicationPage

x:Class="MobileSimpleSongPlay.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Trung Tm Tin Hc H KHTN-TP.HCM Trang 550/617


Gio trnh: Lp trnh Windows Phone

xmlns:phone="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Portrait" Orientation="Portrait"

shell:SystemTray.IsVisible="True">

<StackPanel HorizontalAlignment="Left" Height="768"


VerticalAlignment="Top" Width="480">

<Button x:Name="btnLoadSong" Content="Load"


Click="btnLoadSong_Click"/>

<ListBox x:Name="mylistbox"
MouseLeftButtonDown="mylistbox_MouseLeftButtonDown"></ListBox>

</StackPanel>

</phone:PhoneApplicationPage>

Source code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 551/617


Gio trnh: Lp trnh Windows Phone

using System.Windows.Navigation;

using Microsoft.Phone.Controls;

using Microsoft.Phone.Shell;

using MobileSimpleSongPlay.Resources;

using Microsoft.Xna.Framework;

using Microsoft.Xna.Framework.Input;

using Microsoft.Xna.Framework.Media;

namespace MobileSimpleSongPlay

public partial class MainPage : PhoneApplicationPage

public MainPage()

InitializeComponent();

SongCollection songs = null;

private void btnLoadSong_Click(object sender, RoutedEventArgs e)

MediaLibrary library = new MediaLibrary();

songs = library.Songs;

foreach (Song song in songs)

mylistbox.Items.Add(song.Name);

Trung Tm Tin Hc H KHTN-TP.HCM Trang 552/617


Gio trnh: Lp trnh Windows Phone

private void mylistbox_MouseLeftButtonDown(object sender,


System.Windows.Input.MouseButtonEventArgs e)

if (mylistbox.SelectedIndex == -1)

return;

Song song = songs[mylistbox.SelectedIndex];

MediaPlayer.Stop();

MediaPlayer.Play(song);

IV. Methods

MediaLibrary cung cp mt s hm cn thit cho ta tng tc vi thit b nh sau:

1. GetPictureFromToken

Dng truy vn ra 1 Picture t thit b thng qua mt picture token.

using (MediaLibrary library = new MediaLibrary())

Picture pic = library.GetPictureFromToken("Token Here");

2. SavePicture

Hm dng lu tr hnh nh vo th vin media ca thit b, ch cn thit lp


ID_CAP_MEDIALIB_PHOTO cho Manifest.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 553/617


Gio trnh: Lp trnh Windows Phone

private async void btnLuu_Click(object sender, RoutedEventArgs e) {

if (grayscaleImage == null) return;

await Task.Run(() => {

using (var mediaLibrary = new MediaLibrary())

using (var targetJpegStream = new MemoryStream()) {

grayscaleImage.SaveJpeg(targetJpegStream,
grayscaleImage.PixelWidth,

grayscaleImage.PixelHeight, 0, 100);

targetJpegStream.Seek(0, SeekOrigin.Begin);

string grayscaleFilename = "gray_hinh_moi";

mediaLibrary.SavePicture(grayscaleFilename, targetJpegStream);
}

});

3. SavePictureToCameraRoll

Hm dng lu tr hnh nh vo CameraRoll ca thit b, ch cn thit lp


ID_CAP_MEDIALIB_PHOTO cho Manifest.

private void photoCamera_CaptureImageAvailable(object sender,


ContentReadyEventArgs e)
{
string filename = "thirds" + DateTime.Now.Ticks.ToString() + ".jpeg";
using (MediaLibrary mediaLibrary = new MediaLibrary())
{
mediaLibrary.SavePictureToCameraRoll(filename, e.ImageStream);
}
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 554/617


Gio trnh: Lp trnh Windows Phone

V. Kt lun
Lp MediaLibrary thuc namespace Microsoft.Xna.Framework.Media, lp
ny cung cp cho lp trnh vin hng lot cc Properties, Method tng tc vi Songs,
Album, RootPictureAlbum, Artists, Pictures, SavedPictures

c bit lp trnh vin c th tng tc Camera v thng qua MediaLibrary lu


tr hnh nh vo thit b.
Ta cng c th c thng tin t SD card bng cch thit lp
ID_CAP_REMOVABLE_STORAGE:
private async void btnSDCard_Click(object sender, RoutedEventArgs e)
{ ExternalStorageDevice sdCard = (await ExternalStorage.
GetExternalStorageDevicesAsync()).FirstOrDefault();
if (sdCard != null) {
IEnumerable<ExternalStorageFile> files = await
sdCard.RootFolder.GetFilesAsync();
ExternalStorageFile SelectedFile = files.Where(f =>
f.Name.EndsWith(".txt")).FirstOrDefault();
System.IO.Stream fileStream = await
SelectedFile.OpenForReadAsync();
//Read the entire file into the FileText property
using (StreamReader streamReader = new StreamReader(fileStream)){
txtContent.Text = streamReader.ReadToEnd();
}
fileStream.Close();
}
else {
MessageBox.Show("An SD card was not detected");
}
}

Trung Tm Tin Hc H KHTN-TP.HCM Trang 555/617


Gio trnh: Lp trnh Windows Phone

BI 5. LP TRNH VI THIT B CM NG
(SENSORS)
Sensors l mt trong nhng API khng th thiu i vi cc thit b di ng, hin
nay trn th gii cc hng sn xut ngy cng ch trng ti vic pht trin cc API sensor.
Trong phn ny gio trnh s trnh by cc khi nim v Sensor cng nh cch thc lp
trnh vi Sensor. i vi Windows Phone th c 3 loi cm bin thng dng nht l
cm bin gia tc k, cm bin la bn s v cm bin con quay hi chuyn.

Ni dung ca phn ny s cp ti nhng phn sau:


I) Cc khi nim Sensor ..........................................................................559
1) Cm bin in dung ......................................................................................... 559
2) Cm bin tim cn ........................................................................................... 560
3) Cm bin nh sng........................................................................................... 561
4) Cm bin nh ................................................................................................... 562
5) Gia tc k.......................................................................................................... 562
6) Con quay hi chuyn ....................................................................................... 563
7) La bn s .......................................................................................................... 564
8) Cm bin vn tay ............................................................................................. 565
II) Lp trnh Sensors ph bin trong Windows Phone .............................567
1) Orientation Cm bin xoay mn hnh.......................................................... 567
2) Accelerometer Cm bin gia tc k .............................................................. 572
3) Compass Cm bin la bn s ........................................................................ 578
4) Gyroscope Cm bin con quay hi chuyn .................................................. 580
III) Kt lun ...............................................................................................582

Trung Tm Tin Hc H KHTN-TP.HCM Trang 558/617


Gio trnh: Lp trnh Windows Phone

I. Cc khi nim Sensor

Cc khi nim v Sensor gio trnh ly t cc ngun:

http://www.tinhte.vn (http://www.tinhte.vn/threads/cac-loai-cam-bien-thuong-thay-
tren-thiet-bi-di-dong.2289262/) ,

http://electronics.howstuffworks.com/iphone-accelerometer.htm,
http://en.wikipedia.org/wiki/Accelerometer,

http://en.wikipedia.org/wiki/Proximity_sensor,

http://en.wikipedia.org/wiki/Capacitive_sensing,

http://www.maximintegrated.com/en/app-notes/index.mvp/id/505,

http://msdn.microsoft.com/en-
us/library/windowsphone/develop/hh202968%28v=vs.105%29.aspx .

Hc vin c th vo cc trang trn c bn gc, hoc c cc khi nim di


ny c ly nguyn mu t cc ngun trn.

Ta rng khi ta a my ln tai nghe 1 cuc gi th my s t ng tt mn


hnh, hay thit b t tinh chnh li sng mn hnh, thit b bit khi no ta xoay ngang hay
xoay dc? hay bng cch g in thoi bit khi no chng ta chm vo mn hnh? Nhng
c tnh trn l do cc cm bin c gn trong thit b t x l:

1. Cm bin in dung

y l loi cm bin c t bn di mn hnh cm ng trn thit b di ng ca


cc bn. Cng ngh cm ng in dung dng mt li cc in cc ph trn mn hnh, trn
c mt in th. Khi ngn tay n gn in cc, in dung ca li thay i v c th
o c. Bng vic o tt c cc in cc, ta s nhn bit c v tr ngn tay. C hai loi
in dung dng cho mn hnh cm ng: in dung tng h (mutual capacitance) v in
dung ring (self-capacitance).

Trung Tm Tin Hc H KHTN-TP.HCM Trang 559/617


Gio trnh: Lp trnh Windows Phone

Cng ngh in dung tng h gip chng ta c c mn hnh cm ng a im


v n c s dng cc k ph bin ngy nay trn smartphone, tablet cho n PC. Trong
khi , in dung ring s to ra mt tn hiu mnh hn in dung tng h, cho php nh
v chnh xc ngn tay ang u mt khong cch xa hn, tuy nhin n li khng th
xc nh c v tr ca nhiu ngn tay cng lc nay khng nhiu thit b c tch hp
mn hnh in dung ring.

C mt s thit b c bit s dng kt hp c in dung tng h v in dung


ring phc v cho tnh nng iu khin m khng cn chm vo mn hnh, v d nh
Xperia Sola ca Sony trc y. Ngoi s dng ngn tay, mn hnh cm ng in dung
cn cho php chng ta "cht cht" bng nhng cy bt c u lm bng mt dn in (hoc
mt loi vt liu dn in no khng lm try mt knh).

2. Cm bin tim cn

y l cch m in thoi bit khi no bn p in thoi ln tai t tt hoc


m mn hnh. Cm bin tim cn (Proximity sensor) thng pht ra mt loi trng in
t, mt chm bc x hoc mt loi nh sng (nh hng ngoi chng hn), sau n s
gim st s thay i ca trng hoc nhng tn hiu tr v quyt nh xem bn c ang
smartphone li gn hay khng. Khong cch m cm bin tim cn c th nhn bit i
tng vo khong 2-5cm (cng c nhng loi sensor nhn bit c xa hn nhng ch yu
dng trong lnh vc an ninh v cng nghip).

Trung Tm Tin Hc H KHTN-TP.HCM Trang 560/617


Gio trnh: Lp trnh Windows Phone

Cm bin nh sng l chm mu en bn tri cnh trn ca HTC One, cn chm en bn phi
l cm bin tim cn

Vy v sao phi tt mn hnh i trong lc gi in? Th nht, n s gip thit b


tit kim pin trong qung thi gian my phi tiu th rt nhiu nng lng cho vic kt ni
vo mng di ng. Th hai, n gip hn ch tnh trng mt b phn no trn c th
chng ta chm nhm vo nt dng cuc gi. Trc y mnh tng th xi mt ROM Cook
dnh cho HTC EVO 3D, lc cm bin tim cn cha chy c nn khi gi in mnh
rt hay b tnh trng ngt cuc gi gia chng, nhn li th thy vt m hi du ca tai xut
hin ngay ng v tr ca nt ngt trn mn hnh.

3. Cm bin nh sng

Cm bin nh sng thng c cc nh sn xut t gn cm bin tim cn. Theo


hng Maxim Integrated, hu ht cc loi cm bin nh sng mi trng ang c mt hin
nay dng hai hoc nhiu loi photodiode khc nhau, mi loi s "nhy" vi mt phn nht
nh trong chm nh sng trng. Bng cch kt hp d liu t cc photodiode ri tnh ton,
cm bin c th xut ra mt kt qu tng i chnh xc v sng mi trng xung quanh
di hu ht cc ngun sng ph bin.

Da vo y, h iu hnh hoc mt phn mm no s tinh chnh li sng


mn hnh cho ph hp. V d, khi bn ang trong mt cn phng ti th sng s c
gim li trnh tnh trng nhc mt cho chng ta, cn nu bn ra ngoi tri nng th

Trung Tm Tin Hc H KHTN-TP.HCM Trang 561/617


Gio trnh: Lp trnh Windows Phone

sng c y ln cao nhm m bo hnh nh vn r rng di ngun sng mnh. Bn


cnh vic gip vic nhn ni dung c tt hn th n cng gip tit kim pin hn.

4. Cm bin nh

Cm bin ny rt ph bin trong thi gian hin nay. N l mt tp hp rt nhiu


photodiode c chc nng nhn bit nh sng i t mi trng vo. Sau , cm bin nh
s chuyn thng tin ghi nhn c thnh tn hiu s, p dng thm mt s thut ton x l
mu sc ri kt xut thnh mt tm nh hon chnh cho chng ta xem. Vi nh nh dng
JPEG th mt vi phng php nn v x l khc s c p dng trc khi my ghi thnh
mt tp tin. Cm bin nh c nhiu kch thc khc nhau, thng thy trn thit b di ng
c loi 1/3", mt s my cao cp hn th dng cm bin 1/2,3" hoc 1/1,7". Nh cc bn
bit, n v nh nht dng o chi tit ca nh a ra t cm bin l pixel v 1
megapixel = 1 triu pixel.

Ngoi cm bin nh, thnh phn cu to ca module my nh trn smartphone ca


chng ta thng c thm m-t ly nt (phc v cho tnh nng auto focus), nhiu mch
dn, c th c chip x l tn hiu nh s ring, v khng th khng k n cc thu knh.

5. Gia tc k

Thnh phn ny cng l mt th rt ph bin trn th trng smartphone v ngay


c nhng sn phm gi r cng c tch hp n. Gia tc k (accelerometer) dng ghi
nhn chuyn ng ca thit b cng nh gc nghing so vi phng ngang. Khi c s thay
i v phng hng, cm bin s chuyn thng tin n smartphone hoc tablet ca bn

Trung Tm Tin Hc H KHTN-TP.HCM Trang 562/617


Gio trnh: Lp trnh Windows Phone

bo n a ra nhng phn hi tng ng. V d d thy nht l khi bn xoay ngang


my th giao din cng xoay theo, hoc c mt s game s yu cu bn nghing my sang
tri, phi, ln, xung iu khin vic di chuyn ca nhn vt trong tr chi.

Tnh nng ca gia tc k nghe c v to tt nhng thc cht n c tch hp bn


trong mt con chip MEMS (h thng vi c in t) nh xu gn trn bo mch ch ca thit
b di ng, khng phi l mt h thng c hc g khng l c.

6. Con quay hi chuyn

Loi cm bin ny xut hin ln u tin trn iPhone 4 v tn ting Anh ca n l


gyroscope. Theo nh ngha vt l, con quay hi chuyn l mt thit b dng o c hoc
duy tr phng hng, da trn cc nguyn tc bo ton m men ng lng. Thc cht,
con quay c hc l mt bnh xe hay a quay vi cc trc quay t do theo mi hng.
Phng hng ny thay i nhiu hay t ty thuc vo m men xon bn ngoi hn l lin
quan n con quay c vn tc cao m khng cn m men ng lng ln. V m men xon
c ti thiu ha bi vic gn kt thit b trong cc khp vn nng (gimbal), hng ca
n duy tr gn nh c nh bt k so vi bt k chuyn ng no ca vt th m n ta ln.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 563/617


Gio trnh: Lp trnh Windows Phone

Ni ngn gn hn, con quay hi chuyn dng nh chuyn ng theo cch chng
li trng lc, v y chnh l c tnh ni bt nht ca n. Con quay hi chuyn c dng
kt hp vi gia tc k trong cc thit b di ng hin i ngy nay h tr vic tnh ton
gia tc tuyn tnh tng i so vi khung tham chiu h qui chiu (frame of reference),
t a ra kt qu chnh xc hn. Con quay hi chuyn c kh nhiu ng dng trong lnh
vc game di ng v n s b sung kh nng nhn bit chuyn ng xoay theo phng
dc, th m gia tc k khng lm c.

7. La bn s

Tnh nng ny cng xut hin ngy mt ph bin hn trn cc thit b di ng, nht
l smartphone. Cm bin ny thc cht l mt h thng MEMS (vi c in t) chuyn cm
nhn t trng v n gip vic nh v trn smartphone c chnh xc hn khi kt hp
cng cc loi d liu a l khc nh GPS hay GLONASS. Mt s ng dng di ng hin
nay tn dng la bn s hin th mt mt la bn thc th cho chng ta xem hng ng
ty nam bc, thm ch chng cn o c gc lch so vi hng bc na.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 564/617


Gio trnh: Lp trnh Windows Phone

Vi la bn s, sau mt thi gian khng s dng th chng ta cn phi cn chnh li


n kt qu o t trng c chnh xc. My thng yu cu chng ta cn chnh bng
cch di chuyn thit b theo hnh s 8 nm ngang hoc theo hnh trn.

8. Cm bin vn tay

y l loi cm bin mi l ang ngy cng c nhiu nh sn xut thit b di


ng quan tm. Trc y Motorola tng a cm bin vn tay vo chic Atrix, sau
n lt Pantech ca Hn Quc, mi y c Apple vi iPhone 5s, HTC vi One Max v
Samsung vi Galaxy S5. Thc cht cm bin vn tay c hai loi, loi quang hc v loi
in dung. Loi u thng dng cc my c vn tay gn ngoi hoc my check in
vo c quan, cn loi in dung mi l th c cc nh sn xut a ln smartphone.
Thay v s dng ngun sng nhn ra phn li lm ca vn tay, cm bin qut in dung
Trung Tm Tin Hc H KHTN-TP.HCM Trang 565/617
Gio trnh: Lp trnh Windows Phone

s dng dng in ghi nhn thng tin ny, sau i chiu vi d liu cha trong b
nh xem ngi dng c phi l ngi ng k vi h thng hay khng.

Li ch chnh ca cm bin vn tay in dung l n to hnh nh da vo hnh


dng tht ca vn tay ch khng phi l cc ng nt sng ti, do vic gi mo vn tay
ca h thng cm bin in dung s kh hn nhiu so vi cm bin quang hc. Ngoi ra,
v cm bin in dung dng cc bng bn dn thay v mt chip CCD ln, cm bin in
dung c kch thc nh gn hn nhiu nn mi c tch hp vo cc thit b di ng.
Vic lu tr d liu vn tay thng khng phi dng hnh nh nguyn gc m di dng
d liu s c m ha.

ng dng ca cm bin vn tay trc ht l gip n gin ha vic ng nhp thit


b. Chng ta s khng phi g mt khu unlock my, thay vo ch cn ly ngn tay
nhn ln nt home l xong. Ngoi ra, cm bin vn tay cn c th dng xc thc cc ti

Trung Tm Tin Hc H KHTN-TP.HCM Trang 566/617


Gio trnh: Lp trnh Windows Phone

khon online, thanh ton trc tuyn. Trong tng lai, nhiu kh nng cm bin vn tay s
tip tc xut hin nhiu hn trn cc my di ng.

II. Lp trnh Sensors ph bin trong Windows Phone


Ta i qua cc khi nim v Sensors ni chung, trong Windows Phone hin nay
c cc Sensor ph bin l Gia tc k, La bn s v con quay hi chuyn. Ta s ln lt i
vo lp trnh vi cc API ny:

1. Orientation Cm bin xoay mn hnh

Khi ta thit k phn mm c trng hp ta h tr mn hnh nm ng hoc nm


ngang hoc va nm ng va nm ngang ty thuc vo hng ngi s dng cm thit
b in thoi.

Mi hng hin th c nhng c im khc nhau: V d nu nm ng th


Keyboard li qu nh gy kh khn cho vic nhp liu do nhn nhm phm, nu nm ngang
th Keyboard ln d nhp liu nhng n li bt li do chiu cao ca giao din qu hp gy
kh khn cho vic thao tc vi cc control khc.

h tr Orientation, ta cu hnh trong PhoneApplication cho tt c cc trang:

<phone:PhoneApplicationPage
...
SupportedOrientations="PortraitOrLandscape" Orientation="Portrait"
>
SupportedOrientations l cc hng m phn mm h tr quay xoay theo hng
ngi s dng cm in thoi. Orientation l hng mc nh chnh ca phn
mm.
SupportedOrientations c 3 loi:

SupportedOrientations="Landscape"
SupportedOrientations="Portrait"
SupportedOrientations="PortraitOrLandscape"

Trung Tm Tin Hc H KHTN-TP.HCM Trang 567/617


Gio trnh: Lp trnh Windows Phone

Orientation c 7 loi:

Thng thng ta dng Wrapanel trong Windows Phone Toolkit hin th vic
xoay hng phn mm theo hng ngi s dng cm thit b:

V d: Ta thit k phn mm t ng chuyn hng giao din theo hng ngi


s dng cm in thoi bng WraPanel nh sau:

Bc 1: To Project nh hnh di y:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 568/617


Gio trnh: Lp trnh Windows Phone

Bc 2: Thit k giao din cho MainPage.xaml nh sau:

<phone:PhoneApplicationPage

x:Class="WrapOrientation.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="PortraitOrLandscape" Orientation="Portrait"

shell:SystemTray.IsVisible="True">

<Grid x:Name="LayoutRoot" Background="Transparent">

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

<RowDefinition Height="*"/>

</Grid.RowDefinitions>

<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">

<TextBlock x:Name="ApplicationTitle" Text="WRAP ORIENTATION"


Style="{StaticResource PhoneTextNormalStyle}"/>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 569/617


Gio trnh: Lp trnh Windows Phone

<TextBlock x:Name="PageTitle" Text="mainpage" Margin="9,-7,0,0"


Style="{StaticResource PhoneTextTitle1Style}"/>

</StackPanel>

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

<ListBox

Margin="{StaticResource PhoneHorizontalMargin}" x:Name="PhotoList">

<ListBox.ItemsPanel>

<ItemsPanelTemplate>

<toolkit:WrapPanel x:Name="PhotoPanel"/>

</ItemsPanelTemplate>

</ListBox.ItemsPanel>

<ListBox.ItemTemplate>

<DataTemplate>

<Border Width="210" Height="160" >

<Image

Width="200" Height="150"

Source="{Binding}" CacheMode="BitmapCache"

Stretch="UniformToFill" HorizontalAlignment="Left" />

</Border>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

</Grid>

</Grid>

</phone:PhoneApplicationPage>

Trung Tm Tin Hc H KHTN-TP.HCM Trang 570/617


Gio trnh: Lp trnh Windows Phone

Bc 3: Coding cho MainPage.xaml.cs:

using System.Collections.Generic;

using Microsoft.Phone.Controls;

namespace WrapOrientation

public partial class MainPage : PhoneApplicationPage

private List<string> photos = new List<string>();

public MainPage()

InitializeComponent();

photos.Add("/Assets/Coconuts.jpg");

photos.Add("/Assets/Forest.jpg");

photos.Add("/Assets/Mountain.jpg");

photos.Add("/Assets/Sea.jpg");

photos.Add("/Assets/SunnyTree.jpg");

photos.Add("/Assets/TallPalms.jpg");

PhotoList.ItemsSource = photos;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 571/617


Gio trnh: Lp trnh Windows Phone

Kt qu sau khi chy phn mm (Xoay ng xoay ngang):

2. Accelerometer Cm bin gia tc k

Accelerometer l mt cm bin trong thit b di ng ni chung v Windows Phone


ni ring o gia tc theo 3 trc (X,Y,Z), lin quan n trng lc.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 572/617


Gio trnh: Lp trnh Windows Phone

s dng Accelerometer, ta using th vin Microsoft.Devices.Sensors, ch


rng th vin ny c lp Accelerometer ging nh trong namespace
Windows.Devices.Sensors nn khng b nhm ln v cng tn lp m nm trong 2
namespace khc nhau.

Hai ch nng chnh ca Accelerometer l:


nh hng tng i vi tri t
Pht hin chuyn ng ca thit b so vi trng thi ban u trc
Gi tr tr v l mt n v gia tc, ty vo chiu di chuyn m n c cc gi tr
khc nhau. iu ny c ngha l nu thit b nm nga mt trn mt b mt phng th trc
Z s c l -1.0, hai trc kia s c c 0.0 Di y l hnh minh ha cho cch hin th
cc gi tr khc nhau.

Di y l hnh mnh ha cc chiu nm ca in thoi s cung cp cc gi tr


(X,Y,Z) khc nhau:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 573/617


Gio trnh: Lp trnh Windows Phone

Trung Tm Tin Hc H KHTN-TP.HCM Trang 574/617


Gio trnh: Lp trnh Windows Phone

Cc bc s dng Accelerometer:
Bc 1:S dng cc th vin:

using Microsoft.Devices.Sensors;

using Microsoft.Xna.Framework;

Bc 2: Khai bo i tng thuc lp Accelerometer


Ch dng TimeBetweenUpdates v s kin CurrentValueChanged:

private void appBarStopGo_Click(object sender, EventArgs e)

if (accelerometer == null)

accelerometer = new Accelerometer();

accelerometer.TimeBetweenUpdates = TimeSpan.FromMilliseconds(10);

accelerometer.CurrentValueChanged +=
accelerometer_CurrentValueChanged;

try {

accelerometer.Start();

statusText.Text = "started";

appBarStopGo.Text = "stop";

catch (AccelerometerFailedException ex)

statusText.Text = ex.ToString();

Trung Tm Tin Hc H KHTN-TP.HCM Trang 575/617


Gio trnh: Lp trnh Windows Phone

else {

accelerometer.CurrentValueChanged -=
accelerometer_CurrentValueChanged;

try

accelerometer.Stop();

accelerometer = null;

statusText.Text = "stopped";

appBarStopGo.Text = "go";

catch (AccelerometerFailedException ex)

statusText.Text = ex.ToString();

Bc 3: Qun l s kin CurrentValueChanged, dng AccelerometerReading


ly kt qu, Vector3 ly X,Y,Z.

private void accelerometer_CurrentValueChanged(

object sender, SensorReadingEventArgs<AccelerometerReading> e)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 576/617


Gio trnh: Lp trnh Windows Phone

AccelerometerReading reading = e.SensorReading;

Vector3 acceleration = reading.Acceleration;

Dispatcher.BeginInvoke(() =>

readingText.Text = String.Format("X={0:0.00}, Y={1:0.00}, Z={2:0.00}",

acceleration.X, acceleration.Y, acceleration.Z);

statusText.Text = String.Format("sending @ {0} ms",

accelerometer.TimeBetweenUpdates.Milliseconds);

});

Ta c th kim tra kt qu trn in thoi tht hoc dng Emulator:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 577/617


Gio trnh: Lp trnh Windows Phone

3. Compass Cm bin la bn s

Windows phone s dng lp Compass to i tng kch hot kim tra cm


bin la bn, thng qua SensorReadingEventArgs<CompassReading> c thng s khi
c s thay i.

Cc bc s dng Compass:
Bc 1: S dng cc th vin:

using Microsoft.Devices.Sensors;

using Microsoft.Xna.Framework;

using System.Windows.Navigation;

using System.Windows.Threading;

Bc 2: Khai bo i tng Compass:

private Compass compass;

compass = new Compass();

Trung Tm Tin Hc H KHTN-TP.HCM Trang 578/617


Gio trnh: Lp trnh Windows Phone

Bc 3: Gn cc thuc tnh v s kin:

compass.TimeBetweenUpdates = TimeSpan.FromMilliseconds(33);

compass.CurrentValueChanged += compass_CurrentValueChanged;

// for calibration.

compass.Calibrate += compass_Calibrate;

Bc 4: Kch hot Compass:

compass.Start();

Ch ta cn kim tra nu nh Compass c kch hot th Stop sau Start li

if (compass != null && compass.IsDataValid) {

compass.Stop();

else{

Bc 5: X l cc s kin:

// For calibration.

private double headingAccuracy;

private void compass_CurrentValueChanged(

object sender, SensorReadingEventArgs<CompassReading> e)

double trueHeading = e.SensorReading.TrueHeading;

float headingRadians = MathHelper.ToRadians((float)trueHeading);

// For calibration.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 579/617


Gio trnh: Lp trnh Windows Phone

headingAccuracy = Math.Abs(e.SensorReading.HeadingAccuracy);

//x l headingAccuracy

private void compass_Calibrate(object sender, CalibrationEventArgs e)

compass.Calibrate -= compass_Calibrate;

4. Gyroscope Cm bin con quay hi chuyn

Gyroscope l cm bin con quay hi chuyn hot ng theo nguyn l trnh by


mc khi nim. Di y gio trnh b sung thm mt s hnh nh v Gysroscope:

Movement: Pitch, Yaw, Roll:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 580/617


Gio trnh: Lp trnh Windows Phone

Cc bc s dng Gyroscope:
Bc 1: S dng cc th vin

using Microsoft.Devices.Sensors;

using Microsoft.Xna.Framework;

Bc 2: Khai bo i tng con quay hi chuyn v gn cc s kin

private Gyroscope gyroscope;

gyroscope = new Gyroscope();

gyroscope.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);

gyroscope.CurrentValueChanged += gyroscope_CurrentValueChanged;

Bc 3: Kch hot con quay hi chuyn

gyroscope.Start();

Ch cn kim tra xem kch hot hay cha (ging cc sensor trn)
Bc 4: X l kt qu do cm bin nhn c thng qua

SensorReadingEventArgs<GyroscopeReading>

private void gyroscope_CurrentValueChanged(

object sender, SensorReadingEventArgs<GyroscopeReading> e)

Vector3 currentRotationRate = e.SensorReading.RotationRate;

Dispatcher.BeginInvoke(() =>

currentX.X2 = currentX.X1 + currentRotationRate.X * 50;

Trung Tm Tin Hc H KHTN-TP.HCM Trang 581/617


Gio trnh: Lp trnh Windows Phone

currentY.Y2 = currentY.Y1 - currentRotationRate.Y * 50;

currentZ.X2 = currentZ.X1 - currentRotationRate.Z * 50;

currentZ.Y2 = currentZ.Y1 + currentRotationRate.Z * 50;

});

III. Kt lun
Sensors l mt trong nhng API khng th thiu i vi cc thit b di ng, hin
nay trn th gii cc hng sn xut ngy cng ch trng ti vic pht trin cc API sensor.
i vi Windows Phone th c 3 loi cm bin thng dng nht l cm bin gia tc
k, cm bin la bn s v cm bin con quay hi chuyn.

Ta c th kt hp Motion API h tr cc phn mm nh l nh v, hng di


chuyn nhn vt

Hin ny ngy cng nhiu cc phn mm cn s h tr ca cc Sensor, nn cc lp


trnh vin cn nm r cch thc lp trnh vi Sensor.

Trung Tm Tin Hc H KHTN-TP.HCM Trang 582/617


Gio trnh: Lp trnh Windows Phone

BI 6. S DNG CLIPBOARD V CONTACTS - CALENDAR


RESOURCE
Trong phn ny gio trnh s trnh by v API clipboard v cch khai thc ti
nguyn h thng di ng nh: Truy vn danh b, thm mi, chnh sa v xa danh b ng
thi cng trnh by qua cch s dng Calendar gip lp trnh vin c th to cc lch
hp cng nh truy vn thng tin lin quan ti Calendar.

Ni dung ca phn ny s cp ti nhng phn sau:


I) Clipboard API .....................................................................................585
II) Contacts ...............................................................................................586
1) Khi nim People Hub ..................................................................................... 586
2) Truy vn Contact ............................................................................................. 587
3) Thm mi Contact ........................................................................................... 593
4) Xa Contact...................................................................................................... 594
III) Calendar ..............................................................................................595
1) Truy vn Calendar .......................................................................................... 595
2) To mi cuc hn ............................................................................................. 598
IV) Kt lun ...............................................................................................598

Khoa Cng Ngh Thng Tin Trang 584/582


Gio trnh: Lp trnh Windows Phone

I. Clipboard API
Clipboard l lp c xy dng sn trong Windows phone, n nm trong th vin
System.Windows. Di y l m t cc phng thc ca Clipboard:

Tn hm Cng dng
Clipboard.SetText(Hello DrThanh) Hm dng lu vao Clipboard
Hm kim tra xem Clipboard c cha d liu
Clipboard.ContainsText()
hay khng
Hm ly ni dung Clipboard ra, ch l n
khng c h tr trong Windows Phone nn
khi ta gi hm ny s b bo li.
Clipboard.GetText() Windows Phone cung cp sn biu tng
Paste nu nh Clipboard c cha thng tin, ta
phi bm vo biu tng ny ly d liu t
Clipboard ra

Khi gi lnh Clipboard.SetText th Windows Phone s t xut hin biu tng


Paste nh trn, ta nhn vo nt ny ly Clipboard ra.

Khoa Cng Ngh Thng Tin Trang 585/582


Gio trnh: Lp trnh Windows Phone

II. Contacts
Vi Windows Phone, lp trnh vin c th truy sut thng tin danh b in thoi
cng nh tng tc: Thm, sa, xa thng tin Contact. Gio trnh s cung cp cc k thut
lp trnh gip lp trnh vin c th thao tc mt cch thnh thc vi Contact.

1. Khi nim People Hub

People Hub khng n thun l ni cha danh b, n cn l ni gip bn giao tip


vi mi ngi cng nh theo di hot ng ca mi ngi trong danh b qua mng x hi
m bn tham gia nh Windows Live, Facebook, Twitter hay LinkedIn. Giao din chnh ca
People Hub gm 3 mc v bn ch cn vut sang ngang xem tng mc. Cc mc bao
gm:
Recent
y l mc u tin s xut hin khi bn nhn vo People Hub. Ti y, hnh nh
i din ca nhng ngi bn thng xuyn lin h s hin ra. Qua , bn c th truy xut
nhanh vo danh b ca h thc hin cuc gi, nhn tin, gi email, v.v...
All
Mang ngha "tt c", mc ny th hin ton b nhng ngi c trong danh b
ca bn. Ngay pha bn di ch "all" l hnh nh i din v trng thi cp nht (status)

Khoa Cng Ngh Thng Tin Trang 586/582


Gio trnh: Lp trnh Windows Phone

ca bn. Pha di nh i din l cc nhm - trong hnh chng ta c 1 nhm tn l "Family"


- bn c th to mt nhm gm nhiu ngi c lin quan tin b lin lc v theo di.

Tip theo l danh sch lin lc ca bn c xp theo ch ci ABC. Khi nhn vo


mt k t c trng, chng hn nh ch "a" trong vung mu , mt bng k t s hin

ra bn c th tm nhanh. Ngoi ra, chng ta cn c 1 nt du cng v nt tm

kim trn thanh menu bn di mn hnh. Nt du cng s cho php bn to mi 1 a


ch lin lc hoc 1 nhm v nt tm kim s cho php bn tm kim theo tn ring, tn cng
ty, cc hu t m bn gn cho a ch lin lc.

What's new

C g mi? y l ni th hin tt c cc thng tin cp nht t bn b trong danh


b - nhng ai c s dng cc dch v mng x hi nh nn pha trn. Thng tin s c
cp nht lin tc v bn c th d dng theo di 1 ai m mnh quan tm.

2. Truy vn Contact

Khoa Cng Ngh Thng Tin Trang 587/582


Gio trnh: Lp trnh Windows Phone

Gio trnh s trnh by 2 trng hp truy vn Contact m chng ta thng gp:

Single-contact choosers
Querying contacts programmatically
c th truy vn c Contact, ta dng th vin : Microsoft.Phone.Tasks

i vi Single Contact Choosers th lp trnh vin c th ly thng tin s in


thoi, email, a ch.

PhoneNumberChooserTask: Dng chn s in thoi v tn ca mt Contact


bt k trong in thoi, ng thi hin th mn hnh lin lc.
Cc bc s dng PhoneNumberChooserTask:

Bc 1: Khai bo i tng PhoneNumberChooserTask.

private PhoneNumberChooserTask phoneNumberChooser;


Bc 2: Cp pht b nh v gn s kin Complete cho i tng

phoneNumberChooser = new PhoneNumberChooserTask();


phoneNumberChooser.Completed += phoneNumberChooser_Completed;

Khoa Cng Ngh Thng Tin Trang 588/582


Gio trnh: Lp trnh Windows Phone

Bc 3: Gi phng thc Show()

phoneNumberChooser.Show();
Bc 4: X l s kin Complete t PhoneNumberResult

void phoneNumberChooser_Completed
(object sender, PhoneNumberResult e)
{
if (e.TaskResult != TaskResult.OK)
return;
phoneNumberDisplayNameTextBlock.Text = e.DisplayName;
phoneNumberTextBlock.Text = e.PhoneNumber;
makePhoneCallButton.IsEnabled = true;
}

Ta thy rng PhoneNumberResult c e.DisplayName hin th tn lin lc


e.PhoneNumber hin th s in thoi lin lc.

EmailAddressChooserTask: Ly thng tin lin lc v email


Cc bc thc hin EmailAddressChooserTask:

Bc 1: Khai bo i tng EmailAddressChooserTask

private EmailAddressChooserTask emailAddressChooser;


Bc 2: Cp pht b nh v gn s kin Complete cho i tng

emailAddressChooser = new EmailAddressChooserTask();


emailAddressChooser.Completed +=emailAddressChooser_Completed;
Bc 3: Gi phng thc Show()

emailAddressChooser.Show();
Bc 4: X l s kin Complete t EmailResult

void emailAddressChooser_Completed
(object sender, EmailResult e)

Khoa Cng Ngh Thng Tin Trang 589/582


Gio trnh: Lp trnh Windows Phone

{
if (e.TaskResult != TaskResult.OK)
return;
emailAddressDisplayNameTextBlock.Text = e.DisplayName;
emailAddressTextBlock.Text = e.Email;
sendEmailButton.IsEnabled = true;
}

e.Email ly ra Email ca Contact, e.DisplayName ly ra tn lin lc ca


Contact.

AddressChooserTask: Ly tn lin lc v email ca Contact.

Cc bc thc hin AddressChooserTask:

Bc 1: Khai bo i tng AddressChooserTask

private AddressChooserTask addressChooser;


Bc 2: Cp pht b nh v gn s kin Complete cho i tng

addressChooser = new AddressChooserTask();


addressChooser.Completed += addressChooser_Completed;
Bc 3: Gi phng thc Show()

addressChooser.Show();
Bc 4: X l s kin Complete t AddressResult

void addressChooser_Completed (object sender, AddressResult e)


{
if (e.TaskResult != TaskResult.OK)
return;
addressDisplayNameTextBlock.Text = e.DisplayName;
addressTextBlock.Text = e.Address;
mapItButton.IsEnabled = true;

Khoa Cng Ngh Thng Tin Trang 590/582


Gio trnh: Lp trnh Windows Phone

thc hin 1 cuc gi (ID_CAP_PHONEDIALER capability):

PhoneCallTask pct = new PhoneCallTask();


pct.PhoneNumber = 098.;
pct.Show();
thc hin gi 1 email:

EmailComposeTask emailCompose = new EmailComposeTask();


emailCompose.To = emailAddressTextBlock.Text;
emailCompose.Subject = "Subject here ";
emailCompose.Body = "Hello from Windows Phone!";
emailCompose.Show();
hin th a ch trn bn :

MapsTask mt = new MapsTask();


mt.SearchTerm = addressTextBlock.Text;
mt.Show();

Querying contacts programmatically


Single Contact Chooser n c bt tin l lp trnh vin ch c th ly nhng thng
s n gin nh ly 1 email, 1 s in thoi, 1 a ch trong nhiu trng hp ta cn
chn nhiu Contact v c nhng thao tc nng cao khc. Microsoft.Phone.UserData cung
cp hng lot cc API cho php chng ta thc hin, trong UserData ta c 2 cch truy
vn thng tin: Dng cc phng thc Search n gin, dng LINQ. Ta cn thit lp
ID_CAP_CONTACTS cho ng dng.

Ta c mn hnh v d truy vn thng tin nh sau:

Khoa Cng Ngh Thng Tin Trang 591/582


Gio trnh: Lp trnh Windows Phone

Ta dng hm bt ng b SearchAsync tin hnh truy vn thng tin:

Contacts contactsDb = new Contacts();


contactsDb.SearchCompleted +=
contactsDb_SearchCompleted;
contactsDb.SearchAsync
(string.Empty, FilterKind.None, null);

V d cch s dng:

contactsDb.SearchAsync
(searchTermTextBox.Text, FilterKind.DisplayName, null);

void contactsDb_SearchCompleted(object sender, ContactsSearchEventArgs


e)
{
if (e.State == null) {
contactsListBox.ItemsSource = e.Results;
return;
}
string citySearch = (string)e.State;
var contactsInQueriedCity = from contact in e.Results

Khoa Cng Ngh Thng Tin Trang 592/582


Gio trnh: Lp trnh Windows Phone

from address in contact.Addresses


where address.PhysicalAddress.City.ToUpper() ==
citySearch.ToUpper()
select contact;
contactsListBox.ItemsSource = contactsInQueriedCity;
}

Ta c th s dng cc FilterKind nh sau:

FilterKind.DisplayName;

FilterKind.EmailAddress;

FilterKind.Identifier;

FilterKind.None;

FilterKind.PhoneNumber;

FilterKind.PinnedToStart;

3. Thm mi Contact

Ta dng SaveContactTask trong Microsoft.Phone.Tasks v nh thit lp


ID_CAP_CONTACTS cho php lu 1 mi Contact vo in thoi.

private void btnAddContact_Click(object sender, EventArgs e) {


SaveContactTask saveContact = new SaveContactTask();
saveContact.FirstName = firstNameTextBox.Text;
saveContact.LastName = lastNameTextBox.Text;
saveContact.Completed += SaveContactCompleted;
saveContact.Show();
}
void SaveContactCompleted(object sender, SaveContactResult e) {

Khoa Cng Ngh Thng Tin Trang 593/582


Gio trnh: Lp trnh Windows Phone

if (e.TaskResult == TaskResult.OK) {
MessageBox.Show(" lu thnh cng Contact ");
}
else if (e.TaskResult == TaskResult.Cancel) {
MessageBox.Show("Contact not added. You cancelled it.");
}
}

III. Xa Contact

xa mt Contact khi thit b, ta s dng th vin:


using Windows.Phone.PersonalInformation;

V vit coding nh sau:


private async void deleteContactButton_Click(object sender, EventArgs e)

if (MessageBox.Show("Are you sure you want to delete xyz?",

"Delete contact?", MessageBoxButton.OKCancel) ==


MessageBoxResult.Cancel)

return;

ContactStore contactsDb = await ContactStore.CreateOrOpenAsync();

await contactsDb.DeleteContactAsync("id y");

i tng contactsDb cung cp hng lot cc phng thc ta thao tc vi c s


d liu Contact trong in thoi:

Khoa Cng Ngh Thng Tin Trang 594/582


Gio trnh: Lp trnh Windows Phone

contactsDb.CreateContactQuery;

contactsDb.DeleteAsync;

contactsDb.DeleteContactAsync;

contactsDb.FindContactByIdAsync;

contactsDb.FindContactByRemoteIdAsync;

contactsDb.GetChangesAsync;

contactsDb.LoadExtendedPropertiesAsync;

contactsDb.SaveExtendedPropertiesAsync;

IV. Calendar
s dng Calendar ta cng dng th vin Microsoft.Phone.UserData. Thng
qua Calendar ta c th truy vn cc thng tin v lch hn, gip nhc nh ngi s dng nh
v thc hin mt s kin hay cng vic no ln k hoch.

1. Truy vn Calendar

truy vn ta dng hm SearchAsync ca i tng Appointments

Appointments calendar = new Appointments();

calendar.SearchCompleted += calendar_SearchCompleted;

calendar.SearchAsync(startTime, endTime, null);

Sau y l coding chi tit cho hm tm kim thi gian cuc hn:

public void FindTimeForAppointment


(DateTime date, string timeOfDay, int appointmentLength)
{
DateTime startTime = date;

Khoa Cng Ngh Thng Tin Trang 595/582


Gio trnh: Lp trnh Windows Phone

DateTime endTime = date;


lengthOfAppointmentInMinutes = appointmentLength;
switch (timeOfDay.ToUpper())
{
case "MORNING":
startTime = startTime.AddHours(7);
endTime = endTime.AddHours(12);
break;
case "AFTERNOON":
startTime = startTime.AddHours(12);
endTime = endTime.AddHours(17);
break;
case "EVENING":
startTime = startTime.AddHours(17);
endTime = endTime.AddHours(22);
break;
default:
break;
}
Appointments calendar = new Appointments();
calendar.SearchCompleted += calendar_SearchCompleted;
calendar.SearchAsync(startTime, endTime, null);
}

void calendar_SearchCompleted(object sender, AppointmentsSearchEventArgs


e)
{
List<Appointment> appointments = e.Results.ToList();

Khoa Cng Ngh Thng Tin Trang 596/582


Gio trnh: Lp trnh Windows Phone

// there are no appointments during this period


if (appointments.Count() == 0)
{
AvailableTime = e.StartTimeInclusive;
return;
}
Appointment firstAppointment = appointments[0]
if ((firstAppointment.StartTimee.StartTimeInclusive).TotalMinutes
>=lengthOfAppointmentInMinutes)
{
AvailableTime = e.StartTimeInclusive;
NextAppointment = firstAppointment;
return;
}
Appointment previousAppointment = firstAppointment;
for (int i = 1; i < appointments.Count(); i++)
{
Appointment nextAppointment = appointments[i];
if ((nextAppointment.StartTime - previousAppointment.EndTime)
.TotalMinutes >=lengthOfAppointmentInMinutes)
{
PreviousAppointment = previousAppointment;
NextAppointment = nextAppointment;
AvailableTime = previousAppointment.EndTime;
return;
}
previousAppointment = nextAppointment;
}

Khoa Cng Ngh Thng Tin Trang 597/582


Gio trnh: Lp trnh Windows Phone

if ((e.EndTimeInclusivepreviousAppointment.EndTime).TotalMinutes >=
lengthOfAppointmentInMinutes)
{
AvailableTime = previousAppointment.EndTime;
PreviousAppointment = previousAppointment;
return;
}
}

2. To mi cuc hn

to mi cuc hn hay s kin ny , ta dng SaveAppointmentTask:

using Microsoft.Phone.Tasks;
private void createAppointmentButton_Click
(object sender, RoutedEventArgs e)
{
SaveAppointmentTask newAppointment = new SaveAppointmentTask();
newAppointment.StartTime = AvailableTime;
newAppointment.Subject = appointmentSubjectTextBox.Text;
newAppointment.Location = appointmentLocationTextBox.Text;
newAppointment.EndTime =
AvailableTime.AddMinutes(lengthOfAppointmentInMinutes);
newAppointment.Show();
}
V. Kt lun
Windows Phone cung cp cc API nh Clipboard, Contact, Calendar gip lp
trnh vin c th qun l c b nh m, truy vn c s d liu danh b, thm mi cng
nh xa danh b, Calendar gip lp trnh vin truy vn v to ra cc s kin cng nh lch
trnh cn ghi nh khc.

y l mt trong nhng tnh nng tng i hay ca Windows Phone, lp trnh


vin cn nm r cc k thut ny.

Khoa Cng Ngh Thng Tin Trang 598/582


Gio trnh: Lp trnh Windows Phone

BI 7. PUBLISH APP TO WINDOWS STORE


Bi v a phn cc hc vin u l cc sinh vin hin ti ca cc trng cao ng
i hc nn u c ti khon DreamSpark nn gio trnh s hng dn tng bc cch a
phn mm Windows Phone ln Store. Nu khng phi sinh vin th cc bn phi ng ph
th cc bc li cng n gin, cc bn t nghin cu thm trn mng.

Bi hng dn di ny c mt sinh vin ca Trung tm tin hc Khoa hc


t nhin ging dy hng dn v thc hin, cc hc vin c th lm theo cc bc sau
(hoc xem trc tuyn trn internet):

iu trc tin bt buc hc vin phi c ti khon Developer ca Microsoft, nu


cha c th ta lm nh sau (Nu c ri th qua lun Bc 4):

Bc 1: ng nhp vo https://www.dreamspark.com/

Trong trang DreamSpark ny cc bn chn Windows Phone 8 nh hnh bt u


ng k:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 601/617


Gio trnh: Lp trnh Windows Phone

Sau khi bm vo Windows Phone 8, Ta ko xung pha di cng chn GET


YOUR REGISTRATION CODE

Khi chn s c mt trang mi c m ra, bn chn VERIFY NOW nh hnh:

Sau khi bm Verify, h thng hin th ra mn hnh xc nhn ti khon, ta chn nh


hnh bn di v bm Continue:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 602/617


Gio trnh: Lp trnh Windows Phone

Chn I do not have a DreamSpark account Bm Continue

Sau khi bm Continue, mn hnh nhp thng tin hin th ra nh bn di, bn cn


cung cp thng tin tht chnh xc ri bm Continue to Verify:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 603/617


Gio trnh: Lp trnh Windows Phone

By gi bn hy check mail v kch hot ti khon ca mnh. Sau khi chn link
trong mail bn s nhn c li chc mng KCH HOT THNH CNG

Bc 2: ng nhp ly Code (token)

By gi quay tr li trang sau ly code ng k ti khon developer


free: https://www.dreamspark.com/Student/Windows-Store-Access.aspx

ng nhp vo v chn GET CODE NOW

By gi bn s nhn c code tng ng ca mnh, hy ghi nh code (ch b


bi en ngon ngo):

Trung Tm Tin Hc H KHTN-TP.HCM Trang 604/617


Gio trnh: Lp trnh Windows Phone

Bc 3: By gi truy cp vo dev Center v ng nhp bng ti khon Microsoft


ca bn: http://dev.windowsphone.com/en-us

Sau khi ng nhp chn DashBoard v chn Accept and Continue

Tip tc chon nh hnh bn di (nh chn VIETNAM), bm Enroll now


(Individual):

Trung Tm Tin Hc H KHTN-TP.HCM Trang 605/617


Gio trnh: Lp trnh Windows Phone

By gi hy hon thnh thng tin ca bn v chn NEXT:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 606/617


Gio trnh: Lp trnh Windows Phone

Nhp chn ng v tip tc, n bc thanh ton bn chn Use a Token sau
nhp code vo thanh ton l 0 VND:

Ti y nu thanh ton thnh 0 l bn thnh cng, chn Purchase hon tt:

Bc 4: Sau khi c ti khon developer ri cc bn tin hnh lm nh sau.

Trong Visual Studio cc bn Click Phi chut ti Projetc hon thnh ca mnh
(nh l i APP ICON mc nh - nu khng tester s yu cu upload li) / chn Build
hoc ReBuild nh hnh:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 607/617


Gio trnh: Lp trnh Windows Phone

Sau khi Buil thnh cng cc bn xem phn output s thy thng bo:

By gi vo th mc: Bin/Debug (Release) v kim file XAP ca mnh. Copy ra


Desktop tin up ln store:

Tip theo cc bn CTRL +F5 trong Visual Studio Deloy APP tren Emulator:
chn theo th t nh hnh. Phn 3.Capture cc bn nh Capture -> Save vi tm:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 608/617


Gio trnh: Lp trnh Windows Phone

Bc 5: a ng dng ln Store. By gi cc bn c y FILE XAP v HNH


ng dng. Truy Cp vo https://dev.windowsphone.com/en-us/dashboard

Sau ng nhp / Chon Dashboard nh hnh v Click vo nt Submit APP

Sau khi bm vo nt Submit app, h thng s hin th mn hnh di y (ta chn


mc APP info):

Trung Tm Tin Hc H KHTN-TP.HCM Trang 609/617


Gio trnh: Lp trnh Windows Phone

in thng tin cho APP ca bn.

Bc 5.1: Nhp tn cho ng dng v chn Reserve app name kim tra
tn APP hp l

Bc 5.2: K n chn danh mc cho ng dng v gi tin ng dng ca


bn . Sau chn SAVE:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 610/617


Gio trnh: Lp trnh Windows Phone

Bc 5.3: By gi bn chn 2. Upload and describe your package(s):

My ca bn phi ci Microsoft Silverlight, nu cha c bn s c yu cu


ci trc tip trn trnh duyt:

Nu my cha c th h thng s hin th mn hnh trn, bm OK ci

Trung Tm Tin Hc H KHTN-TP.HCM Trang 611/617


Gio trnh: Lp trnh Windows Phone

Bc 5.4: By gi bn chn Add New v chn file XAP ca bn, sau


chn save:

i mt thi gian ngn APP ca bn c upload ln. Sau nhp cc thng


tin cho APP ca bn:
Version APP:

Trung Tm Tin Hc H KHTN-TP.HCM Trang 612/617


Gio trnh: Lp trnh Windows Phone

Gii thiu v APP:

T kha cho APP :

ICON Cho APP trn STORE: Lu l phi ng kch thc quy nh ( 300300)

Trung Tm Tin Hc H KHTN-TP.HCM Trang 613/617


Gio trnh: Lp trnh Windows Phone

Cp nht nh chp ng dng. Nh chnh sa li kch thc cho ph hp nh,


sau khi upload xong chn Save hon tt :

Trung Tm Tin Hc H KHTN-TP.HCM Trang 614/617


Gio trnh: Lp trnh Windows Phone

Bc 5.5: Tip theo bn hy chn Review and Submit :

By gi bn hy kim tra li cc thng s 1 ln na v sa li nu c (s bo trn


website): v khi ph hp, khng cn bo li bn chn Submit a app ln store.

Sau khi hon tt bn s nhn c li chc mng thnh cng. By gi vic cn li


l i Microsoft Tester duyt v cho php app ln store (1 n vi ngy).

Trung Tm Tin Hc H KHTN-TP.HCM Trang 615/617


Gio trnh: Lp trnh Windows Phone

Nh vy bn ton tt kha hc v a c ng dng Windows Phone ln


APP Store, cc thng tin m t cho ng dng cn chnh xc v kho lo ngi s dng
c th tm kim mt cch d dng

Trung Tm Tin Hc H KHTN-TP.HCM Trang 616/617

You might also like