windows communication foundation 101
DESCRIPTION
TRANSCRIPT
Windows Communication Foundation 101
Lars Wilhelmsen Miles Oslo Session
January 15th 2009
Agenda• Introduction• The ABC of WCF• The Service Model• Message Exchange Patterns• Hosting• Client proxies• Behaviors• Security• Interoperability
Introduction• Originally dubbed ”Codename Indigo”
– A part of WinFx – later named .NET 3.0 (together with WPF, WF & CardSpace)
• Unified Communication Model– Not only ”Windows SOA Foundation” or ”Windows Web
Services Foundation”– Superseeds ASMX, WSE, Remoting, Enterprise Services,
MSMQ in many ways• Enhanched features in .NET 3.5 – REST capabilities,
stronger WF integration etc.• Anticipating the release of WCF+WF 4.0 – first public
drops released at PDC’08 in LA.
Mom, I’ve got WCF!• Played with the Indigo bits since the first public
drops back in 2005 (?)• Applied WCF in different projects
– Gained experience – what works – what doesn’t• Attended Bustamante & Löwy’s Master classes
(2x 5 days)• Frequent Answerer & moderator in the
MSDN/WCF forum.• Done previous presentation on the topic• Connected Systems MVP 2009
The fundamental WCF mantra
ABC = E
Address
• The ”where”• Transport-specific URL
– http://server/App/Service.svc– https://server/App/Service.svc– net.tcp://server/App/Service.svc– net.msmq://server/private/QueuedService– net.pipe://localhost/pipe
Binding• The ”How”• System-provided bindings
– BasicHttpBinding – The compatible one– WSHttpBinding – The best for WCF <-> WCF scenarios (Internet)– WSDualHttpBinding – HTTP/SOAP version that supports callbacks– WSFederationHttpBinding – Federated security– NetTcpBinding – The best for WCF <-> WCF scenarios (Intranet)– NetNamedPipeBinding – Best for IPC on same computer– NetMsmqBinding – One-way, async. queueing– NetPeerTcpBinding – P2P – built on top of the Window PNRP & P2P stack– WebHttpBinding - REST– + Context-enabled bindings – For WF scenarios.
• Custom bindings– Cook your own – more fine-grained control over existing channels /
combinations
Contract
• The ”What”– Service contracts: Operations– Data contracts: The messages– Message contracts: Fine-tune OOB headers etc.– Fault Contracts: Control exception/fault flow
Service Contract
[ServiceContract(Namespace = "http://services.miles.no/TestService/2009/01/")]public interface IMilesService{ [OperationContract] void InviteToSession(SessionInitiationInfo request); [OperationContract] void AddAttendee(CustomMessage request);}
Data Contract [DataContract] public class SessionInitiationInfo : IExtensibleDataObject { [DataMember(Order = 0, IsRequired = true)] public string Presenter { get; set;} [DataMember(Order = 1, IsRequired = true)] public string Topic { get; set; } [DataMember(Order = 2, IsRequired = true)] public DateTime StartTime { get; set;} [DataMember(Order = 3, IsRequired = true)] public DateTime EndTime { get; set;} [DataMember(Order = 4, IsRequired = true)] public AttendeeInfo[] Attendees { get; set; } #region IExtensibleDataObject Members public ExtensionDataObject ExtensionData { get; set; } #endregion }
Data Contract #2
[DataContract] public class AttendeeInfo : IExtensibleDataObject { [DataMember(Order = 0, IsRequired = true)] public string FirstName { get; set; } [DataMember(Order = 1, IsRequired = true)] public string LastName { get; set; } [DataMember(Order = 2, IsRequired = false)] public string EmailAddress { get; set; } #region IExtensibleDataObject Members public ExtensionDataObject ExtensionData { get; set; } #endregion }
Message Contract
[MessageContract]public class CustomMessage{ [MessageHeader] public string CustomHeader { get; set; } [MessageBody] public AttendeeInfo Attendee { get; set; }}
• MessageContract• HasProtectionLevel, ProtectionLevel, IsWrapped, WrapperName, WrapperNamespace
• MessageHeader
Fault Contract
[DataContract] public class NoSuchAttendeeFault { public string Name { get; set; } }
Create a data contract for contain the fault payload
[OperationContract] [FaultContract(typeof(NoSuchAttendeeFault))] AttendeeInfo GetAttendeeById(int id);
Decorate the operation with the [FaultContract] Attribute,and specify the payload type.
Service Model
Client ServerMessaging Layer
Behaviour
Behaviour
Behaviour
Behaviour
Contract Binding
Factory
Channel Address
Channel
ChannelAddress
Listener
Binding
Address Binding Channel
Endpoint
(c) Barry Dorrans - http://idunno.org
MEPs
• Message Exchange Patterns• WCF supports three different kinds
• With or without session support
– Request-Response– OneWay– Duplex
Hosting
• ServiceHost
• Hosting models– IIS / WAS– NT Service– Windows Forms, Console, WPF
Hosting #2
public class SelfHost{ public static void Main() { var baseUri = new Uri("http://localhost:1234/"); var serviceHost = new ServiceHost(typeof(MilesService), baseUri); var binding = new BasicHttpBinding(BasicHttpSecurityMode.None); serviceHost.AddServiceEndpoint(typeof (IMilesService), binding, string.Empty); serviceHost.Open(); }}
Hosting Outlook: Codename ”Dublin”
• Microsoft’s Distributed Application Server• Evolution of IIS/WAS hosting of services• Will be the preferred way to host Services &
Workflows• Better deployment & management features• Will be shipped independent of .NET 4.0• Will work on Windows Server 2008
Client Proxy• The easy way
– Generate from WSDL/Metadata in Visual Studio• Add Service Reference... on project context menu.
– Generated client: flawed design.• Doesn’t support the IDisposable pattern properly.• Luckily the class is marked as partial – a fix can be
implemented ”on the side”• Generated proxies derives from ClientBase<T> or
DuplexClientBase<T> (for duplex proxies)• Run-time generation
– More flexible, but a bit more overhead• Often my preferred method
Client Proxy #2
var ep = new EndpointAddress(baseUri);var proxy = ChannelFactory<IMilesService>.CreateChannel(binding, ep);proxy.InviteToSession(new SessionInitiationInfo { Presenter = "Lars Wilhelmsen", Topic = "WCF 101" // ... });// Optionally: Explicitly close the proxy channel((ICommunicationObject)proxy).Close();
Some lines about behaviors
• Used to modify the normal operational pattern of a service, endpoint or operation
• Multiple ”levels”– Service behaviors– Endpoint behaviors– Operation behaviors
• Service & Endpoint behaviors can be set from configuration – operation behaviors cannot (must be done programmatically).
Commonly used Service Behaviors
• ServiceDebugBehavior– Turn on debug information – optionally send it back
to the client• ServiceMetadataBehavior
– WSDL / Metadata generation• ServiceAuthorizationBehavior
– Configure service authorization methods and settings• ServiceThrottlingBehavior
– Throttling – to tune performance and mitigate possible DoS attacks
Commonly used Endpoint Behaviors
• WebHttpBehavior– To be used in tandem with the WebHttpBinding
• REST
• EnableWebScriptBehavior– Easy REST/JSON generation
• DataContractSerializerBehavior– Tune the underlying data contract serializer
Security
• Big topic– If you can – go for the standard solution
• But if you can’t, the extensibility model is great
• Transport & Message Security• Authentication
– Windows, Kerberos, x509, U/P, Federation, Custom dev.
• Authorization– Windows Domain Groups, ASP.NET Role Provider,
AzMan, Custom dev.
Security Outlook: Codename ”Geneva”
• The next-generation framework for claims-based security
• Secure Token Service (STS)– Runs on Windows Server– Let’s you expose data from AD and other sources
as claims• Client frameworks – web/desktop• Next-gen version of CardSpace• Will be compatible / plugs into WCF
Interoperability
• BasicHttpBinding – backwards compatible with ASMX (Old skool .NET Web Services)
• Adheres to the WS-BasicProfile 1.1 standard• Normally goes well together with Java-based
services.• The standard DataContractSerializer has some
limitations – may fallback to the legacy XmlSerializer
REST
• New in .NET 3.5– Additional features in SP1
• HTTP Verbs – POX - JSON• System.ServiceModel.Web assembly• [WebInvoke] & [WebGet]• UriTemplate• WebOperationContext• WCF REST Starter Kit
– Will be incorporated in WCF 4.0
REST #2
• System.ServiceModel.Syndication– ATOM & RSS Feeds– Atom Publishing Protocol
Questions?
Next up: workshopping, pair-programming, geeking
Domo arigato!