2. WCF Service
A service exposes endpoints
(Endpoint: a port to communicate with outside world)
Sunday, December 16, 2012
Arbind
3. A Client
Exchanges messages with one or more Endpoints.
May also expose an Endpoint to receive Messages from a Service in a duplex
message exchange pattern.
Sunday, December 16, 2012
Arbind
4. Endpoint: Has
1. An Address
2. A Binding
3. A Contract
Sunday, December 16, 2012
Arbind
5. Address:
A network location where the Endpoint resides.
Represented by an EndpointAddress Class
EndpointAddress is a URI, a collection of AddressHeader and identity
Sunday, December 16, 2012
Arbind
6. Bindings: Has
1. A name
2. A namespace
3. A collection of binding elements
Sunday, December 16, 2012
Arbind
7. Collection of binding elements:
Each binding elements describe how to communicate with the end point
1. TcpTransportBindingElement indicates that the Endpoint will
communicate with the world using TCP as the transport protocol.
2. ReliableSessionBindingElement indicates that the Endpoint
uses reliable messaging to provide message delivery assurances.
3. SecurityBindingElement indicates that the Endpoint uses SOAP
message security.
Sunday, December 16, 2012
Arbind
8. Contracts:
Refers to the collection of operations which specify what endpoint will
communicate to out side world
Sunday, December 16, 2012
Arbind
9. ContractDescription class is used to describe WCF Contracts
and their operations.
Each Contract Operation have OperationDescriptions and
each operationDescription have MessageDescription
Sunday, December 16, 2012
Arbind
10. Duplex Contract: Defines two Logical Operations
1. A set that the Service exposes for the Client to call
2. A set that the Client exposes for the Service to call
Sunday, December 16, 2012
Arbind
11. Contract: Has
1. Name
2. Namespace
3. Identity
Sunday, December 16, 2012
Arbind
14. ServiceBehavior is a type which implements
IServiceBehavior and applies to service
Sunday, December 16, 2012
Arbind
15. ChannelBehavior is a type which implements
IChannelBehavior and applies to client
Sunday, December 16, 2012
Arbind
16. Service and Channel Descriptions
The ServiceDescription class describes a WCF Service including the
Endpoints exposed by the Service, the Behaviors applied to the
Service, and the type (a class) that implements the Service.
ServiceDescription is used to create metadata, code/config, and
channels.
Sunday, December 16, 2012
Arbind
18. ChannelDescription describes a WCF Client's Channel to a
specific Endpoint
ServiceDescription can have multiple endpoint but
ChannelDescription have only one endpoint
Sunday, December 16, 2012
Arbind
19. WCF Runtime:
The set of objects responsible for sending and receiving messages
Sunday, December 16, 2012
Arbind
20. Message:
The unit of data exchange between a Client and an Endpoint
A message should be of SOAP message type and can be serialized
using the WCF binary format, text XML, or any other custom
format.
Sunday, December 16, 2012
Arbind
21. Channels:
Channels are the core abstraction for sending Messages to and
receiving Messages from an Endpoint.
Sunday, December 16, 2012
Arbind
22. Two Category of channel:
1. Transport Channels handle sending or receiving opaque octet
streams using some form of transport protocol such as TCP, UDP,
or MSMQ.
2. Protocol Channels, implement a SOAP-based protocol by
processing and possibly modifying messages.
Sunday, December 16, 2012
Arbind
23. Procedure to define WCF Service
Step1: Defining and Implementing a Contract
using System.ServiceModel;
[ServiceContract]
public interface IMath
{
[OperationContract]
int Add(int x, int y);
}
Step2: Define a service class
This contract (interface IMath) is implemented to a class which becomes a
service class
public class MathService : IMath
{
public int Add(int x, int y)
{
return x + y;
}
}
Sunday, December 16, 2012
Arbind
24. Step3: Defining Endpoints and Starting the Service
(endpoint can be defined in code or in config)
In Code:
public class WCFServiceApp
{
public void DefineEndpointImperatively()
{
//create a service host for MathService
ServiceHost sh = new ServiceHost(typeof(MathService));
//use the AddEndpoint helper method to
//create the ServiceEndpoint and add it
//to the ServiceDescription
sh.AddServiceEndpoint( typeof(IMath),
//contract type new WSHttpBinding(),
//one of the built-in bindings "http://localhost/MathService/Ep1");
//the endpoint's address
//create and open the service runtime
sh.Open();
}
public void DefineEndpointInConfig()
{
//create a service host for MathService
ServiceHost sh = new ServiceHost (typeof(MathService));
//create and open the service runtime
sh.Open();
}
}
Sunday, December 16, 2012
Arbind
25. Endpoint in config file:
<!-- configuration file used by above code -->
<configuration
xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<system.serviceModel>
<services>
<!-- service element references the service type -->
<service type="MathService">
<!-- endpoint element defines the ABC's of the endpoint -->
<endpoint address="http://localhost/MathService/Ep1"
binding="wsHttpBinding" contract="IMath"/>
</service>
</services>
</system.serviceModel>
</configuration>
Sunday, December 16, 2012
Arbind
26. Step4: Sending Messages to the Endpoint
using System.ServiceModel;
//this contract is generated by svcutil.exe
//from the service's metadata
public interface IMath
{
[OperationContract]
public int Add(int x, int y)
{
return x + y;
}
}
//this class is generated by svcutil.exe
//from the service's metadata
//generated config is not shown here
public class MathProxy : IMath
{ ... }
Continue……….
Sunday, December 16, 2012
Arbind
27. In the following code first way to send the message to endpoint is like
SendMessageToEndpoint part. This hides the channel creation which is happening
behind the scene
Second way (SendMessageToEndpointUsingChannel) does it explicitly.
public class WCFClientApp
{
public void SendMessageToEndpoint()
{
//this uses a proxy class that was
//created by svcutil.exe from the service's metadata
MathProxy proxy = new MathProxy();
int result = proxy.Add(35, 7);
}
public void SendMessageToEndpointUsingChannel()
{
//this uses ChannelFactory to create the channel
//you must specify the address, the binding and
//the contract type (IMath)
ChannelFactory<IMath> factory=new ChannelFactory<IMath>( new WSHttpBinding(), new
EndpointAddress("http://localhost/MathService/Ep1"));
IMath channel=factory.CreateChannel();
int result=channel.Add(35,7);
factory.Close();
}
}
Sunday, December 16, 2012
Arbind
28. Step5: Defining custom behavior
We need to implement IServiceBehavior for service and IChannelBehavior for
client
All behaviors can be applied imperatively by adding an instance of the
behavior to the ServiceDescription (or the ChannelDescription on the client
side).
ServiceHost sh = new ServiceHost(typeof(MathService));
sh.AddServiceEndpoint( typeof(IMath), new WSHttpBinding(),
"http://localhost/MathService/Ep1");
//Add the behavior imperatively
// InspectorBehavior is a custom behavior
InspectorBehavior behavior = new InspectorBehavior();
sh.Description.Behaviors.Add(behavior);
sh.Open();
Sunday, December 16, 2012
Arbind
29. Secure Hosting and Deployment of WCF Services
Service host is a execution environment for service code
Service has to be hosted before deployment
Sunday, December 16, 2012
Arbind
30. Why host is required?
Provide security context for the execution of WCF service
Providing a mechanism to configure the WCF service
Providing a mechanism to monitor the statistics and health of WCF
service
Provide rapid fail protection and tools for WCF service
management
Sunday, December 16, 2012
Arbind
31. Type of host
1. Managed Application / Self Host
2. Managed Windows Service
3. IIS
4. WAS
Sunday, December 16, 2012
Arbind
32. Criteria for Choosing a WCF Service Host
Consider following things before coming to conclusion
A. Target Deployment Platform
B. Protocol to be supported by the service
Sunday, December 16, 2012
Arbind
33. Example:
If service needed to support HTTP, TCP, MSMQ and Named Pipe and
platform is Windows longhorn server – IIS 7.0 with WAS should
be used
If service needed to support HTTP and platform is Windows server
2003 – IIS 6.0 should be used
if TCP, MSMQ and Named Pipe required to be supported and
platform is Windows server 2003 - Managed Windows Service can
be used
If service need to support HTTP, TCP, MSMQ and Named Pipe
protocols on Windows Vista – IIS 7.0 along with WAS should be
used
On Windows XP, IIS 5.1 should be used if supported protocol is HTTP
and Windows service can be used for TCP, MSMQ and Named Pipe
Sunday, December 16, 2012
Arbind
34. How to select host?
Managed Application / Self Host
Any .NET managed application can host a WCF service by creating an instance
of ServiceHost Class
ServiceHost Class is a member of System.ServiceModel namespace
(Hosting a Service in managed application is also called Self Hosting)
Sunday, December 16, 2012
Arbind
35. Point to note: Self host does not provide features like message
based activation, mechanism to monitor service health or service
host resources or recycling of the service host process upon
detection of error conditions.
And so: This is useful in development environment but not in
production environment
Sunday, December 16, 2012
Arbind
36. In Self Hosting, the Service Host has to be instantiated at the time of
the managed application startup and closed before the managed
application shutdown.
Sunday, December 16, 2012
Arbind
37. The security context in Self Host is the identity under which the
managed application runs
Sunday, December 16, 2012
Arbind
38. A WCF Service hosted in a managed application can be exposed over
TCP, HTTP, HTTPS, Named Pipe and MSMQ protocols.
Sunday, December 16, 2012
Arbind
39. Code sample for creating a Service Host in
managed application
Using(ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService)))
{
//Open the Service Host to start receiving messages
serviceHost.Open();
// The service is now ready to accept requests
…..
…..
// Close the ServiceHost to shutdown the service.
serviceHost.Close();
}
Sunday, December 16, 2012
Arbind
40. The base address and the endpoints for the service host have to be configured in the
<services> sub section of the <system.serviceModel> section of the App.Config as
shown below:
<system.serviceModel>
<services>
<service
name="SecureHosting.Samples.CalculatorService"
behaviorConfiguration="CalculatorServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:9000/SecureHostingSamples/service"/>
</baseAddresses>
</host>
<endpoint address=""
binding="wsHttpBinding"
contract="SecureHosting.Samples.ICalculator" />
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="True" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Sunday, December 16, 2012
Arbind
41. Base Address and endpoint can also be configured
programmatically instead of configuring in App.Config file
// Create a ServiceHost for the CalculatorService type.
using (ServiceHost serviceHost =
new ServiceHost(typeof(CalculatorService),new
Uri("http://localhost:9000/SecureHostingSamples/service")))
{
//Configure the service with an end point
serviceHost.AddServiceEndpoint(typeof(ICalculator),
new WSHttpBinding(), "");
// Open the ServiceHost to start receiving messages
serviceHost.Open();
….
….
….
//Close the service host to shutdown the service
serviceHost.Close ();
}
Sunday, December 16, 2012
Arbind
42. Managed Window Service
(A Window Service running under managed environment)
Service can be installed using Installutil tool.
The service can be exposed to HTTP, TCP, MSMQ and Named Pipe protocol
Sunday, December 16, 2012
Arbind
43. The window service which host the service inherits from the
ServiceBase class and also implements contract
Sunday, December 16, 2012
Arbind
44. Windows Service provides the facility to manage the lifecycle of the
service via the Service Control Manager (SCM) console
Sunday, December 16, 2012
Arbind
45. Windows Service Host does not provide a message based activation
Sunday, December 16, 2012
Arbind
46. Window service leverages the OnStart event to create service host
and host closes on OnStop event.
Sunday, December 16, 2012
Arbind
47. Security context can be configured using Installer Class with the help
of ServiceProcessInstaller.
Sunday, December 16, 2012
Arbind
48. Sample Code to create Managed Window Service
public class CalculatorService : ServiceBase, ICalculator
{
public ServiceHost serviceHost = null;
public static void Main()
{
ServiceBase.Run(new CalculatorService());
}
public CalculatorService()
{
ServiceName = "WCFWindowsCalculatorService";
}
//Start the Windows service.
protected override void OnStart(string[] args)
{
if (serviceHost != null)
{
serviceHost.Close();
}
// Create a ServiceHost for the Service
serviceHost = new ServiceHost(typeof(CalculatorService));
// Start Listening for the Messages
serviceHost.Open();
}
//Stop the Windows Service
protected override void OnStop()
{
if (serviceHost != null)
{
serviceHost.Close();
serviceHost = null;
}
}
}
Sunday, December 16, 2012
Arbind
49. IIS
Allows the Services to be hosted in the App Domains inside the ASP.NET
worker process
Supported IIS: 5.1, 6.0, 7.0 8.0(BETA)
(Only Http and Https can be handled)
Sunday, December 16, 2012
Arbind
50. IIS handles the service request in the same way as it handles web
request
Supports message based activation and service instance is created
only after receiving the first message.
Sunday, December 16, 2012
Arbind
51. The security context for the WCF Service hosted inside the ASP.NET
worker process is provided by the service account under which the
worker process runs.
(Knowledge Sharing)
WHAT WILL BE THE SECURITY TO BE IMPLEMENTED?
Sunday, December 16, 2012
Arbind
52. Hosting a service in IIS requires .SVC file to be created
If required a Custom Service Host we can create it using
System.ServiceModel.Activation.ServiceHostFactory Class
(Virtual applications are created and DLLs and sources are deployed to the
physical path associated with the virtual application)
Sunday, December 16, 2012
Arbind
53. The configuration for the service endpoints has to be defined in the
Web.Config
The .SVC file should contain code like:
<%@ServiceHost language=c# Debug="true" Service="
SecureHosting.Samples.CalculatorService" %>
Sunday, December 16, 2012
Arbind
54. Web.Config for IIS Host:
<system.serviceModel>
<services>
<service name="SecureHosting.Samples.CalculatorService"
behaviorConfiguration="CalculatorServiceBehavior">
<!-- This endpoint is exposed at the base address provided by host:
http://localhost/securehostingsamples/service.svc -->
<endpoint address=""
binding="wsHttpBinding"
contract="SecureHosting.Samples.ICalculator" />
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<!--For debugging purposes set the includeExceptionDetailInFaults attribute to true--
>
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="True" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Sunday, December 16, 2012
Arbind
55. WAS (Windows Activation Service)
WAS enables IIS 7.0 to leverage message based activation for
protocols such as TCP, MSMQ and Named Pipes in addition to the
HTTP protocol
Available with Windows Vista and Windows Longhorn Server
Service deployment process for IIS 7.0/WAS is same as discussed
earlier for IIS host
Sunday, December 16, 2012
Arbind
56. Note:
1. web sites need to be configured via the APPCMD utility to support
non HTTP protocols
2. To do this command shell must be started in “Run as
Administrator” mode
Sunday, December 16, 2012
Arbind
57. Command to run:
%windir%system32inetsrvappcmd.exe set site "Default Web Site"
-+bindings.[protocol='net.tcp',bindingInformation='808:*'] FOR
TCP
%windir%system32inetsrvappcmd.exe set site "Default Web Site"
-+bindings.[protocol='net.msmq',bindingInformation='*'] FOR
MSMQ
%windir%system32inetsrvappcmd.exe set site "Default Web Site"
-+bindings.[protocol='net.pipe',bindingInformation='*'] FOR
NAMED PIPE
Sunday, December 16, 2012
Arbind
58. After running the command APPCMD updates configuration file for WAS
ApplicationHost.Config
<system.applicationHost>
<sites>
<site name="Default Web Site" id="1">
<bindings>
<binding protocol="http"
bindingInformation="*:80:" />
<binding protocol="net.pipe"
bindingInformation="*" />
<binding protocol="net.tcp"
bindingInformation="808:*" />
<binding protocol="net.msmq"
bindingInformation="*" />
</bindings>
</site>
</sites>
</system.applicationHost>
Sunday, December 16, 2012
Arbind
59. To enable the TCP protocol (in addition to the HTTP protocol) for the
“SecureHostingSamples” application, the following command should be run
from an administrator shell:
%windir%system32inetsrvappcmd.exe set app "Default Web
Site/securehostingsamples" /enabledProtocols:http,net.tcp
Sunday, December 16, 2012
Arbind
60. Selecting Binding:
Criteria to select Bindings:
1. Consider the deployment environment whether it is for Internet, Intranet,
Federated Environment, Windows only or a Heterogeneous Environment
2. Security to be implemented
3. Performance Issues
Sunday, December 16, 2012
Arbind
61. A WCF service can be assigned:
1. Transport level security,
2. Message level security or
3. A combination of transport and message level security.
Sunday, December 16, 2012
Arbind
62. A service can be defined with an authentication mode of
1. None,
2. Username,
3. Windows,
4. Certificates and
5. IssuedToken.
Authentication process between the client and the service includes the
authentication of service to the client as well as the authentication of the
client to the service.
Sunday, December 16, 2012
Arbind
63. Deploying a WCF Service over Windows Only Intranet
In Windows only Intranet, if all the service clients are WCF clients, the
service can be deployed using NetTCPBinding and transport level security
to achieve maximum performance.
(NetTCPBinding by default uses transport level security along with TCP
channel and binary message encoding)
ClientCredentialType is set to Windows to enable Windows Authentication
Code Sample:
<bindings>
<netTcpBinding>
<binding name="Binding1">
<security mode="Transport" />
<transport
clientCredentialType="Windows" protectionLevel="EncryptAndSign"/>
</security>
</binding>
</netTcpBinding>
</bindings>
Sunday, December 16, 2012
Arbind
64. Interoperability with web services
The WCF service can be configured to use BasicHttpBinding with transport
level security.
HTTP/GET metadata should be enabled for the service in the service behavior
section.
Sunday, December 16, 2012
Arbind
65. Deploying a WCF Service over Internet or in a Heterogeneous Environment
(needs to potentially interact with the clients on non-windows platforms)
--BasicHttpBinding or WSHttpBinding can be used depending upon the level of
conformance required with the commonly used security standards
If interoperability is required with web service only BasicHttpBinding should be
used.
Sunday, December 16, 2012
Arbind
66. To support SOAP Message Security UserName Token Profile version 1.0, the
WCF service should be configured with BasicHttpBinding with security
mode of TransportWithMessageCredential and client credential type of
UserName.
Example:
<basicHttpBinding>
<binding name="Binding1">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName" />
</security>
</binding>
</basicHttpBinding>
Sunday, December 16, 2012
Arbind
67. Deployment in Federated Environment
WCF Service client obtains a security token from Security Token Service (STS)
which is trusted by WCF Service
WCF Service should be configured for WSFederatedHttpBinding
The security token also contains the address of the endpoint to retrieve
metadata of STS
the certificate used by STS for signing the security token should be added to
the list of known certificates in the service credential section.
Sunday, December 16, 2012
Arbind
69. Assignment For All
Create a WCF service to convert
Fahrenheit to Celsius and vice versa and
to be hosted in IIS
If done: mail it on
arbindkumar_tiwari@satyam.com
Sunday, December 16, 2012
Arbind