Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 35

Visual Studio® 2008:

Windows®
Communication
Foundation
Module 5: Designing and Defining Contracts
• Designing a Coherent and Cohesive WCF Service Interface

• Defining a Service Contract

• Defining Operations on a Service

• Defining a Data Contract


Lesson: Designing a Coherent and Cohesive WCF
Service Interface
• Designing by Contract

• Contracts and Messages

• Contracts and Message Contents

• Contracts and Message Handling

• Contracts and Message Exchange Patterns

• Contracts and Versioning


Designing by Contract

Coherent

Consistent
Parameters
Operations
in and out

Complex Expected Cohesive


data types errors

Designed for
distribution

Service metadata is the definitive service contract


Contracts and Messages

Client
Service
Withdraw

WithdrawResponse

Consists of
SOAP Message

Defines Namespace
Unique method
ContractName address on
this service
Defines OperationName
Contracts and Message Contents

decimal Withdraw(string account, decimal amount);

No funds
exception SOAP
SOAP
Message Message

Body SOAP Body


Message
value account
Body amount
Fault
info

Response Request
Message Message

Error
Message
Contracts and Message Handling

Control message structure with message contracts

Custom SOAP headers

Custom SOAP body elements

Alter SOAP body namespaces

Work with raw messages

Operations pass or return a Message

Beyond the scope of this course


Contracts and Message Exchange Patterns

Contracts support three message exchange patterns

Client Service

Request and Response

Client
Service

One-Way

Client
Service

Duplex
Contracts and Versioning

SOA precludes forced client upgrade when service contract changes

Apply best practices to contract versioning

Add but do not remove

Do not change data types

Message and data validation become a problem

Namespace changes also break the contract


Lesson: Defining a Service Contract
• Service Contracts

• Service Names

• Service Namespaces

• Contract Implementation

• Demonstration: Defining a Service Contract


Service Contracts

Apply ServiceContract attribute and alter properties

Name

Namespace

CallbackContract

ConfigurationName

SessionMode
Service Names

Change service name in metadata by using the Name property

[ServiceContract(Name="BankingService")]
public interface IBank
{

}

Change service name in configuration file by using the ConfigurationName


property

[ServiceContract(ConfigurationName=“TheBankService")]
public interface IBank
{
… <services>
} <service name=“TheBankService">
...
</services>
Service Namespaces

Namespace used as part of the SOAP action

[ServiceContract(Namespace="http://myuri.org/Simple")]
public interface IBank
{
[OperationContract]
decimal GetBalance(string account);
...

<s:Header>
<Action s:mustUnderstand="1"
xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">
http://myuri.org/Simple/IBank/GetBalance
</Action>
</s:Header>
...
<s:Body>
<GetBalance xmlns="http://myuri.org/Simple">
...
</s:Body>
Contract Implementation

Service implementation class

Should be separate
Must have from contract
a parameterless definition
constructor

Can implement multiple contract definitions

Service contract interfaces


Should be separate from implementation

Can be part of an inheritance hierarchy


Demonstration: Defining a Service Contract
In this demonstration, you will see how to use the
properties on a service contract to change its metadata and
hence its message properties
Notes Page Over-flow Slide. Do Not Print Slide.
See Notes pane.
Lesson: Defining Operations on a Service
• Defining an Operation Contract

• Operation Contracts and Names

• Operation Overloading

• One-Way Operations

• Defining Duplex Contracts

• Demonstration: One-Way Operations and Callbacks


Defining an Operation Contract

Apply OperationContractAttribute and alter properties

Name

Action ActionReply

IsOneWay

[ServiceContract(Namespace="http://myuri.org/Simple")]
public interface IBank
{
[OperationContract]
decimal GetBalance(string account);

...
Operation Contracts and Names

Change method name in metadata by using the Name property

[OperationContract(Name="CustomerBalance“)]
decimal GetBalance(string account);

Change SOAP action by using the Action and ReplyAction properties

[OperationContract(Action="http://myuri.org/BankBalanceRequest"
ReplyAction="http://myuri.org/BankBalanceResponse“)]
decimal GetBalance(string account);

Set Action to ‘*’ to handle unknown messages


Operation Overloading

Overloading methods causes problems for services

[OperationContract]
void Deposit(string account, decimal amount);

[OperationContract]
void Deposit(string account, Currency amount);

[OperationContract(Name="DepositLocalCurrency"]
void Deposit(string account, decimal amount);

[OperationContract(Name="DepositAnyCurrency")]
void Deposit(string account, Currency amount);
Client code

proxy.DepositLocalCurrency(string account, decimal amount);


proxy.DepositAnyCurrency(string account, Currency amount);
One-Way Operations

• Specify a one-way message when:


 No response is required
 Response is handled in a different way

[OperationContract(IsOneWay=true)]
void MakeDeposit(string account, decimal amount);

No response message – return type must be void

No way to detect message failure

Benefits in performance
Defining Duplex Contracts
Client Service contract
Service

Callback contract

[ServiceContract(CallbackContract=typeof(ITransferAck))]
public interface IBankTransfer
{
[OperationContract(IsOneWay=true)]
void ExchangeTransferRecord(int transferId, string record);
}
public interface ITransferAck
{
[OperationContract(IsOneWay=true)]
void TransferRecordResendRequest(int transferId);
}

client = OperationContext.Current.GetCallbackChannel<ITransferAck>();
Demonstration: One-Way Operations and Callbacks
In this demonstration, you will see how to:
• Define and implement a one-way operation

• Define and implement a callback contract


Notes Page Over-flow Slide. Do Not Print Slide.
See Notes pane.
Lesson: Defining a Data Contract
• Data Contracts

• Defining a Data Contract

• Customizing a Data Contract

• Versioning Data Contracts

• Consuming Data Contracts

• Demonstration: Defining a Data Contract


Data Contracts
.NET Framework object SOAP
Message

account Body

amount account
amount

Primitive types

Simple types
Any other
complex type
XML-based types requires a
data contract
Collections

Enumerations
Defining a Data Contract
DataContractAttribute
on class
[DataContract]
public class TransferRecord
{
[DataMember] Visibility
public string targetAccount; irrelevant

[DataMember]
private string transferringBank;

private string internalCustomerId;


Ignored by
private string transferId; serializer

[DataMember]
public string TransferId DataMemberAttribute on
{ fields to be serialized
get { return transferId; }
set { transferId = value; }
}
} Must have setter
Customizing a Data Contract
Use properties on DataContractAttribute

Name

Namespace

Use properties on DataMemberAttribute

Name

IsRequired

EmitDefaultValue

Order
Versioning Data Contracts

Similar rules to service contract versioning

Add but do not remove

Do not change datatypes or ordering

Do not change the contract name

Client validation forces a new contract

Implement IExtensibleDataObject from the start


Consuming Data Contracts

Contract
metadata
Client
Generate Service
Data types

Client

Data types Service


Share Share
Demonstration: Defining a Data Contract
In this demonstration, you will see how to define a data
contract that enables a complex type to be passed as a
parameter in an operation on a service contract
Notes Page Over-flow Slide. Do Not Print Slide.
See Notes pane.
Lab: Contracts for Services and Data
• Exercise 1: Defining and implementing a one-way
operation contract
• Exercise 2: Passing complex data with a data contract
• Exercise 3: Defining and implementing a callback
contract

Logon information

Virtual machine 6461A-LON-DEV-05

User name Student

Password Pa$$w0rd

Estimated time: 85 minutes


Lab Review
• What could you do to handle an error in the Patient Letter
service after you have made the operation one-way?
• Where else in the system might you use a data contract
other than in the Appointments contract?
• Why did the ClinicAdminClient project have to handle
exceptions in the duplex contract exercise? Would this
happen in the real-world?
• Why did the clinic management service have to handle
exceptions in the duplex contract exercise? Would this
happen in the real world?
Module Review and Takeaways
• Review questions

• Real-world Issues and Scenarios

• Best Practices

You might also like