310 likes | 474 Views
DB. DT. BT. Why use distributed (client / server) applications?. To connect tiers within the same application... client & server is both .NET assemblies Example: A typical business app has Business and Data Access tiers GUI calls into the business tier to get data, calculation & validation
E N D
DB DT BT Why use distributed (client / server) applications? • To connect tiers within the same application... • client & server is both .NET assemblies • Example: • A typical business app has Business and Data Access tiers • GUI calls into the business tier to get data, calculation & validation • Business tier makes calls to the data tier for writing / reading data Server (.NET) Client (.NET) BusinessTier Data AccessTier
.DLL Distributed app seen from the client and the server Client.exe Server • The client sees the server as an assembly .DLL • sets a reference to a object as normally • The server makes .DLL available in one of two ways: • Runs as a service on the server, that responds on remote calls • Runs in the web server & trigger remote calls via URL • advances? • #1 can use proprietary protocols & formats (more efficient) • #2 is firewall-friendly, easy use of Windows security
Windows Communication Foundation • Introduction • .Net foundations • Communication Protocols • SOA tenets (principles) • WCF • Basics • Contracts • Bindings • Build a WCF application • Build the service • Build the client • Host the service
Distributed applications • Many protocols and api’s for communication Web services .NET Remoting MSMQ COM+ DCOM CORBA Sockets P2P RMI
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 .NetRemoting • 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 (.Netremoting) and loosely typed messages (XML) • Supports multiple web service specs (WS*) e.g. SOAP and JSON • Fully integrated security models (both windows models and independent models)
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: • Boundaries are explicit • Services are autonomous • Services communicates via contract, not implementation • Service compatibility is based on policy
The ABC of WCF • Three things are needed to build a WCF application: • AddressThe location of the service. Normally stored in the config file • BindingHow to bind to the service. Should it be xml, binary etc. • ContractNormally 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 • Together ABC forms an endpoint.
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 • Let’s look at the WCFHelloWorld.
Contract Contract: Uses and references the backend: Implementing the service acting as a proxy for the backend:
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.) Don't confuse the terms tcp and http with OSI.Tcp and http are on different layers in OSI, and as you know http is on top of tcp
Binding – App.config in the WcfService Project Binding and Contract (The “mex” endpoint is used by VS or other EDI)
Binding – app.config in the Client Project Binding and Contract
Exercises • Exercise 1 (from GettingStartedWCF.pdf): • HelloWorld • Add another client:Create a WinForm application that says ´”Hello World” using the same WCF service. Go through the same steps as when the console application was created. • Make your own distributed application:Make a back-end (Calculator) with methods for adding, subtracting and multiplying two numbers in same way as the HelloServer. Add a WCF service that uses the back-end. And finally, add a client.
Http Binding – Open to the world • 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 BasicHttpBindingBasic web service functionality based on http and xml. • Element <wsHttpBinding>, class WSHttpBindingLike BasicHttpBinding, but with support for transactions and reliable messaging • Element <wsDualHttpBinding>, class WSDualHttpBindingLike WSHttpBinding, but makes possible for the service and the client to send message back and forth. • Element <wsFederationHttpBinding>, WSFederationHttpBindingExtended security. Supports ws-federation.
Tcp binding – In-house • Use tcp binding in-house on .Net based platforms • Based on binary streams. Less bytes are transferred and no need for parsing • Element <netTcpBinding>, NetTcpBindingA secure and optimized method. • Element <netNamedPipeBinding>, NetNamedPipeBindingUsed for communication between applications on the same machine. • Element <netPeerTcpBinding>, NetPeerTcpBindingUsed for peer-to-peer • <netMsmqBinding>, NetMsmqBindingUses messages for cross-machine .Net platform communication • <msmqIntegrationBinding>, MsmqIntegrationBindingUsed for communication with COM and native C++
Which binding methods should I know for a start? • BasicHttpBinding (or wsHttpBinding) • NetTcpBinding
The EightBall exampleThe steps • Define the contract == define the interface and add contract attributes • Implement the service class (that implements the interface) • Do the ABC in the App.config file (on the server) • Implement the server • Implement the client • Generate proxy • Use the service Recommended: In VS2010 start by using the WCF Service project template
Step 1: Define the contract • Just make an interface as usual, and add the attributes [ ServiceContract(Namespace="noea.dk")] public interface IEightBall { [OperationContract] stringObtainAnswerToQuestion(stringuserQuestion); }
Step 2: Implement the service • Just a class public classMagicEightBallService:IEightBall { public MagicEightBallService() { Console.WriteLine("The 8-ball awaits your question...."); } public stringObtainAnswerToQuestion(stringuserQuestion) { string[] answers = { "Future uncertain", "Yes", "No", "Hazy", "Ask again later", "Definitely" }; Random r = new Random(); returnstring.Format("{0}? {1}",userQuestion,answers[r.Next(answers.Length)]); } }
The .config file • Configuration files are widely used in .Net • A configuration file provides an easy way of changing different kind of setting. • For example: • Database connection strings • Authorization settings • Remoting settings • Application specific properties • In Visual Studio: Add a new item using the “Application Configuration File” template • Leave the name as app.config. It will be renamed to <assemply filename>.config. • E.g.: MyProgram.exe.config
Step 3: The config file (basic) <?xmlversion="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <services> <servicename="MagicEightBallServiceLib.MagicEightBallService”/> <endpointaddress="" binding="basicHttpBinding" contract="MagicEightBallServiceLib.IEightBall"/> <host> <baseAddresses> <addbaseAddress="http://localhost:8080/MagicEightBallService"/> </baseAddresses> </host> </service> </services> </system.serviceModel> </configuration>
Step 3: The config file (enable wsdl) ………… <servicename="MagicEightBallServiceLib.MagicEightBallService" behaviorConfiguration="EightBallServiceMEXBehavior"> <endpointaddress="" binding="basicHttpBinding" contract="MagicEightBallServiceLib.IEightBall"/> <endpointaddress="mex"binding="mexHttpBinding" contract="IMetadataExchange" /> <host> ………….. </host> </service> </services> <behaviors> <serviceBehaviors> <behaviorname="EightBallServiceMEXBehavior"> <serviceMetadatahttpGetEnabled="true"/> </behavior> </serviceBehaviors> ……………….
Step 4: The Server using System; usingSystem.ServiceModel; usingMagicEightBallServiceLib; namespaceMagicEightBallServiceHost { classProgram { staticvoid Main(string[] args) { Console.WriteLine("ConsoleBased WCF Host"); using (ServiceHostserviceHost = new ServiceHost(typeof(MagicEightBallService))) { serviceHost.Open(); Console.WriteLine("The service is ready."); Console.WriteLine("Press the Enter key to terminate service."); Console.ReadLine(); } } } }
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: { ServiceHostserviceHost = new ServiceHost(typeof(MagicEightBallService))) try { serviceHost.Open(); ….. } finally { if (serviceHost != null) ((IDisposable)serviceHost).Dispose(); } }
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 promptThis will create a config file and a cs file containing the proxy class
Step 5: The ClientAutogenerated config file <?xmlversion="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <bindings> <basicHttpBinding> <bindingname="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"> <readerQuotasmaxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <securitymode="None"> <transportclientCredentialType="None" proxyCredentialType="None" realm="" /> <messageclientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <client> <endpointaddress="http://localhost:8080/MagicEightBallService" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IEightBall" contract="test.IEightBall" name="BasicHttpBinding_IEightBall" /> </client> </system.serviceModel></configuration>
Step 5: The ClientStripped config file <?xmlversion="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <client> <endpointaddress="http://localhost:8080/MagicEightBallService" binding="basicHttpBinding" contract="test.IEightBall" name="BasicHttpBinding_IEightBall" /> </client> </system.serviceModel> </configuration>
Step 5: The ClientThe exe file usingMagicEightBallClient.test; namespaceMagicEightBallClient { classProgram { staticvoid Main(string[] args) { using (test.EightBallClient ball = new EightBallClient()) { Console.Write("Yourquestion: "); stringquestion = Console.ReadLine(); stringanswer = ball.ObtainAnswerToQuestion(question); Console.WriteLine("8-ball says: {0}",answer); } Console.ReadLine(); } } }
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
Exercises • Exercise 2: • Change the EightBall server so it also supports .netTcp • Change the client (or make a new) to use the .netTcp