WCF จะสามารถบริการ Web service ได้ทั้ง windows application กับ web application

1) open visual studio 2012

2) new project windows application form

3) add reference


4) code behide

5) สร้าง Service1 Method

6) ทดสอบสร้างปุ่ม button1 แล้วใส่ code

7) เปิด Browser พิมพ์ http://localhost:8000/hello จะเห็นค่าที่ส่งกลับมา

 หมายเหตุเพิ่มเติม เราสามารถใช้ WCF เพราะไวกว่าไม่ต้องรันใน IIS ก็ได้ ทำเป็น Service ของ Window ก็ได้

8) open server explorer สร้าง db

 9) add newitem ->linq ตั้งชื่อเดียวกับ db

10) ลาก database มาวางใน Linq ที่สร้าง

11) เขียนโค้ดเพื่อเรียกใช้

ตรง webinvoke ทำได้เฉพาะ WCF สามารถใส่ url แบบที่ return ค่าแบบกำหนดได้

12) RUN กดปุ่ม button แล้วเปิด browser พิมพ์ url http://localhost:8000/studentbyid/1

13) ทำให้ JSON สามารถบริการข้ามเครื่องได้คือไม่ได้ run ใน Localhost เรียกว่า JSONP เพิ่ม code

14) สร้างไฟล์เพื่อใช้ JQUERY สร้างไฟล์ 2 ไฟล์ ทดสอบก่อน

 

<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="myscript.js"></script>

 </head>
<body></body>
</html>
$(document).ready(function(){
	$.getJSON('http://localhost:8000/Hello?callback=?',
	null,
	function(data){alert(data);});
//สำคัญมากตรง ?callback=? ควรมี
});

รันด้วย browser

15) สร้าง form แล้วให้แสดงค่าจาก webservice โดยกดปุ่มส่งค่า studentid ไป

<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="myscript.js"></script>

 </head>
<body>
<input type="text" id="hello" value="" /><br/>
<input type="text" id="studentid" value="" /><input type="button" id="submit" value="submit"/><br/>
<input type="text" id="firstname" value="" /><br/>
<input type="text" id="lastname" value="" /><br/>

</body>
</html>
$(document).ready(function(){
	/*
	$.getJSON('http://localhost:8000/Hello?callback=?',
	null,function(data){
	$('#hello').val(data);
	});
	*/
	$('#submit').click(function(){
	$.getJSON('http://localhost:8000/studentbyid/'+$('#studentid').val()+'?callback=?',
	null,function(data){
	$('#firstname').val(data.firstname);
	$('#lastname').val(data.lastname);

	});
	});
});

ต่อที่ PART II สำหรับ update delete insert data ( http://kungtee.rmutp.ac.th/index.php/web-service-part-2/ )

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.