Essential Web Services : Programando con .NET y WSE 2.0

Slides:



Advertisements
Presentaciones similares
Web Services Definición. Ventajas que ofrece.
Advertisements

Web Services.
APLICACIONES DISTRIBUIDAS
Java Web Services Developer Arquitectura
Servicios Web XML 03 de Junio de 2004 Fernando Alonso Blázquez.
.NET y Servicios Web David Carmona Development Advisor
WSE 2.0 (.NET Web Services Enhancements)
WS-Security, WSE 3.0, WCF(Indigo)
Diseño de Aplicaciones SOA usando Visual Studio Team System
Unidad 3 Lenguajes .Net y POO
Rossy Garita Componentes fundamentales de CLR y
ADELA TORRES JONATHAN BEJARANO
Crear y consumir Servicios Web XML
Introducción a ASP.NET.
ATS – Cliente .
J2EE – Java 2 Enterprise Edition
Alberto Pedroso García - Junio/2004 Victor Ricardo Díaz – Junio/2007 Web Services.
Common Object Request Broker Architecture
Lenguajes Servicios Web
Cátedra Pragma Orientación a Servicios Parte I 2 © PRAGMA S.A.
Servicios Web.
Arquitectura Orientada a Servicios (SOA)
Tipos de Servicios Web.
Conceptos de Infopath Microsoft InfoPath es una aplicación  usada para desarrollar formularios de entrada de datos basados en XML. Su primera publicación,
Curso de Java y Aplicaciones Web
IMPLEMENTACIÓN DE ARQUITECTURA EMPRESARIAL
Desarrollando y consumiendo Web Services con Visual FoxPro
Seguridad en ASP.NET Daniel Laco
Daniel A. Seara Director Regional MSDN NDSoft
Acceso a datos y paso de datos entre capas
César de la Torre – Programas Técnicos para Partners División de Desarrollo y Plataforma – Microsoft Spain.
Introducción a Remoting
Intercambio de información Procesamiento Sin intervención del usuario Acelerando tiempos de respuesta Normalización Entre plataformas Entre lenguajes.
RMI Remote Method Invocation
Java 2 Platform Enterprise Edition
Introducción XML y WebServices.
Características generales de un servicio Web.
Objetos Distribuidos – Aplicaciones RMI
Programación Web Servicio Web XML.
WSDL & UDDI Taller de Sistemas de Información 1
Sistemas Operativos Centralizados y Distribuidos Carlos David Zepeda.
Juan Andrada Romero Jose Domingo López López.  Introducción  Conceptos  Arquitectura JXTA  Protocolos  Demostración  Alternativas  Conclusiones.
Ruben Chonlong Alvarez. Que es InfoPath Microsoft Oficce Infopath 2010 ayuda a las personas a recopilar información de sus clientes y socios con herramientas.
Presentación Web Services Interoperability and SOAP Keith Ballinger Microsoft Corporation Alvaro Castromán Alfonso Odriozola.
Sincronización de Objectos Compartidos usando MatchMaker a través de Web Services Thomas Pieper DCC, Universidad de Chile.
Web Services Daniel Seara. Fundamentos Intercambio de información Procesamiento Sin intervención del usuario Acelerando tiempos de respuesta Normalización.
CONCEPTES AVANÇATS DE SISTEMES OPERATIUS Departament d’Arquitectura de Computadors (Seminaris de CASO) Autors Alberto Guirao Rico Jesús Barahona Esteve.
Servicios Web. Servicios web Son programas con funcionalidad accesible a través de protocolo http que permiten la ejecución remota de métodos y funciones.
ASP.NET es una nueva y potente tecnología para escribir páginas web dinámica. Es una importante evolución respecto a las antiguas páginas ASP de Microsoft.
Web Services (consumir servicios)
Contenido: 1- Que es el .Net Framework 2- Arquitectura en .Net
/ Teléfono : Web : Build Solutions IT.
Introducción a los Servicios Web con Java M.C. Juan Carlos Olivares Rojas Julio 2011.
J2EE – Java 2 Enterprise Edition
Arquitectura Orientada a Servicios Alicia Maita Harold Martínez Esteban Reyes Verónica Betancout - SOA -
Haga clic para modificar el estilo de subtítulo del patrón 28/04/09 Por ARLEDY SARRIA MOLINA NAZLY DIAZ ARIZA JHOANNA MARQUELLA DESARROLLO DE SOFTWARE.
Universidad Nacional de San Juan Facultad de Ciencias Exactas, Físicas y Naturales “WEB SERVICES” Integrantes: Ene Adriana Guevara Vanina Martínez Cintia.
Arquitectura para crear Soluciones Conectadas Eduardo Mangarelli Gerente de Socios Estratégicos Wilson Pais Gerente de.NET Microsoft Uruguay.
1 Web Services. 2 Definición de XML Web Services Los servicios XML Web Services son los elementos fundamentales en la evolución hacia la computación distribuida.
Desarrollo de aplicaciones empresariales con Web Services
Desarrollo de aplicaciones empresariales con Web Services
Borland User Group - Guatemala Introducción a WebServices y ejemplos de interoperabilidad entre Win32,.Net y Java Axel Canteo – Banco de Comercio Juan.
Clase 5 Curso Microsoft.NETCurso Microsoft.NET I.S.F.T. N° 182I.S.F.T. N° 182.
Introducción a los Webservices. Contenidos Definición Definición Protocolos que hacen posible la existencia de los Webservices Protocolos que hacen posible.
Servicios Web y Arquitectura 4+1 Vistas
Introducción a .NET Nombre : Ethel García-Simón Matachana
Servicios Web Conjunto de aplicaciones o de tecnologías con capacidad para interoperar en la Web. Estas aplicaciones o tecnologías intercambian datos entre.
Patrón de diseño BROKER
Servicios Web-SOA Aula: Fomento 05/06/2006 a 08/05/2006.
.NET Remoting. 2 Índice Introducción Introducción ¿Qué es.NET Remoting? ¿Qué es.NET Remoting? ¿Por qué utilizar.NET Remoting? ¿Por qué utilizar.NET Remoting?
Transcripción de la presentación:

Essential Web Services : Programando con .NET y WSE 2.0 Eduardo Mangarelli Gabriel Cor gabriel@paradigma.com.uy TechEd 2002

Agenda Arquitecturas Orientadas a Servicios ASMX WebMethods WSE 2.0 Básico Características principales de WSE 2.0 API de Mensajería de WSE 2.0 TechEd 2002

Como era antes Machine A IDL Machine B NDR RPC (TCP) 3 Machine A IDL Machine B RPC 2 request NDR IDL proxy IDL stub response RPC (TCP) Registry Registry 1 4 discovers machine B 1 2 Communications protocol Message format Description language 3 Discovery mechanism 4 TechEd 2002

Sin estándares ni interop Tecnologías de objetos diferían en muchas maneras Interoperabilidad muy compleja Encierra a los clientes en la misma tecnología DCOM CORBA Java RMI RPC Protocol RPC IIOP IIOP or JRMP Message Format NDR CDR Java Ser. Format Description IDL OMG IDL Java Discovery Windows Registry Naming Service RMI Registry or JNDI TechEd 2002

Hacia adelante Los desarrolladores están cansados de estar atados a una tecnología La clave es diseñar una arquitectura que no tenga pre-supuestos acerca de … Plataforma Lenguaje Objetos RPC Service Oriented Architecture (SOA) TechEd 2002

El nuevo mundo de SOA SOA requiere una visión diferente del mundo Servicios autónomos Fronteras explícitas, asumir heterogeneidad Integración basada en formatos de mensaje XML (compartir esquemas, no clases) Compatibilidad basada en políticas TechEd 2002

Web Services Las tecnologías de invocaciónremota (Web services/remoting) son los bloques de construcción de SOA Los Webservices representan una revolución basada en XML de tecnologías distribuidas Diseñados alrededor de la interoperatbilidad Protocolos de comunicación estándar Formatos de representación de datos estándar Lenguajes de descripción estándar Mecanismos de descubrimiento estándar TechEd 2002

Definición de Web Services Una aplicación o servicio que… Se comunica por protocolos abiertos de Internet Procesa los mensajes XML empaquetados en SOAP Describe los mensajes usando un esquema XML Provee una descripción de su interfaz con WSDL Puede ser descubierto via UDDI TechEd 2002

Perfil básico de Web Services (WS-I) UDDI Portable type system Mensajes serializados Empaquetado Descripción de Endpoint Registro de endpoints WSDL XSD SOAP XML 1.0 + Namespaces Wire protocols Detalles en ws-i.org Description languages Discovery mechanisms TechEd 2002

A la manera de WebServices Machine A Machine B Web Service Invoke 2 request XML WSDL proxy WSDL stub response HTTP + SOAP 1 3 4 WSDL UDDI Server WSDL 1 2 Communications protocol Message format Description language 3 Discovery mechanism 4 WSDL WSDL TechEd 2002

A la manera WebServices 2 XML delayed notification SMTP + SOAP 1 Machine A Machine B Web Service Send XML Message one-way request 2 XML TCP + SOAP 1 3 WSDL 4 UDDI Server 1 2 Communications protocols Message format Description language 3 Discovery mechanism 4 WSDL WSDL WSDL TechEd 2002

Es el perfil básico suficiente? El perfil básico (XSD, SOAP, WSDL, UDDI) permite una comunicación básica Intercambios XML Simples Entre fronteras heterogéneas y servicios autónomos Compartiendo esquemas que permiten abstracciones útiles La mayoría de las aplicaciones distribuidas necesitan más… TechEd 2002

Temas Necesarios Los Web Services tienen muchas necesidades en común Modelo de seguridad orientado a mensaje Mensajería confiable Soporte a transacciones Mecanismos de direccionamiento/ruteo Mensajería asincrónica Metadata para políticas/capacidades Soporte a datos binarios TechEd 2002

Framework SOAP SOAP provee el framework para atacar estos temas Distinción entre Header/Body permite extensiones <soap:Envelope xmlns:soap="..."> <soap:Header> </soap:Header> <soap:Body> </soap:Body> </soap:Envelope> <!-- standardized, pluggable headers --> <!-- payload --> TechEd 2002

Extendiendo SOAP SOAP por si mismo no define headers Con Well-known headers las aplicaciones pueden negociar WS-* extiende SOAP con headers estándar Ahora se necesitan implementaciones TechEd 2002

Stack de protocolos WS-* k Microsoft está trabajando de cerca con partners para desarrollar un protocolo completo de WS-* Ataca la mayoría de los temas vistos Construido sobre SOAP de una manera neutra al transporte Para ofrecer mensajes seguros, confiables y transaccionales TechEd 2002

Stack WS-* Applications & Application Infrastructure Connected Applications Business Process … Management Security Reliability Transactions Metadata Foundation MS has worked closely with numerous partners including IBM, SAP, BEA, Verisign, RSA, and Tibco to deliver a complete protocol stack for secure reliable and transacted Web services. We have listened to our customers and have delivered the core set of protocols necessary for building Service Oriented Architectures.  The strategy is to work w/ platform vendor's and subject matter experts to publish specifications that address the needs of each bucket accelerate broad adoption of these specifications and deliver a robust implementation of them. For example, in April 2002 we delivered a joint Security white paper with IBM and published the WS-Security specification w/ IBM and Verisign.  To accelerate the broad adoption, after refining the specification, we submitted it to a technical committee @ OASIS w/ IBM, Verisign and 9 other vendors including Sun and Oracle and other security players, Entrust and RSA.  In early Dec we released the first fully supported implementation of WS-Security in the Web Services Enhancement for Microsoft Visual Studio .NET v 1.0 (WSE).  IBM, RSA, Verisign, TME and others all have production code supporting WS-Security.  You can read about interoperability between different companies providing WS-Security implementations on the Microsoft Web services developer center.   We plan on following a similar strategy w/ other specifications…  Publish w/ subject matter experts and platform vendors, refine specifications with partners based on community feedback, accelerate broad industry adoption, and provide implementation. Transport Box (HTTP, TCP, UDP, SMTP, FTP, etc.) Web services need to be transport independent so that customers can choose what’s best for them. Web services enable the development of Service Oriented Architectures for use within and beyond the enterprise. XML Box Built on XML, SOAP and WSDL Has an extensible protocol framework, which has been used to create the additional capabilities in the Foundation. Has become lingua franca for interoperability across systems and trust boundaries XML, SOAP, and WSDL is supported in shipping products from Microsoft, IBM, Iona, BEA, Sun, Oracle, etc… Foundation Provides secure, reliable and transactional capabilities Wide support among vendors and customers Is complete Connected Apps Once the foundation is in place, people will begin building connected applications. Underlying some of these connected application, there will be a need for advanced business process management and management capabilities Reference Materials to better understand the architecture The WS-Security Roadmap protocols—In April 2002, IBM and Microsoft published a roadmap for Web service security [WS-Security Roadmap] that supports, integrates and unifies several popular security models, mechanisms, and technologies. http://msdn.microsoft.com/webservices/understanding/gxa/default.aspx?pull=/library/en-us/dnwssecur/html/securitywhitepaper.asp Reliable Message Delivery in a Web Services World: A Proposed Architecture and Roadmap http://msdn.microsoft.com/webservices/understanding/gxa/default.aspx?pull=/library/en-us/dnglobspec/html/ws-rm-exec-summary.asp Infoset White Paper: This paper describes the importance of the XML infoset model. http://msdn.microsoft.com/webservices/understanding/default.aspx?pull=/library/en-us/dnxml/html/xmlinfoset.asp List of Specifications for Each Bucket XML Foundation XML - Extensible Markup Language is a subset of SGML. XML Schema - XML Schemas express shared vocabularies and allow machines to carry out rules made by people. They provide a means for defining the structure, content and semantics of XML documents. Description & Discovery UDDI - The UDDI (Universal Description, Discovery and Integration) contains standards-based specifications for service description and discovery. WSDL - Description of Web Services as individual messages. The operations and messages are described abstractly, and then bound to a concrete network protocol and message format to define an endpoint. WS-Policy - Extensions to SOAP that describe a mechanism for requesting and communicating acceptable and required formats, elements, and message characteristics. WS-PolicyAssertions - This document specifies a set of common message policy assertions that can be specified within a policy. WS-PolicyAttachment - This document specifies three specific attachment mechanisms for using policy expressions with existing XML Web service technologies. Futures as published in the Reliable Message Delivery in a Web Services World: A Proposed Architecture and Roadmap WS-MetadataExchange the Represents a generalization of the PolicyExchange mechanisms to provide a web services based mechanism to also aquire WSDL, Schema, and other metadata. This replaces WS-PolicyExchange. Messaging SOAP 1.1 - Previous base standard for sending messages over various transports, including HTTP. SOAP 1.2 - Base standard for sending messages over various transports, including HTTP. Latest working group status. WS-Inspection - Site inspection of services. Merge of DISCO and IBM approaches. UPNP Version 2 Discovery Protocol - We propose defining UPNP v2 discovery as a Web Service protocol that is simple and well integrated into the rest of UPNP v2 architecture. WS-Addressing - WS-Addressing provides transport-neutral mechanisms to address Web services and messages. Replaces WS-Routing and subsumes half of the WS-Messaging spec. Security WS-Security Roadmap - Overview of Web Services Security. WS-Security Security - Protocol for secure communication with SOAP. WS-Security Appnotes - This paper is provided as guidance to implementers of the WS-Security [WSSEC] specification. WS-Security Addendum - This document describes clarifications, enhancements, best practices, and errata of the WS-Security specification. WS-Security Profile for XML-based Tokens - This document describes a general framework to enable XML-based security tokens to be used with WS-Security. Two profiles that use this general framework are provided: one for the Security Assertion Markup Language (SAML) and other for the the eXtensible rights Markup Language (XrML). WS-Trust - This specification defines extensions that build on WS-Security to request and issue security tokens and to manage trust relationships. WS-SecurityPolicy - This document is an addendum to WS-Security and indicates the policy assertions for WS-Policy which apply to WS-Security. WS-SecureConversation - This specification defines extensions that build on WS-Security to provide secure communication. Specifically, we define mechanisms for establishing and sharing security contexts, and deriving session keys from security contexts. Futures as published in the Security in a Web Services World: A Proposed Architecture and Roadmap, IBM and MS WS-Federation - This specification defines mechanisms that are used to enable identity, authentication, and authorization federation across different trust domains including access from Web browsers. WS-Privacy - Defines extensions that build on WS-Policy to declare privacy policies and privacy preferences/requirements; does not define a privacy policy; defines a framework that works with any privacy policy language. WS-Authorization - The WS-Authorization specification defines a format for describing authorization data that integrates with WS-Security and other security extensions. Reliable Messaging WS-ReliableMessaging - A messaging protocol for sending SOAP messages reliably in a bi-directional communication between endpoints. WS-ReliableMessaging Executive Summary - This roadmap provides an overview and top level specification details for Reliable Messaging. WS-TransmissionControl—A set of constructs for controlling the exchange of messages between services to improve reliability by preventing message loss due to service unavailability, overloading queues and other causes. WS-EndpointResolution—A set of Web service mechanisms that support selecting a specific endpoint for an operation or message from a set of allowed candidates. This is particularly useful in server farms and mobile environments. Transactions WS-Transaction - This specification describes coordination types that are used with the extensible coordination framework described in the WS-Coordination specification. WS-Coordination - This specification (WS-Coordination) describes an extensible framework for providing protocols that coordinate the actions of distributed applications. Business Processes BPEL4WS - A language for workflow management that can exploit the foundation laid by WS-Coordination and WS-Transaction. Messaging XML … HTTP TCP SMTP Transports TechEd 2002

WS-* Specifications (Resumen) Messaging WS-Addressing WS-Eventing MTOM (Attachments) Reliability WS-ReliableMessaging Security WS-Security WS-Trust WS-SecureConversation WS-Federation Transactions WS-Coordination WS-AtomicTransaction WS-BusinessActivity Metadata WS-Policy WS-PolicyAssertions WS-PolicyAttachment WS-SecurityPolicy WS-Discovery WS-MetadataExchange Ver Especificación en MSDN http://msdn.microsoft.com/webservices/understanding/specs/default.aspx TechEd 2002

Plataforma .NET de Web Services ASMX es la plataforma actual de WS Soporta el perfil básico de servicios simples No implementa WS-* WSE 2.0 es una extensión Puede usarse para extender el comportamiento de ASMX Puede usarse sin ASMX Provee soporte a varias especificaciones WS-* Indigo es la próxima generación de WS Va a proveer una solución completa WS-* TechEd 2002

Resumen hasta ahora Un Web Sevice es accesible por protocolos estándar XML es un formato de representación de datos SOAP es un framework XML para mensajería Los esquemas XML describen mensajes XML WSDL describe como invocar Web services UDDI es un repositorio de descripción de servicios WS-* extiende SOAP con headers estándar TechEd 2002

ASMX WebMethods TechEd 2002

WebMethods WebMethods mapea métodos a mensajes SOAP Los métodos se calfiican con el atributo [WebMethod] Se encuentra en el namespace System.Web.Services Construido sobre HTTP y un stack XML Ofrece alta producctividad (solo hay que escribir los métodos) <WebMethod()> _ Public Function Add(ByVal n1 As Integer, ByVal n2 As Integer) As Integer Return n1 + n2 End Function TechEd 2002

Web Service Namespace Especifica el namespace XML en la clase Usa el atributo [WebService] [WebService(Namespace=“http://www.paradigma.com.uy/MathService”) public class MathService { [WebMethod] public int Add(int n1, int n2) return n1 + n2; } TechEd 2002

Infraestructura del WebMethod ASP.NET provee la infraestructura para procesar WebMethods La clase del WebMethod está “ligada” a un punto de entrada .asmx El manejador procesa los mensajes de entrada SOAP TechEd 2002

Un punto de entrdada .asmx math.asmx <%@ WebService class="MathService"%> math.cs using System.Web.Services; public class MathService { [WebMethod] public int Add(int n1, int n2) return n1 + n2; } TechEd 2002

Instalando un WebMethod Una vez implementada, la clase debe ser instalada El assembly de pone en el bin del directorio virtual o en el GAC El archivo .asmx se pone en el directorio virtual \inetpub \wwwroot \math math.asmx \bin math.dll Directorio virtual Subdirectorio bin TechEd 2002

.asmx y compilación JIT El archivo .asmx puede contener código del WebMethod Se compila JIT en la primera invocación <%@WebService language="C#" class="MathService"%> using System.Web.Services; public class MathService { [WebMethod] public int Add(int n1, int n2) return n1 + n2; } TechEd 2002

Funcionalidad WebMethod El manejador .asmx del WebMethod provee cuatro áreas de funcionalidad Enviar los mensajes SOAP a los métodos CLR Serialización/deserialización de objetos Generación automática de documentación/WSDL Modelo de extensibilidad TechEd 2002

Method Dispatching POST /math/math.asmx HTTP/1.1 SOAPAction: "urn:math:Mul" <s:Envelope...> <s:Body> <x:Mul>... </s:Body> </s:Envelope> <%@ WebService language="C#" class="MathService" %> using System.Web.Services; public class MathService { [WebMethod] public int Add(int n1, int n2) { return n1 + n2; } public int Sub(int n1, int n2) { return n1 - n2; public int Mul(int n1, int n2) { return n1 * n2; ... .asmx handler IIS TechEd 2002

Serialización de objetos basada en XML Los WebMethods mapean entre XML y los objetos Construido sobre el XmlSerializer Asegura que los objetos mapeen a XML y los tipos a XSD Garantiza la interoperabilidad con otras plataformas No maneja las complejidades de los modelos de objetos modernos… TechEd 2002

Deserialización WebMethod <s:Envelope...> <s:Body> <x:Mul...> <n1>33.3</n1> <n2>66.6</n2> </x:Mul> </s:Body> </s:Envelope> <%@ WebService language="C#" class="MathService" %> using System.Web.Services; public class MathService { [WebMethod] public int Add(int n1, int n2) { return n1 + n2; } public int Sub(int n1, int n2) { return n1 - n2; public int Mul(int n1, int n2) { return n1 * n2; ... .asmx handler Deserialize n1 n2 System.Integer TechEd 2002

Usando tipos complejos Los WebMethods pueden manejar la mayoría de los objetos Los objetos pueden ser usados como entrada/salida Los objetos mapean a objetos complejos XSD public class Point { public double x; public double y; } public class Geometry { [WebMethod] public double Distance(Point orig, Point dest) { // implementation omitted TechEd 2002

Ejemplo de tipo complejo request <soap:Envelope xmlns:soap="..."> <soap:Body> <Distance xmlns="urn:geometry"> <orig> <x>0</x> <y>0</y> </orig> <dest> <x>3</x> <y>4</y> </dest> </Distance> </soap:Body> </soap:Envelope> response <soap:Envelope xmlns:soap="..."> <soap:Body> <DistanceResponse xmlns="urn:geometry"> <DistanceResult>5</DistanceResult> </DistanceResponse> </soap:Body> </soap:Envelope> TechEd 2002

Limitaciones No todos los tipos del CLR son serializables y pueden “romper” escenarios de interoperabilidad Grafos no jerárquicos Estructuras de datos genéricos (DataSet, Collection, etc.) Objetos polimórficos Si lo importante es la interoperabilidad, se debe simplificar TechEd 2002

WebMethods y Errores SOAP define como manejar errores Elemento de falla SOAP en el Body del mensaje Código de estado 500 (“Internal Server Error”) HTTP El manejador .asmx traduce las excepciones a fallas Todas las excepciones del CLR se capturan por la infraestructura Se puede lanzar un SoapException para controlar los detalles TechEd 2002

Generando documentación/WSDL El manejador .asmx genera la documentación Es retornada para los requests GET sin query string El manejador .asmx genera WSDL Se usa '?wsdl' en el query string (ej: math.asmx?wsdl) Los clientes pueden utilizar el WSDL para crear clases proxy TechEd 2002

WSDL y la generación de código <wsdl:definitions ...> ... </wsdl:definitions> wsdl.exe /server wsdl.exe ?wsdl public abstract class MathService : WebService { ... } public class MathService : SoapHttpClientProtocol { ... } .asmx csc.exe service.dll TechEd 2002

Modelo de extensibilidad WebMethods El manejador .asmx provee el modelo Permite pre/post procesamiento de mensajes SOAP Existen puntos de entrada disponibles antes/despues de la serialización/deserialización Conocido como el “SoapExtension framework” Machine B 1 deserialize stage Web Service SOAP Envelope 2 serialize stage TechEd 2002

Limitaciones WebMethod Los WebMethods solo soportan el perfil básico de WS-I No las especificaciones adicionales WS-* Provee puntos de extensibilidad Los WebMethods solo soportan HTTP TechEd 2002

Resumen hasta ahora ASP.NET provee un framework de WebServices WS-I completo El manejador WebMethod (.asmx) provee toda la maquinaria HTTP/XML Envía los mensajes SOAP al CLR Los parámetros son “marshaleados” con la clase XmlSerializer Generación automática de documentación/WSDL Modelo de extensibilidad TechEd 2002

Introducción a WSE 2.0 TechEd 2002

La plataforma de la próxima generación La plataforma de Web services debe evolucionar para cubrir las necesiades comunes (WS-*) Menajes seguros, confiables y transaccionales ¿Cómo extendemos ASMX para que lo haga? TechEd 2002

SoapExtension Framework ASMX provee un framework de extensiones Se puede escribir una clase que será llamada Antes y después de cada mensaje SOAP Antes y después de cada punto de entrada a un WebMethod TechEd 2002

Etapas SoapExtension Las extensiones se llaman en cada etapa ASMX Handler Web service class [WebMethod] public int add int x, int y) { return x+y; } <soap:Envelope … </soap:Envelope> XmlSerializer Extension called (1) Extension called (2) Extension called (3) Extension called (4) TechEd 2002

Clases SOAP Extension Una clase que derive de SoapExtension public class ValidationExtension : SoapExtension { public override object GetInitializer(Type serviceType) { // class-wide static initialization } public override object GetInitializer( LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute) { // method-wide static initialization public override void Initialize(object initializer) { // per-instance initialization public override void ProcessMessage(SoapMessage message) { // perform pre/post-processing just before/after // message deserialization/serialization TechEd 2002

Configurando una SOAP Extension Las clases de extensión pueden ser asociadas con cualquier WebMethod en una aplicación La clase se especifica en el web.config Se llama para cada WebMethod en una aplicació La clase puede ser asociada con un WebMethod específico El método se califica con un atributo personalizado que especifique la extensión La extensión se llama para ese WebMethod TechEd 2002

Configurando una SOAP Extension Para todos los WebMethod <configuration> <system.web> <webServices> <soapExtensionTypes> <add type="ValidationExtension, ValidationTools" priority="1" group="0" /> </soapExtensionTypes> </webServices> </system.web> </configuration> TechEd 2002

WSE 2.0 Microsoft creo los Web Services Enhancements (WSE) Está en la versión 2.0 Provee un SoapExtension para usar con WebMethods Provee un API de transporte de mensajes neutral que no depende de ASMX Implementa varias especificaciones WS-* TechEd 2002

Soporte WSE 2.0 a WS-* Messaging Reliability Security Transactions WS-Addressing WS-Eventing MTOM (Attachments) Reliability WS-ReliableMessaging Security WS-Security WS-Trust WS-SecureConversation WS-Federation Transactions WS-Coordination WS-AtomicTransaction WS-BusinessActivity Metadata WS-Policy WS-PolicyAssertions WS-PolicyAttachment WS-SecurityPolicy WS-Discovery WS-MetadataExchange Implementadas en WSE 2.0 TechEd 2002

WSE 1.0 y 2.0 WSE 2.0 puede ser instalada side-by-side con WSE 1.0 Usa un nombre de assembly diferente Usa un namespace diferente La misma token pública WSE 1.0 WSE 2.0 Assembly Microsoft.Web.Services Microsoft.Web.Services2 Namespace Version 1.0.0.0 2.0.0.0 Public Key Token 31bf3856ad364e35 TechEd 2002

Comenzando a usar WSE 2.0 Para comenzar a usar WSE en un WebMethod Agregar una referencia a Microsoft.Web.Services2 Configurar el WebServicesExtension Agregar using/imports a los namespaces que se necesiten Extender el código del WebMethod apropiadamente // general extension classes using Microsoft.Web.Services2; // if you plan to use WS-Security using Microsoft.Web.Services2.Security; ... TechEd 2002

Configuración en web.config <!--This element adds WSE functionality --> <configuration> <system.web> <webServices> <soapExtensionTypes> <add type= "Microsoft.Web.Services2.WebServicesExtension, Microsoft.Web.Services2, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" priority="1" group="0" /> </soapExtensionTypes> </webServices> TechEd 2002

Usando SoapContext Dentro de un WebMethod, la información WSE está disponible via la clase SoapContext [WebService(Namespace="http://example.org/wse/")] public class Endpoint1 : WebService { [WebMethod] public string Echo() SoapContext reqCtx = RequestSoapContext.Current; SoapContext resCtx = ResponseSoapContext.Current; ... // use Soapcontext to interface with the WS-* // implementations } TechEd 2002

Usando WSE en el cliente Los clientes wsdl.exe puede utilizar WSE Cambiar la clase base a WebServicesClientProtocol // wsdl.exe generated proxy ... public class Endpoint1 : // manually change the base class Microsoft.Web.Services2.WebServicesClientProtocol { Endpoint1 e = new Endpoint1(); SoapContext reqCtx = e.RequestSoapContext; SoapContext resCtx = e.ResponseSoapContext; ... // use Soapcontext to interface with the WSA // implementations TechEd 2002

Configuración adicional de WSE Se configura WSE con una nueva sección config (microsoft.web.services2) Se debe registrar la sección antes de usarla <configuration> <configSections> <section name="microsoft.web.services2" type="Microsoft.Web.Services2.Configuration.Web ServicesConfiguration, Microsoft.Web.Services, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </configSections> ... TechEd 2002

microsoft.web.services La sección en el config se usa para configurar: Seguridad Política Ruteo Diagnósticos Filtros <configuration> <microsoft.web.services2> <security> ... <policy> ... <referral> ... <diagnostics> ... <filters> ... </microsoft.web.services2> </configuration> TechEd 2002

Integración con Visual Studio .NET WSE 2.0 provee integración con Visual Studio .NET Elegir edición “Developer” al isntalar Clic derecho en proyectoy seleccionar “WSE 2 Settings” La herramienta automatiza la configuración del config TechEd 2002

Herramienta WSE Settings Permite … Agregar la referencia al assembly WSE Configurar el SoapExtension Configurar el soporte a protocolo WS-* TechEd 2002

Integración Cliente con Visual Studio .NET Puede habilitarse WSE en proyectos cliente con la herramienta Cunado se agrega una “Web Reference”, genera dos clases proxy Una que usa WSE (ej: “MathServiceWse”) Y una que no lo usa (ej: "MathService") TechEd 2002

WSE 2.0 Tracing WSE ofrece tracing de mensajes built-in Registra todos los mensajes SOAP de entrada/salida Registra los match de políticas // enable tracing in app.config or web.config <configuration> <microsoft.web.services2> <diagnostics> <trace enabled="true" input="inputtrace.xml" output="outputtrace.xml"/> </diagnostics> </microsoft.web.services2> ... TechEd 2002

Características claves de WSE 2.0 TechEd 2002

Soporte a seguridad WSE 2.0 WSE 2.0 soporta WS-Security Autenticación (UsernameToken, X.509, Kerb) Integridad (XML signatures) Privacidad (XML encryption) WSE 2.0 soporta WS-Trust y WS-SecureConversation Usando tokens de seguridad de contexto Conversación segura “automática” WSE 2.0 soporta seguridad basada en roles IPrincipal, IsInRole, etc. TechEd 2002

Soporte a Policy WSE 2.0 WSE 2.0 soporta WS-Policy Una policy es un archivo de configuración que especifica los requerimientos para los mensajes También soporta WS-PolicyAssertion y WS-SecurityPolicy WSE 2.0 usa las policies de dos maneras Fuerza las políticas cuando se reciben los mensajes Puede aplicar políticas (para modificar el mensaje) cuando se envían WSE 2.0 soporta custom policy TechEd 2002

WSE 2.0 Addressing y Routing WSE 2.0 usa WS-Addressing para rutear y entregar mensajes WSE 2.0 provee un manejador de ruteo Soporta WS-Referral para instrucciones de ruteo Soporta ruteo basado en contenido WSE 2.0 provee opciones de ruteo seguro TechEd 2002

API de Mensajería WSE 2.0 TechEd 2002

API de Mensajería WSE ASMX está atado a HTTP, RPC, y métodos Hace pensar en “client/server” El API de mensajería de WSE 2.0 ofrece un modelo más flexible Basado en mensaje - (not necesariamente método) Independiente de transporte (in-proc, TCP, and HTTP) Permite mensajería asincrónica Patrones de intercambio de mensajes personalizados (MEPs) TechEd 2002

Senders y Receivers WSE permite pensar en términos de “senders” y “receivers” Algunos nodos envían mientras otros reciben mensajes Los roles son completamente intercambiables Expuestos via SoapSender y SoapReceiver Sender Receiver and Sender Receiver TechEd 2002

Transparencia de transporte WSE 2.0 permite enviar mensajes por diferentes transportes In-proc, TCP, and HTTP out-of-the-box Transportes personalizados SOAP intermediaries MSMQ initial sender ultimate receiver FTP SMTP HTTP TechEd 2002

SoapReceiver SoapReceiver encapsula el proceso de recibir un mensajes SOAP public class MathReceiver : SoapReceiver { protected override void Receive(SoapEnvelope e) // implement Receive here } ... Uri receiverUri = new EndpointReference( new Uri("soap.tcp://localhost/math")); MathReceiver math = new MathReceiver(); SoapReceivers.Add(receiverUri, math); TechEd 2002

SoapSender SoapSender encapsula el proceso de enviar un mensaje SOAP a una URI ... SoapEnvelope env = CreateAddMessage(); env.Context.Action = "urn:math:add"; SoapSender ss = new SoapSender(new EndpointReference( Uri("soap.tcp://localhost/math"))); ss.Send(env); TechEd 2002

SoapClient y SoapServer SoapClient y SoapServer ofrecen abstracciones de alto nivel Construidos sobre SoapSender y SoapReceiver Mensajes de request/response y de correlación automática public class MathService : SoapService { [SoapMethod("urn:math:add")] public SoapEnvelope Add(SoapEnvelope e) ... // implement Add here } ... TechEd 2002

WseWsdl2.exe WseWsdl2.exe genera código SoapClient de definiciones WSDL El código generado deriva de SoapClient Se puede usar esta clase para enviar mensajes SOAP a receptores SOAP via WSE 2.0 TechEd 2002

Resumen Microsoft's Web Services Enhancements (WSE) provee implementación WS-* para usar en .NET hoy WSE 2.0 extiende el framework de WebMethod WSE 2.0 provee integración con Visual Studio .NET TechEd 2002

Referencias MSDN WS Developer Center http://msdn.microsoft.com/webservices www.paradigma.com.uy/guunet TechEd 2002

© 2004 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. TechEd 2002