Galin Iliev's blog

Software Architecture & Development

How to consume Astoria Service

A week ago I wrote about setting-up Astoria Service. Now is time to expose real power of Astoria - consuming data from client script.

Once you have setup your Web Data Service you're ready to write ASP.NET AJAX script to consume it. Basically you need these things:

  • set Requiest's header "accept" value of "application/json" so the data can be used directly in JS
  • call appropriate URL
  • and, of course, process data

The rest is done form Astoria team :) Kudos for them

this is how the code looks like:

   1:  function loadCustomers(){
   2:      var webRequest = new Sys.Net.WebRequest();   
   3:      
   4:      webRequest.set_url("http://galcho-pc:86/northwind.svc/Customers");   
   5:      
   6:      webRequest.get_headers()["accept"] = "application/json";
   7:      
   8:      webRequest.add_completed(function (result){
   9:          var cust = result.get_object();   
  10:          for (i = 0; i < cust.length; i++){   
  11:              addCustomer(cust[i].ContactName, cust[i].CompanyName);
  12:          }  
  13:      });   
  14:      
  15:      webRequest.invoke(); 
  16:  }
  17:   
  18:  function addCustomer(contactName, companyName){
  19:      $get("customers").innerHTML += "<div>" + contactName + "</div>" + companyName + "<br/>";
  20:  }

There main function is loadCustomers(). It does all I described above. And there is a helper function that fills a DIV's innerHTML property with approperiate content.

Here is the HTML:

   1:  <div id="customers">
   2:      <span style="font-size: large; font-weight: bold; border: solid 1px black; width: 100%;
   3:          display: block;">
   4:          <div>
   5:              Contact Name</div>
   6:          CompanyName</span>
   7:  </div>

And the result looks like:

 

You can download full ASPX file from here:

Astoria-Simple-Test.zip (0.94 KB)

More sophisticated article for Astoria consumer app is coming. It is based on MIX AJAX classed that provide infrastructure for CRUD operations.

Loading