Professional Documents
Culture Documents
GiaoTrinh WindowsPhone
GiaoTrinh WindowsPhone
Khi: i Hc v Cao ng
Nm 2014
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
PHN 1. MODULE 1
BI 1. GII THIU H IU HNH 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.
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.
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.
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
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.
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...
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.
Cc ca s lm vic
1: Toolbox
2: Solution Explorer
3: Emulator Designer
4: XAML Designer
5: Properties
Cu trc th mc ca project
Cc cng c khc
Accelerometer tab
Location tab
Screenshot tab
Network tab
2. Tm tt c php XAML
Vd:
<Stackpanel Orientation="Horizontal"
Collection Syntax
<Grid>
<Button Grid.Row="1"/>
</Grid>
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>
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>
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
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
<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>
TextBox
Dng hin th v nhn d liu input t ngi dng.
s dng textbox, bn khai bo vi c php sau
InputScope = Url
InputScope = Number
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
3. Selection controls
CheckBox
Dng th hin cho nhng la chn mang hai gi tr ng sai
RadioButton
Dng chn 1 hay nhiu la chn thuc cng nhm vi nhau
Slider
Dng thay i gi tr cn bin thin
4. Button control
5. Image control
I. List controls
1. ListBox control
Khi nim
Dng hin th d liu c dng danh sch.
<ListBox>
<ListBoxItem>
</ListBoxItem>
<ListBoxItem>
</ListBoxItem>
</ListBox>
<ListBoxItem>
<TextBlock Text=" Th Thy Nhung"/>
</ListBoxItem>
<ListBoxItem>
<TextBlock Text="Dng Thy Trang"/>
</ListBoxItem>
</ListBox>
//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",
};
public MainPage()
{
InitializeComponent();
MyListBox.ItemsSource = Items;
}
<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.
<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
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"/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>
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:
2. MediaElement control
<MediaElement Name="MediaWindow
Source="Assets/hm_helix_twist_320x240.wmv"/>
MessageBoxResult result =
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>
I. Cc loi ng dng
1. Single page
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
III. Panorama
ng dng panorama s dng panorama control, cho php tao ra ng dng gm
nhiu mn hnh tri di theo chiu ngang
<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>
NavigationService.Navigate(
new Uri("/page1.xaml?ID=2&Ten=abv", UriKind.Relative));
S dng string format
BI 5. DATA BINDING C BN
I. Data binding l g?
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.
1. Binding Mode
Name Description
V d
<StackPanel>
<TextBox x:Name="textBox1">Sample Text</TextBox>
<Label x:Name="label1"/>
</StackPanel>
<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>
<StackPanel>
<TextBox x:Name="textBox1">Sample Text</TextBox>
<Label x:Name="label1"
Content="{Binding ElementName=textBox1, Path=Text, Mode=OneWay}" />
</StackPanel>
<StackPanel>
<TextBox x:Name="textBox1">Sample Text</TextBox>
<TextBox x:Name="textBox2"
Text="{Binding ElementName=textBox1, Path=Text, Mode=TwoWay, Update
SourceTrigger=PropertyChanged}" />
</StackPanel>
Ta s c hm MainPage nh sau
public MainPage()
{
InitializeComponent();
Person person = new Person();
Ta s c code x l nh sau
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:
folder = await
ApplicationData.Current.LocalFolder.GetFolderAsync("myFolder")
;
}
catch (FileNotFoundException exc)
{
folder = null;
}
if (folder == null)
{
MessageBox.Show("The folder doesn't exist");
}
}
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);
}
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);
}
}
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.
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.
Serialization
<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
VII. IsolatedStorageSettings
I. Tm hiu Brush
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;
<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)
);
<DataTemplate x:Key="ListBoxTemplate">
<StackPanel>
<TextBlock Text="Name"/>
<TextBlock Text="{Binding Path=Name}"/>
<TextBlock Text="Surname"/>
<TextBlock Text="{Binding Path=Surname}"/>
</StackPanel>
</DataTemplate>
3. Cc v tr t Resource
Ta s c 3 cch t
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
<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
BI 8. TM HIU SQLITE
I. t vn
II. Cc bc ci t, cu hnh
Ti y, ta kim tra nu file csdl khng tn ti, ta tin hnh to file csdl
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>();
}
}
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
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
<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.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<MediaElement x:Name="VideoPlayer"
Width="800"
Height="480"
Stretch="Fill" />
</Grid>
</phone:PhoneApplicationPage>
using Microsoft.Devices;
using System.Windows.Media;
base.OnNavigatedTo(e);
_camera.Initialized += _camera_Initialized;
_videoBrush.SetSource(_camera);
{
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()
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):
_camera.CaptureImageAvailable += _camera_CaptureImageAvailable;
CameraButtons.ShutterKeyPressed += CameraButtons_ShutterKeyPressed;
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);
});
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);
}
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
<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">
</phone:PhoneApplicationPage>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
namespace LearnMultimedia_ViewModel.ViewModels
if (PropertyChanged != null)
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
get
return _preview;
private set
_preview = value;
NotifyPropertyChanged("Preview");
public CameraViewModel()
_camera.Initialized += camera_Initialized;
_camera.CaptureImageAvailable += camera_CaptureImageAvailable;
_tempBrush.SetSource(_camera);
_camera.Initialized -= camera_Initialized;
_camera.CaptureImageAvailable -= camera_CaptureImageAvailable;
_camera.Dispose();
_camera = null;
_tempBrush = null;
this.Preview = null;
if (e.Succeeded)
Deployment.Current.Dispatcher.BeginInvoke(() =>
this.Preview = _tempBrush;
});
_captureName = fileName;
try
_camera.CaptureImage();
catch (InvalidOperationException) { }
library.SavePictureToCameraRoll(_captureName, e.ImageStream);
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 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);
}
}
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):
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using System.Windows.Resources;
using System.Windows;
FrameworkDispatcher.Update();
effect.Play();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
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 };
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();
}
}
}
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
get
return _preview;
private set
_preview = value;
NotifyPropertyChanged("Preview");
public CameraViewModel()
_camera.Initialized += camera_Initialized;
_camera.CaptureImageAvailable += camera_CaptureImageAvailable;
_tempBrush.SetSource(_camera);
_camera.CaptureStarted += _camera_CaptureStarted;
//gn thm s kin lng nghe khi no Camera chp hnh xong
_camera.CaptureCompleted += _camera_CaptureCompleted;
_camera.Initialized -= camera_Initialized;
_camera.CaptureImageAvailable -= camera_CaptureImageAvailable;
_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
_isCapturing = false;
_isCapturing = true;
if (e.Succeeded)
Deployment.Current.Dispatcher.BeginInvoke(() =>
this.Preview = _tempBrush;
});
else
_effects.Play(EffectTypes.Error);
if (!_isCapturing)
_captureName = fileName;
_camera.CaptureImage();
_effects.Play(EffectTypes.Click);
else
_effects.Play(EffectTypes.Error);
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
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;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows;
namespace LearnMultimedia_ViewModel.Converters
<phone:PhoneApplicationPage
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>
</phone:PhoneApplicationPage.Resources>
<Canvas.Children>
Source="/Assets/Images/focus_bracket.png"
Visibility="{Binding IsFocusing,Converter={StaticResource
BoolToVisibilityConverter}}">
</Image>
</Canvas.Children>
</Canvas>
</phone:PhoneApplicationPage>
get
return _isFocusing;
set
_isFocusing = value;
NotifyPropertyChanged("IsFocusing");
public CameraViewModel()
_camera.AutoFocusCompleted += _camera_AutoFocusCompleted;
_camera.AutoFocusCompleted -= _camera_AutoFocusCompleted;
Deployment.Current.Dispatcher.BeginInvoke(() =>
this.IsFocusing = false;
});
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:
Deployment.Current.Dispatcher.BeginInvoke(() =>
this.IsFocusing = true;
});
_camera.FocusAtPoint(x, y);
{
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);
}
}
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:
MediaElement:
MediaElement l mt Windows Phone Control cho php chng ta xem Video
v Audio.
<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>
MediaPlayerLauncher:
MediaPlayerLauncher l control rt hu dng, n mc nh c s dng trong
Windows Phone.
private void btnLaucher_Click(object sender, RoutedEventArgs e)
player.Media = new
Uri("Assets/videos/ARCastMDISilverlightGridComputing_ch9.wmv", UriKind.Relative);
player.Location = MediaLocationType.Install;
player.Show();
if (this.CanPlay())
mediaPlayer.Play();
FrameworkDispatcher.Update();
if (MediaPlayer.GameHasControl)
canPlay = true;
else
if (MessageBox.Show
("Is it ok to stop currently playing music and play our animal sounds?"
canPlay = true;
MediaPlayer.Pause();
else
canPlay = false;
return canPlay;
Stop (dng)
ngng m media, ta gi phng thc Stop nh di y:
mediaPlayer.Stop();
mediaPlayer.Position = System.TimeSpan.FromSeconds(0);
lblStatus.Text = "Stopped";
if (mediaPlayer.CanPause)
mediaPlayer.Pause();
lblStatus.Text = "Paused";
else
if (lblSoundStatus.Text.Equals("Sound On",
StringComparison.CurrentCultureIgnoreCase))
mediaPlayer.IsMuted = true;
else
mediaPlayer.IsMuted = false;
Margin="13,423,0,0" Name="mediaTimeline"
VerticalAlignment="Top" Width="443"
ValueChanged="mediaTimeline_ValueChanged"
S kin x l thay i thi gian pht, ta cn kim tra xem media cho php dch
chuyn:
RoutedPropertyChangedEventArgs<double> e)
if (mediaPlayer.CanSeek)
<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"
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.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Name="lblTitle"></TextBlock>
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;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework.Media;
Bc 1: Ch xem trc
Bc 2: Ch quay
_captureSource.Stop();
IsolatedStorageFile.GetUserStoreForApplication())
store.CreateFile(path).Close();
_fileSink.CaptureSource = _captureSource;
_captureSource.Start();
Bc 3: Ch pht li
_captureSource.Stop();
if (store.FileExists(path))
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
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.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
VerticalAlignment="Bottom" Margin="176,0,204,69"
Source="/Assets/sound/BachCPE_SonataAmin_1.wma" AutoPlay="False"/>
</Grid>
</phone:PhoneApplicationPage>
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();
FrameworkDispatcher.Update();
if (MediaPlayer.GameHasControl)
canPlay = true;
else
canPlay = true;
MediaPlayer.Pause();
else {
canPlay = false;
return canPlay;
AudioStreamingAgent:
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">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
</StackPanel>
</StackPanel>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
using Microsoft.Phone.BackgroundAudio;
BackgroundAudioPlayer.Instance.SkipPrevious();
if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState)
BackgroundAudioPlayer.Instance.Pause();
else
BackgroundAudioPlayer.Instance.Play();
BackgroundAudioPlayer.Instance.SkipNext();
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;
}
if (null != BackgroundAudioPlayer.Instance.Track)
{
txtCurrentTrack.Text = BackgroundAudioPlayer.Instance.Track.Title +
" by " + BackgroundAudioPlayer.Instance.Track.Artist;
}
}
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 = "";
using System.IO.IsolatedStorage;
using System.Windows.Resources;
if (!storage.FileExists(_fileName))
int byteCount;
file.Write(bytes, 0, byteCount);
CopyToIsolatedStorage();
Bm Ok ta s c kt qu nh hnh di y:
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:
"Nhc Trnh",
"Tun Ngc",
null),
"Nhc Trnh",
"Tun Ngc",
null),
"Nhc Trnh",
"Tun Ngc",
null),
// A remote URI
"Episode 29",
null)
};
currentTrackNumber = 0;
}
PlayTrack(player);
}
PlayTrack(player);
}
switch (playState)
case PlayState.TrackEnded:
//player.Track = GetPreviousTrack();
PlayNextTrack(player);
break;
case PlayState.TrackReady:
player.Play();
break;
NotifyComplete();
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();
}
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
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 :
S dng mu c nh sn:
Trong XAML:
color (invisible), use "00" for those digits (e.g. #000000FF). -->
S dng cc gi tr ARGB:
Trong XAML:
<Rectangle.Fill>
<SolidColorBrush>
<SolidColorBrush.Color>
</SolidColorBrush.Color>
</SolidColorBrush>
</Rectangle.Fill>
</Rectangle>
myRgbRectangle.Width = 50;
myRgbRectangle.Height = 50;
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).
Hnh nh v ta v mu
<Rectangle.Fill>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
diagonalFillRectangle.Width = 200;
diagonalFillRectangle.Height = 100;
LinearGradientBrush myLinearGradientBrush =
new LinearGradientBrush();
myLinearGradientBrush.GradientStops.Add(
myLinearGradientBrush.GradientStops.Add(
myLinearGradientBrush.GradientStops.Add(
myLinearGradientBrush.GradientStops.Add(
diagonalFillRectangle.Fill = myLinearGradientBrush;
<Rectangle.Fill>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
horizontalFillRectangle.Width = 200;
horizontalFillRectangle.Height = 100;
LinearGradientBrush myHorizontalGradient =
new LinearGradientBrush();
myHorizontalGradient.GradientStops.Add(
myHorizontalGradient.GradientStops.Add(
myHorizontalGradient.GradientStops.Add(
myHorizontalGradient.GradientStops.Add(
horizontalFillRectangle.Fill = myHorizontalGradient;
<Rectangle.Fill>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
verticalFillRectangle.Width = 200;
verticalFillRectangle.Height = 100;
LinearGradientBrush myVerticalGradient =
new LinearGradientBrush();
myVerticalGradient.GradientStops.Add(
myVerticalGradient.GradientStops.Add(
myVerticalGradient.GradientStops.Add(
myVerticalGradient.GradientStops.Add(
verticalFillRectangle.Fill = myVerticalGradient;
3. RadialGradientBrush
V d v hnh di y ta lm nh sau:
<Rectangle.Fill>
<RadialGradientBrush
GradientOrigin="0.5,0.5"
<RadialGradientBrush.GradientStops>
</RadialGradientBrush.GradientStops>
</RadialGradientBrush>
</Rectangle.Fill>
</Rectangle>
// Set the gradient center to the center of the area being painted.
radialGradient.RadiusX = 0.5;
radialGradient.RadiusY = 0.5;
radialGradient.Freeze();
// RadialGradientBrush.
aRectangle.Width = 200;
aRectangle.Height = 100;
aRectangle.Fill = radialGradient;
4. ImageBrush
Foreground="White" FontWeight="Bold"
FontSize="16pt" FontFamily="Verdana"
Content="Berries"
Padding="20"
HorizontalAlignment="Left">
<Button.Background>
image. -->
<ImageBrush
Viewport="0,0,0.5,0.5"
TileMode="FlipXY"
ImageSource="sampleImages\berries.jpg" />
</Button.Background>
</Button>
berriesButton.Foreground = Brushes.White;
berriesButton.FontWeight = FontWeights.Bold;
berriesButton.FontSize = (Double)sizeConverter.ConvertFromString("16pt");
berriesButton.Content = "Berries";
berriesButton.HorizontalAlignment = HorizontalAlignment.Left;
// Create an ImageBrush.
berriesBrush.ImageSource =
// the image.
berriesBrush.TileMode = TileMode.FlipXY;
berriesButton.Background = berriesBrush;
II. Canvas
1. c tnh ca Canvas
<Canvas Background="Transparent">
</Canvas>
myParentCanvas.Width = 400;
myParentCanvas.Height = 400;
myCanvas1.Background = Brushes.Red;
myCanvas1.Height = 200;
myCanvas1.Width = 200;
Canvas.SetTop(myCanvas1, 200);
Canvas.SetLeft(myCanvas1, 30);
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;
bitMap.PixelHeight, 0, 100);
ms.Seek(0, SeekOrigin.Begin);
library.SavePicture(string.Format("Images\\{0}.jpg",
Guid.NewGuid()), ms);
using System.Windows.Media;
1. Ellipse
Height="300"
Width="300"/>
ellipse.Width = 300;
ellipse.Height = 300;
mycanvas.Children.Add(ellipse);
Hnh minh ha
2. Rectangle
<Rectangle Fill="Yellow"
Height="275"
Width="350"
Stroke="Red"
StrokeThickness="15"
RadiusX="40"
RadiusY="30"/>
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.
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
Stroke="Red"
StrokeThickness="5"
X1="0" Y1="10"
X2="100" Y2="200"
/>
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>
Stroke="Red" StrokeThickness="10"
Fill="Yellow"
</Canvas>
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;
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"
polygon.StrokeThickness = 10.0;
6. Path
<Path.Data>
</Path.Data>
</Path>
</Canvas>
<Canvas>
</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..
http://multitouchvista.codeplex.com/releases/view/28979
<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"
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>
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_Circle.Resources;
using System.Windows.Input;
using System.Windows.Shapes;
using System.Windows.Media;
namespace LearnSingleTouch_Circle
{
public partial class MainPage : PhoneApplicationPage
{
<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"
DragStarted="GestureListener_DragStarted"
DragDelta="GestureListener_DragDelta"
DragCompleted="GestureListener_DragCompleted" />
</toolkit:GestureService.GestureListener>
<ListBox Name="listMenuItems"
Background="White"
Foreground="Black"
BorderBrush="Gray"
BorderThickness="5"
SelectionChanged="listMenuItems_SelectionChanged"
Width="150"
Height="150">
</ListBox>
</Popup>
</toolkit:WrapPanel>
</phone:PhoneApplicationPage>
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)
{
//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)
{
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_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;
{
//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;
}
4. Flicking i tng
if (e.OriginalSource.GetType().Equals(typeof(Ellipse)) &&
RemoveEventHandlers(targetEllipse);
mypanel.Children.Remove(targetEllipse);
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}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<Image Name="myPhoto"
Source="Assets\thanhdieu.jpg"
Height="300" Width="400">
<Image.RenderTransform>
</Image.RenderTransform>
</Image>
</Grid>
</phone:PhoneApplicationPage>
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_PinchImage.Resources;
namespace Learn_PinchImage
// Constructor
public MainPage()
InitializeComponent();
//BuildLocalizedApplicationBar();
init();
//gn s kin ng
listener.PinchStarted += new
EventHandler<PinchStartedGestureEventArgs>(GestureListener_PinchStarted);
listener.PinchDelta += new
EventHandler<PinchGestureEventArgs>(GestureListener_PinchDelta);
listener.PinchCompleted += new
EventHandler<PinchGestureEventArgs>(GestureListener_PinchCompleted);
myPhoto.Width, myPhoto.Height);
imageScale = photoTransform.ScaleX;
photoTransform.ScaleY = photoTransform.ScaleX;
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
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.
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
using Microsoft.Phone.Tasks;
using System.Threading.Tasks;
using System.Device.Location;
using Windows.Devices.Geolocation;
1. MapsTask
Thuc tnh M t
Start a im xut pht: C kiu LabeledMapLocation
End a im ch cn tm ti : C kiu 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:
start.Label = txtStart.Text;
end.Label = txtEnd.Text;
mapsDic.Start = start; // im bt u
mapsDic.Show();
mapDownloaderTask.Show();
mapUpdaterTask.Show();
4. Xc nh v tr hin ti trn bn
Bc 1: To Project
Giao din n gin nh sau:
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
</Grid>
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;
using System.Threading.Tasks;
namespace LearnWhereAmI
// Constructor
public MainPage()
InitializeComponent();
locator.DesiredAccuracy = PositionAccuracy.High;
GeoCoordinate coordinate =
new GeoCoordinate(position.Coordinate.Latitude,
position.Coordinate.Longitude);
return coordinate;
try
mapTask.Center = coordinate;
mapTask.Show(); // hin th bn
MessageBox.Show("Location is disabled.");
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:
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):
<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>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
</StackPanel>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
</mapControls:Map>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</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"
Grid.Column="1"
Grid.Row="2"/>
</Grid>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
using System.Device.Location;
using Microsoft.Phone.Tasks;
using Windows.Devices.Geolocation;
using System.Threading.Tasks;
using Windows.System;
using Microsoft.Phone.Maps.Controls;
txtwaiting.Visibility = Visibility.Visible;
locator.DesiredAccuracy = PositionAccuracy.High;
GeoCoordinate coordinate =
new GeoCoordinate(position.Coordinate.Latitude,
position.Coordinate.Longitude);
txtwaiting.Visibility = Visibility.Collapsed;
return coordinate;
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
try
((ApplicationBarIconButton)sender).IsEnabled = false;
theMap.Center = coordinate;
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 .
if (theMap != null)
theMap.ZoomLevel = e.NewValue;
Bc 4.7: Tin hnh vit lnh cho php xoay mn hnh ging nh mt sn
(Pitch):
if (theMap != null)
theMap.Pitch = e.NewValue;
if (theMap != null)
theMap.Heading = e.NewValue;
((Button)(sender)).Content = theMap.ColorMode.ToString();
MapColorMode.Dark;
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;
settingsPanel.Visibility =
:Visibility.Visible;
Tham chiu ti th vin Windows Phone Toolkit hoc ti trc tip t NuGet
Packages:
<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"
v :
using System.Windows.Media.Imaging;
using Microsoft.Phone.Maps.Toolkit;
2. To nhn a im hin ti
base.OnNavigatedTo(e);
try {
zoomSlider.Value = 15;
this.UserLocationMarker =
(UserLocationMarker)this.FindName("UserLocationMarker");
this.UserLocationMarker.GeoCoordinate = theMap.Center;
this.UserLocationMarker.Visibility = System.Windows.Visibility.Visible;
catch (Exception) {
if (result == MessageBoxResult.OK)
launchUri();
// Ly hnh nh t Resource ra
// a new MapOverlay
UriKind.RelativeOrAbsolute));
// To i tng MapOverlay
point.Y -= 38;
GeoCoordinate coordinate =
theMap.ConvertViewportPointToGeoCoordinate(point);
overlay.GeoCoordinate = coordinate;
if (layer == null)
Ta s dng th vin:
using Microsoft.Phone.Maps.Services;
routeQuery.Waypoints = locations;
routeQuery.QueryCompleted += routeQuery_QueryCompleted;
routeQuery.QueryAsync();
//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.
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.
V d HttpClient:
To mt project tn AsyncFirstExample:
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
// Constructor
public MainPage()
InitializeComponent();
resultsTextBox.Text +=
contentLength);
// GetStringAsync returns a Task<string>. That means that when you await the
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 then retrieves the string result from getStringTask.
// Any methods that are awaiting AccessTheWebAsync retrieve the length value.
return urlContents.Length;
void DoIndependentWork()
Bc 8: Kt thc
r hn ta xem thm v d th 2:
// ONE
// FOUR
// SIX
resultsTextBox.Text +=
// TWO
Task<string> getStringTask =
client.GetStringAsync("http://msdn.microsoft.com");
// THREE
// FIVE
return urlContents.Length;
ONE: Vo hm startButton_Click.
Gi lnh bt ng b AccessTheWebAsync.
Gi hm bt ng b HttpClient.GetStringAsync.
X l tr v kt qu.
Kt thc hm AccessTheWebAsync.
Bc THREE:
Bc FOUR:
Bc FIVE:
Bc SIX:
Quay tr v bin lu tr kt qu contentLength, xut kt qu v kt thc chng
trnh.
int contentLength = await getLengthTask;
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).
1. BackgroundWorker
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"
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>
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="10" >
Width="200" />
Width="200" />
</StackPanel>
</StackPanel>
</StackPanel>
</Grid>
</phone:PhoneApplicationPage>
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
// Constructor
public MainPage()
InitializeComponent();
bw.WorkerSupportsCancellation = true;
bw.WorkerReportsProgress = true;
bw.DoWork += bw_DoWork;
bw.ProgressChanged += bw_ProgressChanged;
bw.RunWorkerCompleted += bw_RunWorkerCompleted;
//BuildLocalizedApplicationBar();
//Nu khng bn
if (bw.IsBusy != true)
bw.RunWorkerAsync();
if (bw.WorkerSupportsCancellation == true)
//gi lnh hy
bw.CancelAsync();
if ((worker.CancellationPending == true))
e.Cancel = true;
break;
else
System.Threading.Thread.Sleep(500);
worker.ReportProgress(i * 10);
if (e.Cancelled == true)
this.tbProgress.Text = "Canceled!";
else
this.tbProgress.Text = "Done!";
XAML nh sau:
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}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True">
</StackPanel>
</StackPanel>
<ScrollViewer>
</ScrollViewer>
</StackPanel>
</phone:PhoneApplicationPage>
Source code x l:
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 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)
{
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
{
txtProgressBar.Text += "-Done!";
}
}
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.
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.
To mt Task
int s = 0;
s += i;
int s = 1;
s *= i;
string s = "";
s = await sTask;
t.Start();
X l coding:
txtTrace.Text = "";
var t2 = t1.ContinueWith(DoOnSecond);
t1.Start();
Dispatcher.BeginInvoke(()=>txtTrace.Text+=s+"\n");
showInfor(s);
System.Threading.Thread.Sleep(3000);
showInfor(s);
showInfor(s);
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.
txtTrace.Text = "";
var t2 = t1.ContinueWith(DoOnSecond);
t1.Start();
Nhn kt qu tr v t Task
if (n <= 2) return 1;
MessageBox.Show("Fib="+task.Result);
if (n % i == 0) return false;
return true;
int n = 55;
if (task.Result == true)
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;
});
f0.Start();
MessageBox.Show(s);
double d = 0.0;
d += Math.Pow(mean - n, 2);
int n = 5;
int s = 0;
s += i;
return s;
});
task.Wait();
MessageBox.Show("s="+task.Result);
return x * 2;
Task.WaitAll(task1, task2);
MessageBox.Show("x ca task1="+task1.Result);
// You can use this code to create either a WPF app or a Windows Store app.
// To create this example as a Windows Store app, you must add using
// To create this example as a desktop app, you must add a reference and a
// an await.
try
// You can do other work here that doesn't require the result from
// ExampleMethodAsync. . . .
// Wait for intTask to complete, and then access the int result.
catch (Exception)
Task<string> contentsTask =
httpClient.GetStringAsync("http://msdn.microsoft.com");
// After contentTask completes, you can calculate the length of the string.
//// You can combine the previous sequence into a single statement.
// ExampleMethodAsync (in this case, StartButton_Click) can get the integer result.
return exampleInt;
// Sample output:
// Length: 53292
V d await:
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.
I. Background tasks
Windows Phone xy dng flatform chy nn cho php ngi s dng tng tc
theo 2 kch bn nh sau:
1. Alarms
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:
alarm.BeginTime = DateTime.Now.AddSeconds(5);
alarm.ExpirationTime = DateTime.Now.AddSeconds(10);
//a vo ScheduledActionService
ScheduledActionService.Add(alarm);
Source Code:
try
alarm.BeginTime = DateTime.Now.AddSeconds(5*i);
ScheduledActionService.Add(alarm);
MessageBox.Show(ex.Message);
ScheduledActionService.GetActions<Alarm>();
IEnumerable<Alarm> oldAlarms =
ScheduledActionService.GetActions<Alarm>();
ScheduledActionService.Remove(alarm.Name);
IEnumerable<Alarm> oldAlarms =
ScheduledActionService.GetActions<Alarm>();
ScheduledActionService.Remove(alarm.Name);
IEnumerable<Alarm> oldAlarms =
ScheduledActionService.GetActions<Alarm>();
if(alarm.Name=="ten1")
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:
Bc 1: To mt i tng Reminder
Bc 2: Thit lp cc thuc tnh cho Reminder
Bc 3: a Alarm vo ScheduledActionService
{
var uniqueName = Guid.NewGuid().ToString();
//to i tng reminder
try
{
//a vo ScheduledActionService
ScheduledActionService.Add(reminder);
}
MessageBox.Show(ex.Message);
}
Khi Reminder hin th ln, ngi s dng c th thit lp thm thng tin.
ScheduledActionService.Remove(r.Name);
//thi gian bt u
reminder.BeginTime = DateTime.Now.AddSeconds(3);
reminder.ExpirationTime = DateTime.Now.AddSeconds(10);
//tiu
ScheduledActionService.Add(reminder);
base.OnNavigatedTo(e);
string hinh=NavigationContext.QueryString["hinh"];
myimage.Source = img;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Phone.BackgroundTransfer;
Bc 2: To IsolatedStorageFile
public MainPage()
isf = IsolatedStorageFile.GetUserStoreForApplication();
BackgroundTransferRequest btr;
BackgroundTransferService.Add(btr);
btr.TransferProgressChanged += btr_TransferProgressChanged;
btr.TransferStatusChanged += btr_TransferStatusChanged;
// Match the progress bar to the filesize and current download status.
Dispatcher.BeginInvoke(() =>
// tng s byte s ti
progressBar.Maximum = btr.TotalBytesToReceive;
progressBar.Value = btr.BytesReceived;
});
// ti hon thnh
if (btr.TransferStatus == TransferStatus.Completed) {
truy sut ton tp tin c lu vo thit b sau khi ti xong ta dng cch sau:
foreach(BackgroundTransferRequest res in
BackgroundTransferService.Requests)
res.BytesReceived;
res.BytesSent;
res.DownloadLocation;
res.TotalBytesToReceive;
btr = BackgroundTransferService.Requests.FirstOrDefault();
if (btr.TransferStatus == TransferStatus.Completed)
Dispatcher.BeginInvoke(() =>
isf.OpenFile(btr.DownloadLocation.ToString(),
FileMode.Open, FileAccess.Read))
mediaElement.SetSource(file);
mediaElement.Play();
});
<phone:PhoneApplicationPage
x:Class="BackgroundTransferDemo.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.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
</StackPanel>
<StackPanel Orientation="Horizontal">
</StackPanel>
</Border>
</StackPanel>
</Grid>
</phone:PhoneApplicationPage>
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
new Uri(@"http://media.ch9.ms/ch9/4b58/de9f7501-2a51-4875-8b2f-
9f4d014b4b58/IWP22PtorrBkgrndAgnt_ch9.wmv",
UriKind.Absolute);
public MainPage()
InitializeComponent();
isf = IsolatedStorageFile.GetUserStoreForApplication();
BackgroundTransferService.Add(btr);
btr.TransferProgressChanged += btr_TransferProgressChanged;
btr.TransferStatusChanged += btr_TransferStatusChanged;
downloadButton.IsEnabled = false;
btr = BackgroundTransferService.Requests.FirstOrDefault();
if (btr == null) {
downloadButton.IsEnabled = true;
return;
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.
Dispatcher.BeginInvoke(() =>
progressBar.Maximum = btr.TotalBytesToReceive;
progressBar.Value = btr.BytesReceived;
});
if (btr.TransferStatus == TransferStatus.Completed) {
UpdateUi();
Dispatcher.BeginInvoke(() =>
progressBar.Value = btr.BytesReceived;
isf.OpenFile(btr.DownloadLocation.ToString(),
FileMode.Open, FileAccess.Read)) {
mediaElement.SetSource(file);
});
playButton.IsEnabled = true;
mediaElement.Play();
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
<Tasks>
<ExtendedTask Name="BackgroundTask">
<BackgroundServiceAgent Specifier="ScheduledTaskAgent"
Name="GeoAgent" Source="GeoAgent" Type="GeoAgent.ScheduledAgent" />
</ExtendedTask>
</Tasks>
task.ExpirationTime = DateTime.Now.AddDays(1);
Debug.WriteLine(task.LastExitReason.ToString());
if (ScheduledActionService.Find(agentId) != null)
ScheduledActionService.Remove(agentId);
try
ScheduledActionService.Add(task);
ScheduledActionService.LaunchForTest(agentId,
TimeSpan.FromSeconds(10));
// No action required: the system prompts the user when the hard limit of
periodic tasks has been reached.
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.Message);
// 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.
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:
AudioStreamingAgent:
Khi dng Agent ny s to ra stream audio trong ng dng thng qua.
VI. Kt lun
Ta nghin cu nhng background m Windows Phone thng s dng, n h
tr 4 loi Background task nh sau:
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:
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:
<TemplateFlip>
Assets\Tiles\FlipCycleTileSmall.png
</SmallImageURI>
<Count>0</Count>
Assets\Tiles\FlipCycleTileMedium.png
</BackgroundImageURI>
<Title>My Title</Title>
<BackContent></BackContent>
</BackBackgroundImageURI>
<BackTitle></BackTitle>
Assets\Tiles\FlipCycleTileLarge.png
</LargeBackgroundImageURI>
<LargeBackContent />
</LargeBackBackgroundImageURI>
</DeviceLockImageURI>
<HasLarge>True</HasLarge>
</TemplateFlip>
</PrimaryToken>
Count = 6
};
if (tile == null)
else
tile.Update(tileData);
};
1. Iconic
<TemplateIconic>
Assets\Tiles\IconicTileSmall.png
</SmallImageURI>
<Count>6</Count>
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>
Hnh minh ha y :
Count = 6,
WideContent1 = "LargeContent1",
WideContent2 = "LargeContent2",
WideContent3 = "LargeContent3",
};
if (oldTile == null)
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.
<TemplateFlip>
Assets\Tiles\h1XSmall.jpg
</SmallImageURI>
<Count>6</Count>
Assets\Tiles\h2XSmall.jpg
</BackgroundImageURI>
<Title>Surf Sites</Title>
Assets\Tiles\h3XSmall.jpg
</BackBackgroundImageURI>
<BackTitle>Surf Advisories</BackTitle>
Assets\Tiles\h4XSmall.jpg
</LargeBackgroundImageURI>
Assets\Tiles\h5XSmall.jpg
</LargeBackBackgroundImageURI>
<DeviceLockImageURI IsRelative="true"
IsResource="false"></DeviceLockImageURI>
<HasLarge>True</HasLarge>
</TemplateFlip>
SmallBackgroundImage =
BackgroundImage =
Count = 6,
BackBackgroundImage =
WideBackgroundImage =
WideBackBackgroundImage =
};
if (oldTile == null)
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
<TemplateCycle>
Assets\Tiles\h1XSmall.jpg
</SmallImageURI>
<Title>Surf Sites</Title>
Assets\Tiles\h2XSmall.jpg
</Photo01ImageURI>
Assets\Tiles\h3XSmall.jpg
</Photo02ImageURI>
Assets\Tiles\h4XSmall.jpg
</Photo03ImageURI>
Assets\Tiles\h5XSmall.jpg
</Photo04ImageURI>
Assets\Tiles\h6XSmall.jpg
</Photo05ImageURI>
Assets\Tiles\h7XSmall.jpg
</Photo06ImageURI>
</Photo07ImageURI>
</Photo08ImageURI>
</Photo09ImageURI>
<Count>6</Count>
<HasLarge>True</HasLarge>
</DeviceLockImageURI>
</TemplateCycle>
SmallBackgroundImage =
Count = 6,
},
};
if (oldTile == null) {
else
oldTile.Update(tileData);
tileSchedule.StartTime = DateTime.Now;
tileSchedule.Recurrence = UpdateRecurrence.Interval;
tileSchedule.Interval = UpdateInterval.EveryHour;
tileSchedule.RemoteImageUri = remoteUri;
tileSchedule.Start();
UpdateRecurrence.Onetime // lp 1 ln
y ta c th thit lp Interval:
UpdateInterval.EveryDay
UpdateInterval.EveryHour
UpdateInterval.EveryMonth
UpdateInterval.EveryWeek
ngng update:
if (primaryTile != null)
shellTileSchedule.Start();
shellTileSchedule.Stop();
if (tile != null)
SmallBackgroundImage = smallBunnyUri,
BackgroundImage = mediumBunnyUri,
WideBackgroundImage = largeBunnyUri,
Count = 6,
BackBackgroundImage = mediumBunnyUri,
WideBackBackgroundImage = largeBunnyUri
};
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
if (appManifest != null)
if (primaryTokenNode != null)
if (templateNode.Name == "TemplateFlip")
templateType = TemplateType.TemplateFlip;
templateType = TemplateType.TemplateIconic;
templateType = TemplateType.TemplateCycle;
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.
to hnh nn Lock Screen cho in thoi, trc tin ta cn phi cung cp intent
cho Manifest file:
<Extensions>
<Extension ExtensionName="LockScreen_Background"
ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default"
/>
</Extensions>
Sau khi cu hnh xong Manifest phn trc, ta tin hnh vit coding behind
lm Lock Screen nh sau:
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.
var op = await
Windows.Phone.System.UserProfile.LockScreenManager.RequestAccessAsync();
isProvider = op ==
Windows.Phone.System.UserProfile.LockScreenRequestResult.Granted;
if (isProvider)
// At this stage, the app is the active lock screen background provider.
Windows.Phone.System.UserProfile.LockScreen.SetImageUri(uri);
var currentImage =
Windows.Phone.System.UserProfile.LockScreen.GetImageUri();
else
System.Diagnostics.Debug.WriteLine(ex.ToString());
LockHelper("Assets/hinh/h1.jpg", true);
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;
if (currentImage.ToString().EndsWith("_A.jpg"))
fileName = "LiveLockBackground_B.jpg";
else
fileName = "LiveLockBackground_A.jpg";
Sau khi bm Open App th ng dng ca ta s c triu gi, ta nn vit lnh trong
OnNavigatedTo x l:
base.OnNavigatedTo(e);
bool lockscreenValueExists =
NavigationContext.QueryString.TryGetValue(lockscreenKey, out lockscreenValue);
if (lockscreenValueExists)
// Navigate the user to your app's lock screen settings screen here,
</DeviceLockImageURI>
<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>
T solution ta add thm mt Project (New Project -> Windows Phone Scheduled
Task Agent.)
PeriodicTask periodicTask;
periodicTask = ScheduledActionService.Find(periodicTaskName) as
PeriodicTask;
if (periodicTask != null)
try
ScheduledActionService.Remove(periodicTaskName);
catch (Exception)
periodicTask.ExpirationTime = DateTime.Now.AddDays(14);
try
ScheduledActionService.Add(periodicTask);
#if(DEBUG_AGENT)
ScheduledActionService.LaunchForTest(periodicTaskName,
TimeSpan.FromSeconds(30));
#endif
// No user action required. The system prompts the user when the hard
limit of periodic tasks has been reached.
catch (SchedulerServiceException)
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";
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";
LockScreenChange(Imagename, true);
#if(DEBUG_AGENT)
ScheduledActionService.LaunchForTest(task.Name,
TimeSpan.FromSeconds(30));
#endif
// Call NotifyComplete to let the system know the agent is done working.
NotifyComplete();
client.OpenReadCompleted += new
OpenReadCompletedEventHandler(client_OpenReadCompleted);
// 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));
bitmap.SetSource(e.Result);
//img.Source = bitmap;
// Create virtual store and file stream. Check for duplicate tempJPEG files.
if (myIsolatedStorage.FileExists(tempJPEG))
myIsolatedStorage.DeleteFile(tempJPEG);
IsolatedStorageFileStream fileStream =
myIsolatedStorage.CreateFile(tempJPEG);
sri = Application.GetResourceStream(uri);
//bitmap.SetSource(sri.Stream);
fileStream.Close();
LockScreenChange("DownloadedWalleper.jpg", false);
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:
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>
<description>
<img src="http://farm1.static.flickr.com/103/263966036_ee04032cc8.jpg"
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
myRSS.DownloadStringCompleted += new
DownloadStringCompletedEventHandler(myRSS_DownloadStringCompleted);
myRSS.DownloadStringAsync(new Uri(rssURL));
if
(Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsNetworkA
vailable)
.ToArray();
if (imgarray.Length > 0)
imageCount = 0;
// download images
DownloadImagefromServer(Convert.ToString(imgarray[0]));
else
else
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:
client.OpenReadCompleted += new
OpenReadCompletedEventHandler(client_OpenReadCompleted);
bitmap.SetSource(e.Result);
// Create virtual store and file stream. Check for duplicate tempJPEG files.
if (myIsolatedStorage.FileExists(tempJPEG))
myIsolatedStorage.DeleteFile(tempJPEG);
IsolatedStorageFileStream fileStream =
myIsolatedStorage.CreateFile(tempJPEG);
sri = Application.GetResourceStream(uri);
System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, fileStream,
wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
if (imageCount == imgarray.Length - 1)
LockScreenChange("DownloadedWalleper_0.jpg", false);
// start service
StartPeriodicAgent();
imageCount++;
DownloadImagefromServer(Convert.ToString(imgarray[imageCount]));
if (!LockScreenManager.IsProvidedByCurrentApplication)
// If you're not the provider, this call will prompt the user for permission.
await LockScreenManager.RequestAccessAsync();
if (LockScreenManager.IsProvidedByCurrentApplication)
// At this stage, the app is the active lock screen background provider.
LockScreen.SetImageUri(uri);
else
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)
{
}
}
// 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.
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.
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.
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.
[]
<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:sequence>
</s:complexType>
</s:element>
</s:schema>
</wsdl:types>
[]
<s:element name="HelloWorld">
<s:complexType />
</s:element>
<s:element name="HelloWorldResponse">
<s:complexType>
<s:sequence>
</s:sequence>
</s:complexType>
</s:element>
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
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
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.
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.
Sau khi chn New Item, mn hnh Add New Item s hin th ra nh bn di:
/// <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";
}
}
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:
Kt qu:
Bm vo nt Invoke Ta s c kt qu nh hnh di y:
[Serializable]
get;
set;
get;
set;
Sau tin hnh vit coding cho Webservice gi danh sch i tng ny v
Client:
[WebMethod]
return ds;
Kt qu khi ta bm vo hm GetSampleList:
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.
Ta c kt qu khi bm OK:
Ta chn khtn_test/ bn mn hnh phi ta chn tab Content View/ bm chut phi
vo MyWebService.asmx/ chn Browse:
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):
Ta g vo cmd ri bm nt OK:
Mn hnh command line hin th ln ta g lnh ipconfig:
<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">
<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>
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;
namespace Goi_DichVu_PTB2
public MainPage()
InitializeComponent();
int a = 0, b = 0, c = 0;
try
if (client == null)
a = int.Parse(txta.Text);
b = int.Parse(txtb.Text);
c = int.Parse(txtc.Text);
client.GiaiPTB2Async(a, b, c);
client.GiaiPTB2Completed += client_GiaiPTB2Completed;
string s = e.Result;
txtkq.Text = s;
txta.Text = "";
txtb.Text = "";
txtc.Text = "";
txtkq.Text = "";
txta.Focus();
while (((PhoneApplicationFrame)App.Current.RootVisual).CanGoBack)
((PhoneApplicationFrame)App.Current.RootVisual).RemoveBackEntry();
IsolatedStorageSettings.ApplicationSettings.Save();
Application.Current.Terminate();
7- Hm xa Catalog theo ID
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]
16
17 ProductManagerDataContext db = null;
18 public mywebservice () {
19
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)
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)
Trong Project Web Service, m tp tin Web.config v thay th bng chui trn:
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:
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:
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">
<ListBox x:Name="mylistbox"></ListBox>
</StackPanel>
</phone:PhoneApplicationPage>
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
// Constructor
public MainPage()
InitializeComponent();
//BuildLocalizedApplicationBar();
client.getListCatalogAsync();
client.getListCatalogCompleted += client_getListCatalogCompleted;
mylistbox.Items.Clear();
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.
BI 2. WCF V CLOUD
(Windows Communication Foundation v Windows Azure
Mobile Service)
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 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.
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.
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
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.
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).
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.
WebService WCF
S dng thuc tnh [WebService] trong S dng thuc tnh [ServiceContract] thay
class th.
2. Cch to WCF
T Menu File/ chn New/ chn Project (hoc nhn t hp phm Ctrl + Shift +N):
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:
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).
DataMember
Fault Contracts
WCF cho php chng ta nh ngha hnh vi s thc thi khi c li xy ra trong WCF.
[ServiceContract]
[OperationContract]
[FaultContract(typeof(FaultInfo))]
[DataContract()]
[DataMember()]
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.
Kt qu :
http://169.254.80.80/khtn_testwcf/Service1.svc :
<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"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
</StackPanel>
</phone:PhoneApplicationPage>
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();
}
}
Tip theo l Project ca ta cn tham chiu ti Service Model nh sau (bm chut
phi vo References/ chn Add Reference):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace KHTN_WCF_WAS
[ServiceContract]
interface ITest
[OperationContract]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KHTN_WCF_WAS
return a + b;
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.ServiceModel;
using System.ServiceModel.Description;
namespace KHTN_WCF_WAS
public Form1()
InitializeComponent();
sv.HttpGetEnabled = true;
sv.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(sv);
try
host.Open();
host = null;
catch (AddressAlreadyInUseException)
host = null;
MessageBox.Show("a ch vo ri");
catch (Exception) {
host = null;
MessageBox.Show("Li g ");
Tin hnh bin dch ri thc thi (bm chut phi vo .exe v Run as Administrator):
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:
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
{ ..
int a = int.Parse(txtSoa.Text);
int b = int.Parse(txtSob.Text);
client.cong2soAsync(a, b);
client.cong2soCompleted += client_cong2soCompleted;
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.
Sau khi nhp thng tin th bm next gc phi di cng mn hnh qua
trang mi.
Lm vic vi Data
Ta c bng Data Type Mappings
public int Id
{ get; set; }
{ get; set; }
{ get; set; }
[DataContract]
[DataTable("HoneyDoThis")]
[DataMember(Name = "Id")]
[DataMember(Name = "Instructions")]
[DataMember(Name = "DidYouDoIt")]
[IgnoreDataMember]
Chi tit hc vin c th xem thm trong gio trnh Windows Phone 8 Recipes.
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 {
Update:
function update(item, user, request) {
request.execute();
Delete:
function del(id, user, request) {
if(id % 2 === 0) {
} else {
request.execute();
Read:
function read(query, user, request) {
request.execute();
request.execute();
request.execute();
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.
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.
1. Toast Notifications
2. Tile Notifications
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.
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.
Dng cp nht: V d ch
Tile No Yes m s email mi, m ngi
comment trn Facebook
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:
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.
<wp:Notification xmlns:wp="WPNotification">
<wp:Toast>
<wp:Text1>Notification Title</wp:Text1>
<wp:Text2>Notification Text</wp:Text2>
<wp:Param>Parameter List</wp:Param>
</wp:Toast>
</wp:Notification>
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
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("<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();
InitParams();
try
if (txtPushNotificationURL.Text == string.Empty)
return;
if (txtPushNotificationTitle.Text == string.Empty ||
txtPushNotificationText.Text == string.Empty)
return;
HttpWebRequest sendNotificationRequest =
(HttpWebRequest)WebRequest.Create(url);
sendNotificationRequest.Method = "POST";
sendNotificationRequest.ContentType = "text/xml";
//to X-WindowsPhone-Target
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target",
"toast");
//to X-NotificationClass
sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
sendNotificationRequest.ContentLength = strBytes.Length;
requestStream.Write(strBytes, 0, strBytes.Length);
HttpWebResponse response =
(HttpWebResponse)sendNotificationRequest.GetResponse();
MessageBox.Show(ex.ToString());
<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>
Sau y gio trnh s hng dn tng bc coding cho Mobile client nhn
Notification t Server thng qua Service nh th no:
using Microsoft.Phone.Notification;
using System.Diagnostics;
Uri channelUri;
get
return channelUri;
set
channelUri = value;
OnChannelUriChanged(value);
Dispatcher.BeginInvoke(() =>
});
SetupChannel();
EventHandler<NotificationChannelUriEventArgs>(httpChannel_ChannelUriUpdated
);
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;
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.
Push Notification t
Server gi v.
<wp:Param>/StockChart.xaml?companyName=MSFT</wp:Param>
Chi tit:
"<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>";
<wp:Param>?companyName=MSFT</wp:Param>
Chi tit:
"<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>";
base.OnNavigatedTo(e);
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.
<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"
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.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
</Grid>
</phone:PhoneApplicationPage>
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;
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";
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);
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]);
}
}
});
}
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;
}
}
}
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
builder.Append("<wp:Notification xmlns:wp=\"WPNotification\">");
builder.Append(" <wp:Tile>");
builder.Append(" <wp:BackgroundImage>{0}</wp:BackgroundImage>");
builder.Append(" <wp:Count>{1}</wp:Count>");
builder.Append(" <wp:Title>{2}</wp:Title>");
builder.Append("
<wp:BackBackgroundImage>{5}</wp:BackBackgroundImage>");
builder.Append(" </wp:Tile>");
builder.Append("</wp:Notification>");
TilePushXML = builder.ToString();
public Form2()
InitializeComponent();
InitParams();
try
if (txtPushNotificationURL.Text == string.Empty)
return;
return;
return;
if (listboxBackgroundImage.SelectedIndex == -1 ||
listboxBackBackgroundImage.SelectedIndex == -1)
return;
HttpWebRequest sendNotificationRequest =
(HttpWebRequest)WebRequest.Create(url);
sendNotificationRequest.Method = "POST";
sendNotificationRequest.ContentType = "text/xml";
//to X-WindowsPhone-Target
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target",
"token");
//to X-NotificationClass
sendNotificationRequest.Headers.Add("X-NotificationClass", "1");
sendNotificationRequest.ContentLength = strBytes.Length;
requestStream.Write(strBytes, 0, strBytes.Length);
HttpWebResponse response =
(HttpWebResponse)sendNotificationRequest.GetResponse();
MessageBox.Show(str);
MessageBox.Show(ex.ToString());
//picBackgroundImage.ImageLocation=listboxBackgroundIamge.Text;
Thng dng nhn mu tin khi ang chy ng dng. Raw Notifications yu cu
ng dng phi ang trong ch Foreground lifetime.
<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"
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>
</phone:PhoneApplicationPage>
Ni dung File c
Push t Server
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_PushRawNotification.Resources;
using Microsoft.Phone.Notification;
using System.Diagnostics;
namespace Learn_PushRawNotification
Uri channelUri;
set
channelUri = value;
OnChannelUriChanged(value);
Dispatcher.BeginInvoke(() =>
});
// Constructor
public MainPage()
InitializeComponent();
SetupChannel();
try
httpChannel = HttpNotificationChannel.Find(channelName);
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;
httpChannel.HttpNotificationReceived += new
EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNotificationReceived);
else
httpChannel.ChannelUriUpdated += new
EventHandler<NotificationChannelUriEventArgs>(httpChannel_ChannelUriUpdated
);
httpChannel.ErrorOccurred += new
EventHandler<NotificationChannelErrorEventArgs>(httpChannel_ExceptionOccurre
d);
httpChannel.HttpNotificationReceived += new
EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNotificationReceived);
httpChannel.Open();
Dispatcher.BeginInvoke(() =>
if (e.Collection != null)
(Dictionary<string, string>)e.Collection;
collection[elementName]);
});
Debug.WriteLine(e.Message);
ChannelUri = e.ChannelUri;
System.IO.StreamReader(e.Notification.Body);
Dispatcher.BeginInvoke(() =>
txtData.Text=reader.ReadToEnd();
});
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()
{
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
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.
V d ly danh sch Songs t thit b v Play 1 Song u tin trong danh sch:
II. Constructors
Constructor M t
MediaLibrary () Khi to i tng MediaLibrary
MediaLibrary (MediaSource) Khi to i tng MediaLibrary, s dng
MediaSource to mi MediaLibrary
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
1. Albums
album.Name;
album.Songs;
album.Artist;
2. Artists
artist.Songs;
}
}
3. Genres
4. IsDisposed
}
}
5. MediaSource
ICollection<MediaSource> mediaSources =
MediaSource.GetAvailableMediaSources();
source_assign.Name;
source_assign.MediaSourceType;
6. Pictures
picture.Name;
picture.Album;
picture.GetImage;
7. Playlists
playlist.Name;
playlist.Songs;
playlist.Duration;
8. RootPictureAlbum
picAlbum.Name;
picAlbum.Pictures;
picAlbum.Albums;
9. SavedPictures
picture.Name;
picture.Album;
picture.GetImage;
10. Songs
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"
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">
<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;
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 MainPage()
InitializeComponent();
songs = library.Songs;
mylistbox.Items.Add(song.Name);
if (mylistbox.SelectedIndex == -1)
return;
MediaPlayer.Stop();
MediaPlayer.Play(song);
IV. Methods
1. GetPictureFromToken
2. SavePicture
grayscaleImage.SaveJpeg(targetJpegStream,
grayscaleImage.PixelWidth,
grayscaleImage.PixelHeight, 0, 100);
targetJpegStream.Seek(0, SeekOrigin.Begin);
mediaLibrary.SavePicture(grayscaleFilename, targetJpegStream);
}
});
3. SavePictureToCameraRoll
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
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.
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 .
1. Cm bin in dung
2. Cm bin tim cn
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
3. Cm bin nh sng
4. Cm bin nh
5. Gia tc k
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.
8. Cm bin vn tay
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.
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.
<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"
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:
Bc 1: To Project nh hnh di y:
<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.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
</StackPanel>
<ListBox
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel x:Name="PhotoPanel"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Image
Width="200" Height="150"
Source="{Binding}" CacheMode="BitmapCache"
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
using System.Collections.Generic;
using Microsoft.Phone.Controls;
namespace WrapOrientation
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;
Cc bc s dng Accelerometer:
Bc 1:S dng cc th vin:
using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;
if (accelerometer == null)
accelerometer.TimeBetweenUpdates = TimeSpan.FromMilliseconds(10);
accelerometer.CurrentValueChanged +=
accelerometer_CurrentValueChanged;
try {
accelerometer.Start();
statusText.Text = "started";
appBarStopGo.Text = "stop";
statusText.Text = ex.ToString();
else {
accelerometer.CurrentValueChanged -=
accelerometer_CurrentValueChanged;
try
accelerometer.Stop();
accelerometer = null;
statusText.Text = "stopped";
appBarStopGo.Text = "go";
statusText.Text = ex.ToString();
Dispatcher.BeginInvoke(() =>
accelerometer.TimeBetweenUpdates.Milliseconds);
});
3. Compass Cm bin la bn s
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;
compass.TimeBetweenUpdates = TimeSpan.FromMilliseconds(33);
compass.CurrentValueChanged += compass_CurrentValueChanged;
// for calibration.
compass.Calibrate += compass_Calibrate;
compass.Start();
compass.Stop();
else{
Bc 5: X l cc s kin:
// For calibration.
// For calibration.
headingAccuracy = Math.Abs(e.SensorReading.HeadingAccuracy);
//x l headingAccuracy
compass.Calibrate -= compass_Calibrate;
Cc bc s dng Gyroscope:
Bc 1: S dng cc th vin
using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;
gyroscope.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);
gyroscope.CurrentValueChanged += gyroscope_CurrentValueChanged;
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>
Dispatcher.BeginInvoke(() =>
});
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.
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
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.
What's new
2. Truy vn Contact
Single-contact choosers
Querying contacts programmatically
c th truy vn c Contact, ta dng th vin : Microsoft.Phone.Tasks
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;
}
emailAddressChooser.Show();
Bc 4: X l s kin Complete t EmailResult
void emailAddressChooser_Completed
(object sender, EmailResult e)
{
if (e.TaskResult != TaskResult.OK)
return;
emailAddressDisplayNameTextBlock.Text = e.DisplayName;
emailAddressTextBlock.Text = e.Email;
sendEmailButton.IsEnabled = true;
}
addressChooser.Show();
Bc 4: X l s kin Complete t AddressResult
V d cch s dng:
contactsDb.SearchAsync
(searchTermTextBox.Text, FilterKind.DisplayName, null);
FilterKind.DisplayName;
FilterKind.EmailAddress;
FilterKind.Identifier;
FilterKind.None;
FilterKind.PhoneNumber;
FilterKind.PinnedToStart;
3. Thm mi Contact
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
return;
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
calendar.SearchCompleted += calendar_SearchCompleted;
Sau y l coding chi tit cho hm tm kim thi gian cuc hn:
if ((e.EndTimeInclusivepreviousAppointment.EndTime).TotalMinutes >=
lengthOfAppointmentInMinutes)
{
AvailableTime = previousAppointment.EndTime;
PreviousAppointment = previousAppointment;
return;
}
}
2. To mi cuc hn
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.
Bc 1: ng nhp vo https://www.dreamspark.com/
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
Nhp chn ng v tip tc, n bc thanh ton bn chn Use a Token sau
nhp code vo thanh ton l 0 VND:
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:
Sau khi Buil thnh cng cc bn xem phn output s thy thng bo:
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:
Bc 5.1: Nhp tn cho ng dng v chn Reserve app name kim tra
tn APP hp l
ICON Cho APP trn STORE: Lu l phi ng kch thc quy nh ( 300300)