1) เริ่มแรกสร้างโปรเจ็คใหม่เป็น Windows Service Application (C#) และใส่โค้ดในหน้า Service1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WebServiceHost wsh = new WebServiceHost(
typeof(Service2), new Uri("http://localhost:8000"));
// JSONP
WebHttpBinding whb = new WebHttpBinding();
whb.CrossDomainScriptAccessEnabled = true;
wsh.AddServiceEndpoint(typeof(iService1), whb, "");
wsh.Open();
}
protected override void OnStop()
{
}
}
[System.ServiceModel.ServiceContract]
public interface iService1
{
[OperationContract,
WebGet(ResponseFormat = WebMessageFormat.Json)]
string Hello();
[OperationContract,
WebGet(ResponseFormat = WebMessageFormat.Json)]// ต้องครอบทุกตัวด้านบน
List<student> getAllstudent();
[OperationContract,
WebInvoke(Method="GET", ResponseFormat = WebMessageFormat.Json,
UriTemplate="studentbyid/{StudentID}")]// ต้องครอบทุกตัวด้านบน
student getStudentById(String StudentID);
[OperationContract,
WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle=WebMessageBodyStyle.WrappedRequest)]
int AddStudent(String StudentID, String FirstName, String LastName);
}
public class Service2 : iService1
{
public string Hello()
{
return "ss";
}
DataClasses1DataContext mywcfdb1 = new DataClasses1DataContext();
public List<student> getAllstudent()
{
return mywcfdb1.students.ToList();
}
public student getStudentById(String StudentID)
{
int sid = int.Parse(StudentID);
return mywcfdb1.students.Where(
s => s.studentId == sid).SingleOrDefault();
}
public int AddStudent(String StudentID, string FirstName, string LastName)
{
int stdID = int.Parse(StudentID);
student newstudent = new student();
newstudent.studentId = stdID;
newstudent.firstname = FirstName;
newstudent.lastname = LastName;
mywcfdb1.students.InsertOnSubmit(newstudent);
mywcfdb1.SubmitChanges();
return 1;
}
}
}
2) Add new item LINQ to SQL Class

3) เปิด Server Explorer ลาก Table ใน Database มาวาง

3) ปรับ Installer Service

4) ทำการ Build แล้ว Coppy Code ในฟอเดอร Debug ไปไว้ที่ Drive C

5) ไปที่ปุ่ม Start->Visual Studio Tool->Command Prom จะพบกับหน้า DOS ให้พิมพ์
cd C:\wcfservice
installutil -i WindowsService.exe

6) ไปเปิดดู Service Local แล้วคลิ้กขวาเลือก Start

7) เปิด Browser แล้วลองทดสอบการใช้งานตามภาพ
