Silverlight tutorial Creating a data centric web app with DataGrid LINQ and WCF Web Service.docx
- 文档编号:6374955
- 上传时间:2023-01-05
- 格式:DOCX
- 页数:18
- 大小:445.78KB
Silverlight tutorial Creating a data centric web app with DataGrid LINQ and WCF Web Service.docx
《Silverlight tutorial Creating a data centric web app with DataGrid LINQ and WCF Web Service.docx》由会员分享,可在线阅读,更多相关《Silverlight tutorial Creating a data centric web app with DataGrid LINQ and WCF Web Service.docx(18页珍藏版)》请在冰豆网上搜索。
SilverlighttutorialCreatingadatacentricwebappwithDataGridLINQandWCFWebService
TutorialPart1:
Buildingtheapplicationandtestingitlocally
1.Forthistutorialyouwillneedaccesstoawebaccessibledatabase. Asmentionedintheintroduction,IusewebhostingaccountfromwithaSQLServer2008add-on,buttherearemanyoptionsofhostingproviderstochoosefrom. Toestablishaconnectionwithyourremotedatabase,selectViewfromthemenu,andthenServerExplorer. ClickontheconnecttodatabaseoptionandthenfillinwithSQLServerNameandDatabaseLoginthatyoucangetfromyourhostingprovider.Clicktestconnectiontoconfirmthatyou’resetup.
2.CreateanewSilverlightApplicationcalledSilverlightClient. CallthesolutionWcfSqlDemo.
3.VS2008willaskyouifyouwanttoaddaWebtothesolution. Select“WebApplicationProject”insteadofthedefault“WebSite”.NamethewebWcfSqlDemoWeb.
4.RightclickonWcfSqlDemoWebandselectadd,newitem. SelectData,LINQtoSQLClasses,andleavethenameDataClasses1.dbml
Whatyoushouldseenextis:
5.IfyousetupyourserveratthebeginningoftheprojectyouwillalreadyhaveadatabaseintheserverexplorerviewasIdo(inmycaseit’snamedsql2k801.SQL2008_540970).Ifyouhaven’t,clickonthecylinderwithaplussigniconunderServerExplorertoconnecttodatabase.
6.Rightclick“Table”onyourconnecteddatabaseandselectaddnewtable.Fillintableasshownbelow.UnderpropertiesnamethetableDemoTable.
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
Collapse
CopyCode
//Returnthelistofvaliddata
[OperationContract]
publicListGetRows()
{
DataClasses1DataContextdb=newDataClasses1DataContext();
varselected_rows=fromrowsindb.DemoTablesselectrows;
returnselected_rows.ToList();
}
//Insertanewdataintothedatabase
[OperationContract]
publicvoidInsertData(stringtestItem1,
stringtestItem2)
{
DataClasses1DataContextdb=newDataClasses1DataContext();
//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
Collapse
CopyCode
xmlns:
my="clr-namespace:
System.Windows.Controls;assembly=System.Windows.Controls.Data"
15.NowyoucangototheassetlibraryandfindDataGridunderCustomControls.
16.AddaDataGridtotheprojectandsizeit. NamethegridResultsGrid. IfyoulookattheXAMLitshouldlooksimilartothebelow.
Collapse
CopyCode
DataGridMargin="8,283,51,87"AutoGenerateColumns="True" x: Name="ResultsGrid"/> 17.Addabuttonandlabelit“Get”. Theendresultshouldbesomethinglikeasfollows: 18.AddOnGetBtnClickedandOnSubmitBtnClickedtotheclickedeventsoftherespectivebuttonsinExpressionBlend. ThiswilladdtheattributestotheXAMLbuttontagsandwillwakeupVS2008andaddthespecifiedmethodstothecodebehindfile. 19.FillintheOnSubmitBtnClickandOnGetBtnClickasshownbelow. CreateacallbacktohandletheGetRowsCompletedevent.(Bytheway,areyounoticinghoweasythisis? Lookathowmuchisgettingdonewithafewlinesofcodeandlookhowcleanandsensiblethesefewlinesare.) Collapse CopyCode privatevoidOnGetBtnClick(objectsender,RoutedEventArgse) { DemoServiceClientwebService=newDemoServiceClient(); webService.GetRowsCompleted+= newEventHandler(webService_GetRowsCompleted); webService.GetRowsAsync(); } voidwebService_GetRowsCompleted(objectsender,GetRowsCompletedEventArgse) { ResultsGrid.ItemsSource=e.Result; } privatevoidOnSubmitBtnClick(objectsender,RoutedEventArgse) { DemoServiceClientwebService=newDemoServiceClient(); 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. Collapse CopyCode datagridmargin="8,283,51,85"autogeneratecolumns="False"x: name="ResultsGrid" width="641"height="232"> DataGrid.Columns> DataGridTextColumn Header="TestItem1" DisplayMemberBinding="{BindingTestItem1}"/> DataGridTextColumn Header="TestItem2" DisplayMemberBinding="{BindingTestItem2}"/> DataGrid.Columns> datagrid> 22.Buildanddebug.Theresultsshouldlookexactlylikebefore,exceptthistimenocolumnforKey. 23.Bynowyou’reprobablycollectingsomegarbageinyourdatabase,becausewehavenowaytodeleteanyitems. Let’schangethatnow. Firstlet’smodifyourwebservicetobeabletodeleteitemsfromourdatabase.AddthefollowingtoDemoService.Notethatwe’reusingmoreLINQ.ThelinebelowwritteninLINQlooselymeans“Takethetabledb.DemoTableandassigntheelementsofthattabletothecollectionrowsthenselectthoserowswherethekeyisthepassedguidandassignthoseselectedrowstothecollectionselectedrow”. Collapse CopyCode //Deletetheitemspecifiedbythepassedkey [OperationContract] publicvoidDeleteRow(Guidkey) { DataClasses1DataContextdb=newDataClasses1DataContext(); varselected_row=fromrowsindb.DemoTableswhererows.Key==keyselectrows; //Deletetheselected"rows".Therewillactualbeonlyone //iteminthiscollectionbecausetheGuidisuniqueandisthe //primarykeyforthetable. db.DemoTables.DeleteAllOnSubmit(selected_row); //Submitthechangetothedatabase. db.SubmitChanges(); } 24.Addadeletebutton.WhenthedeletebuttonisclickedwilldeletewhateveriteminourDataGridthatwasselected. Collapse CopyCode privatevoidOnDeleteClick(objectsender,RoutedEventArgse) { DemoTableselectedRow=ResultsGrid.SelectedItemasDemoTable; //Nowaccesstheservicetodeletetheitem DemoServiceClientwebService=newDemoServiceClient(); webService.DeleteRowAsync(selectedRow.Key); //Nowrefreshthegrid webService.GetRowsCompleted+= newEventHandler(webService_GetRowsCompleted); webService.GetRowsAsync(); } 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
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Silverlight tutorial Creating data centric web app with DataGrid LINQ and WCF Service
链接地址:https://www.bdocx.com/doc/6374955.html