Now that you have completed the mandatory Hello World introduction to Web services, the next step is to get serious by developing a Web service that potentially could be used in a real-world application. The Web service in this case provides a LookUpCustomer webMethod that retrieves the customer information (Listing 9.2). This service, for instance, can be utilized by a Customer Relationship Management (CRM) application, pulling the customer information from a back-office Enterprise Resource Planning (ERP) application (see Figure 9.5). Figure 9.5. XML data structure returned by the business Web service.
A couple of interesting features are highlighted next:
Listing 9.2 Real-world Web Service<%@ Webservice class="hks.BusinessService" language="C#"%> using System; using System.Xml; using System.Xml.Serialization; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Collections; namespace hks { [WebService(Namespace="http://www.hiteshseth.com/WebServices")] public class BusinessService { [WebMethod(Description="LookUp Customer, Complex Business Service")] public Customer LookUpCustomer(String customerId) { try { return Customer.LookUp(customerId); } catch (Exception Ex) { throw new SoapException( Ex.Message,SoapException.ClientFaultCode,""); } } } public class Customer { private String _name; private String _id; private ArrayList _orders; public String Name { get { return _name; } set { _name = value; } } [XmlAttribute("id")] public String Id { get { return _id; } set { _id = value; } } [XmlElement("Order",Type = typeof(Order))] public ArrayList Orders { get { return _orders; } set { _orders = value; } } public static Customer LookUp(String customerId) { if (customerId==null customerId.Equals("")) { throw new Exception("CustomerId Not Specified"); } // Actual implementation will probably lookup from a database Customer c = new Customer(); c.Id = customerId; c.Name = "ABC Chemicals"; ArrayList orders = new ArrayList(); orders.Add(new Order(customerId,"ABC123",50)); orders.Add(new Order(customerId,"ABC456",100)); orders.Add(new Order(customerId,"ABC789",150)); c.Orders = orders; return c; } } public class Order { public Order() {} private String _customerId; public String CustomerId { get { return _customerId; } set { _customerId = value; } } private String _item; public String Item { get { return _item; } set { _item = value; } } private int _price; public int Price { get { return _price; } set { _price = value; } } public Order(String customerId, String item, int price) { _customerId = customerId; _item = item; _price = price; } } } |