Professional Documents
Culture Documents
WCF4 0
WCF4 0
CONTENTS INCLUDE:
About WCF
Getting Started with
n
n
Configuration Overview
WCF Contracts
Windows Communication Foundation 4.0
n
n
Bindings
n
Behaviors
Hosted Services and more...
By Scott Seely
n
CallbackContract CallbackContract: If the contract implements a duplex MEP, set this to the Order An integer used to alter the ordering of values when read or written.
interface representing the other side of the duplex conversation. By default, values are read and written in alphabetic order. The default
value of Order is 0. Members with the same Order value are serialized
To make methods visible to external callers, mark the methods with alphabetically. Order is sorted ascending.
[OperationContract].
[System.ServiceModel.ServiceContract(
Namespace = “http://www.dzone.com/WCF”)]
BINDINGS
public interface IMyService
{
[System.ServiceModel.OperationContract] WCF supports messaging through a messaging pipeline. The
string SayHi(string name);
} pipeline itself must have stages that represent the transport and
the serialization mechanism. In WCF, the pipeline is created by a
The commonly set properties on [OperationContract] are: type derived from System.ServiceModel.Channels.Binding and the
stages are created by types derived from System.ServiceModel.
IsOneWay Can only be set on methods that return void. Use this to indicate that the Channel.BindingElement. Besides the transport and serialization
method does not send a response. Default is false.
mechanism, the BindingElement also adds stages for security,
IsInitiating Use this to state that a given method can be called to instantiate a new reliability, and transactions. When creating a Binding, the
service. Default value is true.
developer of the Binding decides how to surface the underlying
IsTerminating Use this to state that when a given method is called, the current instance can BindingElement properties. Some settings will be easily set, others
be disposed. Default value is false. If this value is set to true, you must also set
ServiceContractAttribute.SessionMode to SessionMode.Required. made private, and still others surfaced as different concepts.
Your code may also return exceptions to callers. In SOAP messaging, Every binding has settings for timeouts: OpenTimeout,
errors are returned as Fault messages. A given operation may ReceiveTimeout, CloseTimeout. These set the amount of time the
return zero or more faults. One declares the types of faults being user of the Binding will wait for the pipeline to Open, Receive a
returned through [FaultContract]. [FaultContract] has a constructor message, or Close. A Binding also identifies its URL scheme, which
that accepts a type describing what the fault details will look like. is the scheme used by its transport. WCF ships with Bindings
This description is used by the callers to read any faults your service supporting the following schemes: http, https, net.msmq, net.pipe,
might return. net.p2p, and net.tcp. WCF also supports soap.udp, but only in an
internal class used to support WS-Discovery.
[System.ServiceModel.ServiceContract(
Namespace = “http://www.dzone.com/WCF”)]
public interface IMyService
{
Each of the Bindings has a common set of properties
[System.ServiceModel.OperationContract()] not required by the base class, Binding:
[FaultContract(typeof(FaultDetails))]
string SayHi(string name);
}
EnvelopeVersion Sets the version of any SOAP Envelope. Normally, this is set to None,
Soap11, Soap12. Use None for REST or other non-SOAP messaging;
Data Contracts Soap11 to send a SOAP 1.1 envelope and related headers; Soap12 to
WCF reads and writes objects to and from different formats using send a SOAP 1.2 envelope and related headers.
serialization (write) and deserialization (read). WCF supports
MaxBufferPoolSize Most messages are received into memory. The buffer pool is used to
serialization through several mechanisms: System.Xml.Serialization,
allocate memory for receiving messages. By default, each buffer in the
System.ISerializable, [System.Serializable], and through System. pool is 65536 bytes. Adjust this value to change the size of the individual
Runtime.Serialization. The first three mechanisms exist to support buffers.
legacy code. When developing your own declarations, you will
ReaderQuotas This sets quotas on reading inbound messages. The type,
normally use System.Runtime.Serialization to describe your data System.Xml.XmlDictionaryReaderQuotas is found in
contracts. In WCF 4.0, an unattributed type will automatically read System.Runtime.Serialization. The quotas set limits which limit the
and write any public fields or properties using the name of the damage a denial of service attack or poorly formed XML document
property in the generated format. To control what gets written, mark can do. By default, arrays can be no longer that 16384 elements
the type with [DataContract] and any members to be written with (MaxArrayLength), strings must be less than 8192 characters
(MaxStringContentLength), and XML nodes must be no more than 32
[DataMember].
levels deep (MaxDepth).
[System.Runtime.Serialization.DataContract] Scheme Identifies the scheme used by the underlying transport protocol.
public class Name
{
[System.Runtime.Serialization.DataMember]
public string FirstName { get; set; } Depending on which protocol you want to use, you have different
bindings available. Most of the bindings in WCF support HTTP.
[System.Runtime.Serialization.DataMember]
public string LastName { get; set; } The rest of the supported protocols are represented by one
}
binding. The following table shows which bindings support
When you explicitly mark a member with [DataMember], that duplex communications, message level security, reliable
field will be read and written regardless if the member is private, messaging, flowing transactions, and workflow context. Transport
protected, or public. level security is available through all bindings in WCF.
Binding Duplex Message level Reliable Transactions [ServiceBehavior] contains several properties. The most commonly
security used are:
BasicHttpBinding *
ConcurrencyMode Controls the internal threading model to enable support
BasicHttpContextBinding *
for reentrant or multithreaded services. By default,
MsmqIntegrationBinding concurrency is single threaded per instance.
NetMsmqBinding InstanceContextMode Controls how instances are created for the service. By
NetNamedPipeBinding default, each session gets a new service instance. Set
this property to PerSCall to allow for a new instance for
NetPeerTcpBinding every method call. Set this property to Single if you need
singleton behavior for the service.
NetTcpBinding
Bindings appear in configuration in the system.serviceModel/ WCF contains many configuration elements. Here, we focus on
bindings section under configuration that matches a camelCased the commonly configured behaviors for services. The following
version of the binding name. For example, the collection behaviors allow you to configure your service behaviors as
of WSHttpBinding can be found in system.serviceModel/
part of configuration within system.serviceModel/behaviors/
bindings/wsHttpBinding. Each configured binding has a
serviceBehaviors/:
name. A binding without a name becomes the default set of
settings for that particular binding. For example, to create a
reliable WSHttpBinding, use the following configuration: serviceCredentials Allows the service to pick how it authenticates itself using X.509,
Windows, username/password, and other valid tokens.
<system.serviceModel> serviceDebug Allows you to set up the HttpHelp page and to include exception
<bindings> details in faults.
<wsHttpBinding>
<binding name=”reliable”> serviceDiscovery Enables the WS-Discovery endpoint.
<reliableSession enabled=”true”/>
</binding> serviceMetadata Enables the WS-MetadataExchange endpoint.
</wsHttpBinding>
</bindings>
</system.serviceModel>
On an endpoint, you can configure other behaviors. The following
commonly used behaviors allow you to configure your endpoint
behaviors as part of configuration within system.serviceModel/
BEHAVIORS behaviors/endpointBehaviors/:
Behaviors influence the hosting environment for a service. They callbackDebug Allows you to state if a callback contract should include exception details
are used to handle instancing, expose metadata, enhance in faults.
discoverability, and more. There are four types of behaviors: service, clientCredentials Allows the client to pick how it authenticates itself using X.509, Windows,
contract, endpoint, and operation. All behaviors may be applied username/password, and other valid tokens.
in code. Service and endpoint behaviors may also be applied by enableWebScript Enables a Web Script endpoint on the service. This allows the service
configuration. (Note: There is no notion of contract configuration to return JavaScript when the URL end in /js or /jsdebug. This behavior
anywhere in WCF.) Service and contract behaviors are normally is automatically included if using the System.ServiceModel.Activation.
applied via attributes in code. WebScriptServiceHostFactory on a .SVC.
webHttp Allows the endpoint to dispatch messages based on URL. This behavior
A service behavior applies to a service instance and may alter is automatically included if using the System.ServiceModel.Activation.
aspects of the service, all endpoints, and all contracts. A contract WebScriptServiceHostFactory or System.ServiceModel.Activation.
behavior applies to a contract and all implementations of the WebServiceHostFactory as the factory name on a .SVC.
contract. Endpoint behaviors apply to a specific endpoint instances.
Finally, operation behaviors apply to specific operations.
HOSTING SERVICES
Attribute-based Behaviors
There are two service behaviors: WCF services can listen for messages anywhere: Windows
[AspNetCompatibilityRequirements] and [ServiceBehavior]. Services, desktop applications, and Internet Information Services
[AspNetCompatibilityRequirements] has a single property, (IIS). All environments use the same configuration elements. In
RequirementsMode, that allows a service to declare that ASP all cases, an instance of a ServiceHost will be used to reflect over
features such as identity impersonation are Required, Allowed, or a service implementation to determine service requirements.
NotAllowed (default). When set to Required, configuration must The ServiceHost then marries the code with any configuration
enable compatibility too: to produce an entity that can listen for, dispatch, and respond
to messages that arrive over the various transports.
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled=”true”/>
</system.serviceModel>
To demonstrate hosting, we use the following contract:
TCP Activation:
Once the using block exits, host.Dispose() is called. You
can do something similar in a WinForm/WPF application by 1. Run the following command (on one line):
opening the service on window Load and explicitly calling
ServiceHost.Dispose() when the window is closed/unloaded. %windir%\system32\inetsrv\appcmd.exe set site “Default Web Site” -+bindings.
[protocol=’net.tcp’,bindingInformation=’808:*’]
Hosting in a Windows Service
A Windows Service requires you to be able to respond to 2. Run the following command to enable the http and net. pipe
Start and Resume events very quickly. In order to do this, you protocol on your site (on one line):
do not want to block in the start if at all possible. Creating a
single WCF ServiceHost does not normally take much time. %windir%\system32\inetsrv\appcmd.exe set app
However, we should always be prepared for things to take a “Default Web Site/[your v-dir]” /enabledProtocols:http,net.tcp
while and have the services behave nicely. To host the same
WCF service in a Windows Service, write the following code: Named Pipe Activation
1. Run the following command (on one line): var client = new DZoneService.MyServiceClient(
“BasicHttpBinding_IMyService”);
try
{
%windir%\system32\inetsrv\appcmd.exe set site “Default Web Site”
Console.WriteLine(client.SayHi(“DZone”));
-+bindings.[protocol=’net.pipe’,bindingInformation=’*’]
}
catch (TimeoutException timeoutException)
{
2. Run the following command to enable the http and net. pipe client.Abort();
protocol on your site (on one line): }
catch (FaultException<KnownFaultType> faultException)
{
client.Abort();
%windir%\system32\inetsrv\appcmd.exe set app }
“Default Web Site/[your v-dir]” /enabledProtocols:http,net.pipe catch (FaultException faultException)
{
client.Abort();
With Vista SP1 and Server 2008, you can also enable these protocols }
catch (CommunicationException communicationException)
in the IIS Manager. {
client.Abort();
}
For the demo application, remove the <host> base
addresses and add in these two endpoints:
DIAGNOSTICS
<endpoint contract=”DZone.Contracts.IMyService” address=”/MyService”
binding=”netTcpBinding” />
<endpoint contract=”DZone.Contracts.IMyService” address=”/MyService”
binding=”netNamedPipeBinding” /> WCF also comes with a rich set of diagnostics information.
Unlike other aspects of WCF, diagnostics can only be set in
configuration. The diagnostics allows for tracing, message
OperationContext
logging, WMI inspection, and performance counters.
Every incoming message is associated with an OperationContext.
Think of OperationContext as WCF’s version of HttpContext.
OperationContext.Current yields the current operation context
Tracing/WMI
All production applications should be deployed with System.
with pointers to the following commonly used properties:
ServiceModel tracing configured but turned off. WMI
should be enabled so that an administrator can enable
IncomingMessageHeaders Headers on the incoming message. tracing through WMI. The configuration looks like this:
OutgoingMessageHeaders Can use this to add more headers to the response.
<system.diagnostics>
IncomingMessageProperties The message properties serve as a mechanism to send <sources>
information in between layers within the message processing <source name=”System.ServiceModel”
pipeline about a specific message. switchValue=”Off”
propagateActivity=”true”>
<listeners>
ServiceSecurityContext Gain access to the identity of the currently logged in user. <add name=”ServiceModelTraceListener” />
Also available through ServiceSecurityContext.Current. </listeners>
Contains a property, AuthorizationContext, where you can </source>
</sources>
investigate the ClaimSets for the current user. <sharedListeners>
<add initializeData=”.\logs\web_tracelog.svclog”
type=”System.Diagnostics.XmlWriterTraceListener, System,
The OperationContext also has two often used methods: Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”
name=”ServiceModelTraceListener”
SetTransactionComplete() Allows the service to complete a transaction in code instead traceOutputOptions=”Timestamp” />
</sharedListeners>
of automatically on exit. </system.diagnostics>
<system.serviceModel>
GetCallbackChannel<T>() For duplex services, allows the service to send messages <diagnostics wmiProviderEnabled=”true” />
back to the service. </system.serviceModel>
With WMI on, you can also inspect all the running endpoints <diagnostics>
including binding data, behaviors, and many other items. <messageLogging
logMessagesAtTransportLevel=”true”
logMessagesAtServiceLevel=”true” />
Message Logging </diagnostics>
Message logging is enabled in two places. First, create the message
logging trace source. If you are logging and tracing, you can get Typically, you will log messages at the transport level to see an
all the traces into one file with the following configuration: XML 1.0 text representation of what the ServiceModel saw including
message headers added by the message pipeline. You log at the
<system.diagnostics> service level to see what the message looked like after the message
<sources>
<source name=”System.ServiceModel” is decrypted.
switchValue=”Off”
propagateActivity=”true”>
<listeners> Performance Counters
<add name=”ServiceModelTraceListener” /> To enable performance counters, viewed in tools like PerfMon,
</listeners>
</source>
you add the following configuration to system.serviceModel:
<source name=”System.ServiceModel.MessageLogging”
switchValue=”Off”
propagateActivity=”true”> <diagnostics performanceCounters=”ServiceOnly” />
<listeners>
<add name=”ServiceModelTraceListener” />
</listeners> Performance Counters can have one of four values:
</source>
</sources>
<sharedListeners>
Default WCF_Admin is created and SQM data is collected. The values
<add initializeData=”.\logs\web_tracelog.svclog”
type=”System.Diagnostics.XmlWriterTraceListener, System, are never updated.
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”
name=”ServiceModelTraceListener” Off Performance counters are disabled.
traceOutputOptions=”Timestamp” />
</sharedListeners> ServiceOnly Only service level counters are enabled.
</system.diagnostics>
All Counters for the service, endpoints, and operations
are created.
In the ServiceModel configuration, you can set what you want to log:
#82
CONTENTS INCLUDE:
■
■
About Cloud Computing
Usage Scenarios Getting Started with
Aldon Cloud#64Computing
■
Underlying Concepts
Cost
by...
■
Upcoming Refcardz
youTechnologies ®
■
Data
t toTier
brough Comply.
borate.
Platform Management and more...
■
Chan
ge. Colla By Daniel Rubio
tion:
dz. com
tegra ternvasll
ABOUT CLOUD COMPUTING one time events. TEN TS
INC ■
HTML LUD E:
us Ind Anti-PPaat
Basics
Automated growthHTM
ref car
nuorn
■
Valid
ation one time events, cloud ML
connected to what is now deemed the ‘cloud’. Having the capability to support
Apache Ant
Usef
Du
ti
■
ul M.
computing platforms alsoulfacilitate
#84
Open the gradual growth curves
n an
Page Source
o
■
s
Vis it
C
faced by web applications. Tools
Core
By Key ■
Elem
Patte
has changed substantially in recent years, especially with Structur
E: al Elem ents
INC LUD gration the entrance of service providers like Amazon, Google and Large scale growth scenarios involvingents
specialized
NTS and mor equipment
rdz !
HTML
CO NTE Microsoft. es e... away by
(e.g. load balancers and clusters) are all but abstracted
Continu at Every e chang
m
About ns to isolat
relying on a cloud computing platform’s technology.
Software i-patter
space
Hadoop
rdz .co
■
n
Re fca
e Work
Build
riptio
and Ant
Desc
These companies have a Privat
are in long deployed
trol repos
itory
webmana applications
ge HTM
L BAS
■
Build
re
Buil Repo
This Refcard active
will introduce are within
to you to cloud riente computing, with an
d units
RATION etc. Some platforms ram support large grapRDBMS deployments.
■
The src
dy Ha
softw
e ine loping and Java s written in hical on of
INTEG attribute
task-o it all
softwar emphasis onDeve es by
Mainl these
ines providers, so youComm can better understand
also rece JavaScri user interfac web develop and the rris
Vis it
Spring Security
codel chang desc
INUOU ding Task Level as the
e code
w ww.dzone.com
Label
Build
manu
al
d tool
depe deplo t need but as if
eve , a ) stalle the same nmen for stan overlap uen
(i.e. , inef Build t, use target enviro Amazon EC2: Industry standard it has
software and uagvirtualization ine. HTM , so <a>< tly are) nest
with terns problem ce pre-in whether dards
ated b></
ory. ns (i.e. Autom Redu ymen
has bec become e with a> is
via pat ticular d deploEAR) in each very little L
Subversion
reposit -patter s that Pay only cieswhat you consume
tagge or Amazon’s cloud
the curr you cho platform
computing isome
heavily based moron fine. b></ ed insid
lained ) and anti the par solution duce nden For each (e.g. WAR es t
ent stan ose to writ more e imp a></ e
not lega each othe
x” b> is
be exp text to “fi are al Depeapplication deployment
Web ge until t a
librarifew years agonmen
t enviro was similar that will softwaredard
industry standard and virtualization app
e HTM technology.
orta nt,
tterns to pro Minim packa nden
Mo re
CI can ticular con used can rity all depe all targe
s will L or XHT arent. Reg the HTM l, but r. Tags
etimes Anti-pa they
tend
es, but to most phone services:
y Integ alizeplans with le that
late fialloted resources, ts with an and XHT simplify all help ML, und ardless
L VS
XHTM <a><
in a par hes som
Centr
end,
Binar
pro cess. the practic enti ng incurred costgeme
nt
whether e a single
such
temp
resources on
were consumed
t enviro
nmen
orthenot. Virtualization MLaare your
othe
you prov
erst of L
b></
in muchallows physical piece of hardware to
ide be HTM
rily bad
Mana based
approac ed with the cial, but, implem anding
Creat targe es to actually r web
nden
cy rties are nt
of the a solid L has
into differe coding.resources
necessa pared to
chang
efi Depe prope itting utilized by multiple operating
function systems.simplerThis allows foundati job adm been arou
associat to be ben
er
Ge t
te builds commo
are not Fortuna
late Verifi e comm than on
n com Cloud computing asRun it’sremo
known etoday has changed this.
befor alitytohas irably, nd for
They they
etc.
Temp Build (e.g. bandwidth, n memory, CPU) be allocated exclusively to tely exp that som
lts whe
ually,
appear effects. Privat y, contin Every elem mov used
to be, HTML
ecte job e time
ed resu The various resourcesPerfo rm a
consumed by webperio applications
dicall (e.g. nt team
pag
individual operating entsinstances. ed to CSS
system Brow d. Earl
y HTM has expand . Whi
gration
opme because
adverse unintend d Builds sitory Build r to devel common e (HTML . ser ed far le it has don
ous Inte web dev manufacture L had very
Stage Repo
e bandwidth, memory, CPU) areIntegtallied
ration on a per-unit CI serve basis or XHT
produc tinu e Build rm an from
extensio .) All are more e its
e.com
DZone, Inc.
Cloud Computing
the
s on
expand
ISBN-13: 978-1-934238-75-2
140 Preston Executive Dr. ISBN-10: 1-934238-75-9
Suite 100
50795
Cary, NC 27513