Open Source .NET Development [Electronic resources]

Brian Nantz

نسخه متنی -صفحه : 275/ 112
نمايش فراداده

Web Service Example

Chapter 10. This is the function that will be wrapped as a Web service and called by the ASP.NET page with the results shown later in Figure 11-4.

Listing 11.2. Data Access Library Assembly

public DataSet GetTracksForCd(string cdname) { tsStart = new TimeSpan(System.DateTime.Now.Ticks); conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=bnantz;Password=bnantz;Database=cddb;"); conn.Open(); ds = new DataSet(); ds.Tables.Add("Tracks for CD: " + cdname); da = new NpgsqlDataAdapter("select * from tracks where cd = (select DISTINCT id from cds where title = '" + cdname + "')", conn); da.Fill(ds.Tables [0]); conn.Close(); if (_logger.IsDebugEnabled) { tsEnd = new TimeSpan(System.DateTime.Now.Ticks); tsEnd -= tsStart; msg = new StringBuilder(); msg.AppendFormat(@"{0} ms", tsEnd.TotalMilliseconds); _logger.Debug(msg.ToString()); } return ds; }

Figure 11-4. ASP.NET Page on Linux.

[View full size image]

Listing 11.3 is simply how to use a C# custom attribute to wrap the functionality of Listing 11.2 in a Web service.

Listing 11.3. Web Service Wrapper around the Data Access Library

[WebMethod] public DataSet GetTracksForCd(string cdname) { try { if(cdname.Length>0) { dataAccess da = new dataAccess(); return da.GetTracksForCd(cdname); } else throw new ArgumentException("Input can not be empty string."); } catch(Exception ex) { if(_logger.IsErrorEnabled) _logger.Error(ex.ToString()); } return new DataSet(); }

The custom attribute does all the magic to make sure that the method is now exposed as a Web service. ASP.NET basically takes care of the SOAP messages, which you would otherwise have to do in a custom ASP.NET handler (basically like an ISAPI extension), which is easier than it used to be but still is no small task. In addition, this little tag automatically creates the WSDL needed for the Web service client to consume the Web service. It also maps all the CLI types to SOAP types (like exceptions, strings, ints, etc.). That is a lot of functionality for one line of additional code. The real power is that you can take Listing 11.2 and turn it into Listing 11.3 so easily and get a Web service that anyone (Java, Perl, or anyone talking SOAP) can use!