450 likes | 568 Views
Architecture Bindings http tcp Msmq Serialization part 1 With [DataContract] Running the services In your own program As a webservice on IIS As a service on the machine Serialization part 2 General serialization. DB. DT. BT. Why use client/server?.
E N D
Architecture • Bindings • http • tcp • Msmq • Serialization part 1 • With [DataContract] • Running the services • In your own program • As a webservice on IIS • As a service on the machine • Serialization part 2 • General serialization
DB DT BT Why use client/server? • 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
Why use proprietary technology? Server.exe (.NET) Client.exe (.NET) • The advanced of proprietary technologies is a common platform on both sides: • Allows use of a proprietary communication protocol • Allows use of a proprietary dataformat • Meaning? • More efficient • Examples of proprietary technologies: • COM (MS), CORBA (omg.com), RMI (Java) • WCF (partly proprietary), .Net remoting • There might be different OS's on client and server i.e. Windows and Linux • Alternative to proprietary technologies can web services as we’ll see in the next lesson
.DLL Remoting seen from the clientand 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
Comp Data Proxy Comp Stub Data Data Proxy Data Stub Design, more detailed • Business and calculation objects lives on the server • Data objects marshals to the clients Client call Client call Server
Architecture • Bindings • http • tcp • Msmq • Serialization part 1 • With [DataContract] • Running the services • In your own program • As a webservice on IIS • As a service on the machine • Serialization part 2 • General serialization
Bindingfrom last session • 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
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 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.
Http binding • Http binding is text format • The advantage is independency of platforms and network architecture • The drawbacks are more bytes are sent, and you have to parse the call in some way. • Common webservice protocols are • SOAP – Based on XML, the old web service standard • JSON – Suitable for JavaScript / AJAX. Not XML. • REST – Based on HTTP operations (GET, POST, PUT, DELETE) • REST is the most used protocol pt. • More on protocols in the next session
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>, 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++
Tcp binding • Tcp binding is a binary format • It is normally not an easy task, if possible, to use binary formats on different platforms • The format reflects the way datatypes are stored in memory, and that depends on programming language, hardware, OS etc. • But binary formats are compact and faster to parse
MSMQ • MSMQ is for messaging systems • Http binding and tcp binding are most used for RPC where sender and receiver has to know each other. • In order to obtain lower coupling messaging can be used. • Here the sender and the receiver does not necessary know each other, and therefore one part can be changed, duplicated or throttled independent of the other part(s) • An message can be an operation or an object, and might be expressed in XML or anything else. • There will a lot more on that topic in "System Integration" on PBA-SW
Architecture • Bindings • http • tcp • Msmq • Serialization part 1 • With [DataContract] • Running the services • In your own program • As a webservice on IIS • As a service on the machine • Serialization part 2 • General serialization
Serialization, briefly • In order to send an object by any kind of stream it necessary to serialize it • It can be serialized to anything but the most common options are a proprietary binary format or to some kind of XML • For starters we will see how it is done in WCF with the [DataContract] and the [DataMember] attributes
[DataContract] • From MSDN: Specifies that the type defines or implements a data contract and is serializable by a serializer, such as the DataContractSerializer. • When you use [DataContract], you don't need [Serializable] • Some properties: • IsReference: Used for solving 2-way references in the XML. Else the serialization will loop. • Name: Set the name of XML element (tag) • Namespace: Set the namespace for the XML • Name and Namespace are interesting if you need to serialize to certain XML language
[DataMember] • From MSDN: When applied to the member of a type, specifies that the member is part of a data contract and is serializable by the DataContractSerializer. • You can use it to mark which attributes to serialize • Some properties: • Name: Set the name of XML element (tag) • IsRequired: if true then the property is mandatory • Order: indicates which order to serialize/deserialize in. • EmitDefaultValue: true if the default value for a member should be generated in the serialization stream;
An example DataContract (IsReference=true)] //IsReference is necessary if it is double references: A->B & B->A publicclassClassA { [DataMember] publicstring Name { get; set; } [DataMember] publicClassBPropB { get; set; } publicoverridestringToString() { returnString.Format("{0} contains {1}", Name, PropB.Name); } } • ClassB is alike.
How to serialize it (in your own code) • We have seen that WCF does it automatically • You can do it your self by using DataContractSerializer • In this example it is streamed to a file using System.Runtime.Serialization; ... stringfileName = "ClassA.xml"; FileStream writer = newFileStream(fileName, FileMode.Create); DataContractSerializerser = newDataContractSerializer(typeof(ClassA)); ser.WriteObject(writer, a); writer.Close();
The resulting XML <ClassAz:Id="i1" xmlns="http://schemas.datacontract.org/2004/07/ExDataContract"xmlns:i="http://www.w3.org/2001/XMLSchema-instance"xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" > <Name>Class A</Name> <PropBz:Id="i2"> <Name>Class B</Name> <PropAz:Ref="i1"/> </PropB> </ClassA>
How to deserialize itHere: Read from the file // Open file FileStreamfs = newFileStream(fileName, FileMode.Open); // Open stream for reading (here xml) XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, newXmlDictionaryReaderQuotas()); // Open serializer for a ClassA object DataContractSerializerdSer = newDataContractSerializer(typeof(ClassA)); // Deserialize the data and read it into the instance. ClassAnewA = (ClassA)dSer.ReadObject(reader, true); // Close nicely reader.Close(); fs.Close();
Architecture • Bindings • http • tcp • Msmq • Serialization part 1 • With [DataContract] • Running the services • In your own program • As a webservice on IIS • As a service on the machine • Serialization part 2 • General serialization
Back to WCF • There are 3 ways to run the service: • In your own server program (as you saw in last session) • As a service on the machine • As a Web Service
Run as a service on the machine • Assume that the dll with the service class(es) has been implemented. It is the MagicEightBallServiceLib in the 8-ball example. • A few more steps are needed: • Add a new project to the solution. Use the Windows Service template • Add references to System.ServiceModel and MagicEightBallServiceLib • Implement the OnStart and OnStop methods • Create an installer for the service • Install the service • Slides for step 3-5. Else look in the book (and the demo now).
Remember the MagicEightBallHost class Program { static void Main(string[] args) { Console.WriteLine("Console Based 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(); } } }
Implement OnStart methodSimilar to MagicEightBallHost ServiceHostserviceHost; protectedoverridevoidOnStart(string[] args) { if (serviceHost != null) { serviceHost.Close(); serviceHost = null; } serviceHost = new ServiceHost(typeof(MagicEightBallService)); serviceHost.Open(); }
OnCloseJust close the service protectedoverridevoidOnStop() { if (serviceHost != null) { serviceHost.Close(); } }
Create the installer • Right-click somewhere in the designer and select Add Installer • Set user to 'LocalSystem' in serviceProcessInstaller1 properties • And set Name, description and ServiceName in serviceInstaller1
Install the service • Open Visual Studio Command prompt as administrator • Go to the bin directory of the service, e.g. (on my pc):cd C:\slet\Exercise8Ball\EightBallService\bin\Debug(You can use ‘tab’ the same way as in unix) • Run the installer:installutil EightBallService.exe
Start the server • Open the services console • Easiest way: write service in the "Search programs and files" and select services. • Find eightball service and select start.
Uninstall service • Is done by:installutil /u EightBallService.exe • It happens that you have to restart
WCF Web services • More in next session • But else it is easy if you used the WCF Service Application template:Just right-click on project and select Publish. Then you can publish to a webserver by using ftp, webdeploy etc. • Do it from by using the web site wcf template as described in the book .
Exercise • Continue with the bank system. • Make a server program so it can started without VS • Make a persistence tier • Save customers (and the referenced accounts) to a file. • Read customers from the file when the service is started. • Implement the as a service • Implement the system so it runs as a service on the machine.
Architecture • Bindings • http • tcp • Msmq • Serialization part 1 • With [DataContract] • Running the services • In your own program • As a webservice on IIS • As a service on the machine • Serialization part 2 • General serialization
Serialization • Serialization • Purpose • Standard serializers
Stream • A stream is an abstraction for data flowing between a source and a destination • Stream provides a common way to transfer a sequence of data (e.g. an array) regardless of the device • The device could be a file, the keyboard, a network connection, a printer, the memory etc. • Btw. The stream metaphor is known from C++:cout>>”Hello World”;
Serialization – Send objects by a stream • A object have to be serialized before it can be send by a stream • In C#, it can be done simply by setting the attribute [Serializable] before the class token. • 3 built-in methods that you can use to serialize: • BinaryFormatter • SoapFormatter • XmlSerializer
Serilization - continued.... • What is serialized? • By BinaryFormatter is public/private fields and properties serialized. A remake of the object shall be possible in another place • Also by SoapFormatter is public/private fields and properties serialized. But it cannot handle generic types • XmlFormatter is only public fields and properties serialized. • If [NonSerialized] is stated before a field/property, then it will not be serialized. • Note that methods are never serialized.
Example [Serializable] class Person { public String FirstName {get; set;} public String LastName {get; set;} public DateTime Birthday {get; set;} public float Height {get; set;} [NonSerialized] public int Id {get; private set;}; .... }
Serialize to binary format using System.IO; using System.Runtime.Serialization.Formatters.Binary; ... Person p = new Person(23, "Donald", "Duck", DateTime.Now, 0.4f); Stream bs = new FileStream(@"c:\temp\bp.dat", FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(bs, p); bs.Close();
Deserialize using System.IO; using System.Runtime.Serialization.Formatters.Binary; .... BinaryFormatter bf = new BinaryFormatter(); Stream fstream = File.OpenRead (@"c:\temp\bp.dat”) Person bp = (Person)bf.Deserialize(fstream); Console.WriteLine("{0} {1}", bp.FirstName, bp.BirthDay);
Serialization result: Xml Something strange here ?
Exercise • Exercise 1 • Construct a list of person objectsYou are free to use the Person class from the slides • Serialize the objects and save the objects to a binary file • Read from the file and reconstruct the list • Exercise 2 • Make a WCF service that searches the file for a person with a specified id and returns it to the client. • The interface could be:Person GetPerson(int id); • Hints: Remove [NonSerialized] on idUse fstream.Position<fstream.Length to determine end_of_file • In this exercise you are on your own, but look in the solution for the bank