You are on page 1of 16

Bi 8

MT S V D S DNG WINDOWS COMMUNICATION FOUNDATION

Mc lc
1 To dch v WCF h tr lm vic vi AJAX ....................................................................................................2 1.1 1.2 1.3 1.4 2 To ng dng web qun l nhn vin ......................................................................................2 To dch v qun l nhn vin ......................................................................................................4 Thit lp cu hnh h tr AJAX ...............................................................................................7 S dng cc phng thc ca dch v WCF bng AJAX ............................................................8

To dch v WCF lm vic vi REST .............................................................................................................10 2.1 2.2 2.3 Xy dng URI Template cho vic ly d liu (HTTP GET) ......................................................12 Xy dng URI Template cho vic cp nht d liu (HTTP PUT) .............................................14 Xy dng URI Template xo mt nhn vin (HTTP DELETE)............................................15

Ti liu tham kho ...........................................................................................................................................16

Cc bi trc chng ta bit cc thnh phn cu thnh mt dch v trn WCF cng nh cch xy dng mt dch v WCF, ng thi cng c gii thiu cch xy dng chng trnh ng dng s dng cc dch v WCF. Trong bi cui cng ny, chng ta s c lm quen vi mt s ng dng ca dch v WCF theo mt s cch khc nhau: To ng dng trn Web s dng cng ngh AJAX lm vic vi dch v WCF To dch v WCF lm vic vi REST

1 To dch v WCF h tr lm vic vi AJAX


phc v cho mc ch gii thiu vic h tr ca WCF trong lm vic vi REST hay JSON, u tin chng ta to ra mt dch v WCF c h tr tt khi client l trnh duyt vi AJAX. Mc tiu ng dng ca chng ta vn l ng dng qun l nhn vin nh trong cc v d cc bi trc. Tm tt li, ng dng qun l nhn vin n gin gm c cc mc sau: Thm mi mt nhn vin Sa thng tin mt nhn vin Xo mt nhn vin Ly thng tin chi tit ca mt nhn vin Ly danh sch cc nhn vin Tm kim nhn vin

1.1
1. 2.

To ng dng web qun l nhn vin


M Visual Studio, chn File->New Web Site, sau cho chn ASP.NET Web Site t tn Web site l HRManagement

Microsoft Vietnam | WCF Bi 8: Mt s v d s dng WCF

Figure 1 To mt web site mi Do phn client cho web site tng i di, nn cc bn xem trong phn source code v d tip tc lm vic cho tin. y, phn client s c 3 trang. Trang ch: hin th ton b nhn vin v cc thng tin chi tit ca nhn vin Trang son tho: Sa thng tin ca nhn vin Trang thm mi: Thm mt nhn vin

C 3 trang ny u s dng mt trang master gi l Application.master. Khi m solution km theo bn s thy web site project nh sau:

Microsoft Vietnam | WCF Bi 8: Mt s v d s dng WCF

Figure 2 Web site project

1.2

To dch v qun l nhn vin

ng dng web ca bn lm vic vi cc dch v WCF, bn cn thc hin cc bc sau: 1. 2. 3. Click chut phi vo HRManagement project, chn Add New Item Chn Thm AJAX-enabled WCF Service t tn cho dch v ca bn l HRService.svc

Microsoft Vietnam | WCF Bi 8: Mt s v d s dng WCF

4.
using using using using using

Figure 3 Thm mi dch v WCF Thm on m sau y ci t dch v


System.Collections.Generic; System.Linq; System.Runtime.Serialization; System.ServiceModel; System.ServiceModel.Activation;

[DataContract] public class PersonData { [DataMember] public int PersonId; [DataMember] public string FirstName; [DataMember] public string LastName; [DataMember] public string EmailAddress; [DataMember] public string Department; } [ServiceContract(Namespace = "urn:hr")] [AspNetCompatibilityRequirements(RequirementsMode AspNetCompatibilityRequirementsMode.Allowed)] public class HRService { [OperationContract] public IList<PersonData> GetAll()

Microsoft Vietnam | WCF Bi 8: Mt s v d s dng WCF

{ using (var personCtx = new DataClassesDataContext()) { // Set up the query var persons = from p in personCtx.Persons orderby p.FirstName select new PersonData { PersonId = p.PersonId, FirstName = p.FirstName, LastName = p.LastName, EmailAddress = p.EmailAddress, Department = p.Department }; return persons.ToList(); } } [OperationContract] public PersonData GetPerson(int personId) { using (var personCtx = new DataClassesDataContext()) { // Set up the query var person = (from p in personCtx.Persons where p.PersonId == personId select new PersonData { PersonId = p.PersonId, FirstName = p.FirstName, LastName = p.LastName, EmailAddress p.EmailAddress, Department = p.Department }).Single(); return person; } } [OperationContract] public void UpdatePerson(int personId, PersonData newData) { using (var personCtx = new DataClassesDataContext()) { // Set up the query var person = personCtx.Persons.Single(p => p.PersonId personId); if (person != null) { person.FirstName = newData.FirstName; person.LastName = newData.LastName; person.EmailAddress = newData.EmailAddress; person.Department = newData.Department; personCtx.SubmitChanges(); } }

==

Microsoft Vietnam | WCF Bi 8: Mt s v d s dng WCF

} [OperationContract] public void AddPerson(PersonData p) { using (var personCtx = new DataClassesDataContext()) { var person = new Person { PersonId = p.PersonId, FirstName = p.FirstName, LastName = p.LastName, EmailAddress = p.EmailAddress, Department = p.Department }; personCtx.Persons.InsertOnSubmit(person); personCtx.SubmitChanges(); } } [OperationContract] public void DeletePerson(int personId) { using (var personCtx = new DataClassesDataContext()) { var person = personCtx.Persons.Single(p => p.PersonId personId); if (person != null) { personCtx.Persons.DeleteOnSubmit(person); personCtx.SubmitChanges(); } } } }

==

5.

Trong on m trn c 2 im cn ch :

a. Ging nh cc dch v khc, khi nh ngha kiu d liu ca chng ta, chng ta cn phi thm vo data contract (trong trng hp ny l lp PersonData c thm thuc tnh DataContract) b. Khi lm vic vi AJAX, ta nn ng k namespace ca dch v, s dng tham s Namespace trong thuc tnh ServiceContract. Trong v d ny l
[ServiceContract(Namespace = "urn:hr")]

1.3

Thit lp cu hnh h tr AJAX

Trong thc t, khi bn to ra mt project ASP.NET Web Site v thm vo dch v WCF nh trn, Visual Studio s t ng thm vo cc cu hnh cn thit, bn s khng cn lm g m c th s dng dch v. chc chn, hay kim tra tp tin cu hnh xem c ging nh sau khng:
<system.serviceModel> <behaviors> <endpointBehaviors>

Microsoft Vietnam | WCF Bi 8: Mt s v d s dng WCF

<behavior name="HRServiceAspNetAjaxBehavior"> <enableWebScript/> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <services> <service name="HRService"> <endpoint address="" behaviorConfiguration="HRServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="HRService"/> </service> </services> </system.serviceModel>

1.4

S dng cc phng thc ca dch v WCF bng AJAX

s dng cc phng thc ca dch v WCF, u tin bn cn thm vo mt ScriptManager trong trang aspx ca bn, sau thm vo Services v tr ti dch v bn mun s dng, v d trong trang default.aspx, bn thm vo ngay sau th form nh sau:
<asp:ScriptManager ID="ScriptManager1" runat="server"> <Services> <asp:ServiceReference Path="~/HRService.svc" /> </Services> </asp:ScriptManager>

Sau khi thm vo tham chiu dch v WCF, bn hon ton c th gi cc phng thc ca dch v nh sau:
function GetData() { var hrs = new hr.HRService(); hrs.GetAll(PersonsReturnedEventHandler, null, null); } function PersonsReturnedEventHandler(value) { alert("Tong cong co " + value.length, " nhan vien"); }

Nh vy cch s dng dch v WCF l: To mt instace (th hin) ca dch v: var hrs = new hr.HRService(); Gi hm ca dch v : hrs.GetAll(...)

Nh vy chng ta c mt ng dng web tng i hon chnh qun l nhn vin. Trang ch mc nh:

Microsoft Vietnam | WCF Bi 8: Mt s v d s dng WCF

Figure 4 Trang ch Xo nhn vin

Microsoft Vietnam | WCF Bi 8: Mt s v d s dng WCF

Figure 5 Xo nhn vin Sa thng tin

Figure 6 Sa thng tin v mt nhn vin

2 To dch v WCF lm vic vi REST


Da trn c s project chng ta xy dng trn. Thm vo mt dch v WCF nh sau: 1. Click chut phi vo project HRManagement, chn Add New Item, sau chn thm vo WCF Service 2. t tn cho service l RESTHRService.svc

Microsoft Vietnam | WCF Bi 8: Mt s v d s dng WCF

10

3.

Figure 7 Thm dch v REST WCF Sa tp tin cu hnh nh sau:

<system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="AJAXFriendly"> <enableWebScript /> </behavior> <behavior name="RESTFriendly"> <webHttp /> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <services> <service name="HRService"> <endpoint address="" behaviorConfiguration="AJAXFriendly" binding="webHttpBinding" contract="HRService" /> </service> <service name="RESTHRService"> <endpoint address="" behaviorConfiguration="RESTFriendly" binding="webHttpBinding" contract="IRESTHRService" /> </service> </services> </system.serviceModel>

Microsoft Vietnam | WCF Bi 8: Mt s v d s dng WCF

11

4. Chng ta vn s dng DataContract l PersonData. Thm vo khai bo dch v IRESTHRService nh sau:


[ServiceContract] public interface IRESTHRService { [OperationContract] IList<PersonData> GetAll(); [OperationContract] PersonData GetPerson(int personId); [OperationContract] void UpdatePerson(int personId, PersonData newData); [OperationContract] void AddPerson(PersonData p); [OperationContract] void DeletePerson(int personId); }

2.1

Xy dng URI Template cho vic ly d liu (HTTP GET)

thc hin dch v thng qua REST chng ta cn a vo cc verb tng ng trong REST nh HTTP GET, POST, PUT, DELETE. Vi verb HTTP GET chng ta c th a vo bng cch thm thuc tnh WebGet cho cc hm trong dch v, v d nh:
[OperationContract] [WebGet] PersonData GetPerson(int personId);

Gi tr tr v chng ta c th quy nh l dng XML hoc cng c th l JSON. y ta quy nh gi tr tr v l di dng XML nh sau:
[OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Xml)] PersonData GetPerson(int personId);

Ngoi ra khi tr v gi tr, dch v ca chng ta cng cn phi bo cho client bit l request c thnh cng hay khng. Vic tr v trng thi li c thc hin thng qua WebOperationContext.Current. Nh vy, phn ci t cho hm GetPerson s nh sau:
public PersonData GetPerson(int personId) { var ctx = WebOperationContext.Current; try { using (var personCtx = new DataClassesDataContext()) { // Set up the query var person = personCtx.Persons.SingleOrDefault(p => p.PersonId == personId); if (person == null) { ctx.OutgoingResponse.SetStatusAsNotFound(); return null;

Microsoft Vietnam | WCF Bi 8: Mt s v d s dng WCF

12

} var personData = new PersonData { PersonId = person.PersonId, FirstName = person.FirstName, LastName = person.LastName, EmailAddress = person.EmailAddress, Department = person.Department }; ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK; return personData; } } catch { ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.BadRequest; return null; } }

Mt trong nhng c im c bn ca REST l chng ta ch lm vic vi cc URI. Do dch v ca chng ta theo ng kiu ca REST, ta cn thm tham s UriTemplate cho thuc tnh WebGet nh sau:
[OperationContract] [WebGet(UriTemplate = "person/{personId}", ResponseFormat = WebMessageFormat.Xml)] PersonData GetPerson(int personId);

Khi gi s dch v ca chng ta ti a ch sau: http://wcf.contoso.com/HRManagement/RESTHRService.svc Hm GetPerson s c kch hot vi personId=31 ti a ch sau: http://wcf.contoso.com/HRManagement/RESTHRService.svc/person/31 M trnh duyt Internet Explorer vo a ch trn ta c th nhn c kt qu nh sau:

Microsoft Vietnam | WCF Bi 8: Mt s v d s dng WCF

13

Figure 8 Kt qu ly thng tin mt nhn vin Trong trng hp bn s dng nh dng tr v l Json nh sau:
[OperationContract] [WebGet(UriTemplate = "person/{personId}", ResponseFormat = WebMessageFormat.Json)] PersonData GetPerson(int personId);

Khi truy xut ti a ch http://wcf.contoso.com/HRManagement/RESTHRService.svc/person/31 s cho ta kt qu nh sau:


{"Department":"Human Resources","EmailAddress":"Belinda.S.Estes@dodgit.com","FirstName":"Belinda", "LastName":"Kalin","PersonId":31}

2.2 PUT)

Xy dng URI Template cho vic cp nht d liu (HTTP

Vic cp nht d liu bao gm sa mt bn ghi (thng tin nhn vin) sn c hoc thm mi mt nhn vin. Vic ny c thc hin da vo verb HTTP PUT trong REST. m t mt phng thc trong dch v WCF s c kch hot bng verb PUT, ta s dng thuc tnh m t l WebInvoke, vi tham s Method l PUT. ch ra ta s cp nht thng tin vo nhn vin no, ta cng s dng URI Template nh phn trn. Nh vy, hm cp nht (hoc thm mi) nhn vin s c khai bo nh sau:
[OperationContract] [WebInvoke(Method = "PUT", UriTemplate = "person/{personId}", RequestFormat = WebMessageFormat.Json)] void UpdatePerson(string personId, PersonData personData);

M ngun ci t chi tit cho hm ny nh sau:


public void UpdatePerson(string personId, PersonData personData)

Microsoft Vietnam | WCF Bi 8: Mt s v d s dng WCF

14

{ WebOperationContext ctx = WebOperationContext.Current; System.Net.HttpStatusCode status = System.Net.HttpStatusCode.OK; try { using (var dataContext = new DataClassesDataContext()) { Person person = dataContext.Persons.SingleOrDefault( prod => prod.PersonId == Convert.ToInt32(personId)); if (person == null) { person = new Person(); dataContext.Persons.InsertOnSubmit(person); status = System.Net.HttpStatusCode.Created; } person.FirstName = personData.FirstName; person.LastName = personData.LastName; person.Department = personData.Department; person.EmailAddress = personData.EmailAddress; dataContext.SubmitChanges(); ctx.OutgoingResponse.StatusCode = status; return; } } catch { ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.BadRequest; return; } }

Trn trang web ta gi hm dch v WCF nh sau:


function updatePersonEventHandler(sender, args) { var url = "../RESTHRService.svc/person/" + args.PersonId; var proxy = new Sys.Net.WebServiceProxy(); proxy.restInvoke(url, "PUT", args, "GetData", updatePersonSucceeded, null, null); }

2.3 DELETE)

Xy dng URI Template xo mt nhn vin (HTTP

ra lnh xo mt resource (trong trng hp ny l nhn vin) bng REST, chng ta s dng verb HTTP DELETE. Tng t nh phn cp nht, chng ta khai bo phng thc vi thuc tnh m t l WebInvoke vi Method l DELETE:
[OperationContract] [WebInvoke(Method = "DELETE", UriTemplate = "person/{personId}")]

Microsoft Vietnam | WCF Bi 8: Mt s v d s dng WCF

15

void DeletePerson(string personId);

V m ngun ci t cho vic xo nhn vin:


public void DeletePerson(string personId) { WebOperationContext ctx = WebOperationContext.Current; try { using (var dataContext = new DataClassesDataContext()) { Person person = dataContext.Persons.SingleOrDefault( p => p.PersonId == Convert.ToInt32(personId)); if (person == null) { ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound; return; } dataContext.Persons.DeleteOnSubmit(person); dataContext.SubmitChanges(); ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK; return; } } catch { ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.BadRequest; return; } }

Pha client gi hm DeletePerson nh sau:


function DeletePersonEventHandler(sender, args) { if (confirm("Do you want to delete person: " + args.FirstName + " " + args.LastName)) { var url = "../RESTHRService.svc/person/" + args.PersonId; var proxy = new Sys.Net.WebServiceProxy(); proxy.restInvoke(url, "DELETE", null, "DeletePersonEventHandler", OnDeleted, null, null); } }

3 Ti liu tham kho


1. REST in WCF Blog Series Index (URL: http://blogs.msdn.com/bags/archive/2008/08/05/rest-in-wcf-blog-series-index.aspx) 2. Using WebHttpBinding & JSON Support in WCF (URL: http://spellcoder.com/blogs/bashmohandes/archive/2008/01/05/9423.aspx) Consuming JSON data in .NET with WCF (URL: http://www.codeproject.com/KB/WCF/consuming-json-wcf.aspx) 3.

Microsoft Vietnam | WCF Bi 8: Mt s v d s dng WCF

16

You might also like