WCF

advertisement
Windows Communication Foundation
• Introduction
– .Net foundations
– Communication Protocols
– SOA tenets
• WCF
– Basics
– Contracts
– Bindings
• Build a WCF application
– Build the service
– Build the client
– Host the service
Nordjyllands Erhvervakademi - 2009
1
.NET At The Core
Nordjyllands Erhvervakademi - 2009
2
Distributed applications
• Many protocols and api’s for communication
Web services
.NET Remoting
MSMQ
COM+
DCOM
Corba
Sockets
P2P
RMI
Nordjyllands Erhvervakademi - 2009
3
WCF
• WCF provides a single extendable programming object
model that can be used to interact with number of
distributed technologies
• It makes it possible to offer multiple ways of
communications, e.g. Web Services or .Net Remoting
• It is possible to extend the application with a new protocol
without adding or refactoring code. It is done in the config
file
• WCF is based on the design principles of SOA Service-Oriented Architecture
• Supports strongly typed (.Net remoting) and loosely typed
messages (XML)
• Supports multiple web service specs (WS*) e.g. Soap and
Jason
• Fully integrated security models
(both windows models and independent models)
Nordjyllands Erhvervakademi - 2009
4
Service-Oriented Architecture
• Many definitions exists.
• The simple definition:
SOA is a way to design distributed systems where several
autonomous services works in conjunction by passing
messages across boundaries using interfaces
• WCF is based on 4 tenets of SOA:
1.
2.
3.
4.
Boundaries are explicit
Services are autonomous
Services communicates via contract, not implementation
Service compatibility is based on policy
Nordjyllands Erhvervakademi - 2009
5
The ABC of WCF
• Three things are needed to build a WCF application:
A. Address
The location of the service. Normally stored in the config file
B. Binding
How to bind to the service. Should it be xml, binary etc.
C. Contract
Normally implemented as an interface in c#. But it is
possible to add [ServiceContract] attributes to a normal
class.
• Note: You don’t have to do it in the order of A, B and C.
Actually in most cases you do it the opposite order
Nordjyllands Erhvervakademi - 2009
6
Contract
• Make an interface as usual.
The interface methods will be the operations of the service.
• Use [ServiceContract] to define the interface as a (uhm..)
service contract.
• Use [OperationContract] to define the method as an
operation
Nordjyllands Erhvervakademi - 2009
7
Binding
• The binding specifies how to use the service
• There may be specified more than one binding, meaning
that there may be more than one way to access the service.
• The binding can specify:
– The contracts implemented by the service
– The transport layer (http, tcp, named pipes, msmq)
– The channel for the transport (request-reply, one-way,
duplex)
– The encoding method (xml, binary, etc)
– If a WS: Any supported web service protocols
(WS-Transaction, WS-Security etc.)
Nordjyllands Erhvervakademi - 2009
8
Http Binding
• The binding can be specified in the code by declaring an object, or
(the easiest way) in the config file (using xml)
• Use http if the service should be reached by non .Net platforms or
through Nat’s and firewalls
• There are by default 4 types of http binding:
• Element < basicHttpBinding> or the class BasicHttpBinding
Basic web service functionality based on http and xml.
• Element <wsHttpBinding>, class WSHttpBinding
Like BasicHttpBinding, but with support for transactions and
reliable messaging
• Element <wsDualHttpBinding>, class WSDualHttpBinding
Like WSHttpBinding, but makes possible for the service and the
client to send message back and forth.
• Element <wsFederationHttpBinding>, WSFederationHttpBinding
Extended security. Supports ws-federation.
Nordjyllands Erhvervakademi - 2009
9
Tcp binding
• Use tcp binding in-house on .Net based platforms
• Based on binary streams. Less bytes are transferred and no
need for parsing
• Element <netTcpBinding>, NetTcpBinding
A secure and optimized method.
• Element <netNamedPipeBinding>, NetNamedPipeBinding
Used for communication between applications on the same
machine.
• Element <netPeerTcpBinding>, NetPeerTcpBinding
Used for peer-to-peer
• <netMsmqBinding>, NetMsmqBinding
Uses messages for cross-machine .Net platform communication
• <msmqIntegrationBinding>, MsmqIntegrationBinding
Used for communication with COM and native C++
Nordjyllands Erhvervakademi - 2009
10
Which binding methods should I know for a start?
• BasicHttpBinding
• NetTcpBinding
Nordjyllands Erhvervakademi - 2009
11
The EightBall example
The steps
1. Define the contract ::= define the interface and add contract
attributes
2. Implement the service class (that implements the interface)
3. Do the ABC in the App.config file (on the server)
4. Implement the server
5. Implement the client
– Generate proxy
– Use the service
Nordjyllands Erhvervakademi - 2009
12
Step 1: Define the contract
• Just make an interface as usual, and add the attributes
[ServiceContract(Namespace="noea.dk")]
public interface IEightBall
{
[OperationContract]
string ObtainAnswerToQuestion(string userQuestion);
}
Nordjyllands Erhvervakademi - 2009
13
Step 2: Implement the service
• Just a class
public class MagicEightBallService:IEightBall
{
public MagicEightBallService()
{
Console.WriteLine("The 8-ball awaits your question....");
}
public string ObtainAnswerToQuestion(string userQuestion)
{
string[] answers =
{ "Future uncertain", "Yes", "No", "Hazy", "Ask again later", "Definitely" };
Random r = new Random();
return string.Format("{0}? {1}",userQuestion,answers[r.Next(answers.Length)]);
}
}
Nordjyllands Erhvervakademi - 2009
14
Step 3: The config file (basic)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="MagicEightBallServiceLib.MagicEightBallService”/>
<endpoint address=""
binding="basicHttpBinding"
contract="MagicEightBallServiceLib.IEightBall"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/MagicEightBallService"/>
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>
Nordjyllands Erhvervakademi - 2009
15
Step 3: The config file (enable wsdl)
…………
<service name="MagicEightBallServiceLib.MagicEightBallService"
behaviorConfiguration="EightBallServiceMEXBehavior">
<endpoint address="" binding="basicHttpBinding"
contract="MagicEightBallServiceLib.IEightBall"/>
<endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange" />
<host>
…………..
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="EightBallServiceMEXBehavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
……………….
Nordjyllands Erhvervakademi - 2009
16
Step 4: The Server
using System;
using System.ServiceModel;
using MagicEightBallServiceLib;
namespace MagicEightBallServiceHost
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Console Based WCF Host");
using (ServiceHost serviceHost = new
ServiceHost(typeof(MagicEightBallService)))
{
serviceHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press the Enter key to terminate service.");
Console.ReadLine();
}
}
}
}
Nordjyllands Erhvervakademi - 2009
17
The using statement
(not the using declaration)
• The using statement ensures that the object is disposed,
when it goes out of scope.
• Is similar to this code:
{
ServiceHost serviceHost = new
ServiceHost(typeof(MagicEightBallService)))
try
{
serviceHost.Open();
…..
}
finally
{
if (serviceHost != null)
((IDisposable) serviceHost).Dispose();
}
}
Nordjyllands Erhvervakademi - 2009
18
The Client
• Basically create the proxy class
• It can be done in VisualStudio by adding a Service
Reference
• If you have the server and the client in the same solution,
you have start the server from outside of VS before adding
the reference
• Another way is to use svcutil.exe from the command prompt
This will create a config file and a cs file containing the
proxy class
Nordjyllands Erhvervakademi - 2009
19
Step 5: The Client
Autogenerated config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IEightBall" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8080/MagicEightBallService"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IEightBall"
contract="test.IEightBall" name="BasicHttpBinding_IEightBall" />
20
Nordjyllands
- 2009
</client> Erhvervakademi
</system.serviceModel></configuration>
Step 5: The Client
Stripped config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<client>
<endpoint address="http://localhost:8080/MagicEightBallService"
binding="basicHttpBinding"
contract="test.IEightBall" name="BasicHttpBinding_IEightBall" />
</client>
</system.serviceModel>
</configuration>
Nordjyllands Erhvervakademi - 2009
21
Step 5: The Client
The exe file
using MagicEightBallClient.test;
namespace MagicEightBallClient
{
class Program
{
static void Main(string[] args)
{
using (test.EightBallClient ball = new EightBallClient())
{
Console.Write("Your question: ");
string question = Console.ReadLine();
string answer = ball.ObtainAnswerToQuestion(question);
Console.WriteLine("8-ball says: {0}",answer);
}
Console.ReadLine();
}
}
}
Nordjyllands Erhvervakademi - 2009
22
Run the example
• The server must run in administrator mode on Vista and
Windows 7
• Either start Visual Studio or the server in administrator
mode: right click-> run as administrator
Nordjyllands Erhvervakademi - 2009
23
Exercise
• Change the EightBall server so it also supports .netTcp
• Change the client to use the .netTcp
• Change the RemoteBank to WCF.
Use the WCF Service Library template, and test it by using
WcfTestClient.exe
see Troelsen p. 901
• If you are fast:
Make it possible to run RemoteBank as a service
see Troelsen p. 903 ->
Nordjyllands Erhvervakademi - 2009
24
Download