Saturday 3 November 2012

WCF Tips and Tricks



WCF Tips and Tricks[a selection] from the field
Christian Weyer, thinktecture
christian.weyer@thinktecture.com
andChristian Weyer

Support & consulting for Windows and .NET software developers and architects
Developer coaching and mentoring
Architecture consulting and prototyping
Architecture and code reviews
Applicationoptimization, troubleshooting, debugging
Focus on distributed applications, service orientation, workflows, cloud computing, interoperability, security, end-to-end solutions
Windows Server, WCF, WF, MSMQ, Azure Services, Windows Azure
http://www.thinktecture.com
christian.weyer@thinktecture.com

2
For starters: Super-duper TIP
WCF is not just Web Services !
WCF is not always about SOA !
WCF does not stand for
Web Services Consumption Foundation
Windows Cool-SOA Foundation
It is the Windows CommunicationFoundation!

3
Agenda –Dealing with...
Consuming
Hosting
Bindings
Quotas & throttles
Metadata/WSDL
Performance & throughput
Large data
Tracing

Problems èSolutions/Tips è
Samples4
Notcovered, some...
Contract modelling
REST
Security
Asynchronous processing
Fault handling
Deep extensibility
WF integration
NATs & firewalls
... and surely more ...

5
Consuming–Problems
Do I always need to create a proxy class from WSDL/MEX?
How can I make consuming services more robust?
Is there a way to improve performance when calling services?
How can I call in-process ‘services’ and WCF services in the same way?

6
Consuming–Solutions I
For non-interopno need to use svcutil.exeor ‘Add Service Reference’
shared contracts approach works good in WCF-to-WCF scenarios
ChannelFactory<T>and DuplexChannelFactory<T> are powerful means
use custom interface extending service contract & IClientChannel
Avoid usingstatement when dealing with proxies (ICommunicationObject-derivedobjects)
can still throw at end of using block, e.g. for network errors
explicit exception handling; can be dealt withe.g. in extension method

7
Consuming–Solutions II
Try to cache proxy or ChannelFactoryin high-throughput applications
creating them can mean significant overhead
ASP.NET client applications should not create ChannelFactoryon each page call
Abstract away channel/proxy creation details with Activator.CreateInstance& ChannelFactory<T>
Service Agent pattern
for local and remote services
no WCF-isms available, like sessions etc.
WCF 4.0 will offer in-process, intra-AppDomainchannel

8
Consuming–Samplesinterface IMyContractChannel: IMyContract, System.ServiceModel.IClientChannel{}
ChannelFactory<IMyContractChannel> cf= new ChannelFactory<IMyContractChannel>(binding, address);
IMyContractChannelclient = cf.CreateChannel();
client.DoIt(…);
client.Close();try{… client.Close();}catch (CommunicationExceptione){… client.Abort();}catch (TimeoutExceptione){… client.Abort();}catch (Exception e){… client.Abort();throw;}
IMyContractChannelchannel=
ChannelFactoryManager<IMyContractChannel>
.GetChannel("BasicHttpBinding");
Client sideClient side
Client side
Client side9
Hosting-Problems
Which host to use? IIS/WAS or a self-host?
How do I inject logic in IIS/WAS hosting?

10
Hosting–Solutions
Use IIS/WAS for robust, highly scalable services
beware of the process & AppDomainlifecycle features
when using non-HTTP (TCP, Named Pipes, MSMQ) with WAS hosting AppDomainrecycling still comes into your way
Use self-hosting in Windows Service to have full control and light-weight hosting environment
Custom ServiceHost& ServiceHostFactoryimplementations to provide custom initialization code
hook up factory in .svcfile for IIS/WAS

11
Hosting–Samplesclass MyServiceHost: System.ServiceModel.ServiceHost{public MyServiceHost(Type serviceType, paramsUri[] baseAddresses): base(serviceType, baseAddresses){...}protected override void ApplyConfiguration(){...}}
class MyServiceHostFactory: System.ServiceModel.Activation.ServiceHostFactory
{
protected override ServiceHostCreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
return new MyServiceHost(serviceType, baseAddresses);
}
}
<%@ ServiceHostLanguage="C#" Debug="true" Service="MediaService" Factory="MyServiceHostFactory" %>Custom ServiceHost
Custom ServiceHostFactory
.svc file12
Bindings-Problems
MyWCF serviceisslow, whatishappening?
I wanttouseHTTP but not necessarilyangle brackets(aka‚XML‘)
HowcanI choosefromthebestcommunicationoptions?
13
Bindings–Solutions I
Beware of using the wrong bindings
e.g. Visual Studio WCF wizards use WsHttpBinding(heavy with message security & session-based)
only use features you really need
Think about the real need for session-bound channels/bindings
sessions change the game of fault and error handling
use sessions when you need session semantics in your service
But: sessions cangive performance improvements
e.g. security token hand-shake happens only once with SecureConversation
14
Bindings–Solutions II
Custom bindings will save your day
e.g. binary over HTTP often a good trade-off for WCF-to-WCF communication scenarios
build custom binding in configor code
Create user-defined binding for easier re-usage
bake common custom binding setups into re-usable code and configimplementations
Use a custom encoder for providing encoding-level tweaks & optimizations
e.g. enhanced text encoder in SDK or FastInfoSetencoder from 3rdparty
15
Bindings-Samples
<extensions>
<bindingExtensions>
<add name="netHttpBinding"
type="NetHttpBindingCollectionElement, Thinktecture.ServiceModel, Version=…" />
</bindingExtensions>
</extensions>
<bindings>
<netHttpBinding>
<binding name="unsecureNetHttp" securityMode="None" />
</netHttpBinding>
<customBinding>
<binding name="binaryHttp">
<binaryMessageEncoding/>
<httpTransport/>
</binding>
</customBinding>
</bindings>
public class NetHttpBinding:
System.ServiceModels.Channels.Binding,
ISecurityCapabilities
{
HttpTransportBindingElementhttpTransport;
HttpsTransportBindingElementhttpsTransport;
BinaryMessageEncodingBindingElementbinaryEncoding;
NetHttpSecurityModesecurityMode;
...
}app/web.config
User-defined binding16
Quotas & Throttles -Problems
Beyond Hello World, all my services and consumers fail with strange exceptions
My services do not perform the way they are supposed to
How can I teach WCF to be less ‘conservative’ in Intranet environments?

17
Quotas & Throttles -Solutions
Bindings
adjust buffers, connection limits, timeouts
Behaviors
configure throttling service behavior
Serializers
check maximum items in object graph value
Custom ChannelFactoryand ServiceHostcan automate all this
e.g. through profiles

Defaultsnot true!
SvcConfigEditor18
Quotas & Throttles -Samples
<bindings>
<webHttpBinding>
<binding name="rawStreamingWeb" transferMode="StreamedResponse">
<readerQuotasmaxArrayLength="999999999"/>
</binding>
</webHttpBinding>
<customBinding>
<binding name="httpStreaming" sendTimeout="Infinite">
<binaryMessageEncoding/>
<httpTransporttransferMode="Streamed" />
</binding>
</customBinding>
<bindings><behaviors><serviceBehaviors><behavior name="MyServiceBehavior"><serviceThrottlingmaxConcurrentCalls="1500" maxConcurrentInstances="1500" maxConcurrentSessions="1500" /> </behavior></serviceBehaviors></behaviors>
app/web.configapp/web.config
Consuming code
19
WSDL & Metadata -Problems
Some non-WCF consumers cannot understand the WSDL WCF produces
My WSDL contains the wrong host name
I cannot use multiple IIS web site bindings with my WCF services

20
WSDL & Metadata –Solutions I
Use custom extension to flatten WSDL into one file
need to use same namespace values forServiceContract, ServiceBehavior, BindingNamespace
eliminates wsdl:importand xsd:import
Register hostheadersin IIS toreflectnamesintoWSDL
forHTTP andHTTPS
Specifydifferent URIs forlisteningandexposingin WSDL

<endpointaddress="https://www.tt.com/TheUriIWantInWSDL" listenUri="http://localhost/TheActualUriServiceListensToOnThisBox" ...>
Considerexposinga staticWSDL whichdocumentsyourpublishedinterfaceversion

21
WSDL & Metadata –Solutions II
Multiple IIS site bindings result in multiple base addresses
WCF only supports a single base address in this scenario
fix yourself in .NET 3.0 with custom ServiceHostFactory
.NET 3.5 supports <baseAddressPrefixFilters>
pass-through filter which provides a mechanism to pick the appropriate IIS bindings
22
WSDL & Metadata -Samples<bindings><binding protocol="http”bindingInformation="*:80:www.thinktecture.com" /><binding protocol="https" bindingInformation="*:443:www.thinktecture.com" /></bindings>
<serviceHostingEnvironment>
<baseAddressPrefixFilters>
<add prefix="http://thinktecture.de/"/>
<add prefix="http://thinktecture.com"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
<%@ ServiceHostLanguage= "C#" Service="ProductCatalog" Factory="Thinktecture.ServiceModel.Activation.FlatWsdlServiceHostFactory" %>
.svc fileapp/web config
applicationHost.config(IIS7)
23
Large Data -Problems
Myserviceeatsa lotofmemoryandchokestheCPU whensending/receivinglarge data
Biggermessagesaremakingmycommunicationreallyslow
I havearbitrary, non-structureddatatotransfer

24
Large Data –Solutions I
WCF supportsMTOM forencodingbinarydata
MTOM especiallyusefulforinterop
ChunkingchannelsavailableasSDK & communitysamples
enablessendingchunksofdatainsteadofonesinglepiece
transparentlyworkswithdifferent transportsasa bindingelement
25
Large Data –Solutions II
Considerusingstreamingfortransferingabitrarydata
requirescertaincontractshape
Stream
Message
Streamassinglebodyin MessageContract
worksoveranytransportbesidesMSMQ
workswithtransportandmixed-modesecurity
still watchout forquotas
powerful withweb programmingmodel
26
Large Data -Samples
[ServiceContract]
public interface IVideoPlayer
{
[OperationContract]
[WebGet(UriTemplate= "videos/{videoID}")]
[WebContentType(MimeType= "video/x-ms-wmv")]
StreamPlay(string videoID);
}WebServiceHostwebHost= new WebServiceHost(typeof(VideoPlayerService));WebHttpBindingbinding = new WebHttpBinding();binding.TransferMode= TransferMode.Streamed;webHost.AddServiceEndpoint(typeof(IVideoPlayer),binding,"http://localhost:7777/Services/player");
Service contract
HostClient
27
Performance/Throughput-Problems
SomehowmyentireWCF-basedapplicationis‚slow‘
Hosting myWCF servicein IIS seemsnot toperformwell underhighload
I cannotseemtogeta highthroughputwhenclientstalk tomyservicevia HTTP
All thatdataisbeingtransferredagainandagain, itmakesmysystemslow
28
Performance/Throughput–Solutions
Configuring throttling can heal a lot (look there!)
.NET 3.5 SP1 provides asynchronous HTTP module & handler for hosting WCF in IIS for better behavior
Client-side HTTP communication is limited to 2 concurrent connections to a server
configurable through System.Net
Cache, cache, cache!
try to use caching intensively (but wisely) to save unnecessary round-trips
29
Performance/Throughput-Samples<system.net><connectionManagement><add address="*" maxconnection="20"/></connectionManagement></system.net>
public List<Episode> ListEpisodes()
{IDataCachecache = DataCacheFactory.CreateInstance();
List<Episode> episodes = cache.Get<List<Episode>>(CacheConstants.AllEpisodes);
if (episodes == null)
{
varepisodeList= mediaLogic.ListAllEpisodes();
episodes = EpisodeDataMapper.MapAllEpisodes(episodeList);
cache.Add(CacheConstants.AllEpisodes, episodes);
}


return episodes;
}
public interface IDataCache
{


void Add(string key, object cacheItem);
TCacheItemGet<TCacheItem>(string key);
void Remove(string key);


}
app/web.configE.g. service facade
Caching lib
30


Performance/Throughput–Cache Solution
Cache shouldbeabstractedfromactualcacheproduct/implementation
Genericinterfacewithdifferent implementations
local, in-proccache
distributedcache
ASP.NET‘sweb cachecanalso beusedoutside ofASP.NET
Distributed cachesnecessaryforfarmandscale-out scenarios
MemcacheD
SharedCache
‚Velocity‘
31
Special Case: Tracing
Useit!Itcansave your… J
Ifthingsgowrongandyouhavenocluewhy: trace!
But do not overuseitwhenin production
wrongusagecanmeansevereoverhead
Configuredvia configfile
canbemanipulatedvia code, but onlythroughWMI
DidI alreadysaytracingcansave your…?
32
Tracing-Sample<system.diagnostics><sources><sourcename="System.ServiceModel" switchValue="Warning" propagateActivity="true"><listeners><addtype="System.Diagnostics.DefaultTraceListener" name="Default" /><addname="ServiceModelTraceListener" /></listeners></source></sources><sharedListeners><addinitializeData=„MyService_Trace.svclog"type="System.Diagnostics.XmlWriterTraceListener, …"name="ServiceModelTraceListener" traceOutputOptions="Timestamp" /></sharedListeners><traceautoflush="true" /></system.diagnostics>
$ms= get-wmiobject-class "AppDomainInfo" -namespace "root\servicemodel" -computername"." | where{$_.Name -eq"MyWCFHost.exe"}
$ms.TraceLevel= "Warning, ActivityTracing"
$ms.Put()
<system.serviceModel>
<diagnosticswmiProviderEnabled="true"/>
app/web.configPS script
app/web.config
33
Resources
Avoiding problems with the using statement
http://msdn.microsoft.com/en-us/library/aa355056.aspx
Custom encoders
http://msdn.microsoft.com/en-us/library/ms751486.aspx
http://blogs.msdn.com/drnick/archive/2006/05/16/598420.aspx
Tracing
http://msdn2.microsoft.com/en-us/library/ms732023.aspx
http://msdn2.microsoft.com/en-us/library/aa751795.aspx
http://msdn2.microsoft.com/en-us/library/ms733025.aspx
http://msdn2.microsoft.com/en-us/library/aa751917.aspx
34
Resources
Setting upIIS SSL hostheaders
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/596b9108-b1a7-494d-885d-f8941b07554c.mspx
http://blogs.iis.net/thomad/archive/2008/01/25/ssl-certificates-on-sites-with-host-headers.aspx
baseAddressPrefixFilter
http://msdn.microsoft.com/en-us/library/bb924492.aspx
Chunkingchannel
http://code.msdn.microsoft.com/WCFResources/Release/ProjectReleases.aspx?ReleaseId=1546
35
Resources
AsynchronousWCF HTTP Module/Handler forIIS7 forBetterServer Scalability
http://blogs.msdn.com/wenlong/archive/2008/08/13/orcas-sp1-improvement-asynchronous-wcf-http-module-handler-for-iis7-for-better-server-scalability.aspx
WCF bindings& more
http://www.noemax.com
36
Resources
We have code solutions for some WCF problems, for free of course
Thinktecture.ServiceModel
èEmail Christian Weyer
christian.weyer@thinktecture.com
Weblog Christian Weyer
http://blogs.thinktecture.com/cweyer
thinktecture
http://www.thinktecture.com

37
http://www.thinktecture.com/
christian.weyer@thinktecture.com
http://blogs.thinktecture.com/cweyer/


In-depth support and consulting for software architects and developers
{ } 38

No comments:

Post a Comment

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...