You are on page 1of 17

Infoway

Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT

CHNG VII:
LM VIC VI D LIU TRONG SILVERLIGHT
1 Cc cng ngh truy cp d liu trong Silverlight
Trong cc ng dng trn nn tng Silverlight 2 c cho php truy cp d liu theo nhiu cng ngh hay
phng thc khc nhau. Cch n gin nht hin th v tng tc ngi dng l Data Binding.
Cch khc na truy cp d liu t ng dng my khch, nh l mt s thay th ti u ca cookie,
chng ta c th s dng cng ngh Isolated Storage. Silverlight cng cho php c v ghi trn d liu
XML bng cch s dng XmlReader hoc LINQ to XML . Ngoi ra cch ph bin trong cc ng dng
hin nay thng lm l truy cp d liu SQL Server thng qua cc cng ngh Web service, WCF v
ADO.Net Data Service.
Trong chng ny chng ta s tm hiu mt s cng ngh truy cp d liu sau:

- Data Binding
- Isolated Storage
- X l d liu XML vi LINQ to XML
- Truy cp c s d liu SQL Server vi Web Service(WCF)
2 S dng Data Binding

Data Binding cung cp mt cch n gim cho ng dng nn tng silverlight truy cp v
tng tc ti d liu. Thng thng Data Binding qun l d liu theo lung gia ngi dng
v cc i tng d liu. Tc k khi mt binding c to v d liu c thay i, th giao din
ngi dng cng c trnh by v thay i theo d liu(t ng nh x ). Tng t khi
ngi dng thay i trn giao din th n cng c th lm thay i i tng d liu. V d
nh khi ngi dng thay i gi tr trn mt TextBox, gi tr d liu cng t ng cp nht
theo thay i .
o S lin kt gia giao din ngi dng v d liu


- Binding Object: Nh l mt xc tc giaBindingTarget v Binding Source
- Binding Source: Cha cc thuc tnh d liu, cn c th l i tng ca CLR
- Binding Target: L cc thuc tnh giao diu ngi dng c th hin th hoc thay
i ti d liu. Binding target c th l DependencyProperty ca FramworkElement
Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


2
- Value Converter: Thnh phn ty chn p dng cho nhng trng hp d liu
cn phn tch hoc chuyn i
- iu hng ca lung d liu: Quyt nh ti vic tng tc d liu qua li gia
Binding Source v Binding Target (xem chi tit mc di)
V d di y s ch r cch trnh by thuc tnh mu ca ch (ForeGround Color) ca mt
TextBox:
M XAML:
<TextBox x:Name="MyTextBox" Text="Text" Foreground="{Binding Brush1,
Mode=OneWay}"/>
M C# :
//To mt lp MyColors thc thi giao tip INotifyPropertyChanged.
MyColors textcolor = new MyColors();

// Brush1 thit lp mt SolidColorBrush vi gi tr mu Red.
textcolor.Brush1 = new SolidColorBrush(Colors.Red);

// Thit lp DataContext ca MyTextBox.
MyTextBox.DataContext = textcolor;
Khi s dng DataContext trong m C# trn y, n cho php cc th UI tha k thng tin v
d liu ngun. V d ging nh trong ASP.NET bn s dng phng thc gn DataSouce
hin th d liu trn mt Grid.
o Cc phng thc iu hng ca lung d liu

Mi mt kiu binding data u c mt phng thc iu hng lung d liu(Mode propery). Ci ny
quyt nh khi no v lm th no d liu chy trn. C 3 phng thc iu hng lung d liu
sau
- OneTime: binding d liu ti target (giao din ngi dng) mt ln v sau kt thc kt
ni khng binding na. Phng thc ny ph hp khi hin th d liu m t khi hoc khng
bao gi cn thay i.
- OneWay: Binding d liu ti target v gi n n khi Source (ngun d liu) thay i th
target cng thay i theo. Phng thc ny ph hp khi trnh by d liu m ngi dng
khng c php thay i
- TwoWay: Binding d liu ti target v gi n n khi source thay i th target cng thay
i theo, nhng khi target thay i th source cng thay i theo. Phng thc ny ph
hp khi trnh by d liu m cho php ngi dng thay i d liu ngun
o Change Notification

cho hp l vi cc thay i gi tr gia Source object v Target objects th chng ta phi thc thi
mt interface l InotifyPropertyChanged. Trong InotifyPropertyChanged c cung cp mt event
PropertyChanged.
Trong v d di y. Class MyColors thc thi giao tip InotifyPropertyChanged cho phng thc
OneWay
namespace DataBinding
{
//Tao mot class thua ke interface INotifyPropertyChanged
public class MyColors : INotifyPropertyChanged
{
private SolidColorBrush _Brush1;
Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


3

// Khai bao su kien PropertyChanged.
public event PropertyChangedEventHandler PropertyChanged;

//Tao thuoc tinh cua SolidColorBrush
public SolidColorBrush Brush1
{
get { return _Brush1; }
set
{
_Brush1 = value;
// Goi NotifyPropertyChanged khi thuoc tinh nguon duoc cap nhap
NotifyPropertyChanged("Brush1");
}
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}

3 S dng Isolated Storage

Silverlight dng Isolated Storage nh mt h thng file o lu tr d liu trong mt th mc n
trn my tnh ca bn. N chia d liu vo lm 2 phn ring bit: Phn th nht cha cc thng tin
qun l nh dung lng cho php v phn th 2 cha d liu thc s. Mi ng dng Silverlight c
phn b mt vng ring trong h thng lu tr ny vi dung lng lu tr mc nhin l 1 MB.

o u im:
- Isolated Storage l mt thay th tuyt vi cho cookie, c bit l nu bn ang lm vic vi
mt tp ln d liu. Mt s v d v kh nng ca Isolated Storage bao gm undo li mt s
thao tc ca ng dng, hay gi hng, cc ci t v ca s hay bt k ci t no m bn
mun truy cp vo ln np tip theo.
- Isolated Storage lu tr theo ngi dng cho php cc ng dng lu gi cc ci t cho
tng ngi dng ring bit.
o Mt s vn c th xy ra:
- Ngi qun tr c th t gii hn a trn mi ngi dng v assembly, khng c bt k
cnh bo no v khng gian trng cn li. V l do ny, bn nn kim tra v bt cc ngoi l
trong ng dng ca bn.
- D rng Isolated Storage c t trong mt th mc n trong h thng, nhng khng c
ngha ngi dng khng th tm ra th mc ny, do vy Isolated Storage khng hon ton
an ton v ngi dng c th thay i hoc xa cc file. Tuy nhin, nu mun ngi dng
khng th thay i cc file, bn c th dng cc lp m ha m li cc file ny trc khi
lu.
- Cc my tnh c th b kha bi cc chnh sch bo mt v cc ng dng s khng th lu
c vo IsolatedStorage. C th hn, bn cn c IsolatedStorageFilePermission c th
lm vic c vi IsolatedStorage
Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


4
Gi hy xem qua v d v vic lu v c d liu t IsolatedStorage. Nh rng bn cn dng using
tham chiu n namespace System.IO.IsolatedStorage cng nh l System.IO.

Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


5

using System.Windows.Controls;
using System.IO.IsolatedStorage;
using System.IO;
using System;


namespace Samples_Chap7
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
//Luu du lieu vao file dulieu.txt
SaveData("Day la du lieu cua toi", "dulieu.txt");
//Lay du lieu tu file dulieu.txt
string test = LoadData("dulieu.txt");
}
private void SaveData(string data, string fileName)
{
//Lay Isolated Storage cua nguoi dung danh cho ung dung
using (IsolatedStorageFile isf =
IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = new
IsolatedStorageFileStream(fileName, FileMode.Create, isf))
{
using (StreamWriter sw = new StreamWriter(isfs))
{
//Luu du lieu
sw.Write(data);
sw.Close();
}
}
}
}

private string LoadData(string fileName)
{
string data = String.Empty;
//Lay Isolated Storage cua nguoi dung danh cho ung dung
using (IsolatedStorageFile isf =
IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = new
IsolatedStorageFileStream(fileName, FileMode.Open, isf))
{
using (StreamReader sr = new StreamReader(isfs))
{
string lineOfData = String.Empty;
while ((lineOfData = sr.ReadLine()) != null)
//Doc du lieu
data += lineOfData;
}
}
}
return data;
}

}
}

Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


6

4 Khi qut v lm vic vi d liu XML, LINQ to XML

Trong Silverlight bn c th phn tch d liu XML bng mt trong hai cch l LINQ to XML hoc
XmlReader
i vi nhng ti liu XML ln i hi vic ti d liu v tn nhiu b nh trong lm gim hiu sut
chng trnh. Trong trng hp ny chng ta nn s dng XmlReader vi nhng c tnh nh c d
liu nhanh, forward-only, non-caching parser. Ngc li vi nhng ti liu XML nh hn bn nn s
dng LINQ to XML, n cung cp nhng tnh nng v tin ch hu dng hn XmlReader
Trong phn ny chng ti s hng dn cc bn v cch x l d liu xml vi LINQ to XML( Silverlight).
o Khi qut v LINQ to XML

LINQ to XML cng ging nh Document Object Model(DOM) trong n em ti liu XML ny vo
trong b nh. Bn c th truy vn v thay i ti liu ny, sau khi thay i n bn c th lu n v mt
file hoc chuyn i ha n (Serialize) ri gi n thng qua mng Internet. Tuy nhin LINQ to XML
khc bit so vi DOM ch: N cung cp mt i tng mi nh nhng hn v d dng lm vic vi
chng hn, ngoi ra LINQ to XML cn l s ci tin ca ngn ng Visual C# 2008.
Mt li th quan trng nht ca LINQ to XML l n tch hp vi Language-Integrated Query (LINQ). Vi
s tch hp ny n cho php bn vit cu truy vn ti liu XML khi trong b nh
tr v tp hp cc Element v attribute. LINQ to XML c th so snh c vi cc chc nng ca
XPath v Xquery.
o To mt XAML ng vi LINQ to XML
Trong mc ny chng ta s ch r cc to mt control TextBlock bng LINQ to XML.
Trc tin ty chnh project silverlight trong Visual Studio chng ta chy v d di y
1. Trong Solution Explorer, thm assembly reference ti System.Xml.Linq.dll
2. Thay i ni dung file page.xaml ca bn theo m di y
<UserControl x:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Canvas x:Name="LayoutRoot" Background="White">
</Canvas>
</UserControl>
3. Trong file page.xaml.cs thm cc khai bo using sau y
using System.Windows.Markup;
using System.Xml.Resolvers;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Text;

Di y l v d chi tit v to mt i tng XElement v lu n vi thng tin lin h.

// Tao XElement de luu thong tin lien he ban be
XElement contacts =
new XElement("Contacts",
new XElement("Contact1",
new XElement("Ten", "Pham Chi Cuong"),
new XElement("DienThoai", "0906 123 480"),
new XElement("DiaChi",
new XElement("DuongPho", "Nguyen Hong"),
Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


7
new XElement("ThanhPho", "HaNoi")
)
),
new XElement("Contact2",
new XElement("Ten", "Tran Duy Bien"),
new XElement("DienThoai", "0904 252 161"),
new XElement("DiaChi",
new XElement("DuongPho", "Pham Van Dong"),
new XElement("ThanhPho", "HaNoi")
)
)
);

// Tao TextBlock1
// Luu y rang Element nay phai khai bao 2 XAML namespace
XElement textBlock1 = XElement.Parse(
@"<TextBlock
xmlns='http://schemas.microsoft.com/client/2007'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
TextWrapping= 'Wrap'
Width = '400'
Canvas.Top = '10'
Text=''/>");

// Lay child Element cua contact1
XElement contact1 = contacts.Element("Contact1");

// Gan gia tri vao thuoc tinh Text o cuoi cung voi noi dung cua cac
contact trong xml
textBlock1.LastAttribute.SetValue(contact1.ToString());
// Lay child element thu hai
XElement contact2 = contacts.Element("Contact2");

// Tao TextBlock2
// Luu y rang Element nay phai khai bao 2 XAML namespace
XNamespace xmlns = "http://schemas.microsoft.com/client/2007";
XElement textBlock2 = new XElement(xmlns + "TextBlock",
new XAttribute(XNamespace.Xmlns + "x",
"http://schemas.microsoft.com/winfx/2006/xaml"),
new XAttribute("Canvas.Top", 250),
new XAttribute("Width", "600"),
new XAttribute("Text", contact2.ToString())
);


// Them TextBlock1 vao trong trang

LayoutRoot.Children.Add(XamlReader.Load(textBlock1.ToString()) as
UIElement);
// Them TextBlock2 vao trong trang
LayoutRoot.Children.Add(XamlReader.Load(textBlock2.ToString()) as
UIElement);

o Cch load file XML t mt URI bt k

1. To mt i tng WebClient, thm trnh x l (handler), Gi phng thc
OpenReadAsync. Lm theo m lnh di y
WebClient wc = new WebClient();
wc.OpenReadCompleted += wc_OpenReadCompleted;
wc.OpenReadAsync(new Uri(uriString));
2. Thc thi hm callback wc_OpenReadCompleted
Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


8
private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
//Kiem tra thuoc tinh Error cho cac loi
if (e.Error != null)
{
OutputTextBlock.Text = e.Error.Message;
return;
}
//Neu khong co loi, Lay du lieu stream ve va phan tich chung toi XDocument thong
qua phuong thuc Load
using (Stream s = e.Result)
{
XDocument doc = XDocument.Load(s);
OutputTextBlock.Text = doc.ToString(SaveOptions.OmitDuplicateNamespaces);
}
}

5 Truy cp d liu SQL Server vi WCF
Trong phn ny chng ta s xy dng mt ng dng nh kt ni vi CSDL SQL Server. hon thin
c ng dng ny chng ta cn tp hp c nhng k nng sau
- Kt ni ti mt WCF Web Service
- S dng LINQ truy vn v tr v d liu
- S dng Control DataGrid hin th d liu
o Khi to chng trnh
To mt Project Web Application (File -> New ->Project -> Silverlight Application) . Chng ta t tn
cho ng dng ny l SQLData

Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


9
Bm OK chng ta s c mt Solution nh hnh v di y

o Tm hiu v LINQ to SQL

LINQ to SQL l mt phin bn hin thc ha ca O/RM (object relational mapping) c bn trong .NET
Framework bn Orcas (nay l .NET 3.5), n cho php bn m hnh ha mt c s d liu dng cc
lp .NET. Sau bn c th truy vn c s d liu (CSDL) dng LINQ, cng nh cp nht/thm/xa d
liu t .
LINQ to SQL h tr y transaction, view v cc stored procedure (SP). N cng cung cp mt cch
d dng thm kh nng kim tra tnh hp l ca d liu v cc quy tc vo trong m hnh d liu
ca bn.
bit thm v cng ngh ny bn c th xem chi tit ti ScottGu's tutorial
o Thm LINQ to SQL Classes

- Bng cch chut phi vo Server Project v chn Add -> New Item sau chn LINQ to SQL
Classes. class ny c tn l DataClasses1.dbml

Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


10
- Chng ta m Server Explorer (View->Server Explorer) v chn c s d liu
AdventureWorkLTs ( ci t sn trong SQL Server hoc c th download Microsoft.com)

- Sau khi m kt ni ti CSDL AdventureWorkLTs, chng ta tip tc ko bng Customer vo
DataClasses1.dbml trong m trong Designer

- Nhiu kh nng s bn s nhn c cnh bo nh hnh v di y, bn bm vo Yes
tip tc

Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


11
- Sau khi ko vo vng trng ca DataClasses1.dbml s nhn thy c kh nng chuyn ha
t i tng bng (Customer table) sang m hnh lp nh hnh v di y

Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


12

o To Web Service (WCF)
- Chut phi vo Web Project chn Add New, bn trong templates chn WCF Service

Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


13
- Kt qu nhn c t vic to trn l 3 file theo hnh v di y

- M file IService1.cs bn s thy on m c to sn di y
public interface IService1
{
[OperationContract]
void DoWork();
}
- Thay i on m trn bng on m di y
public interface IService1
{
[OperationContract]
List<Customer> GetCustomersByLastName(string lastName);
}
- M file Service1.svc, thm vit on m nh di y
public List<Customer> GetCustomersByLastName(string lastName)
{
DataClasses1DataContext db = new DataClasses1DataContext();
var matchingCustomers = from cust in db.Customers
where cust.LastName.StartsWith(lastName)
select cust;
return matchingCustomers.ToList();
}
- Lu Mc nh ca WCF s dng wsHttpBinding, xem trong file Web.config
<services>
<service behaviorConfiguration="SQLData_Web.Service1Behavior"
name="SQLData_Web.Service1">
<endpoint address="" binding="wsHttpBinding"
contract="SQLData_Web.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
</service>
</services>
Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


14
- Tuy nhin n ch h tr trong basic binding (SOAP 1.1, etc.), v vy bn cn thay i binding
tng ng nh sau
<endpoint address="" binding="basicHttpBinding"
contract="SQLData_Web.IService1">
o To ng dng Silverlight
- Tip theo chng ta s to mt ng dng Silverlight v tng tc vi web service WCF va
to c. Chut phi vo references trong silverlight project v chn Add Service Reference

- Sau khi chn Add Service Reference, bn bm chut vo Discover v chn Services in
Solution. Service m bn va to s c tm thy v hin th. Bm OK

- Service sau khi c thm vo project ca bn, bn c th truy cp vo Web service ny.
Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


15

o To XAML

- Trong file Page.xaml bn thm on m di y
<Grid x:Name="LayoutRoot" Background="White" ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition Height="10" />
<!--0 Margin-->
<RowDefinition Height="50" />
<!--1 Prompts-->
<RowDefinition Height="*" />
<!--2 DataGrid-->
<RowDefinition Height="10" />
<!--3 Margin-->
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10" />
<!--0 Margin-->
<ColumnDefinition Width="*" />
<!--1 Controls-->
<ColumnDefinition Width="10" />
<!--2 Margin-->
</Grid.ColumnDefinitions>
</Grid>
- Bn mn hnh Designer s thy nh hnh nh sau
Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


16

- t cc Control sau y vo hng th nht ca Datagrid

<Border BorderBrush="Black" BorderThickness="2" Grid.Row="1"
Grid.Column="1"/>
<StackPanel Grid.Row="1" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="Last name to search for: " VerticalAlignment="Bottom"
FontSize="18" Margin="15,0,0,0" />
<TextBox x:Name="LastName" Width="250" Height="30" Margin="2,0,0,4"
VerticalAlignment="Bottom"/>
<Button x:Name="Search" Width="75" Height="30" Margin="20,0,0,4"
Content="Search" VerticalAlignment="Bottom" Background="Blue" FontWeight="Bold"
FontSize="14" />
</StackPanel>
- t cc Control sau y vo hng th nht ca Grid
- Ko th DataGrid trong toolbox vao trong XAML
<my:DataGrid x:Name="theDataGrid" AlternatingRowBackground="Beige"
AutoGenerateColumns="True" Width="700" Height="500" Grid.Row="2" Grid.Column="1"
CanUserResizeColumns="True" />
o Vit x l s kin cho nt Search

- M file page.xaml.cs thm on m di y
public Page()
{
InitializeComponent();
Loaded += new RoutedEventHandler(Page_Loaded);
}

void Page_Loaded(object sender, RoutedEventArgs e)
{
Search.Click += new RoutedEventHandler(Search_Click);
}

void Search_Click(object sender, RoutedEventArgs e)
{
//Gan Service1Client toi mot doi tuong o local l webService
Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio
Infoway
Solutions
CHNG VII: LM VIC VI D LIU TRONG SILVERLIGHT


17
ServiceReference1.Service1Client webService = new
SQLData.ServiceReference1.Service1Client();

//Cai dat trinh xu ly su kien
webService.GetCustomersByLastNameCompleted += new
EventHandler<SQLData.ServiceReference1.
GetCustomersByLastNameCompletedEventArgs>(webService_GetCustomersByLastNameComplete
d);

//Goi asynchronous
webService.GetCustomersByLastNameAsync(LastName.Text);

void webService_GetCustomersByLastNameCompleted(object sender,
SQLData.ServiceReference1.GetCustomersByLastNameCompletedEventArgs e)
{
//Trinh bay ket qua vao Datagrid
theDataGrid.ItemsSource = e.Result;
}






o Kt qu hin th


Smith Nguyen Studio.
https:/ / www.facebook.com/ SmithNguyenStudio

You might also like