Perform CRUD operations using WCF REST Services - 01. Creating Service

by Jagadish Pulakhandam on 8/8/2011 2:37:09 PM
Rated 3 from 1 votes
Brief: Demonstrates on developing a WCF REST Service from the scratch using "WCF Service Library" template.
Posted to: Hosting WCF REST Services
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Attached Video demonstrates the following:

  • Developing a WCF REST service from the scratch
  • Using "WCF Service Library" template for developing WCF REST Service
  • Specifying various WCF REST endpoints for various operations (to perform CRUD operations)
  • Configuring "WCF REST Service" using service configuration editor
  • Executing and testing "WCF REST Service" using WCF Service Host (of Visual Studio)
  • Testing an endpoint using IE.
More testing (on all CRUD operations along with "consuming WCF REST Service") is covered in up coming videos.

01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Text;
05. 
06.using System.Data;
07.using System.Data.SqlClient;
08. 
09.namespace SampleEmpServiceLib
10.{
11.    public class DbHelper
12.    {
13. 
14.        private static string ConnectionString
15.        {
16.            get
17.            {
18.                return System.Configuration.ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
19.            }
20.        }
21. 
22.        public DataTable GetResultSet(string sql)
23.        {
24.            DataTable dt = new DataTable();
25.            using (SqlDataAdapter da = new SqlDataAdapter(sql, ConnectionString))
26.            {
27.                da.Fill(dt);
28.            }
29.            return dt;
30.        }
31. 
32.        public void SqlExecute(string sql)
33.        {
34.            using (SqlCommand cmd = new SqlCommand(sql, new SqlConnection(ConnectionString)))
35.            {
36.                cmd.Connection.Open();
37.                cmd.ExecuteNonQuery();
38.                cmd.Connection.Close();
39.            }
40.        }
41. 
42.    }
43.}
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Text;
05. 
06.using System.ServiceModel;
07.using System.ServiceModel.Web;
08. 
09.namespace SampleEmpServiceLib
10.{
11.    [ServiceContract()]
12.    public interface IEmpService
13.    {
14.        [OperationContract()]
15.        [WebGet(UriTemplate="Employees")]
16.        List<Employee> GetEmployeeList();
17. 
18.        [OperationContract()]
19.        [WebGet(UriTemplate = "Employees/{Empno}")]
20.        Employee GetEmployeeById(string Empno);
21. 
22.        [OperationContract()]
23.        [WebInvoke(UriTemplate = "Employees", Method="POST")]
24.        void AddEmployee(Employee oEmp);
25. 
26.        [OperationContract()]
27.        [WebInvoke(UriTemplate = "Employees", Method = "PUT")]
28.        void UpdateEmployee(Employee oEmp);
29. 
30.        [OperationContract()]
31.        [WebInvoke(UriTemplate = "Employees/{Empno}", Method = "DELETE")]
32.        void DeleteEmployee(string Empno);
33. 
34.    }
35.}
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Text;
05. 
06.using System.Data;
07. 
08.namespace SampleEmpServiceLib
09.{
10.    public class EmpService : IEmpService
11.    {
12.        public List<Employee> GetEmployeeList()
13.        {
14.            var dt = (new DbHelper()).GetResultSet("SELECT empno, ename, sal, deptno FROM emp");
15.            var qEmp = from dr in dt.AsEnumerable()
16.                       select new Employee()
17.                       {
18.                           Empno = dr["empno"].ToString(),
19.                           Ename = dr["ename"].ToString(),
20.                           Sal = dr["sal"].ToString(),
21.                           Deptno = dr["deptno"].ToString()
22.                       };
23. 
24.            return qEmp.ToList();
25.        }
26. 
27.        public Employee GetEmployeeById(string Empno)
28.        {
29.            var dt = (new DbHelper()).GetResultSet("SELECT empno, ename, sal, deptno FROM emp WHERE empno = " + Empno);
30.            if (dt.Rows.Count > 0)
31.            {
32.                var dr = dt.Rows[0];
33.                return new Employee()
34.                {
35.                    Empno = dr["empno"].ToString(),
36.                    Ename = dr["ename"].ToString(),
37.                    Sal = dr["sal"].ToString(),
38.                    Deptno = dr["deptno"].ToString()
39.                };
40.            }
41.            return null;
42.        }
43. 
44.        public void AddEmployee(Employee oEmp)
45.        {
46.            StringBuilder sb = new StringBuilder();
47.            sb.Append("INSERT INTO Emp (Empno, Ename, Sal, Deptno) VALUES ");
48.            sb.AppendFormat("( {0}, '{1}', {2}, {3} )",
49.                oEmp.Empno, oEmp.Ename, oEmp.Sal, oEmp.Deptno);
50. 
51.            (new DbHelper()).SqlExecute(sb.ToString());
52. 
53.        }
54. 
55.        public void UpdateEmployee(Employee oEmp)
56.        {
57.            StringBuilder sb = new StringBuilder();
58.            sb.Append("UPDATE Emp SET ");
59.            sb.AppendFormat(" ename = '{0}', sal = {1}, deptno = '{2}' WHERE empno = {3} ",
60.                oEmp.Ename, oEmp.Sal, oEmp.Deptno, oEmp.Empno);
61. 
62.            (new DbHelper()).SqlExecute(sb.ToString());
63. 
64.        }
65. 
66.        public void DeleteEmployee(string Empno)
67.        {
68.            (new DbHelper()).SqlExecute("DELETE FROM Emp WHERE empno = " + Empno);
69.        }
70.    }
71.}
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Text;
05. 
06.using System.Runtime.Serialization;
07. 
08.namespace SampleEmpServiceLib
09.{
10.    [DataContract(Namespace = "")]
11.    public class Employee
12.    {
13. 
14.        [DataMember(Order = 0)]
15.        public string Empno { get; set; }
16. 
17.        [DataMember(Order = 1)]
18.        public string Ename { get; set; }
19. 
20.        [DataMember(Order = 2)]
21.        public string Sal { get; set; }
22. 
23.        [DataMember(Order = 3)]
24.        public string Deptno { get; set; }
25. 
26.    }
27.}
01.<?xml version="1.0"?>
02.<configuration>
03. 
04.  <connectionStrings>
05.    <add name="cn" connectionString="Data Source = .\sql2k8; initial catalog=Sample; user id=sa; password=sql2008"/>
06.  </connectionStrings>
07. 
08.  <system.web>
09.    <compilation debug="true"/>
10.  </system.web>
11. 
12.  <startup>
13.    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
14.  </startup>
15.   
16.   
17.  <system.serviceModel>
18.    <behaviors>
19.      <endpointBehaviors>
20.        <behavior name="SampleEmpSvcWebBehavior">
21.          <webHttp />
22.        </behavior>
23.      </endpointBehaviors>
24.      <serviceBehaviors>
25.        <behavior name="SampleEmpSvcBehavior">
26.          <serviceDebug includeExceptionDetailInFaults="true" />
27.          <serviceMetadata httpGetEnabled="true" />
28.        </behavior>
29.      </serviceBehaviors>
30.    </behaviors>
31.    <services>
32.      <service behaviorConfiguration="SampleEmpSvcBehavior" name="SampleEmpServiceLib.EmpService">
33.        <endpoint address="" behaviorConfiguration="SampleEmpSvcWebBehavior"
34.          binding="webHttpBinding" bindingConfiguration="" name="SampleEmpSvcWebHttpBinding"
35.          contract="SampleEmpServiceLib.IEmpService" />
36.        <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
37.          name="SampleEmpSvcMexEndPoint" contract="IMetadataExchange" />
38.        <host>
39.          <baseAddresses>
40.            <add baseAddress="http://localhost:8080/SampleEmpService" />
41.          </baseAddresses>
42.        </host>
43.      </service>
44.    </services>
45.  </system.serviceModel>
46.</configuration>


Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 3 from 1 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following

Video/Screen Recording (may not have audio narration/annotations)
You need to Login or Join for FREE to download the following