A WCF
Restful based service (15 min)
Tools
required: (minimum)
- Visual C# 2010 Express (minimum)
- SQL
server express
My intention
with this guide is to create a couple of services using two serialization
formats: XML and Json; To make it worth the services will return data from a
SQL Server database using EF, so we will start creating a database that will
contain a table named clients.
1)
Open MSMS and execute the
following script:
(Make sure that
you have a folder C:\Temp as shown
in the script)
CREATE DATABASE [DBTest] ON PRIMARY
( NAME = N'DBTest', FILENAME = N'C:\Temp\DBTest.mdf'
, SIZE = 3072KB,
MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB
)
LOG ON
( NAME = N'DBTest_log', FILENAME = N'C:\Temp\DBTest_log.ldf'
, SIZE = 1024KB
, MAXSIZE =
2048GB , FILEGROWTH =
10%)
GO
USE DBTest
GO
CREATE TABLE [dbo].[Clients]
(
[ClientId]
[int] IDENTITY(1,1) NOT NULL,
[Name]
[nvarchar](100)
NOT NULL,
[Email]
[nvarchar](100)
NOT NULL,
[Phone]
[nvarchar](50) NOT NULL,
CONSTRAINT [PK_Clients] PRIMARY
KEY CLUSTERED
(
[ClientId]
ASC
)
WITH
(
PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS
= ON, ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
) ON [PRIMARY]
GO
2)
Open Visual Studio
3) Create a New Project, Name it SvcClient
4) From Installed Templates
select WCF > WCF Service Application > Click on “Create directory for solution” and click OK.
5)
Rich click on the project we’ve
just created and Select Add > New Project
6)
From
Installed Templates select Data >
ADO.NET Entity Data Model and click Add.
10)
Right Click on the model you’ve
just created, select Properties and
change Code Generation Strategy to None (Save and close the file)
12)
Right
click on Entities folder > Add > Class… > name it: Client
[DataMember]
public Int32 ClientId { get; set; }
[DataMember]
public String Name { get; set; }
[DataMember]
public String Email { get; set; }
[DataMember]
public String Phone { get; set; }
14)
Decorate
your class with the following attribute:
[DataContract]
15)
Resolve
the errors:
16)
Add another
class to the folder entities and name it EFContext.cs,
(right click on Entities folder > Add > Class… > name it: EFContext.cs)
17)
Add
the following code to the EFContext class:
public EFContext() : base("name=DBTestEntities", "DBTestEntities")
{
_Clients = CreateObjectSet<Client>("Clients");
}
public ObjectSet<Client> Clients
{
get
{
if (_Clients == null)
{
_Clients = base.CreateObjectSet<Client>("Clients");
}
return _Clients;
}
}
private ObjectSet<Client> _Clients;
18)
Inherit
EFContext from ObjectContext
19)
Resolve
errors, and save.
21)
Add
the following code to your class ClientRepository
private EFContext model = new EFContext();
public Client[] GetAllClients()
{
return model.Clients.ToArray();
}
public Client GetClient(int clientId)
{
return model.Clients.Where(c => c.ClientId == clientId).FirstOrDefault();
}
22)
Resolve
errors.
23)
Open
IService1.cs, remove the class CompositeType and replace the body of the class IService1 with the
following code:
[OperationContract]
[WebGet(UriTemplate = "Clients")]
Client[] GetAllClients();
[OperationContract]
[WebGet(UriTemplate = "Clients/json", ResponseFormat = WebMessageFormat.Json)]
Client[] JsonGetAllClients();
[OperationContract]
[WebGet(UriTemplate = "Clients?clientId={clientId}")]
Client GetClient(int clientId);
[OperationContract]
[WebGet(UriTemplate = "Clients/xml?clientId={clientId}", ResponseFormat = WebMessageFormat.Xml)]
Client GetXmlClient(int clientId);
[OperationContract]
[WebGet(UriTemplate = "Clients/json?clientId={clientId}", ResponseFormat = WebMessageFormat.Json)]
Client GetJsonClient(int ClientId);
25)
Open Service1.svc
and replace the body of the class Service1 with the following:
ClientRepository clientRepository;
public Service1()
{
clientRepository = new ClientRepository();
}
public Client[] GetAllClients()
{
return clientRepository.GetAllClients();
}
public Client[] JsonGetAllClients()
{
return clientRepository.GetAllClients();
}
public Client GetClient(int clientId)
{
return clientRepository.GetClient(clientId);
}
public Client GetXmlClient(int clientId)
{
return clientRepository.GetClient(clientId);
}
public Client GetJsonClient(int clientId)
{
return clientRepository.GetClient(clientId);
}
26)
Resolve
errors
27)
Right
click on Service.svc and select View Markup
28)
Replace
the current code with following markup, note that we are only adding the “Factory”
attribute.
<%@ ServiceHost Language="C#"
Debug="true" Service="Post2.Service1" CodeBehind="Service1.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
29)
Insert
a couple of records in the client’s table.
INSERT INTO Clients( name, email, phone)
VALUES( 'Dwyane Wade', 'wade@email.com', '234 234 2345')
INSERT INTO Clients( name, email, phone)
VALUES( 'Maria Sharapova', 'maria@email.com', '234 234 2222')
30)
Press
F5 and test the following URLs
We’ve just quickly created 5 services using
WebGet (HTTP verb GET), use WebInvoke for POST, PUT and DELETE.
Considerations