1 / 42

Introduction to Web Service

Introduction to Web Service. ISYS 512. Service Oriented Architecture.

melliott
Télécharger la présentation

Introduction to Web Service

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Web Service ISYS 512

  2. Service Oriented Architecture • SOA is a software architecture that defines the use of loosely coupled software services where software routines can be called by an application and executed as needed to support the requirements of the business processes and software users. • In an SOA environment, resources on a network are made available as independent services that can be accessed without knowledge of their underlying platform implementation. • For example, Web services are loosely coupled software modules that are invoked on demand when required.

  3. Web Service • XML Web Service • Web services are classes that are stored on the web which can instantiate and use in both Windows and Web applications. • It uses SOAP for communication.

  4. Simple Object Access Protocol, SOAP • SOAP is a protocol specification for exchanging structured information in the implementation of Web Services in computer networks. It relies on Extensible Markup Language (XML) for its message format, and usually relies on other Application Layer protocols, most notably Hypertext Transfer Protocol (HTTP), for message transmission. • SOAP specifies exactly how to encode an HTTP header and an XML file so that a program in one computer can call a program in another computer and pass it information. It also specifies how the called program can return a response.

  5. A Web Service Example • http://www.webservicex.net/stockquote.asmx • Service Description • GetQuote: • SOAP • HTTP Get • HTTP Post

  6. Create a New Web Service • Project/Add New Item/Web Service • Web Service has an extension: ASMX • Web Services are defined as Web Method: • <WebMethod()> _

  7. A Web Service Example public class TestWS : System.Web.Services.WebService { [WebMethod] public string GetCname(string CID) { string strConn = "Data Source=(localdb)\\projects;Initial Catalog=SalesDB;Integrated Security=True"; SqlConnection objConn = new SqlConnection(strConn); string strSQL = "select * from customer where CID = '" + CID + "';"; SqlCommand objComm = new SqlCommand(strSQL, objConn); objConn.Open(); SqlDataReader objDataReader; objDataReader = objComm.ExecuteReader(); string returnValue; if (objDataReader.Read() == true) returnValue= objDataReader["CNAME"].ToString(); else returnValue="Not exist"; objConn.Close(); return (returnValue); } }

  8. Web Service Description Language (WSDL) • A WSDL file is an XML document containing a complete description of the web service. It shows a web service’s name, methods, and parameter types. • Help page: After entering web service’s URL, a help page is displayed. You can click the Service Description link to see the WSDL file.

  9. Returning a Complex Data Type • Examples: • DataSet • User-defined object • Customer Class • List

  10. Example: Returning a DataSet [WebMethod] public DataSet getCustomerOrders() { string strConn = "Data Source=(localdb)\\projects;Initial Catalog=SalesDB;Integrated Security=True"; SqlConnection objConn = new SqlConnection(strConn); string strSQL = "select * from customer;"; SqlDataAdapter objAdapter = new SqlDataAdapter(strSQL, objConn); DataSet objDataSet = new DataSet(); objAdapter.Fill(objDataSet, "Customer"); string strSQL2 = "select * from orders;"; objAdapter.SelectCommand.CommandText = strSQL2; objAdapter.Fill(objDataSet, "orders"); return objDataSet; }

  11. Consuming a Local Web Services from a Web Application • Add a web reference to the web service: • Project/Add Service Reference • Click Discover to show local web services • Declare a web service class variable.

  12. Use the Dataset Returned by a Web Service protected void Page_Load(object sender, EventArgs e) { WebService1 useWS = new WebService1(); DataSet myDS = new DataSet(); myDS = useWS.getCustomerOrders(); GridView1.DataSource = myDS; GridView1.DataMember = "customer"; GridView1.DataBind(); }

  13. Web Service that returns an user-defined object: Customer Class [WebMethod] public Customer GetCustomerObj(string CID) { Customer myCust = new Customer(); myCust.getCustomerData(CID); return myCust; } Note: View the Service Description.

  14. Using the web service TestWS useWS = new TestWS(); Customer myCust = new Customer(); myCust = useWS.GetCustomerObj(TextBox1.Text); if (myCust.RecExist) TextBox2.Text = useWS.GetCname(TextBox1.Text); else TextBox2.Text = "Record not exist";

  15. Consuming a Services Found On Internet • Find the web service: • http://www.webservicex.net/stockquote.asmx • Add a reference to the web service: • Project/Add Service Reference • Click Advanced button • Click Add Web Reference at the bottom of the dialog • Paste the web service’s URL to the address box • Declare a web service class variable.

  16. Example of using the service protected void Button1_Click(object sender, EventArgs e) { net.webservicex.www.StockQuote ws = new net.webservicex.www.StockQuote(); TextBox2.Text= ws.GetQuote(TextBox1.Text); }

  17. Mortgage Calculator Web Service on Internet • http://www.webservicex.net/mortgage.asmx • Requires many inputs and returns an object with more than one properties.

  18. Properties of the returned object:MortgageResults

  19. Code Example protected void Button1_Click(object sender, EventArgs e) { int term; double rate, loan, tax, insurance; term = int.Parse(TextBox1.Text); rate = double.Parse(TextBox2.Text); loan = double.Parse(TextBox3.Text); tax=double.Parse(TextBox4.Text); insurance = double.Parse(TextBox5.Text); net.webservicex.www1.Mortgage ws = new net.webservicex.www1.Mortgage(); TextBox6.Text= ws.GetMortgagePayment(term, rate, loan, tax, insurance).MonthlyPrincipalAndInterest.ToString(); // Method 2: get the result object net.webservicex.www1.MortgageResults result = new net.webservicex.www1.MortgageResults(); result = ws.GetMortgagePayment(term, rate, loan, tax, insurance); TextBox6.Text = result.MonthlyPrincipalAndInterest.ToString(); }

  20. Windows Communication Foundation(WCF) Service • The Windows Communication Foundation is an application programming interface (API) in the .NET Framework for building connected, service-oriented applications. • It is designed to support distributed computing where services have remote consumers. Clients can consume multiple services; services can be consumed by multiple clients. • Services are loosely coupled to each other.

  21. Implementing a Service Class:Namespace:System.ServiceModel • A service class is marked with ServiceContract. • It defines one or more contracts (the operations this service exposes) that consist of all methods in the class that are marked with OperationContract. • It’s also possible (and usually better) to specify service contracts explicitly using an interface type. • An operations will typically convey some data (parameters). So a service contract also implies some kind of data contract describing the information that will be exchanged. • Simple types: • Complex type: marked with [DataContract] and can be a class or structure.

  22. Visual Studio WCF Project • New project:C# / WCF / WCF Service Library

  23. Files Added to WCF Projects • Visual Studio will create the project which contains 3 files: IService1.cs, Service1.cs, and App.config. The IService1 file contains a default service contract. The Service1 file contains a default implementation of the service contract. The App.config file contains configuration needed to load the default service with the Visual Studio WCF Service Host.

  24. WCF Test Client

  25. Consuming a WCF Service • Run two projects: • 1. The WCF service project • 2. A website project as a client. • Start the WCF service • Switch to the website project: • Add a reference to the WCF service: • Project\Add Service Reference • Copy/paste the service’s address and click GO

  26. Example of Designing and Creating a New WCF Service • A class that of two methods: • GetCustName: Takes a CID and returns the customer name. • GetCustData: Takes a CID and returns all the fields. • DataContract: CustomerType class with CID, Cname, City, Rating. • Database server: SQL Server

  27. IService File public interface IService1 { [OperationContract] string GetCustName(string CID); [OperationContract] CustomerType GetCustomerData(string CID); } [DataContract] public class CustomerType { [DataMember] public string CID { get; set; } [DataMember] public string Cname { get; set; } [DataMember] public string City { get; set; } [DataMember] public string Rating { get; set; } }

  28. GetCustName Method (Note:Cannot use localdb) public string GetCustName(string CID) { string custName; string strConn = "Data Source=David-PC\\SQLEXPRESS;Initial Catalog=TestSQLServer;Integrated Security=True;Pooling=False"; SqlConnection objConn = new SqlConnection(strConn); string strSQL = "select * from customer where cid='" + CID + "'"; SqlCommand objComm = new SqlCommand(strSQL, objConn); objConn.Open(); SqlDataReader objDataReader; objDataReader = objComm.ExecuteReader(); if (objDataReader.Read() == false) { objConn.Close(); return "Not exisst"; } else { custName= objDataReader["Cname"].ToString(); return custName; objConn.Close(); } }

  29. public CustomerType GetCustomerData(string CID) { CustomerType myCust=new CustomerType(); string strConn = "Data Source=David-PC\\SQLEXPRESS;Initial Catalog=TestSQLServer;Integrated Security=True;Pooling=False"; SqlConnection objConn = new SqlConnection(strConn); string strSQL = "select * from customer where cid='" + CID + "'"; SqlCommand objComm = new SqlCommand(strSQL, objConn); objConn.Open(); SqlDataReader objDataReader; objDataReader = objComm.ExecuteReader(); if (objDataReader.Read() == false) { myCust.CID = "NA"; myCust.Cname="NA"; myCust.City = "NA"; myCust.Rating = "NA"; } else { myCust.CID = objDataReader["CID"].ToString(); myCust.Cname=objDataReader["Cname"].ToString(); myCust.City = objDataReader["City"].ToString(); myCust.Rating = objDataReader["Rating"].ToString(); } objConn.Close(); return myCust; } GetCustomerData Method

  30. Using the service protected void Button1_Click(object sender, EventArgs e) { ServiceReference3.Service1Client ms = new ServiceReference3.Service1Client(); ServiceReference3.CustomerType myCust = new ServiceReference3.CustomerType(); myCust= ms.GetCustomerData(TextBox1.Text); TextBox1.Text = myCust.CID; TextBox2.Text = myCust.Cname; TextBox3.Text = myCust.City; TextBox4.Text = myCust.Rating; }

  31. WCF Data Services • WCF Data Services enables you to create services that use the Open Data Protocol (OData) to expose and consume data over the Web. • OData exposes data as resources that are addressable by URIs. http://localhost:12345/northwind.svc/Customers http://localhost:12345/northwind.svc/Customers(‘C01')

  32. Odata and Entity Frame Work • OData uses the entity-relationship conventions of the Entity Data Model to expose resources as sets of entities that are related by associations. • Visual Studio tools make it easier for you to create an OData-based service by using an ADO.NET Entity Framework data model.

  33. Creating the WCF Data Service • http://msdn.microsoft.com/en-us/library/vstudio/dd728275(v=vs.100).aspx • Create an ASP.NET Web application. • Define the data model by using the Entity Data Model tools. • Add the data service to the Web application. • Enable access to the data service.

  34. Define the data model by using the Entity Data Model tools • 1.In Solution Explorer, right-click the name of the ASP.NET project, and then click Add New Item. • 2.In the Add New Item dialog box, click the Data template and then select ADO.NET Entity Data Model. • 3. Enter a name for the data model. It has an extension “edmx”. • 4.In the Entity Data Model Wizard, select Generate from Database, and then click Next.

  35. Add the data service to the Web application • 1.In Solution Explorer, right-click the name of your ASP.NET project, and then click Add New Item. • 2.In the Add New Item dialog box, select WCF Data Service. • 3.Enter the name of the service. • Visual StudioVisual Studio creates the XML markup and code files for the new service. By default, the code-editor window opens. In Solution Explorer, the service will have the entered name with the extension .svc.cs or .svc.vb. • 4.In the code for the data service, replace the comment /* TODO: put your data source class name here */ in the definition of the class that defines the data service with the type that is the entity container of the data model

  36. Entities and DataSets

  37. To enable access to data service resources // Grant only the rights needed to support the client application. config.SetEntitySetAccessRule("Orders", EntitySetRights.AllRead | EntitySetRights.WriteMerge | EntitySetRights.WriteReplace ); config.SetEntitySetAccessRule("Order_Details", EntitySetRights.AllRead | EntitySetRights.AllWrite); config.SetEntitySetAccessRule("Customers", EntitySetRights.AllRead);

  38. Accessing the Service from a Web Browser • http://msdn.microsoft.com/en-us/library/vstudio/dd728279(v=vs.100).aspx • In Internet Explorer, from the Tools menu, select Internet Options, click the Content tab, click Settings, and clear Turn on feed viewing. • Example of query: • Whole table • One record

  39. http://localhost:50423/WcfDataService1.svc/

  40. http://localhost:50423/WcfDataService1.svc/Customers

  41. http://localhost:50423/WcfDataService1.svc/Customers('C1')/Ordershttp://localhost:50423/WcfDataService1.svc/Customers('C1')/Orders

More Related