Silverlight tutorial Creating a data centric web app with DataGrid LINQ and WCF Web Service.docx

上传人:b****5 文档编号:6374955 上传时间:2023-01-05 格式:DOCX 页数:18 大小:445.78KB
下载 相关 举报
Silverlight tutorial Creating a data centric web app with DataGrid LINQ and WCF Web Service.docx_第1页
第1页 / 共18页
Silverlight tutorial Creating a data centric web app with DataGrid LINQ and WCF Web Service.docx_第2页
第2页 / 共18页
Silverlight tutorial Creating a data centric web app with DataGrid LINQ and WCF Web Service.docx_第3页
第3页 / 共18页
Silverlight tutorial Creating a data centric web app with DataGrid LINQ and WCF Web Service.docx_第4页
第4页 / 共18页
Silverlight tutorial Creating a data centric web app with DataGrid LINQ and WCF Web Service.docx_第5页
第5页 / 共18页
点击查看更多>>
下载资源
资源描述

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页珍藏版)》请在冰豆网上搜索。

Silverlight tutorial Creating a data centric web app with DataGrid LINQ and WCF Web Service.docx

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模板 > 动态背景

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1