Silverlight tutorial Creating a data centric web app with DataGrid LINQ and WCF Web ServiceWord文档下载推荐.docx
《Silverlight tutorial Creating a data centric web app with DataGrid LINQ and WCF Web ServiceWord文档下载推荐.docx》由会员分享,可在线阅读,更多相关《Silverlight tutorial Creating a data centric web app with DataGrid LINQ and WCF Web ServiceWord文档下载推荐.docx(18页珍藏版)》请在冰豆网上搜索。
7.DragDataTableontoDataClasses1.dbml
8.Setkeyastheprimarykey
9.ViewpropertiesforDataClasses1.dml.
Settheserializationmodetounidirectionalsothatitiscompatiblewithwebservices.
10.Okay,thattakescareofyourdatabase.
Nowlet’ssetupthewebservice.
RightclickontheWcfSqlDemoWebprojectandaddanewitem.SelecttheSilverlight-enabledWCFServicetemplateandnameitDemoService.svc
11.DeleteDoWorkmethodandreplacewiththetwomethodsbelowplusthefollowingusingreferences.Bytheway,the“varselected_rows=fromrowsindb.DemoTablesselectrows”stuff,that’sLINQ.It’sfantastic.
It’saverycleansensiblequerylanguagethatisbuiltinto.NET3.5thatcanbeusedforqueryingdatabases,XML,andevencollections.Oneoftheeasierwaystofigureoutwhatlinkis,istolookatsomeexamples.
IrecommendMicrosoft’s101LINQSamples.TheLINQlinethatIuseintheGetRowsmethodlooselymeans“Takethetabledb.DemoTableandassigntheelementsofthattabletothecollectionrowsthenselectallthoserowsandassignthemtothecollectionselectedrows”.
Collapse
CopyCode
usingSystem.Collections.Generic;
usingSystem.Text;
andalso
//Returnthelistofvaliddata
[OperationContract]
publicListGetRows()
{
DataClasses1DataContextdb=newDataClasses1DataContext();
varselected_rows=fromrowsindb.DemoTablesselectrows;
returnselected_rows.ToList();
}
//Insertanewdataintothedatabase
publicvoidInsertData(stringtestItem1,
stringtestItem2)
//Createanewrowobject.
DemoTablerow=newDemoTable
Key=Guid.NewGuid(),
TestItem1=testItem1,
TestItem2=testItem2
};
//Addthenewobjecttothecollection.
db.DemoTables.InsertOnSubmit(row);
//Submitthechangetothedatabase.
db.SubmitChanges();
12.NowweneedtoletourSilverlightclientknowaboutthewebservicewe’vejustcreated.RightclickSilverlightClientandselectAddServiceReference.
ClickDiscover.
VS2008shouldfindtheservicefromtheproject.AllowittobesavedinthenamespaceServiceReference1.
13.Openpage.xamlinExpressionBlend.
MakeaformthatlookssomethinglikewhatI’vecreatedbelow.Namethetext
boxesTestItem1TxtBox
andTestItem2TxtBox
14.Nowlet’saddthedatagridintowhichthedataweretrievefromthewebservicewillbeplaced.TheDatagridcontrolisnotadefaultcontrolofyourSilverlightproject,soyou’llhavetoaddit.RightclickonreferencesinSilverlightClientandaddareferencetoSystem.Windows.Control.Data.
Gotopage.xaml.
AddthefollowingattributetotheusercontrolelementsowecangetaccesstotheDataGrid
xmlns:
my="
clr-namespace:
System.Windows.Controls;
assembly=System.Windows.Controls.Data"
15.NowyoucangototheassetlibraryandfindDataGridunderCustomControls.
16.AddaDataGridtotheprojectandsizeit.
NamethegridResultsGrid.
IfyoulookattheXAMLitshouldlooksimilartothebelow.
<
my:
DataGridMargin="
8,283,51,87"
AutoGenerateColumns="
True"
x:
Name="
ResultsGrid"
/>
17.Addabuttonandlabelit“Get”.
Theendresultshouldbesomethinglikeasfollows:
18.AddOnGetBtnClickedandOnSubmitBtnClickedtotheclickedeventsoftherespectivebuttonsinExpressionBlend.
ThiswilladdtheattributestotheXAMLbuttontagsandwillwakeupVS2008andaddthespecifiedmethodstothecodebehindfile.
19.FillintheOnSubmitBtnClickandOnGetBtnClickasshownbelow.
CreateacallbacktohandletheGetRowsCompletedevent.(Bytheway,areyounoticinghoweasythisis?
Lookathowmuchisgettingdonewithafewlinesofcodeandlookhowcleanandsensiblethesefewlinesare.)
privatevoidOnGetBtnClick(objectsender,RoutedEventArgse)
DemoServiceClientwebService=newDemoServiceClient();
webService.GetRowsCompleted+=
newEventHandler(webService_GetRowsCompleted);
webService.GetRowsAsync();
voidwebService_GetRowsCompleted(objectsender,GetRowsCompletedEventArgse)
ResultsGrid.ItemsSource=e.Result;
privatevoidOnSubmitBtnClick(objectsender,RoutedEventArgse)
webService.InsertDataAsync(TestItem1TxtBox.Text,TestItem2TxtBox.Text);
20.Buildandtest.Trysubmittingafewitemsandthengettingtheresults.
Youshouldseesomethinglikethefollowing:
21.Easyright?
Noticehowwedidn’tevenhavetodoanythingtogettheDataGridtodisplayourresultsotherthanassignourresultstotheDataGrid’sItemsSource.
Theonlydownsidetothissimplicityisthatwe’reseeingeverythingreturnedincludingtheguidrepresentingthekey.
That’snotveryuserfriendly.
Let’sgetridoftheauto-generationofcolumnsandcreatecustomones.AlsoitseemsIneededtoaddanexplicitsizetotheDataGridorI’dgetafunnyrenderingofthegridwhenit’sempty.
datagridmargin="
8,283,51,85"
autogeneratecolumns="
False"
x:
name="
width="
641"
height="
232"
>
<
DataGrid.Columns>
DataGridTextColumn
Header="
TestItem1"
DisplayMemberBinding="
{BindingTestItem1}"
TestItem2"
{BindingTestItem2}"
/my:
datagrid>
22.Buildanddebug.Theresultsshouldlookexactlylikebefore,exceptthistimenocolumnforKey.
23.Bynowyou’reprobablycollectingsomegarbageinyourdatabase,becausewehavenowaytodeleteanyitems.
Let’schangethatnow.
Firstlet’smodifyourwebservicetobeabletodeleteitemsfromourdatabase.AddthefollowingtoDemoService.Notethatwe’reusingmoreLINQ.ThelinebelowwritteninLINQlooselymeans“Takethetabledb.DemoTableandassigntheelementsofthattabletothecollectionrowsthenselectthoserowswherethekeyisthepassedguidandassignthoseselectedrowstothecollectionselectedrow”.
//Deletetheitemspecifiedbythepassedkey
publicvoidDeleteRow(Guidkey)
varselected_row=fromrowsindb.DemoTableswhererows.Key==keyselectrows;
//Deletetheselected"
rows"
.Therewillactualbeonlyone
//iteminthiscollectionbecausetheGuidisuniqueandisthe
//primarykeyforthetable.
db.DemoTables.DeleteAllOnSubmit(selected_row);
24.Addadeletebutton.WhenthedeletebuttonisclickedwilldeletewhateveriteminourDataGridthatwasselected.
privatevoidOnDeleteClick(objectsender,RoutedEventArgse)
DemoTableselectedRow=ResultsGrid.SelectedItemasDemoTable;
//Nowaccesstheservicetodeletetheitem
webService.DeleteRowAsync(selectedRow.Key);
//Nowrefreshthegrid
25.RebuildandDebug.Nowyoucanselectitemsanddeletethem.
TutorialPart2:
Deployingthewebapptoaremoteserver
25.
1.Publishingtheapplicationtothewebcanbealittledifficult.Theinstructionsbelowhavebeentriedoutonmywebhostingprovider,butyou’relikelytoneedtodosomethingsimilarforotherhostprovidersaswell.
2.Toseethedifficulty,publishthewebsite.
NowDemoServiceislocatedatyourserverright?
Allyoumightthinkyouneedtodoisreconfigureyoursilverlightclienttoreferencetheserviceatyourwebsite.
Goaheadandtryit.
RightclickonServiceReference1andselectConfigureservicereference.Addtheaddressoftheservice.Inmycaseitis
You’llgettheerrorbelowandyouwon’tbeabletoproceed.
3.Here’stheworkaround.We’regoingtooverridethewaytheservercreatestheServiceHost.
AddthefollowingclasstoDemoService.svc.cs
publicclassMyServiceHostFactory:
ServiceHostFactory
{
protectedoverrideServiceHostCreate