You are on page 1of 62

.NET 3.

5 WCF
Programming
Introduction
Presented by Cuong@microsoft.com

Agenda
Basic Demo
Some tools for WCF programming
Self hosting and IIS hosting

Windows Communication Foundation - ABC


Architecture
ABC
Contract
Binding Custom Binding
WCF for SilverLight, JSON

Behaviors
Concurrency and Instancing Mode

Security

.NET 2.0 ASMX Web Service


Rehearse how to create a ASP.net 2.0 web service.
Lets do a simple WCF web service.
Not much different at basic level:
[WebMethod] vs [Operation]
Both can be hosted in IIS7

But WCF can do more than that


Support different transport protocols: HTTP, TPC,
NamePipe, MSMQ,
Concurrency and Instancing modes.

WCF Design Goals


The unified programming model for rapidly
building service-oriented applications on the
Windows
Unifies todays distributed

Unification
Productive
Service-Oriented
Programming
Interoperability &
Integration

technology stacks
Composable functionality
Appropriate for use on-machine, in
the intranet, and cross the Internet

Service-oriented programming
model
Supports 4 tenets of serviceorientation
Maximized developer productivity
WS-* interoperability with applications
running
on other platforms
Interoperability with todays
distributed stacks

Unified Model

ASMX

Enterprise
Services

Basic
Open
Interop

Fast
Secure
Binary
Txns

WSE

Remotin
g

Secure
Open
Interop

Fast
Secure
Binary

MSMQ
Queued
Txns

Before we have
Remote Procedure Call
COM+
.NET Remoting
ASP.net web service
Hard code TCP Socket
MSMQ

With WCF .net 3.5

Unified Model Benefits


Programming model
Learning curve
Consistency
Write less code when using multiple
technologies

Flexibility
Environments
Productivity in development environment
Simplify Automated Integration Testing
Deployment options in production
Design for distribution, run local

Elements in WCF

Before we go further
WCF Service can be configured in code
WCF Service can be configured in XML or
mix.
03 different ways to host WCF
Self Hosting
IIS Hosting
Windows Service

Implement WCF in code


ServiceHost serviceHost = new ServiceHost(typeof(StockService),
new
Uri("http://localhost:8000/EssentialWCF"));
serviceHost.AddServiceEndpoint(
typeof(IStockService),
new BasicHttpBinding(),
"");
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(behavior);
serviceHost.AddServiceEndpoint(
typeof(IMetadataExchange),
MetadataExchangeBindings.CreateMexHttpBinding(),
"mex");
serviceHost.Open();
// The service can now be accessed.
Console.WriteLine("The services is ready. Press <ENTER> to
terminate.\n\n");
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
serviceHost.Close();

Demo

WCF Configuration File


<system.serviceModel>
<services>
<service name="EssentialWCF.StockService"
behaviorConfiguration="myServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/EssentialWCF"/>
</baseAddresses>
</host>
<endpoint address=""
binding="basicHttpBinding"
contract="EssentialWCF.IStockService" />
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="myServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Demo C:\WCF\SomeWebServices\SimpleService\Config\Service

Services and Clients

Endpoints

Client

Service
Endpoint

Endpoint

Message

Endpoint

The service endpoint contains the information about the Address,


Binding, Contract, and Behavior required by a client to find and
interact with the service at this endpoint.

Address, Binding, Contract

Client

Service

Message

Address Binding Contract


(Where)

(How)

(What)

How client knows WCF service mex


Metadata tells client how to connect & communicate to web service.
Design time, client sends request defined in WS-Metadata exchange
standard and get WSDL in return.
WSDL is then used to create proxy class and create config file at client

Expose mex endpoint by code or config


httpGetEnabled allows client to query mex through
file
Http Get method.

<system.serviceModel>
<services>
<service name="WCFServiceApplication.Service1"
behaviorConfiguration="WCFServiceApplication.Service1Behavior">
<endpoint address="" binding="wsHttpBinding"
contract="WCFServiceApplication.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WCFServiceApplication.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false
and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

Some tools to debug, and test


WCF
WCF Test Client

WCF Service
Configuration Editor

WCF Architecture: Messaging


Runtime

Client

Protocol(s
)

Service
Dispatcher

Contract
and
Behaviors

Protocol(s
)

Encoder

Encoder

Transport

Transport

Binding

Address

WCF Architecture: Composition &


Behaviors

Formatter
Behavior

Transactio
n Behavior

Formatter
Behavior

Message
Inspector

Service
Code
Instancing
Behavior

Service Model Layer

Securit
y
Channe
l

TCP
Transpor
t

Securit
y
Channe
l

TCP
Transpor
t

Messaging Layer

Influences system operation Moves messages back and forth


based on incoming and
and adds transfer semantics.
outgoing messages.
Channels are symmetric.
Effects of behaviors are local.

Contracts

Three Types of Contracts


Service Contract
Maps the class methods of a .NET type to WSDL services, port
types, and operations. Operation contracts within service
contracts describe the service operations, which are the methods
that implement functions of the service.

Data Contract
Describe data structures that are used by the service to
communicate with clients. A data contract maps CLR types to XML
Schema Definitions (XSD) and defines how they are serialized and
deserialized. Data contracts describe all the data that is sent to or
from service operations.

Message Contract
Map CLR types to SOAP messages and describe the format of the
SOAP messages and affect the WSDL and XSD definitions of those
messages. Message contracts provide precise control over the
SOAP headers and bodies.

Data Contract

[DataContract]
public class ComplexNumber
{
[DataMember]
public double Real = 0.0D;
[DataMember]
public double Imaginary = 0.0D;
public ComplexNumber(double r, double i)
{
this.Real = r;
this.Imaginary = i;
}
}

Demo
Basic data type data contract
Class data type data contract
Hierarchy data type data contract
Collection data contract

C:\WCF\Contracts\HRServi
ce

Multiple Contracts in an EndPoint


[ServiceContract]
public interface IGoodStockService
{
[OperationContract]
double GetStockPrice(string ticker);
}
[ServiceContract]
public interface IGreatStockService
{
[OperationContract]
double GetStockPriceFast(string ticker);
}
[ServiceContract]

public interface IAllStockServices : IGoodStockService,


IGreatStockService { };
public class AllStockServices : IAllStockServices
{
public double GetStockPrice(string ticker)
{
}
public double GetStockPriceFast(string ticker)
{
}
}

Ways to Talk / Service Contract


One Way

Client

Service
Request-Reply
Duplex (Dual)

One Way:
Datagram-style delivery

Request-Reply
Immediate Reply on same logical thread

Duplex
Reply later and on backchannel (callbackstyle)

Service Contract

using System.ServiceModel;
[ServiceContract]
public interface ICalculate
{
[OperationContract]
double Add( double a, double b);
[OperationContract]
double Subtract( double a, double b);
}

Synchronous vs Asynchronous Request


Response
Main Thread
Service

BeginOperation

New Thread

EndOperation

client.AddCompleted += new EventHandler<MathPlayer.


MathService.AddCompletedEventArgs>(client_AddCompleted);
client.AddAsync(int.Parse(txtA.Text), int.Parse(txtB.Text));

Service Contract: OneWay


[ OperationContract(IsOneWay = true)]
void DoBigAnalysisFast(string ticker);
[OperationContract]
void DoBigAnalysisSlow(string ticker);

The client just needs acknowledgement of successful delivery;


it does
not need an actual response from the service

Demo C:\WCF\03_OneWay

Duplex Communication
Use
wsDualHttpBinding
Since two endpoints are
used, we can define two
different bindings,
protocol for each
channels

Service Contract: Duplex


Asymmetric
[ServiceContract(Session=true,
CallbackContract=typeof(ICalculatorResults)]
public interface ICalculatorProblems
{
[OperationContract(IsOneWay=true)]
void SolveProblem (ComplexProblem p);
}
public interface ICalculatorResults
{
[OperationContract(IsOneWay=true)]
void Results(ComplexProblem p);
}

Service Contract: Duplex


Symmetric

[ServiceContract(Session=true,
CallbackContract=typeof(IChat)]
public interface IChat
{
[OperationContract(IsOneWay=true)]
void Talk(string text);
}

Demo
Request Reply
One Way
One Service many EndPoints

Service Contract: Faults


[ServiceContract(Session=true)]
public interface ICalculator
{
[OperationContract]
[FaultContract(typeof(DivideByZero))]
ComplexProblem SolveProblem (ComplexProblem p);
}
try {
return n1 / n2;
}
catch (DivideByZeroException e) {
DivideByZero f = new DivideByZero (Calculator);
throw new FaultException<DivideByZero>(f);
}

Message Contract

[MessageContract]
public class ComplexProblem
{
[MessageHeader]
public string operation;
[MessageBody]
public ComplexNumber n1;
[MessageBody]
public ComplexNumber n2;
[MessageBody]
public ComplexNumber solution;
// Constructors
}

Bindings

Bindings & Binding Elements

Binding
HTTP

Transport

Text Security Reliability

Encoders

TX

Protocol

TCP

HTTP

Text

Security

Reliability

MSMQ

IPC

Binary

TX

.NET

Custom

Custom

Custom

Standard Bindings in WCF.net


3.0
Binding

Interop

Security

Session

TX

Duplex

BasicHttpBinding

BP 1.1

N, T

n/a

WSHttpBinding

WS

M, T, X

N, T, RS N, Yes n/a

WSDualHttpBinding

WS

RS

N, Yes Yes

WSFederationBinding

Federation M

N, RS

N, Yes No

NetTcpBinding

.NET

T, M

T ,RS

N, Yes Yes

NetNamedPipeBinding .NET

T, N

N, Yes Yes

NetPeerTcpBinding

Peer

NetMsmqBinding

.NET

T, M, X

N, Yes No

N, Yes n/a

MsmqIntegrationBindi
MSMQ
ng

Yes

N = None | T = Transport | M = Message | B = Both | RS = Reliable Sessions

New bindings in WCF.net 3.5


ws2007HttpBinding
ws2007FederationBinding

Supported Features of Each


Binding

Choose a binding that suits your


need

Reliability and Transactions


End-to-end Reliable messaging
In-order guarantees
Exactly once guarantees

Transport-Independent Sessions
Integration with ASP.NET Sessions in IISHosted compatibility mode

Transactions
Guaranteed atomic success or failure
across services

Bindings & Behaviors: Reliable


Sessions
Client
C

Service

Bindings
provide
Session and
Guarantees

Reliable Messaging: in-order and exactly once


(similar to MSMQ and MQSeries guarantees).

Bindings & Behaviors:


Transactions
Client
C

Be

Service

Be

Bindings Flow
Transactions
Behaviors
AutoEnlist and
AutoComplete
1- Multistep business process : Long running transaction WF
integrates with WCF
2- Short running transaction
In next training, I will talk more detail with demo for transactions

Defining Endpoints

<?xml version="1.0" encoding="utf-8" ?>


<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<system.serviceModel>
<services>
<service serviceType="CalculatorService">
<endpoint address="Calculator"
bindingSectionName="basicProfileBinding"
contractType="ICalculator" />
</service>
</services>
</system.serviceModel>
</configuration>

Configuring Bindings
<endpoint address="Calculator"
bindingSectionName="basicProfileBinding"
bindingConfiguration="Binding1"
contractType="ICalculator" />

<bindings>
<basicProfileBinding>
<binding configurationName="Binding1"
hostnameComparisonMode="StrongWildcard"
transferTimeout="00:10:00"
maxMessageSize="65536"
messageEncoding="Text"
textEncoding="utf-8"
</binding>
</basicProfileBinding>
</bindings>

Custom Bindings
<bindings>
<customBinding>
<binding configurationName="Binding1">
<reliableSession bufferedMessagesQuota="32"
inactivityTimeout="00:10:00"
maxRetryCount="8"
ordered="true" />
<httpsTransport manualAddressing="false"
maxMessageSize="65536"
hostnameComparisonMode="StrongWildcard"/>
<textMessageEncoding maxReadPoolSize="64"
maxWritePoolSize="16"
messageVersion="Default"
encoding="utf-8" />
</binding>
</customBinding>
</bindings>

Multiple EndPoints in a Service


Scenarior: SilverLight app can connect to
basicHttpBinding while WPF app can
connect to wsHttpBinding. If we have one
service how can we serve two types of
clients.
<service behaviorConfiguration="MathWCFServiceApplication.MathServiceBehavior"
name="MathWCFServiceApplication.MathService">
<!--EndPoint ny s dng cho WPF client-->
<endpoint name="wsHttpMath" address="ws" binding="wsHttpBinding"
contract="MathWCFServiceApplication.IMathService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<!--EndPoint ny s dng cho SilverLight client-->
<endpoint name="basicHttpMath" address="basic" binding="basicHttpBinding"
contract="MathWCFServiceApplication.IMathService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>

Example: SilverLight consumes


WCF

WCF returns JSON


JSON short for JavaScript Object Notation, is a lightweight computer
data interchange format. It is a text-based, human-readable format for
representing simple data structures and associative arrays (called
objects).
<services>
<service name="Wcf2Ajax.Service1"
behaviorConfiguration="Wcf2Ajax.Service1Behavior">
<endpoint address="" behaviorConfiguration="AjaxBehavior"
binding="webHttpBinding" contract="Wcf2Ajax.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="AjaxBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>

C:\WCF\GadgetDemo_WCFReturnJSON

Service Behaviors:
Instance and Concurrency
Management

Instance and Concurrent modes


WCF can control concurrency by the following two behaviors:
InstanceContextMode and ConcurrencyMode.

03 instance modes:
Per-Session instance mode
Per-Call instance mode
Singleton Instance Mode

03 concurrent modes:
Single - default setting. Instructs the runtime to allow access
on one thread per instance of the service class. This setting
is the safest one because service operations do not need to
worry about thread safety.
Reentrant - Only one thread at a time can access the service
class, but the thread can leave the class and come back later
to continue.
Multiple - Multiple threads may access the service class
simultaneously. This setting requires the class to be built in a
thread-safe manner.

Per Session

One service instance for one session

Per Call

One instance for each call, even a call from same


client

Singleton Instance

Service Throttling
maxConcurentInstances: controlling how many
services can be created by service. With this
setting we are defining the upper boundary of the
number of instances resides in a memory.
maxConcurentCalls: - controlling how many
concurrent calls can be active. What we can
manage here is actually the number of threads
used in our service processing.
maxConcurrentSessions: - used to control how
many active sessions we have especially when
using PerSession instance mode.

WCF Security
Authentication
Authorization
Confidentiality
Integrity
Transport and Message Security
Please look at
http://wcfsecurityguide.codeplex.com/

Workflow Services Architecture


Service.cs
Workflow.cs
or
Workflow.xoml
App.confi
g

Workflow
ServiceHost
ServiceHost

Service
Runtime

WorkflowOperationInvok
OperationInvoker
er
OperationSelector
InstanceProvider
DurableInstanceProvider
MessageContextInspect
MessageInspector
or

ServiceDescripti
on
ServiceBehavior
WorkflowServiceBehavior
OperationBehavio
WorkflowOperationBehav
r
ior

ContextChannel
ListenerChannel

Service
Instance
Workflow
Instance
ReceiveActivity
Operation 1 1
Operation 2 2
ReceiveActivity

Workflow Runtime

WF Persistence DB

StockTrader.net: a good WCF


http://msdn.microsoft.com/en-us/netframework/bb499684.asp
example
x

WCF Summary
Application

Error
Behavior

Service Model

Secure
Channel

Hosting
WAS
Environments

HTTP
Channel

ASP.NET

Instance
Behavior

Transaction Type Integ. Concurrency


Behavior
Behavior
Behavior

Throttling
Behavior

Messaging

Metadata
Behavior

WPF

Text/XML
Encoder

Reliable
Channel

TCP
Channel

WinForm

Queue
Channel

Binary
Encoder

NT Service

COM+

Good References
Book Essential Windows Communication
Foundation for .NET 3.5
PluralSight video training
http://
www.pluralsight.com/main/screencasts/defaul
t.aspx

Channel 9
http://channel9.msdn.com/shows/Endpoint/

WCF Summary
WCF is good for SOA, distributed computing
It combines the best of all existing Microsoft
distributed computing stacks
It uses WS-* standards for interoperability and
.NET value-add for performance and integration
with existing solutions

You might also like