Content by Category
.NET 1.x
.NET 2.0
.NET 3.0
.NET 3.5
.NET 4.0
.NET Assemblies
.NET Framework
.NET Getting Started
Accessibility
ADO.NET
Advertorials
Agile Development
AJAX
Architecture
ASP.NET
ASP.NET MVC
ASP.NET WebForms
Azure
B2B (Business Integration)
Bing
BizTalk
Book Excerpts
Build and Deploy
C#
C++
ClickOnce
Cloud Computing
Code Contracts
CODE on the Road!
COM+
Community
Conferences
Continuous Integration
Crystal Reports
CSLA.NET
CSS
Data
Design Patterns
Development Process
Display Technologies
Distributed Computing
DotNetNuke
DSL
Dynamic Programming
Editorials
Enterprise Services ("COM+")
Entity Framework
Events
Expression Blend
F#
Fox to Fox
Frameworks
Functional Programming
Git
Graphics
Internet Explorer 8.0
Interviews
iPhone
Iron Ruby
Java
Java Script
jQuery
LINQ
Linux
Mac OS X
MDX
Microsoft Application Blocks
Microsoft Business Rules Framework
Microsoft Dynamics
Microsoft Expression
Microsoft Office
Mobile Development
Mobile PC
Mono
MsBuild
Network
NHibernate
Object Oriented Development
Odata
Open Source
Opinion
Opinions
Oracle
ORM
Other Languages
Parallel Programming
Patterns
Podcasts
Post Mortem
PowerPoint
Print/Output
Prism
Product News
Product Reviews
Project Management
Python
Q&A
Rails
Rake
Reporting Services
REST
RIA Services
Ruby
Ruby on Rails
Search
Security
Services
SharePoint
Silverlight
SOA
Social Networks
Software & Law
Software Business
Source Control
Speech-Enabled Applications
SQL Server
SQL Server 2000
SQL Server 2005
SQL Server 2008
SQL Server CE/AnyWhere/Mobile/Compact
SSIS
Subversion
Sync Framework
Tablet PC
TDD
Team System
Techniques
Testing and Quality Control
Tips
UI Design
UML
User Groups
VB Script
VB.NET
Version Control
VFP and .NET
VFP and SQL Server
Virtual Earth
Vista
Visual Basic
Visual Basic 6 (and older)
Visual FoxPro
Visual Studio .NET
Visual Studio 2005
Visual Studio 2008
Visual Studio 2010
Visual Studio Tools for Office
VSX
WCF
Web Development (general)
Web Services
WF
Whitepapers
Windows 7
Windows Azure
Windows Live
Windows Server
Windows Vista
WinForms
Workflow
WPF
XAML
XML
XNA
XSLT



CODE Training


 


Free Webinar

Reader rating:
Click here to read 40 comments about this article.
Article source: CoDe (2006 - May/Jun)


Article Pages: < Previous - 1 2  3  4 5 - Next >


WCF Essentials-A Developer’s Primer (Cont.)

Binding

There are multiple aspects of communication with any given service. There are many possible communication patterns: messages can be synchronous request/reply or asynchronous fire-and-forget, messages can be bidirectional, messages can be delivered immediately or queued, and the queues can be durable or volatile.

"
A binding is merely a consistent pre-canned set of choices regarding the transport protocol, message encoding, communication pattern, reliability, security, transaction propagation, and interoperability.
"

There are many possible transport protocols for the messages such as HTTP (or HTTPS), TCP, P2P (peer network), IPC (named pipes), or MSMQ. There are a few possible message encoding options: you can chose plain text to enable interoperability, binary encoding to optimize performance, or MTOM (Message Transport Optimization Mechanism) for large payloads.

There are a few options for securing messages: you can choose not to secure them at all, you can use them to provide transport-level security only or to provide message-level privacy and security, and of course, there are numerous ways for authenticating and authorizing the clients. Message delivery might be non-reliable or reliable end-to-end across intermediaries and dropped connections, and the messages might be delivered in the order they were sent or in the order they were received.

Your service might need to interoperate with other services or clients that are only capable of using the basic Web service protocol, or they may be capable of using the score of WS-* modern protocols such as WS-Security and WS-Atomic Transactions. Your service may need to interoperate with legacy clients over raw MSMQ messages, or you may want to restrict your service to interoperate only with another WCF service or client.

In short, there are many aspects of communication involving dozens of parameters and decision points. Some of those choices may be mutually exclusive and some may mandate other choices. Clearly, both the client and the service must be aligned on all these options in order to communicate property. To simplify and make it more manageable, WCF groups together provide a set of such communication aspects in bindings.

A binding is merely a consistent pre-canned set of choices regarding the transport protocol, message encoding, communication pattern, reliability, security, transaction propagation, and interoperability. Ideally, you would extract all these “plumbing” aspects out of your service code and allow it to focus solely on the implementation of the business logic. Doing so enables you to use the same service logic over drastically different plumbing. Binding enables you to do just that.

You can use the WCF-provided bindings as is, or you can tweak their properties, or you can write your own custom bindings from scratch. A service publishes its choice of binding in its metadata, enabling clients to query for the type and specific properties of the binding because the client must use the exact same binding as the service. A single service can support multiple bindings on separate addresses.

Generally, the service does not specify about the binding itself. WCF defines nine standard bindings, listed in Table 1. Text-based encoding enables a WCF service (or client) to communicate over HTTP with any other service (or client) regardless of its technology and binary encoding over TCP or IPC yields the best performance but at the expense of interoperability, by mandating WCF to WCF communication.

Choosing MSMQ for a transport protocol mandates WCF to WCF or WCF to MSQM communication, but it provides for disconnected offline work. Choosing a binding for your service should follow the decision-activity diagram shown in Figure 4.

Click for a larger version of this image.

Figure 4: This is choosing a binding.

The first question you should ask yourself is whether or not your service needs to interact with non-WCF clients. If the answer is yes, and if the client is a legacy MSMQ client, choose the NetMsmqBinding that enables your service to interoperate over MSMQ with such a client. If you need to interoperate with a non-WCF client and that client expects basic Web service protocol (ASMX Web services), choose the BasicHttpBinding, which exposes your WCF service to the outside world as if it were an ASMX Web service.

The downside is that you cannot take advantage of any of the modern WS-* protocols. However, if the non-WCF client can understand these standards, choose one of the WS bindings, such as WSHttpBinding, WSFederationBinding or WSDualHttpBinding. If you can assume that the client is a WCF client yet it requires offline or disconnected interaction, choose the NetMsmqBinding that uses MSMQ for transporting the messages. If the client requires connected communication but could be calling across computer boundaries, choose the NetTcpBinding that communicates over TCP.

If the client is on the same computer as the service, choose the NetNamedPipeBinding that uses named pipes (IPC) to maximize performance. Note that a service using the NetNamedPipeBinding cannot accept calls from any other computer besides its own, and thus is also inherently more secure. You may fine-tune binding selections based on additional criteria such as the need for callbacks (WSDualHttpBinding) or peer network (NetPeerTcpBinding), or federated security (WSFederationBinding).

Endpoints

Every service is associated with an address that defines where the service is, a binding that defines how to communicate with the service, and a contract that defines what the service does. This triumvirate governing the service is easy to remember as the ABC of the service.

In fact, WCF formalizes this relationship in the form on an endpoint. The endpoint is the fusion of the address, contract, and binding (see Figure 5). Every endpoint must have all three, and the service exposes the endpoint. Logically, the endpoint is the service’s interface, and is analogous to a CLR or COM interface.

Click for a larger version of this image.

Figure 5: This is the endpoint.

Every service must expose at least one business endpoint and each endpoint has exactly one contract. All endpoints on a service have unique addresses, and a single service can expose multiple endpoints. These endpoints can use the same or different bindings and can expose the same or different contracts. It is important to point out that nothing in the service code pertains to its endpoints and they are always external to the service code. You can configure endpoints either administratively using a config file or programmatically.

Administrative Endpoint Configuration

Consider the following service definition:

namespace MyNamespace
{
   [ServiceContract]
   interface IMyContract
   {...}
   class MyService : IMyContract
   {...}
}

Listing 2 shows the required entries in the host process config file. Administrative configuration is the option of choice in the majority of cases because it provides the flexibility to change the service address, binding, and even exposed contracts without rebuilding and redeploying the service.

Listing 3 shows a config file defining a single service that exposes multiple endpoints. Note that the endpoint must provide a base address that is consistent with the binding, such as HTTP with WSHttpBinding. A mismatch causes an exception at the service load time. You can configure multiple endpoints with the same base address as long as the URI is different:

<service name="MyNamespace.MyService">
   <endpoint
     address="net.tcp://localhost:8001/Service1/" 
      ...
   />
   <endpoint
     address="net.tcp://localhost:8001/Service2/" 
      ...
   />
</service>

You can also omit the address, in which case, the service uses the base address registered with the host (and the host must provide a matching base address):

<endpoint
   binding="wsHttpBinding"
   contract="MyNamespace.IMyContract" 
/>

You can provide only a URI, in which case, the address is that relative address under the base address (and the host must provide a matching base address):

<endpoint
   address="SubAddress" 
   ...
/>

When providing a base address, the endpoint overrides any base address provided by the host:

<endpoint
   address="http://localhost:8000/MyService/" 
   ...
/>

Note that when hosting with IIS, the service must use the IIS base address (computer name + virtual directory over HTTP).

Programmatic Endpoint Configuration

Programmatic endpoint configuration is completely equivalent to administrative configuration yet it does not resort to a config file and instead, you make programmatic calls to add endpoints to the ServiceHost instance. Again, these calls are always outside the scope of the service code. ServiceHost provides overloaded versions of the AddServiceEndpoint() method:

public class ServiceHost :
ServiceHostBase   
{
   public ServiceEndpoint
AddServiceEndpoint(
                        Type
implementedContract, 
                        Binding
binding, 
                        string
address);
   //Additional members 
}

Listing 4 demonstrates programmatic configuration of the same endpoints as in Listing 3. To rely on the host base address, provide just the URI as the address:

Uri tcpBaseAddress = new 
                    Uri("http://localhost:8000/");

ServiceHost serviceHost = new 
    ServiceHost(typeof(MyService),
    tcpBaseAddress);

Binding tcpBinding = new 
NetTcpBinding();

//Use base address as address 
serviceHost.AddServiceEndpoint(typeof(
   IMyContract) , tcpBinding,"");

//Add relative address 
   serviceHost.
AddServiceEndpoint(
   typeof(IMyContract) ,
   tcpBinding,"MyService");
//Ignore base address 
serviceHost.AddServiceEndpoint(
   typeof(IMyContract)
 ,tcpBinding,"net.tcp://localhost:8001/
   MyService);
   serviceHost.Open();
&


Table 1: WCF standard bindings
NameTransportEncodingInterop
BasicHttpBindingHTTP/HTTPSText+
NetTcpBindingTCPBinary-
NetPeerTcpBindingP2PBinary-
NetNamedPipeBindingIPCBinary-
WSHttpBindingHTTP/HTTPSText,MTOM+
WSFederationBindingHTTP/HTTPSText,MTOM+
WSDualHttpBindingHTTPText,MTOM+
NetMsmqBindingMSMQBinary-
MsmqIntegrationBindingMSMQBinary+


Listing 2: Administrative service configuration
<system.serviceModel>
   <services>
      <service name="MyNamespace.MyService">
         <endpoint
            address="http://localhost:8000/MyService/"
            binding="wsHttpBinding"
            contract="MyNamespace.IMyContract" 
         />
      </service>
   </services>
</system.serviceModel>


Listing 3: Multiple service endpoints configuration
<service name="MyNamespace.MyService">
   <endpoint
      address="http://localhost:8000/MyService/" 
      binding="wsHttpBinding"
      contract="MyNamespace.IMyContract" 
   />
   <endpoint
      address="net.tcp://localhost:8001/MyService/" 
      binding="netTcpBinding"
      contract="MyNamespace.IMyContract" 
   />
   <endpoint
      address="net.tcp://localhost:8002/MyService/" 
      binding="netTcpBinding"
      contract="MyNamespace.IMyOtherContract" 
   />
</service>


Listing 4: Prograqmmtic configuraqtio of multiple service endpoints
public static void Main()
{
   ServiceHost serviceHost = new 
      ServiceHost(typeof(MyService));
   
   Binding wsBinding  = new WsHttpBinding();
   Binding tcpBinding = new NetTcpBinding();
   
   serviceHost.AddServiceEndpoint(typeof(IMyContract),
                                  wsBinding,
                   "http://localhost:8000/MyService");
   serviceHost.AddServiceEndpoint(typeof(IMyContract),
                                  tcpBinding,
                "net.tcp://localhost:8001/MyService");
                 serviceHost
         .AddServiceEndpoint(typeof(IMyOtherContract),
                 tcpBinding,
                             "net.tcp://localhost:8002/MyService");
   
   serviceHost.Open();

   Application.Run(new MyForm());

   serviceHost.Close();
}


Article Pages: < Previous - 1 2  3  4 5 - Next Page: 'Client-Side Programming' >>

Page 1: WCF Essentials-A Developer’s Primer
Page 2: Service Contract
Page 3: Binding
Page 4: Client-Side Programming
Page 5: WCF Architecture

How would you rate the quality of this article?
1 2 3 4 5
Poor      Outstanding

Tell us why you rated the content this way. (optional)

Average rating:
3.5 out of 5

305 people have rated this article.

      iPhone iPad Developers Conference

 

Devscovery