08.01.2015 Views

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 7 ■ .<strong>NET</strong> 3.0: WINDOWS COMMUNICATION FOUNDATION 169<br />

As you can see, this is just a straightforward class implementation. The idea is that<br />

your “custom” code to define a WCF service exists outside of your implementation code,<br />

<strong>and</strong> is configured via a <strong>Web</strong>.config file. This means that the business logic developers concentrate<br />

on the business logic <strong>and</strong> don’t wrap it up in the plumbing. It’s a very neat aspect<br />

of the WCF design that will make the implementation of enterprise-grade services easy.<br />

Next, you build the operation itself. Here’s the code:<br />

public string GetAddresses(string strZIP)<br />

{<br />

string strReturn = "";<br />

AddressDataTableAdapters.AddressTableAdapter da =<br />

new AddressDataTableAdapters.AddressTableAdapter();<br />

AddressData.AddressDataTable dt = da.GetData(strZIP);<br />

strReturn = FormatDTasXML(dt);<br />

}<br />

return strReturn;<br />

This takes in a string, the ZIP code, <strong>and</strong> uses it as a parameter in pulling the address<br />

data (as a DataTable) from the AddressTableAdapter, which is implemented by the<br />

DataSet. Then it sends this data to a helper function to format it as XML <strong>and</strong> serialize it<br />

into a string. This string will then be returned by the service.<br />

Here’s the listing for this helper function:<br />

private string FormatDTasXML(AddressData.AddressDataTable dt)<br />

{<br />

MemoryStream memStream = null;<br />

XmlTextWriter xmlWriter = null;<br />

try<br />

{<br />

memStream = new MemoryStream();<br />

xmlWriter = new XmlTextWriter(memStream, Encoding.Unicode);<br />

dt.WriteXml(xmlWriter);<br />

int count = (int)memStream.Length;<br />

byte[] arr = new byte[count];<br />

memStream.Seek(0, SeekOrigin.Begin);<br />

memStream.Read(arr, 0, count);<br />

UnicodeEncoding utf = new UnicodeEncoding();<br />

return utf.GetString(arr).Trim();

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!