Manual WCF
Manual WCF
CHAPTER 1 Contracts
Namespace CallbackContract
Description Specifies a different name for the contract instead of the default, which is simply the interface or class type name. This contract name is what will appear in the portType name when consumers access the WSDL. Specifies a target namespace in the WSDL for the service. The default namespace is http://tempuri.org. Associates another Service contract as a Callback contract. This sets up the infrastructure for a duplex MEP and thereby allows the service to initiate sending messages to the client. The Message Exchange Patterns section of this lesson discusses MEPs in more detail. Enables the Service contract to specify constraints on how messages to all operations in the contract are protected on the wire, that is, whether they are signed and encrypted. See Chapter 8, User-Level Security, for more about security. Specifies the name attribute of the service element in a configuration file. The default is the name of the service implementation class, that is, the service type. Specifies whether sessions should be enabled by the endpoint exposing this Service contract. See Chapter 10, Sessions and Instancing, for more about sessions and session management. Aconsejable utilizar la propiedad Namespace para proporcionar un identificador uniforme de recursos(URI) Utilizar la propiedad Name, para eliminar el I de la interfaz
ProtectionLevel
ConfigurationName SessionMode
y y
Named Parameter Description Name Specifies a different name for the operation instead of using the default, which is the method name. Action Controls the action header for messages to this operation. ReplyAction Controls the action header for response messages from this operation. IsOneWay Indicates whether the operation is one-way and has no reply. When operations are one-way, ReplyAction is not supported. IsOneWay is covered in more detail later in this lesson, in the section called OneWay, while discussing MEPs. ProtectionLevel Enables the Service contract to specify constraints on how messages to all operations in the contract are protected on the wire, that is, whether they are signed and encrypted. See Chapter 8 for more about security. The setting for this property at the operation level overrides the ProtectionLevel property of the ServiceContractAttribute. IsInitiating IsTerminating Indicates whether invoking the operation initiates a new session between the caller and the service. See Chapter 10 for more about sessions and session management. Indicates whether invoking the operation terminates an existing session between the caller and the service. See Chapter 10 for more about sessions and session management.
[ServiceContract] public interface SomeCrudContract { [OperationContract(IsOneWay = true, Action = "urn:crud:insert")] void ProcessInsertMessage(Message message); [OperationContract(IsOneWay = true, Action = "urn:crud:update")] void ProcessUpdateMessage(Message message); [OperationContract(IsOneWay = true, Action = "urn:crud:delete")] void ProcessDeleteMessage(Message message); // The catch-all operation: [OperationContract(IsOneWay = true, Action = "*")] void ProcessUnrecognizedMessage(Message message); }
PATRONES DE INTERCAMBIO DE MENSAJES (MEP) Los MEP describen el protocolo de intercambio de mensajes que el cliente debe realizar para conversar correctamente con el servicio. Por ejemplo, si un cliente enva un mensaje, necesita saber si debe esperar un mensaje de vuelta o si simplemente enviar la solicitud es suficiente. Los 3 MEP: Request/Response: El ms utilizado y el que menos hay que configurar. IsOneWay=false.
[ServiceContract()] public interface ILogisticsService { [OperationContract()] WorkOrderAcknowledgement SubmitWorkOrder(WorkOrder workOrder); [OperationContract()] void CancelWorkOrder(int workOrderNumber); }
y y -
No se puede utilizar con FaultContract (utiliza duplex) Si se desea que la entrega de los mensajes sea en cola, se debe utilizar OneWay
Duplex: Doble canal de mensajes que se utiliza cuando el cliente enva un mensaje al servicio para iniciar un proceso largo de ejecucin y, posteriormente exige confirmacin. Este MEP esta declarado para asociar un ServiceContract con un Callback
[ServiceContract] interface IGreetingHandler { [OperationContract(IsOneWay = true)] void GreetingProduced(string greeting); }
[ServiceContract(CallbackContract = typeof(IGreetingHandler))] interface IGreetingService { [OperationContract(IsOneWay = true)] void RequestGreeting(string name); } [ServiceBehavior(InstanceContextMode =InstanceContextMode.PerSession)] class GreetingService : IGreetingService { public void RequestGreeting(string name) { Console.WriteLine("In Service.Greet"); IGreetingHandler callbackHandler = OperationContext.Current.GetCallbackChannel<IGreetingHandler>(); callbackHandler.GreetingProduced("Hello " + name); } }
CANALES DUPLEX Y SERVIDORES PROXY DE CLIENTE Puntos a tener en cuenta antes de usar Duplex: Duplex es problemtico en el mundo real porque necesita volver a conectarse con el cliente. Da problemas por cuestiones de seguridad No escala muy bien Si se utiliza Duplex se pierde interoperabilidad Problemas de Threading cuando las operaciones en cada extremo del canal no son OneWay
[DataContract(Namespace = "http://schemas.fabrikam.com/customers/")] public class ContactInfo { [DataMember(IsRequired = false)] public string PhoneNumber; [DataMember(IsRequired = false)] public string EmailAddress; }
DataContractAttribute: Tipo del DataContract. Se puede aplicar a enum, structs y class, no es heredable y tiene 2 parametros:
Named Parameter Description Name Determines the type name as it is generated in the resulting schema. The default is the .NET type name as it is declared. Namespace Sets the target namespace for the schema. This defaults to http://schemas.datacontract.org/2004/07/[CLR namespace], where [CLRnamespace] is the namespace in which the complex type is defined. y DataMemberAttribute: Se aplica a los miembros del DataContract.
Named Parameter Description Name Controls the schema element name generated for the member (that is, the field or property) the attribute adorns. The default behavior is to use the field or property name as defined in the .NET type. IsRequired Controls the minOccurs attribute for the schema element. The default value is false, that is, the element is optional, which translates into minOccurs = 0. Order Controls the order of each element in the schema. By default, if this property is not set explicitly, the data members appear alphabetically, followed by elements for which this property is set explicitly. EmitDefaultValue Controls whether default values will be included in the serialization. This property is true by default, so that all data members are serialized. If this property is set to false, any member that is set to its default value for its type (for instance, null for reference types) will not be serialized.
Collections: Se puede utilizar varios tipos de colecciones (siempre y cuando implementen las interfaces IEnumerable o IEnumerable<T>)
[ServiceContract()] interface ITaskManager { [OperationContract()] Task[] GetTasksByAssignedName( string name); }
Known Types: WCF tambin proporciona KnownTypeAttribute que permite designar clases derivadas de un determinado DataContract
[DataContract()] [KnownType(typeof(LoanApprovalTask))] class Task { // Etc... } [DataContract()] class LoanApprovalTask : Task { // Etc... }
con
tipos
polimrficos
en
el
ServiceContract,
se
requiere
MESSAGE CONTRACTS Al desarrollar servicios WCF, los ServiceContracts permiten definir la estructura de los datos que sern enviados en el cuerpo de los mensajes SOAP, ya sea en la entrada (peticin) o en la salida (respuesta). Razones para usar Mensajes: - Controlar como los Mensajes SOAP estn estructurados y serializados - Dar y acceder a encabezados personalizados Atributos de los mensajes: y MessageContractAttribute
Named Parameter IsWrapped Description If true, the message body includes a wrapper element named by using the Message contract type or the WrapperName if specified. If false, the message body is unwrapped, and body elements appear directly beneath it. Enables the Service contract to specify constraints on how messages to all operations in the contract are protected on the wire, that is, whether they are signed and encrypted. See Chapter 8 for more about security. Supplies a custom name for the body wrapper element.
ProtectionLevel
WrapperName
MessageHeaderAttribute: Se aplican a los miembros del Message Contract para indicar que elementos pertenecen
Description Controls the name of the serialized header element. Supplies a namespace for the header element and its children unless otherwise overridden at the type level. Enables the Service contract to specify constraints on how messages to all operations in the contract are protected on the wire, that is, whether they are signed and encrypted. See Chapter 8 for more about security. A URI value indicating which actor is the intended target of the header. By default, the receiving service is assumed. Indicates whether the recipient of the header (designated through the Actor property) is required to process this header. If this property is set to true and the actor doesnt understand the header, the actor should issue a fault. Indicates whether this header should be forwarded to the next recipient of the message in the event the message is not being processed by the actor.
Actor MustUnderstand
Relay
MessageBodyMemberAttribute : se aplica a los miembros del Message Contract para declarar qu elementos pertenecen al cuerpo del mensaje.
Description Controls the name of the serialized body element. Supplies a namespace for the body element and its children unless otherwise overridden at the type level. Enables the Service contract to specify constraints on how messages to all operations in the contract are protected on the wire, that is, whether they are signed and encrypted. See Chapter 8 for more about security. Controls the order of each element in the schema. By default, if this property is not set explicitly, the data members appear alphabetically, followed by elements for which this property is set explicitly. The same rules are used to apply ordering as are used with Data contracts. (See the section titled The DataMemberAttribute.)
Order
CONTROLAR LA SERIALIZACIN Como asegurarnos que los mensajes enviados y recibidos estn en el formato XML correcto y Serialization vs Encoding: Cuando estamos trabajando con un objecto DataContract o con un objeto serializable y queremos devolverlo en alguna operacin debemos serializarlo en un objeto mensaje (representacin de un mensaje SOAP). WCF tiene 2 mtodos para serializar: DataContractSerializar, XmlSerializer. El siguiente paso es codificar el mensaje en un flujo de bytes, para ello WCF dispone de 4 codificadores: Estndar XML, MTOM, WCF-WCF binary encoding. Atributos de los Serializadores: Ambos serializadores tienen los atributos Rpc y Document, pero adems, XmlSerializer dispone de Use.
[ServiceContract()] [XmlSerializerFormat(Style=OperationFormatStyle.Rpc, Use=OperationFormatUse.Encoded)] interface ISomeLegacyService { [OperationContract()] string SomeOp1( string name); } [ServiceContract()] [DataContractFormat(Style=OperationFormatStyle.Rpc)] interface ISomeRpcService2 { [OperationContract()] string SomeOp2( string name);
} o
Caractersticas: El atributo por defecto es Document, Rpc est anticuado. DataContractSerializer es el serializador por defecto, aunque hay algunos esquemas complejos XML o XSD que es mejor serializar con XmlSerializer
Manejo de excepciones en el Servicio: o Un DataContract en un .cs para cada tipo de excepcin en Entities o En la interfaz del Servicio, para cada OperationContract declaramos un [FaultContract(typeof( .cs))] o En el Servicio lanzamos las excepciones (throw new ) Manejo de excepciones en Cliente o Capturamos las excepciones con bloques Using, Try, Catch
wsHttpBinding
wsDualHttpBinding webHttpBinding
wsFederationHttpBinding This secure and interoperable binding supports federated security. It supports HTTP and HTTPS transport protocols as well as text and MTOM encoding methods. netTcpBinding This secure binding is used to send binary-encoded SOAP messages from one WCF computer to another. It uses Transmission Control Protocol (TCP) and includes support for reliability, transactions, and security. This secure binding should be used on a single WCF computer. Binary-encoded SOAP messages are sent over named pipes. This queued binding is used to send binary-encoded SOAP messages over MSMQ. Communication should occur between two computers. This secure binding is used for peer-to-peer communication Communication should occur between two or more computers. over TCP.
msmqIntegrationBinding This interoperable binding can be used for existing MSMQ applications that use COM and native C++ application programming interfaces (APIs). basicHttpContextBinding This binding provides support for HTTP cookies and enables SOAP headers to exchange context. netTcpContextBinding wsHttpContextBinding This secure binding enables SOAP headers to be used in the exchange of content. This secure and interoperable binding enables SOAP headers to exchange context while also supporting reliability, transactions, and security.
o Si hay varios Endpoints, el Address debe ser diferente. Si tienen diferentes Contracts si pueden tener el mismo Address
USANDO BASE ADDRESS
<configuration> <system.serviceModel> <services> <service name="OrderService"> <host> <baseAddresses> <add baseAddress="http://localhost:8000/OrderService/"/> <add baseAddress="net.tcp://localhost:8001/OrderService/"/> </baseAddresses> </host> <endpoint address="" contract="MyNamespace.IOrderService" binding="BasicHttpBinding"> </endpoint> <endpoint address="secure" contract="MyNamespace.IOrderService" binding="wsHttpBinding"> </endpoint> <endpoint address="" contract="MyNamespace.IOrderService" binding="NetTcpBinding"> </endpoint> </service> </services> </system.serviceModel> </configuration>
Uri httpAddress = new Uri("http://localhost:8000/OrderService/"); Uri tcpAddress = new Uri("net.tcp://localhost:8001/OrderService/"); Uri[] baseAddresses = {httpAddress, tcpAddress}; ServiceHost host = new ServiceHost(typeof(MyNamespace.OrderService),baseAddresses); BasicHttpBinding basicBinding = new BasicHttpBinding(); WSHttpBinding wsBinding = new WSHttpBinding(); NetTcpBinding netBinding = new NetTcpBinding(); host.AddServiceEndpoint( typeof(MyNamespace.IOrderService), basicBinding, ""); host.AddServiceEndpoint( typeof(MyNamespace.IOrderService), wsBinding, "secure"); host.AddServiceEndpoint( typeof(MyNamespace.IOrderService), netBinding,
"");
PUBLICAR METADATAS A TRAVS DE LOS ENDPOINT y y Se publica y se accede a Metadata usando Http-Get (por eso hay que habilitar a true su nodo) Creamos un endpoint especial:
<configuration> <system.serviceModel> <services> <service name="OrderService" behaviorConfiguration="MexGet"> <endpoint address="http://localhost:8000/OrderService/" contract="MyNamespace.IOrderService" binding="BasicHttpBinding"> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors>
<serviceBehaviors> <behavior name="MexGet"> <serviceMetadata httpGetEnabled ="True" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
</configuration>
Existen muchas propiedades a cambiar y cada binding posee las suyas por defecto Parmetros personalizables
Description Default Value Boolean value that determines whether the client accepts False and propagates cookies. Boolean value that determines whether to bypass the proxy False server for local addresses. TimeSpan value that indicates how much time should pass 1 minute while closing a connection before an exception is thrown.
HostNameComparisonMode Determines whether the hostname is used to reach the StrongWildcard service when matching the URI. MaxBufferPoolSize MaxRecievedMessageSize MessageEncodng Name Namespace OpenTimeout ProxyAddress ReaderQuotas Long value that determines maximum amount of memory 65,536 bytes allocated for the buffer manager. Long value that determines maximum size for a message. 65,536 bytes
Determines whether MTOM or Text/XML is used to encode Text messages. Name of the binding. Can be helpful if you use multiple Null reference versions of a certain binding. Determines the XML namespace for the binding. http://tempuri.org/
TimeSpan value that indicates how much time should pass 1 minute while opening a connection before an exception is thrown. Determines the URI address of the HTTP proxy. Property is Null reference ignored if UseDefaultWebProxy is true. Determines the constraints applied to string content within None a message. For example, can be used to specify a maximum length for string content. TimeSpan value that determines how long a connection can 10 minutes remain inactive before an exception is thrown. TimeSpan value that determines how long a write operation 1 minute can take before an exception is thrown. Determines the encoding used for message text. UTF8Encoding
Boolean value that determines whether the binding should false support flowing WS-Transactions. Boolean value that determines whether the autoconfigured True HTTP proxy should be used.
<system.serviceModel> <services> <service name="OrderService"> <endpoint address="" contract="MyNamespace.IOrderService" binding="WsHttpBinding" bindingConfiguration="CloseTimeout"> </endpoint> </service> </services> <bindings> <wsHttpBinding> <binding name="CloseTimeout" closeTimeout="00:03:00"> </binding> </wsHttpBinding> </bindings> </system.serviceModel>
Tambin se puede crear un Binding desde cero, pero es mejor personalizar uno creado.
CREAR UN SERVICIO HOST FACTORY y Se utiliza para crear instancias de Servicios Host de forma dinmica conforme llegan las peticiones
}
HOSPEDAR USANDO UN WINDOWS SERVICE y Los Windows Service son tiles cuando se trata de WCF de larga duracin que no requieren un interfaz de usuario y PASOS: o Usar la plantilla de VisualStudio WindowsService o Declarar la variable ServiceHost public ServiceHost serviceHost = null;
Para situar el servicio en una ConsoleWindows, configura la propiedad ServiceName. Tambin hay que declarar un punto de entrada para la aplicacin que hospeda.
public OrderWindowsService() { ServiceName = "Order Service Windows Service"; } public static void Main() { ServiceBase.Run(new OrderWindowsService());
} Aadir cdigo al mtodo OnStart para crear una instancia del ServiceHost y al OnClose para cerrarlo
protected override void OnStart(string[] args) { if (serviceHost != null) { serviceHost.Close(); } serviceHost = new ServiceHost(typeof(OrderService)); serviceHost.Open();
}
protected override void OnStop() { if (serviceHost != null) { serviceHost.Close(); serviceHost = null; }
Configurar el AppConfig (baseAddress y los endpoints). Una vez compilado podemos crear un servicio ejecutable. Usando la lnea de cdigo en el prompt de VS puedes instalarlo installutil C:\MyProjects\bin\OrderWindowsService.exe Una vez instalado puedes accede a travs del Service Control Manager escribiendo en el prompt services.msc
HOSPEDAR USANDO WCF-PROVIDED HOST Para hospedar servicios de forma rpida y fcil para principiantes
WcfSvcHost.exe /service:C:\MyProject\bin\SimpleService.dll /config:C:\MyProject\App.Config
Merges the generated configuration file into an existing file instead of overwriting the existing file. Indicates the programming language in which to generate code. Possible language names are c#, cs, csharp, vb, visualbasic, c++, and cpp. Default: csharp (short form: /l). Maps a WSDL or XML schema target namespace to a .NET namespace. Using an asterisk (*) for the target namespace maps all target namespaces without an explicit mapping to the matching .NET namespace. Default: derived from the target namespace of the schema document for Data contracts. The default namespace is used for all other generated types (short form: /n). Generates Message contract types (short form: /mc). Generates both synchronous and asynchronous method signatures. Default: generates only synchronous method signatures (short form: /a). Generates data types that use the XmlSerializer for serialization and deserialization.
/namespace:<targetNamespace, .NETNamespace>
/messageContract /async
/serializer:XmlSerializer
Un ejemplo:
svcutil /async /config:app.config /mergeConfig /namespace:*,SvcUtilProxy /out:ServiceUtilProxy.cs http://localhost:8080/orders/
Desde VS creamos un WPF Application . Aadir una Service Reference con el botn derecho en el Solution Explorer y configurarla para crear una clase Proxy (Address, Namespace, Generate Asynchronous, ObservableCollection, etc ). y Crear una clase Proxy manualmente: Suponiendo el siguiente ServiceContract
[ServiceContract()] public interface IOrderEntryService { [OperationContract()] OrderAcknowledgement SumbitOrder(Order order);
// Etc...
USAR PROXIES PARA LLAMAR A SERVICIOS Es tan fcil como llamar a un mtodo del objeto Proxy. Suponiendo el siguiente servicio:
[DataContract()] public class Order { [DataMemberAttribute()] public string Product; [DataMemberAttribute()] public int Quantity; // Etc... } [DataContract()] public class OrderAcknowledgement { [DataMemberAttribute()] public string TrackingNumber; // Etc... } [ServiceContract()] public interface IOrderEntryService { [OperationContract()] OrderAcknowledgement SumbitOrder(Order order); // Etc... } public class OrderEntryService : IOrderEntryService { public OrderAcknowledgement SumbitOrder(Order order) { OrderAcknowledgement ack = new OrderAcknowledgement(); ack.TrackingNumber = "alpha-bravo-123"; return ack; } // Etc... }
Podemos llamar al Proxy en varios pasos: 1) Usar la clase ChannelFactory para crear un Proxy dinmicamente
Binding binding = new NetTcpBinding(); ChannelFactory<IOrderEntryService> factory; factory = new ChannelFactory<IOrderEntryService>( binding, "net.tcp://localhost:6789/orders/"); IOrderEntryService proxy = factory.CreateChannel(); Order order = new Order(); order.Product = "Widget-ABC"; order.Quantity = 10;
// Etc... OrderAcknowledgement ack = proxy.SumbitOrder(order); Console.WriteLine( "Order submitted; tracking number: {0}", ack.TrackingNumber);
Order order =
4) Si has utilizado SVCUTIL o VS para generar la clase Proxy, debes usar la clase generada as:
OrderEntryServiceClient proxy = new OrderEntryServiceClient(); Order order = new Order(); order.Product = "Widget-ABC";
order.Quantity = 10; // Etc... OrderAcknowledgement ack = proxy.SumbitOrder(order); Console.WriteLine("Order submitted; tracking number: {0}", ack.TrackingNumber); y
Invocar operaciones del Servicio Asncronamente: En muchas ocasiones, una llamada a un mtodo en un Proxy, el cual es transformado en un mensaje puede tardar demasiado tiempo. Una buena solucin es llamar al mtodo asncronamente. Podemos usar la opcin /async del SVCUTIL. Despus en Add Service Reference->Advanced seleccionamos Generate Asynchronous Methods. Suponemos que se ha generado un proxy para OrderEntryService con mtodos asincrnicos. Adems de la operacin SubmitOrder en la clase de proxy, existen los mtodos BeginSubmitOrder y EndSubmitOrder. Estos mtodos pueden ser usado tal que as:
OrderEntryServiceClient proxy = new OrderEntryServiceClient(); Order order = new Order(); order.Product = "Widget-ABC"; order.Quantity = 10; // Etc... AsyncCallback cb = new AsyncCallback(HandleCallback); proxy.BeginSumbitOrder(order, cb, proxy); Console.WriteLine( "Order submitted asynchronously; waiting for callback");
El Mtodo HandleCallback (definido abajo) es llamado cuando la invocacin del mtodo asncrono ha sido completada.
static void HandleCallback(IAsyncResult result) { OrderEntryServiceClient proxy = result.AsyncState as OrderEntryServiceClient; OrderAcknowledgement ack = proxy.EndSumbitOrder(result); Console.WriteLine( "Order submitted; tracking number: {0}", ack.TrackingNumber); }
Cerrar el Proxy
using(MyServiceClient proxy = new MyServiceClient()) { proxy.SomeOp1(); }
proxy.SomeOp1(); }
Duplex Channels con Proxies Para habilitar un Proxy usando un Duplex Channel o un Callback Channel, debes seguir los siguiente pasos: o Define la clase que implemente el Callback contract o Crea una instancia de la clase y pasala al constructor InstanceContext o Pasa el objeto InstanceContext al constructor de la clase Proxy o La clase Proxy debe heredar de DuplexClientBase en vez de ClientBase Service Agents Es muy comn que desee ajustar el uso de un proxy en otra clase que tiene algunas capacidades adicionales para interactuar con el servicio remoto. Lo que hace que estos objetos faciliten el acceso a un servicio remoto es un Service Agent.
y y
ADDRES: Evalua la direccin asociada al endpoint del servicio. Es un string que representa el URI del servicio porque el cliente no soporta base address ni relative address. BINDING:
Description Used to communicate with earlier (that is, pre-WCF) ASMX Web services. The same as basicHttpBinding except that context is provided to the requests through cookies. Uses MSMQ as part of the transportation channel for requests. It is expected that the service on the receiving end of the request will be a non-WCF application such as a COM+ service. Uses MSMQ as part of the channel for requests. This binding is used when both ends of the channel are WCF applications. Provides a reliable, secure channel that is optimized for same-machine, cross-process communication, using named pipes. Allows for multiparty communication, using peer networking over TCP. Provides a channel optimized for cross-machine message passing, using TCP as the underlying communications protocol. Uses the same TCP mechanism as netTcpBinding to transport messages, but context is provided through information added to the message, typically in the SOAP header. For use with endpoints that accept HTTP formatted requests (as opposed to SOAP-formatted messages). Defines a duplex channel to a service that uses SOAP formatted messages. Configures the requests for communications with a service that supports WSFederation. Uses HTTP for transport along with providing support for WS-Security and WS-Reliable Messaging. Uses the same channel as wsHttpBinding, but context is provided through cookies.
ws2007FederationHttpBinding Provides the same functionality as ws2007HttpBinding along with the support
Binding Name
ws2007HttpBinding
Defines a binding that provides support for the correct versions of security, reliable session, and transaction flow binding elements.
El Binding tambin se puede configurar con el atributo BindingConfiguration y CONTRACT: El nombre de la interfaz del servicio
DEFINIR ENDPOINT HEADERS Dan informacin adicional al endpoint. En este ejemplo se crean 2 endpoint con un tipo de respuesta diferente determinado en los headers (Expedite y Standard).
<system.serviceModel> <client> <endpoint address="http://localhost:8080/UpdateOrder" binding="wsHttpBinding" contract="IUpdateService" name="WSHttpBinding_UpdateOrder"> <headers> <Priority xmlns="http://tempuri.org/">Expedite</Priority> </headers> </endpoint> <endpoint address="http://localhost:8080/CancelOrder" binding="wsHttpBinding" contract="IUpdateService" name="WSHttpBinding_CancelOrder"> <headers> <Priority xmlns="http://tempuri.org/">Standard</Priority> </headers> </endpoint> </client> </system.serviceModel>
Si se configuran los headers en el cliente, en el servicio se deben configurar de igual manera. METADATA EN EL ENDPOINT DEL CLIENTE Definen como los metadatas del servicio van a ser procesados en el cliente.
Name Description policyImporters Defines the types that process the policy information provided by the services metadata. wsdlImporters Defines the types that process the policy information found in the Web Services Description Language (WSDL) associated with a service.
CONFIGURAR BEHAVIORS De igual manera se puede configurar los Behaviors con el atributo behaviorConfiguration:
ELEMENTO clientCredentials Muchos servicios requieren Autentificacin y Autorizacin. ClientCredentials permite que se haga esto.
<clientCredentials type="String" supportInteractive="<Boolean>" > <clientCertificate /> <httpDigest /> <issuedToken /> <peer /> <serviceCertificate /> <windows /> </clientCredentials>
Element clientCertificate Description Indicates the client certificate used to authenticate the client to the service. This element must be of type X509ClientCertificateElement. The attributes for this element are broken into two groups. The first group (storeLocation and storeName) specifies the store and location in which the X.509 certificate is found. The second group (findValue and X509FindType) identifies the certificate within the store to be used. Here is an example:
Element
Description
ELEMENTO callbackDebug Similar al ServiceDebug de los servicios. Contiene un atributo includeExceptionDetailsInFaults que si lo ponemos a True los detalles de cualquier excepcin en el callback son enviados al servicio. ELEMENTO callbackTimeouts Se utiliza cuando el cliente implementa un mtodo por el cual el servicio vuelve a llamar al cliente. Este elemento tiene un solo atributo transactionTimeout que indica como de larga tiene que ser la transaccin antes de que sea abortada. ELEMENTO clientVia Facilita el debug de mensajes enviados entre cliente y servidor. Funciona como un intermediario en la comunicacin para asegurar que el mensaje no ha sido tratado por un usuario malicioso. ELEMENTO dataContractSerializer Controla la serializacin. Soporta 2 atributos: MaxItemInObjectGraph y IgnoreExtensionDataObject ELEMENTO synchronousReceive Por defecto, WCF recibe una respuesta y la procesa Asncronamente. Con este elemento WCF crea un thread para cada respuesta y lo procesa. Hay un nmero limitado de Threads y esto puede causar un problema en la escabilidad. ELEMENTO transactedBatching Se puede aplicar a clientes que soporten mtodos de callback. Al igual que las transacciones se pueden propagar desde el cliente al servicio, tambin pueden propagarse de nuevo las operaciones del servicio al cliente. El elemento transactedBatching soporta un solo atributo, maxBatchSize. Es un valor entero que contiene el nmero mximo de solicitudes recibidas en una sola transaccin.
CONFIGURACIN IMPERATIVA A pesar de que configurar el cliente de una aplicacin de mensajera de WCF a travs de un archivo de configuracin es muy poderoso, no siempre es factible. Si tuviramos que cambiar algo en tiempo de ejecucin no podramos modificar el archivo de configuracin. CONSTRUIR UN ADDRESS
EndpointAddress endpoint = new EndpointAddress("http://localhost:8080/UpdateService"); UpdateServiceProxy proxy = new UpdateServiceProxy(new WSHttpBinding(), endpoint);
es:
UpdateServiceProxy proxy = new UpdateServiceProxy("WSHttpBinding_IUpdateService");
ADDRESS HEADERS WCF proporciona un mecanismo para dar cabida a sofisticados enrutamientos y dispaching. La idea es proporcionar informacin adicional con cada solicitud. Esta informacin puede ser utilizada por los dispositivos intermedios o por los endpoint para determinar routing o processing logic.
AddressHeader header = AddressHeader.CreateAddressHeader("premium", "http://tempuri.org/ServiceLevel", null);
CONSTRUIR UN BINDING
EndpointAddress endpoint = new EndpointAddress("http://localhost:8080/UpdateService"); WSHttpBinding binding = new WSHttpBinding(); UpdateServiceProxy proxy = new UpdateServiceProxy(binding, endpoint);
CONSTRUCTORES DE BINDING El primero y ms simple, el contructor toma un string con el nombre del Binding del archivo de configuracin.
<system.serviceModel> <bindings> <basicHttpBinding> <binding name="NameOfBinding" receiveTimeout="00:10:00" sendTimeout="00:10:00" openTimeout="00:10:00" closeTimeout="00:10:00" /> </basicHttpBinding> </bindings> </system.serviceModel>
TransportWithMessageCredential The transport layer determines the credentials to be included with the request. TransportCredentialOnly The message includes a set of credentials along with the message. The content is not secured, and it is up to the service to authenticate the requestor.
la direccin relativa:
ServiceHost host = new ServiceHost(typeof(UpdateService), new Uri[] { new Uri("net.tcp://localhost:8000") } ); host.AddServiceEndpoint(typeof(IUpdateService), new NetTcpBinding(), "UpdateService");
Listener URI Sera el cuarto parmetro en la llamada a AddServiceEndpoint. El Listener da un punto medio para el cliente cuando manda la peticin. El cliente puede aadir el atributo viaUri para indicar que endpoint es eventualmente usado para procesar la peticin.
ServiceHost host = new ServiceHost(typeof(UpdateService)); Uri commonUri = new Uri("net.tcp://localhost:8888/common"); NetTcpBinding binding = new NetTcpBinding(); host.AddServiceEndpoint(typeof(IUpdateService), binding, "/UpdateService1", commonUri); host.AddServiceEndpoint(typeof(IUpdateService), binding, "/UpdateService2", commonUri);
Para un servicio definido de esta manera, el cdigo de cliente para conectar sera:
EndpointAddress endpoint = new EndpointAddress("net.tcp://localhost:8000/UpdateService2"); NetTcpBinding binding = new NetTcpBinding(); Uri commonUri = new Uri("net.tcp://localhost:8888/common"); UpdateServiceProxy proxy = new UpdateServiceProxy(binding, endpoint); proxy.Endpoint.Behaviors.Add(newViaUriBehavior(commonUri));
CONSTRUIR UN BINDING y basicHttpBinding: Este binding tiene 4 modos de seguridad. El modo sin seguridad tiene 2 atributos TextMessageEncodingBindingElement y HttpTransportBindingElement. El primero de ellos codifica los mensajes a formato SOAP. Las propiedades de este atributo son:
Property Description MaxReadPoolSize Determines the number of readers allocated to the pool. These readers will be used to process incoming requests. MaxWritePoolSize Determines the number of writers allocated to the pool. These writers will be used to process outgoing requests. MessageVersion ReaderQuotas Contains the SOAP and WS-Addressing versions used to determine the details of the message encoding. Defines the constraints on the complexity of SOAP messages processed. The constraints include the maximum length, the longest string content, the number of bytes processed per read, the maximum depth of the message hierarchy, and the number of characters in the name table. The encoding used to format the characters in the text message.
WriteEncoding
El atributo HttpTransportBindingElement soporta la tranmisin del mensaje bajo el protocolo Tcp. Sus propiedades son:
Property AllowCookies AuthenticationScheme BypassProxyOnLocal HostNameComparisonMode Description A Boolean value that indicates whether cookies are accepted by the client and then presented to the service on subsequent requests. The authentication scheme used by the client to authenticate with the HTTP listener on the service. A Boolean value that indicates whether any configured proxy server should be bypassed if the address for the service is a local address. Indicates how the host name will be matched in the URI. The possible values include an exact match (which would preclude interchanging localhost and the machine name, for example) or a strong and weak wildcard match. A Boolean value indicating whether a persistent connection to the service should be established. The URI for the proxy that will be used as part of the transport chain. The scheme that will be used to authenticate the client with the proxy prior to sending the request. The realm used by basic and digest authentication to segregate different sets of protected resources. The mode by which the request will be transferred over the transport layer. The possible choices include buffered or streamed. With the streamed option, the response, the request, or both can be streamed.
UnsafeConnectionNtlmAuthentication This value indicates whether connection sharing is occurring on the server. If connection sharing is enabled, NTLM authentication will be performed once for each TCP connection. This is necessary because those connections could be shared, and the security context might be different for each connection. UseDefaultWebProxy A Boolean value that indicates whether the machine-wide proxy will be used instead of the custom one defined elsewhere in the binding element.
Con el modo de seguridad, el security mode se carga a Transport, HttpTransportBindingElement se cambia a HttpsTransportBindingElement, cuyas propiedades son:
Property Description
RequreClientCertificate A Boolean value that indicates whether SSL client authentication is required. Scheme Although this property actually comes from the TransportBindingElement class, the value of the property will be https for this class.
netTcpBinding: 3 elementos involucrados: La clase BinaryMessageEncodingBindingElement es responsable de convertir el mensaje en un formato binario para la transmission. TransactionFlowBindingElement cuya nica propiedad de inters es TransactionProtocol. (especifica el nmero de transacciones que fluyen del el cliente al servicio). Por ltimo TcpTransportBindingElement cuyas propiedades son:
Property
Description
ChannelInitializationTimout The time limit for a channel initialization request to be accepted. ConnectionBufferSize ConnectionPoolSettings ListenBacklog PortSharingEnabled TeredoEnabled The size of the buffer used to transmit the serialized message. The collection of settings used to control the connection pool. The maximum number of queued connection requests that can be pending. A Boolean value indicating whether the sharing of the TCP port is enabled for the connection. Teredo is a technology used to access clients who are behind a firewall. This Boolean value indicates whether the technology should be employed for this connection. The mode by which the request will be transferred over the transport layer. The possible choices include buffered or streamed. With the streamed option, the response, the request, or both can be streamed.
TransferMode
Property
ChannelInitializationTimeout The time limit for a channel initialization request to be accepted. ConnectionBufferSize ConnectionPoolSettings TransferMode The size of the buffer used to transmit the serialized message. The collection of settings used to control the connection pool. The mode by which the request will be transferred over the transport layer. The possible choices include buffered or streamed. With the streamed option, the response, the request, or both can be streamed.
ReceiveErrorHandling
or move the message to the poison-message queue. ReceiveRetryCount RetryCycleDelay TimeToLive Indicates the number of attempts made to send a message before it is moved into the retry queue. Value specifying the number of seconds to wait before attempting another retry cycle. A numeric value specifying how long a message will be allowed to exist in the various retry cycles before it is moved to the dead-letter queue.
TransactedReceiveEnabled Boolean value indicating whether the receive operation for a message should be part of a transaction. UseActiveDirectory UseMsmqTracing UseSourceJournal Boolean value indicating whether the queue address should be converted using Active Directory Domain Services (AD DS). Boolean value that enables or disables the tracing functions built into MSMQ. A Boolean flag that indicates whether copies of the message processed through the binding should be stored in the source journal queue.
Property
ListenIPAddress Specifies the IP address on which the peer node will listen for incoming requests Port Security Specifies the port number on which requests will be listened for The collection of settings used to control the security this binding uses
wsDualHttpBinding: Se implementan los elementos TransactionFlowBindingElement, TextMessageEncodingBindingElement, y HttpTransportBindingElement. Adems el elemento CompositeDuplexBindingElement habilitado cuando se produce un callback. Por ltimo ReliableSessionBindingElement que asegura el orden en los mensajes que llegan en un callback. Sus propiedades son:
Description
Property
AcknowledgementInterval Specifies the amount of time that the service will wait before sending an acknowledgement to the client EnableFlowControl InactivityTimeout MaxPendingChannels MaxRetryCount MaxTransferWindowSize Ordered A Boolean value that indicates whether flow control is enabled within the binding Determines how long the service will remain active when there is no processing of requests The largest number of messages that can be waiting before an exception is raised The maximum number of attempts to be made before an exception is raised The largest number of messages that can be buffered, either on the sending or receiving side Boolean value indicating whether the binding should ensure that messages are received in exactly the same order as the order in which they are sent
Resto de Bindings:
Binding Elements TextMessageEncodingBindingElement, HttpTransportBindingElement. Both of these are described in the basicHttpBinding Binding section. The main difference is that allowCookies is set to True.
Binding basicHttpContextBinding
msmqIntegrationBinding
BinaryMessageEncodingBindingElement, MsmqTransportBindingElement. These elements are described in the netMsmqBinding Binding section.
netTcpContextBinding
BinaryMessageEncodingBindingElement, TransactionFlowBindingElement, TcpTransportBindingElement. These elements are described in the netTcpBinding Binding section. TextMessageEncodingBindingElement, HttpTransportBindingElement. Both of these are described in the basicHttpBinding Binding section. The main difference in this binding is the formatting of the message.
webHttpBinding
wsFederationHttpBinding
TransactionFlowBindingElement, HttpTransportBindingElement.
TextMessageEncodingBindingElement,
These elements are described in the basicHttpBinding Binding section. wsHttpContextBinding TransactionFlowBindingElement, HttpTransportBindingElement. TextMessageEncodingBindingElement,
These elements are described in the basicHttpBinding Binding section. ws2007FederationhttpBinding TransactionFlowBindingElement, HttpTransportBindingElement. TextMessageEncodingBindingElement,
These elements are described in the basicHttpBinding Binding section. ws2007HttpBinding TransactionFlowBindingElement, HttpTransportBindingElement. TextMessageEncodingBindingElement,