Se ha denunciado esta presentación.
Se está descargando tu SlideShare. ×

Develop ASP.Net Web Service

Cargando en…3

Eche un vistazo a continuación

1 de 104 Anuncio

Más Contenido Relacionado

Presentaciones para usted (20)

A los espectadores también les gustó (13)


Similares a Develop ASP.Net Web Service (20)

Más reciente (20)


Develop ASP.Net Web Service

  1. 1. Developing XML Web Service using MS ASP.NET 2008 It doesn't matter how fast technology moves as long as we are building our own technology 7/13/2016 Safaa Farouk-ITI 1
  2. 2. Course Outline • Day 1  Module 1: The Need for XML Web Services  Module 2: XML Web Service Architectures  Module 3: Implementing a Simple XML Web Service • Day2  Module 4: The Underlying Technologies of XML Web Services  Module 5: Consuming XML Web Services • Day3  Module 6: Deploying XML Web Services  Module 7: Securing XML Web Services  Module 8: Designing XML Web Services 7/13/2016 Safaa Farouk-ITI 2
  3. 3. Session Cautions • You can talk anytime. • You can go anywhere. • You can answer any kind of calls. • You can ask for whatever you want. Actually… You can do anything you want!!!
  4. 4. 7/13/2016 Safaa Farouk-ITI 4 Module 1 :The Need for XML Web Service
  5. 5. Applications Architecture 7/13/2016 Safaa Farouk-ITI 5
  6. 6. Applications Architecture cont Single– Tier(Mainframe based) • User Services, Data Services and Business Services are centralized in one application. • Dumb terminals are connected to mainframe • Advantages : – Deploying. – Maintenance. • Disadvantage: – Scalability. – Processing. 7/13/2016 Safaa Farouk-ITI 6
  7. 7. Applications Architecture cont Two- tiers • Processing is shared between client and server . • Application talking to backend DB – User services places in client side – Data services places in server side – Business services ? 7/13/2016 Safaa Farouk-ITI 7
  8. 8. Applications Architecture cont N-tiers • Data services reside in database server . • Business services reside in a application server . • User services reside in client side . 7/13/2016 Safaa Farouk-ITI 8
  9. 9. Web based application • Client side application – Web sites were simple collections of single pages that interact together – HTML,JS • Server-side applications – They had become individual applications – ASP,PHP,JSP 7/13/2016 Safaa Farouk-ITI 9
  10. 10. XML • XML has been a corner stone in the development of the programmable Internet. • XML is designed as a metalanguage. That is, it provides the foundation for marking up anything we want in plain text. • By using XML to mark up data, we can make that data available in a platform-neutral format that can be shared online regardless of the operating system, database, and firewalls the host platform uses. 7/13/2016 Safaa Farouk-ITI 10
  11. 11. Distributed Applications • What is a distributed application? – A distributed application is an application whose processing requirements may be satisfied by multiple physical computers, and whose data may be stored in many physical locations. 7/13/2016 Safaa Farouk-ITI 11
  12. 12. Why Distributed Applications • Cost of mainframes • Data ownership • No single point of failure • Shared processing Distributed applications as service providers… 7/13/2016 Safaa Farouk-ITI 12
  13. 13. Distributed Applications cont • the architectures and frameworks on which distributed applications were built – RMI(remote method invocation) – .NET Remoting – CORBA(Common Object Request Broker Architecture) – DCOM(Distributed Component Object Model) 7/13/2016 Safaa Farouk-ITI 13
  14. 14. Problems with Distributed Applications • The machines were tightly coupled. • Interoperability • Machines compatibility • Data formats. • Firewalls. • Server failures or loss of server response. • Client failures. • Retrying a call . 7/13/2016 Safaa Farouk-ITI 14
  15. 15. Building a New Technology 7/13/2016 Safaa Farouk-ITI 15 New Technology Binary Calls Platform-Natural Calls Distributed Application Web based Application
  16. 16. What they need? • A platform-independent format language for structured data exchange. • A way of describing the structure of the data being exchanged • A standard method of packaging the data for transmission over the Internet • A way for Web services to describe their public interface to clients • A framework for programmatically locating Web services via their capabilities or description 7/13/2016 Safaa Farouk-ITI 16
  17. 17. Evolution of web service 7/13/2016 Safaa Farouk-ITI 17 Data formats compatibility Firewalls friendly
  18. 18. The Answer… • SOAP (Simple Object Access Protocol) – XML based application that is a message template for sending request and receiving response to web services between the browser and web service. • WSDL (Web service description language) – WSDL able to describe the service details to the client • UDDI – standard for Web service cataloging, UDDI server lets you store the contact locations of your Web service 7/13/2016 Safaa Farouk-ITI 18
  19. 19. Introducing Web Services • What are Web services? – Web service is a method of making information available in a standardized way that could be accessed by any developers applications over the web. 7/13/2016 Safaa Farouk-ITI 19
  20. 20. Web services and .NET 7/13/2016 Safaa Farouk-ITI 20 System.Net.Sockets System.Net System.Runtime.Remoting System.Web.Services TCP/IP HTTP Binary calls Loosely coupling components
  21. 21. Now, Before you start to learn how to make a new thing look at what it really do . • • • • • 7/13/2016 Safaa Farouk-ITI 21
  22. 22. Why web service • Interoperability. – Any web service can interoperate with any other web service. – Any network node that support both XML and HTTP can host and access Web service. • Multi language support. • Use of industry – supported standards. 7/13/2016 Safaa Farouk-ITI 22
  23. 23. Notices about WS • First: would you use your WS or just use the ready made one ? – No guarantee it will be exist next day. – No guarantee it will be with the same cost. • Second : the lack of education – People are still unaware of what web service can offer. • Third : the magic of your work – a good web service should exist in your application while the user should never know it’s there 7/13/2016 Safaa Farouk-ITI 23
  24. 24. Tip… Think of a web service that’s can be used in a lot of applications. Try to make it … Let others share it for free… Then… Ooh ,it’s been Gone  Learn how to make money  7/13/2016 Safaa Farouk-ITI 24
  25. 25. 7/13/2016 Safaa Farouk-ITI 25 Module 2 XML Web Service Architectures
  26. 26. Service-Oriented Architecture (SOA) 7/13/2016 Safaa Farouk-ITI 26 Service Broker Service Provider Service Consumer Publish Find Bind
  27. 27. Web Service Architectures 7/13/2016 Safaa Farouk-ITI 27 UDDI (Web Service Broker) Web Service Provider IIS Web Service Consumer Any client SOAP SOAP SOAP Internet
  28. 28. Roles in a Web Services Architecture • The Web Service Provider. • The Web Service Consumer. • The Web Service Broker. 7/13/2016 Safaa Farouk-ITI 28
  29. 29. Web Service Types • Simple Services. • Application Integration services. • Business Integration services • Commercial Web services • Framework services. 7/13/2016 Safaa Farouk-ITI 29
  30. 30. Remoting Vs Web services  Protocol  State Management  Type System  Interoperability  Reliability  Extensibility  Ease-of-Programming
  31. 31. 7/13/2016 Safaa Farouk-ITI 31 Module 3 Implementing a Simple XML Web Service
  32. 32. Creating Web Service • Every web service you create must have basically 4 items – Processing Directive • <%@ WebService Language="C#" CodeBehind="~/App_Code/Service.cs" Class="Service" %> – NameSpaces • System.web • • – Public class • [webservice ] public class {} – Web Method • [webMethod] public string HelloWS() { retrun “Hello My first web sevice” } 7/13/2016 Safaa Farouk-ITI 32
  33. 33. Creating a Web Service Project Create A web service project 7/13/2016 Safaa Farouk-ITI 33
  34. 34. Web Service Attributes WebService Class Attributes: • WebService Properties – Description – Name – Namespace • WebServiceBinding Properties – ConformsTo – EmitConformanceClaims – Location – Name – NameSpace 7/13/2016 Safaa Farouk-ITI 34
  35. 35. Web Method Attribute Web Method Attributes – BufferResponse – CacheDuration – Description – EnableSession – MessageName – TransactionOption 7/13/2016 Safaa Farouk-ITI 35
  36. 36. Web Service data types • Web service has a limitation on the data type of the passing parameters or the return result, • This limitation are designed to ensure cross platform compatibility – Primitive data types and strings – Enumeration – DataSet and DataTable – XMLNode – Custom Object – ArrayList and collections 7/13/2016 Safaa Farouk-ITI 36
  37. 37. Lab Assignment MazadWS 7/13/2016 Safaa Farouk-ITI 37
  38. 38. 7/13/2016 Safaa Farouk-ITI 38 Module 4 The Underlying Technologies of XML Web Services
  39. 39. Allied technology SOAP WSDL DISCO UDDI 7/13/2016 Safaa Farouk-ITI 39
  40. 40. SOAP Simple Object Access Protocol 7/13/2016 Safaa Farouk-ITI 40
  41. 41. SOAP overview • Simple Object Access Protocol (SOAP) – is a lightweight protocol ( XML based ) intended for the exchange of structured information in decentralized, distributed environments. – is a message template for sending request and receiving responses to web services between the browser and web service • SOAP elements  SOAP Envelope  SOAP Header  SOAP Body  Soap Fault 7/13/2016 Safaa Farouk-ITI 41
  42. 42. SOAP and HTTP – Data you put wrapped up by three ways  HTTP-get  HTTP-post  SOAP Web service life cycle 1. client calls a web service. 2. client invoke a specific method. 3. server returns values or an acknowledgments. 4. client acts on information or call another web service. 7/13/2016 Safaa Farouk-ITI 42
  43. 43. SOAP and HTTP cont • When you type, You decide the protocol that you are using – HTTP – Service location • passes information backward and forward using – http-request /http-response 7/13/2016 Safaa Farouk-ITI 43
  44. 44. – Your request has the following info • Web service’s URL • The fact that it is an http request • The amount of information • The type of doc you want back from the web service • Information about the client • The date of the request • The parameters you want to send to web service – Browser collects this information and wraps it up in a document ready for transmission “serialization” in the form of xml document. 7/13/2016 Safaa Farouk-ITI 44
  45. 45. Http overview • Stateless protocol. • Http Request • Http Response 7/13/2016 Safaa Farouk-ITI 45 Request-Method URL version Headers Message body Version status-code description Headers Message Body
  46. 46. Post vs. Get Request methods • Http - Get • Http- Post 7/13/2016 Safaa Farouk-ITI 46 GET URL/Path? query string version Host: host name POST URL/path version Host: host name Headers Query string
  47. 47. SOAP message SOAP Request SOAP Response 7/13/2016 Safaa Farouk-ITI 47 <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope > <soap12:Body> <SumResponse xmlns = "http://www.e-"> <SumResult>int</SumResult> </SumResponse> </soap12:Body> </soap12:Envelope> <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope > <soap12:Body> <Sum xmlns= ""> <x>int</x> <y>int</y> </Sum> </soap12:Body> </soap12:Envelope>
  48. 48. SOAP cont 7/13/2016 Safaa Farouk-ITI 48 <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi=…> <soap:Header> </soap:Header> <soap:Body> <GetAccount mlns=""> <acctID>int</acctID> </GetAccount> </soap:Body> </soap:Envelope> <soap:Envelope xmlns:soap="”> <soap:Body> <soap:Fault> <faultcode>123XYZ</faultcode> <faultstring>Server Error</faultstring> <detail> <bank:faultdetails xmlns:bank="urn:OnlineBank"> <message>Your account is overdrawn</message> <errorcode>1234</errorcode> </bank:faultdetails> </detail> </soap:Fault> </soap:Body> </soap:Envelope>
  49. 49. ASP.NET Web services generally use SOAP over HTTP using the HTTP Post protocol. 7/13/2016 Safaa Farouk-ITI 49
  50. 50. SOAP with HTTP-Post • HTTP Request 7/13/2016 Safaa Farouk-ITI 50 HTTP Post SOAP Envelope Header Body POST /HelloWS/Service.asmx HTTP/1.1 Host: localhost Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "" <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope > <soap12:Body> <Sum xmlns= ""> <x>int</x> <y>int</y> </Sum> </soap12:Body> </soap12:Envelope>
  51. 51. Serialization 7/13/2016 Safaa Farouk-ITI 51
  52. 52. Serialization • The term serialization describes the process of persisting (and possibly transferring) the state of an object into a stream (file stream, memory stream, etc.). • .NET framework supports two types of serialization – Binary Serialization using BinaryFormatter – XML serialization using SoapFormatter and XmlSerializer 7/13/2016 Safaa Farouk-ITI 52
  53. 53. Serialization cont • SoapFormatter – handles the formatting of a remote procedure call when using SOAP. • The SoapFormatter – uses the xmlSerializer class to serialize and deserialize parameters and results. • XML serializer – only works with public data members. – No need to mark class as serializable . – will serialize all attributes even those which are marked as NonSerializable. 7/13/2016 Safaa Farouk-ITI 53
  54. 54. Serialization Example 7/13/2016 Safaa Farouk-ITI 54
  55. 55. XML Serialization 7/13/2016 Safaa Farouk-ITI 55 XmlRoot Attribute XmlElement Attribute XmlAttribute Attribute XmlArray Attribute XmlArrayItem Attribute System.Xml.Serialization The System.Xml.Serialization namespace provides classes that you can use to modify the way objects are serialized. [XmlRoot("account")] public class Acct { [XmlElement("description")] public string Description; [XmlElement("number")] public string Number; [XmlElement("type")] public string Type; [XmlElement("balance")] public decimal Balance; [XmlAttribute("status")] public string Status; }
  56. 56. XML Include 7/13/2016 Safaa Farouk-ITI 56 [WebMethod] [XmlInclude(typeof(Person))] [XmlInclude(typeof(Customer))] [XmlInclude(typeof(Employee))] public Person[] DisplayAll() { Person[] personArr = new Person[2]; Customer cust = new Customer("ALi"); Employee emp = new Employee("Ahmed","Eng"); personArr[0] = cust; personArr[1] = emp; return personArr; } Person EmployeeCustomer
  57. 57. WSDL Web Service Description language 7/13/2016 Safaa Farouk-ITI 57
  58. 58. WSDL • WSDL – is an XML-based language for describing Web services and how to access them. • WSDL document uses the following core elements in the definition of network services – Types : defines the various data types that are used to exchange messages. (such as XSD). – Message: describes the messages to be communicated. – Operation: identifies a set of operations and the messages that are involved with each of those operations – Binding: specifies the protocol details for various service operations and describes how to translate the abstract content of these messages into a concrete format. – Service element groups a set of related ports together. 7/13/2016 Safaa Farouk-ITI 58
  59. 59. WSDL Structure 7/13/2016 Safaa Farouk-ITI 59 Service Port (e.g. http://host/svc) Binding (e.g. SOAP) Abstract interface portType operation(s) inMesage outMessage Port Binding
  60. 60. WSDL Definitions ‘ elements • Documentation • Types • Message • PortType • Binding • Service 7/13/2016 Safaa Farouk-ITI 60 - <wsdl:definitions targetNamespace=“http://www.e- “> <wsdl:documentation>a simple web service that contains simple service for adding int's </wsdl:documentation> + <wsdl:types> + <wsdl:message name="SumSoapIn"> + <wsdl:message name="SumSoapOut"> + <wsdl:portType name="My_first_web_serviceSoap"> + <wsdl:binding name="My_first_web_serviceSoap" type="tns:My_first_web_serviceSoap"> + <wsdl:binding name="My_first_web_serviceSoap12" type="tns:My_first_web_serviceSoap"> + <wsdl:service name="My_first_web_service"> </wsdl:definitions>
  61. 61. WSDL elements Cont • Type Equivalent 7/13/2016 Safaa Farouk-ITI 61 <wsdl:types> -<s:schema elementFormDefault="qualified" targetNamespace> -<s:element name="Sum"> -<s:complexType> <s:sequence> <s:element minOccurs="1" maxOccurs="1" name="x" type="s:int" /> <s:element minOccurs="1" maxOccurs="1" name="y" type="s:int" /> </s:sequence> </s:complexType> </s:element> - <s:element name="SumResponse"> -<s:complexType> <s:sequence> <s:element minOccurs="1" maxOccurs="1" name="SumResult" type="s:int" /> </s:sequence></s:complexType> </s:element> </s:schema> </wsdl:types> <types> <Sum> <x>int</x> <y>int</y> </Sum> <SumResponse> <SumResult>int</SumResult> </SumResponse> <types>
  62. 62. WSDL elements Cont • Message • Port 7/13/2016 Safaa Farouk-ITI 62 <wsdl:message name="SumSoapIn"> <wsdl:part name="parameters" element="tns:Sum" /> </wsdl:message> - <wsdl:message name="SumSoapOut"> <wsdl:part name="parameters" element="tns:SumResponse" /> </wsdl:message> <wsdl:portType name="My_first_web_serviceSoap"> - <wsdl:operation name="Add"> <wsdl:documentation xmlns:wsdl="">su m two given intergrs and return the result of summation</wsdl:documentation> <wsdl:input name="Sum" message="tns:SumSoapIn" /> <wsdl:output name="Sum" message="tns:SumSoapOut" /> </wsdl:operation> </wsdl:portType>
  63. 63. WSDL elements Cont • Binding • Service 7/13/2016 Safaa Farouk-ITI 63 <wsdl:binding name= "My_first_web_serviceSoap" type="tns:My_first_web_serviceSoap"> <soap:binding transport= "" /> - <wsdl:operation name="Add"> <soap:operation soapAction="http://www.e-" style="document" /> -<wsdl:input name="Sum"> <soap:body use="literal" /> </wsdl:input> - <wsdl:output name="Sum"> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> </wsdl:binding> <wsdl:service name="My_first_web_service"> <wsdl:documentation >a simple web service that contains simple service for adding int's</wsdl:documentation> - <wsdl:port name="My_first_web_serviceSoap" binding="tns:My_first_web_serviceSoap"> <soap:address location= "http://localhost:49166/HelloWS/Service.asmx" /> </wsdl:port> </wsdl:service>
  64. 64. Web service generation • First generation 1. web services are being used to bridge the gap between modern applications and older technologies. 2. allow different applications to interact Example:- • an organization might use a web service to provide access to a legacy database. • allows a payroll system to interact with another type of financial application in the same company. 7/13/2016 Safaa Farouk-ITI 64
  65. 65. WS generation • Second Generation – web services are those that allow partnering companies to work together. – Example:- • an e-commerce company might need to submit orders or track parcels through the web service provided by a shipping company. – Second-generation web services require two companies to work closely together to devise a strategy for exposing the functionality they each need. 7/13/2016 Safaa Farouk-ITI 65
  66. 66. WS generation • Third Generation – web services will allow developers to create much more modular applications by aggregating many different services into one application. – Example:- – For example, you might add a virtual hard drive to your web applications using a third-party web service. – This third generation of web services will require new standards and enhancements that will allow web services to better deal with issues such as reliability, discovery, and performance. – Already, you can use third-party web services from companies such as eBay, Amazon, and Google. 7/13/2016 Safaa Farouk-ITI 66
  67. 67. Module 5: Consuming XML Web Services 7/13/2016 Safaa Farouk-ITI 67
  68. 68. Consuming cont • You can consume web service from any kind of application. – Web based application – Desktop application – Mobile application
  69. 69. Consuming cont • You can generate proxy class using two ways – Add web reference tool – Wsdl.exe tool • Calling web service from http-post. • Calling web service from http-get.
  70. 70. Managing State in WS public class StatefulService : System.Web.Services.WebService { [WebMethod(EnableSession = true)] public void StoreName(string name) { Session["Name"] = name; } [WebMethod(EnableSession = true)] public string GetName() { if (Session["Name"] == null) { return ""; } else { return (string)Session["Name"]; } }} private System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer(); StatefulService proxy = new StatefulService(); proxy.CookieContainer = cookieContainer; proxy.StoreName("John Smith"); MessageBox.Show("You set: " + proxy.GetName()); 7/13/2016 Safaa Farouk-ITI 70 Service Provider Consumer
  71. 71. Module 6: Deploying and publishing XML Web Services 7/13/2016 Safaa Farouk-ITI 71
  72. 72. • You can deploy a Web service to a test or production server. • You have several options available when using Microsoft® Visual Studio® 2005: – Copy the Web site hosting the Web service to a remote Web server – Publish a compiled version of the Web service. – Create a Web Setup project 7/13/2016 SafaaFarouk-ITI 72
  73. 73. Web Service Discovery • The process by which you locate a web service and its description and learn how to interact with it • There are two types of Discovering Using DISCO Using UDDI 7/13/2016 Safaa Farouk-ITI 73
  74. 74. DISCO Microsoft Discovery Files 7/13/2016 Safaa Farouk-ITI 74
  75. 75. DISCO • DISCO – is a Microsoft-defined specification for discovering Web services that are available on a server. However, its scope extends only to individual servers and to providing the client with a WSDL document. • Advantage – .disco file is used only with a web service – You can insert <disco>element for as many web services as you want . • Disadvantage – Locate WSDL document at known endpoint only. 7/13/2016 Safaa Farouk-ITI 75
  76. 76. UDDI Universal Description Discovery and Integration 7/13/2016 Safaa Farouk-ITI 76
  77. 77. UDDI cont • UDDI specification – provides repositories where business can advertise all the web service they have. – Is an industry initiative that is working to enable businesses to quickly ,easily and dynamically find and carry out transactions with ne another. • UDDI creates a platform-independent, open framework & registry for: – Describing services – Discovering businesses – Integrating business services 7/13/2016 SafaaFarouk-ITI 77
  78. 78. UDDI cont • UDDI Business Registry UBRs – defines a complete programming interface that specifies how soap message can be used to retrieve information about web service. – URBs enable companies to advertise the business products and services they provide ,this UDDI registry has the potential of the growth of B2B e-commerce. • There are 4 basic companies that offer this kind of registry – – – – 7/13/2016 Safaa Farouk-ITI 78
  79. 79. UDDI cont • UDDI and WS – The owners of WS publish them to the UDDI registry ,once published the UDDI registry maintains pointes to the web service description and to the service . – UDDI registry allows clients to search this registry ,find a specific WS and retrieve its details. • Data Structures (XML) – – Business entity: general information + business services – – Business services: business level description + binding templates – – Binding templates: access point + tModel (service types) – – tModel: abstract definition of a web service 7/13/2016 Safaa Farouk-ITI 79
  80. 80. Module 7: Designing XML Web Services 7/13/2016 Safaa Farouk-ITI 80
  81. 81. Designing web service • there are a number of issues that you must consider when designing your Web service like. – Performance – Aggregating Web Services 7/13/2016 Safaa Farouk-ITI 81
  82. 82. Performance • General Considerations – Caching – Making asynchronous call • .NET-Specific Considerations – Disable session state 7/13/2016 Safaa Farouk-ITI 82
  83. 83. Caching • If you cache the wrong data, then you waste memory. • If you cache too much data, then you have less memory for other operations. • If you cache too little data, then the cache will be ineffective because you must reprocess the data that was not cached. • If you cache time-sensitive data for too long, then it will become outdated. 7/13/2016 Safaa Farouk-ITI 83
  84. 84. Caching in Web Services • ASP.NET provides two types of caching that you can use to create high-performance Web services: – Output caching • allows you to store responses that are generated by a Web service method. – Data caching • programmatically stores arbitrary objects in memory, so that your application can save the time and resources that it takes to recreate them. 7/13/2016 Safaa Farouk-ITI 84
  85. 85. Caching cont • Output caching for a Web service method is enabled by adding the CacheDuration property to the WebMethod attribute. – [WebMethod(CacheDuration=60)] • Data caching can be implemented by Cache object that can be accessed through the Context object. – Context.Cache["ListOfSources"] = dsSources; 7/13/2016 Safaa Farouk-ITI 85
  86. 86. Asynchronous Web Service • consuming Web services asynchronously. • The Web service proxies that Visual Studio .NET and Wsdl.exe generate support asynchronous invocation of Web service methods. • The asynchronous behavior is implemented by using delegates. 7/13/2016 Safaa Farouk-ITI 86
  87. 87. Asynchronous calls cont • Option for making Asynchronous calls – Delegate –based • All methods have BeginInvoke EndInvoke methods – Event driven –based • MethodAsync and MethodCompleted 7/13/2016 Safaa Farouk-ITI 87
  88. 88. Asynchronous calls Example 7/13/2016 Safaa Farouk-ITI 88
  89. 89. .NET-Specific Considerations • Disable session state – <%@ Page EnableSessionState="false" %> – <sessionstate mode="off" /> • The SQL data provider is recommended for building high-performance Web applications. • Disable debug mode before deploying 7/13/2016 Safaa Farouk-ITI 89
  90. 90. Configure Transmission Protocols <configuration> <system.web> <webServices> <protocols> <remove name="HttpGet" /> <remove name="HttpPost" /> <add name=“soap12”/> </protocols> </webServices> </system.web> </configuration> 7/13/2016 Safaa Farouk-ITI 90
  91. 91. Exception handling • Using SoapException – Code – Actor – Message – Enforce service to throw exception and be caught at the client 7/13/2016 Safaa Farouk-ITI 91
  92. 92. Timeout Exception webService proxy = new webService (); // This timeout will apply to all web service method calls. proxy.Timeout = 3000; // 3,000 milliseconds is 3 seconds. try { proxy.service() } catch (System.Net.WebException err) { if (err.Status == WebExceptionStatus.Timeout) { MessageBox.Show("Web service timed out after 3 seconds.“); } else {} } 7/13/2016 Safaa Farouk-ITI 92
  93. 93. Connecting Through a Proxy // Create the web service proxy. WebService Service = new WebService(); // Specify a proxy server for network communication. WebProxy connectionProxy = new WebProxy("ProxyServer", 80); Service.Proxy = connectionProxy; 7/13/2016 Safaa Farouk-ITI 93
  94. 94. Module 8: Securing XML Web Services 7/13/2016 Safaa Farouk-ITI 94
  95. 95. Security Overview 7/13/2016 Safaa Farouk-ITI 95 Security Authorization Secure communication Authentication Role based security Code access security Soap header authentication IIS-Windows authentication Encryption
  96. 96. Authentication Determining who a user is, usually via a username/password combination 7/13/2016 Safaa Farouk-ITI 96
  97. 97. IIS Authentication – IIS can authenticate users in a number of ways: • Anonymous access No authentication is performed. • Basic authentication is in the form of a plain text username and password combination sent by the client. • Digest authentication A challenge/response mechanism whereby a hash of the user’s password rather than plain text is transmitted. • Integrated A Windows-specific challenge/response mechanism that uses hashes. Similar to digest authentication. • Client certificates Users are identified by a digitally signed key. 7/13/2016 Safaa Farouk-ITI 97
  98. 98. Example 7/13/2016 Safaa Farouk-ITI 98 [WebMethod] public string HelloWorld() { return "Hello" + Context.User.Identity.Name; } HelloService service = new HelloService(); ICredentials credentials = new NetworkCredential("Administrator“,"password", ""); service.Credentials = credentials; string s; try { s = service.HelloWorld(); } catch { Console.WriteLine("Authentication failed"); } Consumer Service provider
  99. 99. Custom Authentication 7/13/2016 Safaa Farouk-ITI 99 • To define a SOAP header for a Web service and use that header in the Web service method: – Derive a class from SoapHeader – Add a public field of the SoapHeader-derived type – Apply the SoapHeader attribute
  100. 100. Custom Authentication 7/13/2016 Safaa Farouk-ITI 100 public class AuthHeader : SoapHeader { public string Username; public string Password; } public class AccountService : WebService { public AuthHeader sHeader; [WebMethod] [SoapHeader("sHeader")] public decimal GetAcctBalance(string acctID) { } } Service proxy = new service(); ServiceAuthInfo authInfo = new ServiceAuthInfo (); authInfo.Username = "Adam"; authInfo.Password = "password"; proxy.ServiceAuthInfoValue = authInfo; proxy.webMethod(); <authentication mode = "None"/> Web.config consumer Service provider
  101. 101. Authorization Determining whether a user has permission to perform a task 7/13/2016 Safaa Farouk-ITI 101
  102. 102. Role-Based Security • The .NET Framework extends the idea of role- based security by using two concepts – principals (user in role) • WindowsPrincipal • GenericPrincipal – identities (user) • GenericIdentity • WindowsIdentity 7/13/2016 Safaa Farouk-ITI 102
  103. 103. Windows Identity • S • Web.config WindowsPrincipal 7/13/2016 Safaa Farouk-ITI 103 If (User.Identity.Name = “account“) { //permit code here } If (User.IsInRole (“Account”)) { Permit access to code } <authorization> <allow roles = Managers"/> <deny roles = "*"/> </authorization>
  104. 104. Secure Communication • Using SSL – Need digital certification • Using custom SoapExtensionAttribute – Difficult to implement 7/13/2016 Safaa Farouk-ITI 104

Notas del editor

  • Before we have been talking about XML web service we have to know some key points (principles)

    The need means in marketing fundamental that there is something people need to (do , have , use ) but they didn’t find the way within the available resources.

    So lets know the need(what actually people want to make ) , the resources(the available technology ) , the reason(why this resources can not meet their need).
  • Any application has its own architecture
  • business logic , presentation logic and data storage are centralized in one application
    Data services + business services + user services in one application
    Terminals -> Centralize business logic + Deploying + maintenance

    Scalability, Processing
  • Processing is shard between Client And server
    User services places in client side , data services places in server side

    Business services place in client side=intelligent client based architecture
    when business change -> client version released

    Business services place in server side=intelligent server based architecture
    (processing)stored procedure is not flexible and efficient more than implementing it using programming (crud create delete update retrieve )

    Business services be shared between client and server

    adding more logical tiers to your application or placing your application files on different computers doesn't make your application distributed
  • Data services reside in a database server side
    User services reside in client side
    Business services reside in server side (may be separated in N-layer)
    1- migrate from oracle to SQL middle tier that talking to database will be changed
    2-business tier (code to enforce business rules)

    Implementation such business objects using COM –DCOM CORBA,RMI,REMOTING(Remote Object based ),RPC,Web server
  • Web sites became a Web-based front end.
    HTML request ,HTML response
    They could design Business components just like any other three-tier application
  • HTML, which is designed to identify and mark up the various elements in a Web page
  • -A distributed application is an application whose processing requirements may be satisfied by multiple physical computers, and whose data may be stored in many physical locations, but whose logical function is not determined by the physical topology that is used to implement the application.

    RPC Based Architecture:

    -Applications splitting their workload privately and securely over more than one machine, using their system’s own Remote Procedure Call (RPC) protocol to call methods( synchronously) and send information from machine to machine to machine as if they were all the same machine.

    Message Based Architecture:

    Message-Oriented Middleware provides applications with interprocess communication services by using message queuing technology as the basis for a guaranteed service level for critical applications(Asynchronously)
  • The need of Distributed-Applications
    Cost of mainframes: has a single point of failure
    Data ownership :sites that owned the data did not like to delegate the responsibility of managing their data to some other central location.
    Security: sensitive corporate data still must be secured.

    To reach the goal of reuse, it became useful to view the distributed components of an application as providers of services to a logical application.
    Application=provider of services

  • The machines were tightly coupled together, and each architecture had its own RPC protocol, message format, and message description language

    Interoperability :
    Each architecture had its own RPC protocol, message format, and message description language.
    DCOM, CORBA, Java RMI—worked exclusively with themselves.
    An application written in CORBA would not cooperate with—or, indeed, understand—the same application written in DCOM or Java RMI on another machine, and vice-versa.

    Machines compatibility:
    Your machines’ setups had to be almost identical to get a distributed application to work at all.

    Data Format:
    You must consider how to handle data types that are not compatible across different systems.

    Fire Walls :
    Not only must you consider authentication and authorization, but you also must consider how to secure the communication between machines, and how to guard against several attacks.

    Server Failure:
    Failure of any point can cause the entire distributed application to fail. Therefore, you must consider how to handle server failures and loss of server response .

    Client Failure:
    If client fails, then you must consider how the server will be notified. You also must consider if it is necessary to reclaim resources on the server that were in use by the client.

    Recalling methods:
    Recall method that already executed but the server didn't give any notification to the client or may it be lost.
  • how could they (XML , HTTP) transform RPC calls over a proprietary protocol into something any system could receive and understand?
  • SOAP message(Request/Response) is written in plain XML text and adheres to the SOAP standard, so any system can understand what it says and act accordingly

    How to describe the interface between the client and service and the required resources(the type and structure of the calls, required parameters, return values, protocol bindings)
  • Web Service :
    URL-addressable set of functionality exposed over a network.
  • .asmx file: front-end for a Web service that is implemented by using ASP.NET.
  • .asmx file: front-end for a Web service that is implemented by using ASP.NET.
  • SOA:-It is a conceptual architecture for implementing dynamic, loosely coupled, distributed applications.
    SOA consists of 3 roles:

    Service Provider :
    A service provider is a node on the network (intranet or Internet) that provides access to the interface to a software service that performs a specific set of operation.
    Service consumer:
    A service consumer is a node on the network that binds to a service from a service provider and uses the service to implement a business solution.
    Service broker :
    A service broker is a node on the network that is a repository of service descriptions and can be used like an address book to find the location of service.

    Basic operations :

    1-Publish services
    Service providers publish their services to a service broker. The information published includes the service interface definition, location of service providers, and possibly other supporting information or documentation.

    2-Find services
    Service consumers find required/desired services by using a service broker.

    3-Bind to services
    Service consumers bind to specific services that are provided by a service provider.
  • The basic elements in a Web service architecture are:

    -The Web service provider:
    which is a network node hosting a Web service, node that hosts a registry.

    -The Web service consumer:
    which is a network node hosting any client can communicate by using Hypertext Transfer Protocol (HTTP)

    -The Web service broker(Universal Description, Discovery, and Integration (UDDI)):
    which is a network node hosting a global registry of available Web services much like a global address book
  • Simple Service: Service that provides a simple piece of functionality to the client, data retrieval or simple calculations

    Application Integration Services: service that works as intermediary between applications that wouldn’t normally be able to talk with each other because they were written for different platforms or use different component architectures.

    .NET client running on Windows 2000 can easily invoke a Java Web service running on mainframe or Unix machine to retrieve data from a legacy application.
    Organizations can send electronic purchase orders to suppliers and receive electronic invoices
    commercial Web services target applications not humans as their direct users, Continental Airlines exposes flight schedules and status Web
    services for travel Web sites and agencies to use in their applications.
  • Protocol
    Web Services:Can be accessed only over HTTP
    Remoting: Can be accessed over any protocol (including TCP, HTTP, SMTP and so on)

    State Management
    Web service: Web services work in a stateless environment
    Remoting: Provide support for both stateful and stateless environments through Singleton and SingleCall objects

    Type System
    Web service:Web services support only the datatypes defined in the XSD type system, limiting the number of objects that can be serialized.
    Remoting: Using binary communication, .NET Remoting can provide support for rich type system

    Web service: Web services support interoperability across platforms, and are ideal for heterogeneous environments.
    Remoting: .NET remoting requires the client be built using .NET, enforcing homogenous environment.

    Web service: Highly reliable due to the fact that Web services are always hosted in IIS
    Remoting: Can also take advantage of IIS for fault isolation. If IIS is not used, application needs to provide plumbing for ensuring the reliability of the

    Web service: Provides extensibility by allowing us to intercept the SOAP messages during the serialization and deserialization stages.
    Remoting: Very extensible by allowing us to customize the different components of the .NET remoting framework.

    Web service: Easy-to-create and deploy.
    Remoting:Complex to program.
  • Name Space =URL where you are hosting the XML Web service.
    Name = enables you to change how the name of the Web service is presented to the developer via the ASP.NET test page
    Description = Description allows you to provide a textual description of the Web service.

    Web Service Binding
  • Buffer response= the response from the XML Web service is held in memory and sent as a complete package=true
    Setting BufferResponse to false makes sense only when the web service returns a large amount
    of data.

    Cache Duration=Specifies the number of seconds that the response should be held in the system’s cache Default=0
    Description=Applies a text description to the WebMethod that appears on the .aspx test pag

    EnableSession=enable session state for a particular method

    MessageName=give unique name for a method(required in overloaded )

    TransactionOption= transaction options disabled-supported-notsupported-required-requirednew
    using System.EnterpriseServices;
    public DataSet TransactionMethod()
  • SOAP Envelope :
    The Envelope element is the root node of an XML document that represents the SOAP message. It contains the Header and Body elements and is mandatory.

    SOAP Header:
    The Header element is the first immediate child element of the SOAP Envelope element.

    SOAP Body :
    If the SOAP Envelope element does not contain the Header element, then the Body element must be the first immediate child element of the Envelope. If the Header element is present, then the Body element must immediately follow the Header element.

    SOAP Fault :
    is used to transport error or status information or both, within a SOAP message. If the SOAP Fault element is present, it must be
    a body entry and may not appear more than once within the Body element.

    The faultcode element :is intended for use by the Web service consumer to identify the fault. This element must be present within the SOAP Fault

    faultstring :The purpose of the faultstring element is to provide a human-readable explanation of the fault. It must be present within the SOAP Fault element and must provide information explaining the nature of the fault.

    faultactor :The purpose of the faultactor element is to provide information about who caused the fault to happen within the message path. It indicates the source of the fault. The value of the faultactor element is a URI that identifies the source.

    detail : is for holding application-specific error information related to the Body element. It is included if the contents of the Body element could not be successfully processed.
  • .asmx file: front-end for a Web service that is implemented by using ASP.NET.
  • .asmx file: front-end for a Web service that is implemented by using ASP.NET.
  • HTTP is a stateless protocol:
    This means that whenever the client makes a request, the connection to the server is closed after the client receives the response.

    Request method : POST-GET-Connect…

    URL: resource location

    Headers: Host name , content type , content length , …

    Message body : query string or parameters is exist
  • XMLSerializer:
    Work with public fields only or private one that has a public property

  • The XmlElementAttribute class:
    You can apply the XmlElement attribute to public fields or public properties to control the characteristics of XML elements, such as the element name and namespace.If you apply it to a field or property that returns an array, the items in the array are generated as a sequence of XML elements.

    The XmlAttributeAttribute :
    When you apply the XmlAttribute attribute to a public field or property, the XML serializer serializes the member as an XML attribute. XML attributes can only be simple types.

    The XmlArrayAttribute :
    When you apply the XmlArray attribute class to a class member, the XML class serializer generates a nested sequence of XML elements from that member.

    The XmlArrayItemAttribute class :
    Using XmlArrayItem allows you to ensure that polymorphic arrays (arrays containing derived objects of the
    base array type) are correctly serialized.
  • Session state will disappear when the session times out. The client will have no way of
    knowing when the session times out, which means the web service may behave

    Session state is tied to a specific user, not to a specific class or object. This can cause
    problems if the same client wants to use the same web service in two different ways or
    creates two instances of the proxy class at once.

    Session state is maintained only if the client preserves the session cookie. The state
    management you use in a web service won't work if the client fails to take these steps.
  • It is unlikely that a Web service provider would publish the service descriptions of all the Web services through a Web service broker.
  • Explain how to implement asynchronous Web methods.
    Explain how to use output and data caching to improve Web service performance.
    Explain how the use of Application and Session state can affect the performance and scaling of Web services.
    Implement a Web service that uses multiple Web services.
  • If you must execute an operation that takes a significant amount of time, then use asynchronous calls to execute the operation.
  • // Define the Begin method.
    [WebMethod] public IAsyncResult BeginMethod(params, AsyncCallback callback, object asyncState)
    // Begin asynchronous communictation with a different XML Web service.
    return remoteService.BeginReturnedStronglyTypedDS(params, callback,asyncState);
    // Define the End method.
    [WebMethod] public datatype EndMethod(IAsyncResult asyncResult)
    { // Return the asynchronous result from the other XML Web service.
    return remoteService.EndReturnedStronglyTypedDS(asyncResult);

    return callWebService(params)
    WebService service = new WebService();
    service.ServiceCompleted += new ServiceCompletedEventHandler(this.Serviceompleted);
    return ServiceCompleted(params) {}
  • For example, a human resources application can define the roles Manager and Employee. Users in the Managers role might have access to a
    GetEmployeeSalary() method, whereas users in the Employee role might not.