Returning Arrays of Simple Types

ASP.NET treats arrays of simple types as a list of items. Like everything we have seen so far, developers have little to think about other than stating that an array is being passed in or returned. To demonstrate the power here, we will write a Web Method in Listing 1.3 that returns an array of random numbers. As arguments, it will take the number of items to be returned as well as the smallest and largest permissible values to be returned.

Listing 1.3. Source for the FirstService.GetRandomNumbers Function
<WebMethod()> Public Function GetRandomNumbers( _
    ByVal arraySize As Long, ByVal min As Long, _
    ByVal max As Long) As Long()

    Dim retval(arraySize - 1) As Long
    Dim rnd As New System.Random()
    Dim index As Long
    For index = 0 To retval.Length - 1
        retval(index) = rnd.Next(min, max)
    Next
    GetRandomNumbers = retval
End Function
					

The code creates an array of size arraySize and a random number generator. Using the random number generator, the code loops through all the elements assigning them different values, and then returns those values to the caller. The Next function takes two values and returns a random number within that range. The return value from this function will be as small as the minimum value but never as large as the maximum. In mathematical terms, Next returns a value in the range (min, max). When testing this function from Internet Explorer, we will continue to use HTTP/GET. The message exchange will look something like the following:

Request:

GET /Chapter1/FirstService.asmx/GetRandomNumbers? arraySize=string&min=string&max=string
 HTTP/1.1
Host: localhost

Response:

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfLong xmlns="http://tempuri.org/">
  <long>long</long>
  <long>long</long>
</ArrayOfLong>

To get five values between –1000 and 1000, I would fill in the generated form as shown in Figure 1.6. The outgoing request is then formatted within the URL as http://localhost/Chapter1/FirstService.asmx/GetRandomNumbers?arraySize=5&min=-1000&max=1000. This request returns the XML shown in Listing 1.4.

Figure 1.6. Using the ASP.NET–generated Web page to call GetRandomNumbers.


Listing 1.4. Returned XML for call to GetRandomNumber
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfLong
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns="http://tempuri.org/">
  <long>-593</long>
  <long>203</long>
  <long>-158</long>
  <long>799</long>
  <long>20</long>
  <long>-930</long>
</ArrayOfLong>
					

Simple arrays get passed around all the time. It may be a list of temperatures, dates, strings, or something else. Arrays of structured data are equally common.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.172.38