Professional Documents
Culture Documents
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
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.1
1. 2.
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:
1.2
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
4.
using using using using using
[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()
{ 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(); } }
==
} [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
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>
<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, 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:
10
3.
<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>
11
2.1
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;
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:
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);
2.2 PUT)
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);
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; } }
2.3 DELETE)
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}")]
15
16