Connecting Flash with ASP.NET Web Pages

In this tutorial you will learn how ASP.NET Web Pages with Razor syntax can be used to build a RESTful web service that is capable of delivering weather forecast data to an Adobe Flash application. We will be using WebMatrix, a lightweight tool for web development to write code and manage the website throughout this tutorial.

Getting Started

The Current Weather Site

The REST service that you will create will be built on top of the Current Weather WebMatrix site that was built in the tutorial Consuming and Storing Data from a REST service with Razor. In that tutorial we learned how the integrated database features of WebMatrix could be used to retrieve and cache weather service data. Some of the code you will be looking at in this tutorial will directly reference the weather forecast features developed for the Current Weather site, so if you would like to familiarize yourself with how the site works, feel free to review that tutorial before continuing.

What You’ll Need

In addition to WebMatrix and the Razor syntax, you will be working with some standard web technologies in this tutorial. If you have a basic understanding of HTML, CSS, JSON and Flash tools you will be set.

A RESTful Service

The first thing we will want to do is review the Razor methods that the Current Weather site uses to retrieve forecast data. The functions we want to use are located in a Razor function block in the App_Code folder of the site. Function blocks are called using the following signature:

FileName.FunctionName([DataType arg], [DataType arg]…);

The filename that the Current Weather site uses is Weather.cshtml and the function is GetForecastByZipcode(string zip). So to call this function using Razor you would write:

@{

var temp = Weather.GetForecastByZipcode("92805");

}

As you can see, we simply pass any valid zip code to the function in order to receive the forecast data for that area. The object that is returned is a simple container that holds the temperature data that is retrieved from a remote weather service.

public class Temperature

{

public string Zip { get; set; }

public string Latitude { get; set; }

public string Longitude { get; set; }

public int MaxTemp { get; set; }

public int MinTemp { get; set; }

public string Forecast { get; set; }

}

Each property of the Temperature object can be easily accessed through the ‘temp’ variable. For example, the following Razor code will write the forecast description into an HTML paragraph:

<p>@temp.Forecast</p>

So now that now you understand how weather forecast data is accessed, let’s take a look at how the data stored in the Temperature object can be converted to a format that is suitable for use by Flash.

What is REST

A RESTful web service is simply a service that is implemented using HTTP as a protocol. That means that requests are made from client to server using a valid URI as a locator. A typical RESTful API will respond to requests with a standards compliant data format like JSON or XML. For this tutorial you will be creating a very simple service layer on top of the GetForecastByZipcode method that we discussed in the last section.

Using Razor to Deliver RESTful Content

In order to create a RESTful web service layer on top of the Current Weather site, we will need to add some code that accepts a client supplied zip code and returns data in a standardized format. So let’s start by creating an empty Razor page to hold the required code. For this tutorial we are using a page called JsonService.cshtml, but you are free to name it anything you like. This page will only contain a small Razor code block, so any default HTML can safely be removed.

Now that we have a place to hold the service code, let’s discuss how we can add support for accepting zip codes. Since a RESTful web service is implemented over HTTP, the simplest means of passing HTTP compliant data into a URL is with query string parameters. So let’s add a code block the page and extract a query parameter from the Request object called ‘zip’.

@{

var zip = Request.QueryString["zip"];

}

Now whenever a request is made to the following URL:

http://localhost/CurrentWeather/JsonService.cshtml?zip=92805

The Razor variable, zip, will contain the requested zip code. You will also probably want to make sure that if the zip parameter is missing that the page handles it appropriately. So let’s add a little more code to make sure that the request is properly formatted.

@{

var zip = Request.QueryString["zip"];

if(zip == null){

Response.Write("Missing Zip Parameter");

return;

}

if(zip != string.Empty){

//zip code exists

}else{

Response.Write("Invalid Zip Code");

}

}

If either the zip parameter is missing a value or not even included in the URL, the client that issued the request will receive a simple message indicating what went wrong.

Alright, so now that we have a zip code supplied by a client request, we can retrieve the weather forecast data using the same function call to GetForecastByZipcode we looked at earlier. However we still need a convert the data held in the Temperature object to a format that any client can consume. To do this we will be using the JavaScript Object Notation (JSON) protocol. JSON is a text-based open standard that has become the leading interchange format for sharing data in a web environment. The JSON standard uses a concise key/value pair format that is perfect for parsing data into a readable format. Although the JSON specification is well documented, the code required to convert a Razor object into JSON would be pretty lengthy to write yourself. Thankfully, the WebMatrix environment comes preinstalled with a JSON Helper that simplifies the process of encoding and decoding objects into a few simple functions.

Let’s take look at how the WebMatrix Json Helper can be used to encode and decode the Temperature object returned by the GetForecastByZipcode function by adding some test output to the service page.

if(zip != string.Empty){

//zip code exists

var temp = Weather.GetForecastByZipcode("92805");

Response.Write("<p>" + temp.Forecast + "</p>");

var json = Json.Encode(temp);

Response.Write("<p>" + json + "</p>");

var temp2 = Json.Decode(json);

Response.Write("<p>" + temp2.Forecast + "</p>");

Json.Write(temp, Response.Output);

}else{

Response.Write("Invalid Zip Code");

}

If you were to run this code in a browser from within the Current Weather site you would see the following page output:

Rain

{"Zip":"92805","Latitude":"33.8263","Longitude":"-117.911","MaxTemp":52,"MinTemp":45,"Forecast":"Rain"}

Rain

{"Zip":"92805","Latitude":"33.8263","Longitude":"-117.911","MaxTemp":52,"MinTemp":45,"Forecast":"Rain"}

The Json Helper contains two methods, Encode and Decode, which are used to convert the Temperature object in and out of a JSON formatted string. Notice that the encoded output has converted the properties of the Temperature object to keys and associated the property data to each key as a string value. When the JSON string is decoded, the properties of the object can once again be accessed as they were prior to encoding. Since we only need to encode and write directly to the response stream, the process can be simplified through the use of the Json.Write method as demonstrated in the last line of code.

A Quick Test

Your final output of the REST service should look something like this:

@{

var zip = Request.QueryString["zip"];

if(zip == null){

Response.Write("Missing Zip Parameter");

return;

}

if(zip != string.Empty){

var temp = Weather.GetForecastByZipcode(zip);

Json.Write(temp, Response.Output);

}else{

Response.Write("Invalid Zip Code");

}

}

Now whenever a valid zip code is sent to the service, the requesting client will receive a JSON formatted string that can be decoded by a native JSON parser.

Creating a Flash Client

RESTful web services that rely on open standards are the ideal way to enable your site to deliver content to a variety of disparate systems. Practically every popular computing platform available today is capable of sending and receiving data over HTTP. In this section we will explore the benefits of building REST services by looking at how an Adobe Flash client can consume the weather service that we just created.

The easiest way to create a data driven Flash client is through the use of a development IDE from Adobe called Flash Builder. Flash Builder is an IDE that can be used to create cross platform rich internet applications (RIA’s) that run in the browser using the Flash plugin or on the desktop with Adobe AIR. The tools available in Flash Builder make consuming and interacting with RESTful web services very easy. In fact, to create a simple demonstration application we won’t even have to write any code.

Working with Flash Builder

Let’s get started by creating a new project with Flash Builder. In the following screen a project called CurrentWeather has been created using the default settings. As soon as the project is created an MXML file is added using the same name that was assigned to the project. MXML is the markup language used by Flash Builder to create user interfaces in Flash. Flash Builder will use this file to add to the interface components we need to communicate with the REST service.

clip_image001

 

The next thing we want to do is add a reference to the REST service that we created in the last section. This is done by running the DataService wizard in Flash Builder. Notice in the following screen that there are a variety of data services available. If you recall from the last section, a RESTful web service communicates over HTTP so we will select the HTTP service type from the first page of the wizard.

clip_image002

This will open a new screen that will allow you to configure the data service to connect to the URL for the REST service of the CurrentWeather WebMatrix site. Notice that the zip code query parameter that the REST service uses to lookup data is added as a parameter. Once the URL is configured we assign a name that we can use to reference the service wrapper in other areas of the project.

clip_image003

 

When configuration is complete Flash Builder will automatically generate the code required to communicate with the Current Weather service. The following screen shows some of the support code that was generated. The IDE interface has been adjusted slightly to make the service structure and code a little easier to view.

clip_image005

At this point you will have a functional service in place that is capable of requesting and receiving JSON data from the Current Weather service. The next thing we need to do is configure the Flash site to convert that data into a usable format.

Converting from JSON

The Service Explorer window enables us to create additional functionality for the WeatherService service that we just added. By default, the service return type will be stored in a plain Object type. While this technically is enough to gain access to the JSON data, it would be nicer to have a strongly typed object similar to the Temperature class we created in the last section.

clip_image007

Using either the context menu for the WeatherOperation item or the shortcut in the toolbar, you will be able to launch the “Configure Return Type” wizard. This wizard uses a default value for the REST service to make a request and retrieve the JSON formatted response. It will then analyze the response data and determine the object layout that best matches the keys in the JSON data.

clip_image008

The layout that is assigned is then displayed in a property grid. You are then able to adjust the object name, property names and property types as necessary. Since the JSON data we are using is pretty simple there is nothing to change. We only need to add an object name, for consistency sake we will just call it “Temperature”.

clip_image009

When the wizard is finished the object will automatically be generated in code and added to the project. If we open up the code file that was generated, you will notice that it looks very similar to the Temperature class we created in the last section.

clip_image010

If we return to the Service Explorer window, you can see that the WeatherOperation is no longer using an Object type. Instead it is now configured to return a Temperature object after each request.

clip_image012

Generating a User Interface

The last thing we need to do is create a user interface that we can load in the browser to test the service. Let’s keep things simple and use the Generate Form wizard to bind an input control form to the data returned by the service. The wizard is started by selecting “Generate Form” from the Data menu in Flash Builder.

clip_image013

When the wizard loads, the WeatherService service that we created will be preselected since it is the only object available in the project for binding. On the second page of the wizard you will be able to customize the control output that will be automatically generated. The controls are set to TextInput by default but can also be changed to other suitable control types depending on the property type that is being used.

clip_image014

When the wizard is complete the default MXML file will be updated with the code and user interface elements that we configured. If you switch to Design view, you can see now the controls that the wizard added are going to appear in user interface.

clip_image015

The Design view is an easy way to make visual updates to the user interface. At this point we could update the layout by adding additional controls or repositioning the existing elements. Now let’s take a look at how the application we have created will look when run in a browser. The easiest way to run the application is to select the green arrow button in the toolbar. This will load a temporary HTML page with the required scripts along with the Flash output from the project.

clip_image016

 

The WeatherOperation button will submit the supplied zip code to the Current Weather service running in WebMatrix. When the response is received it is converted to the new Temperature object in Flash and each value is bound to the controls we created.

Summary

In this tutorial you saw how WebMatrix can be used to create a RESTful content delivery service that can be consumed by a variety of user interfaces. You also saw how a completely different platform like Flash is capable of communicating with a WebMatrix site using Adobe Flash Builder.

WebMatrix was created from the ground up to be a simple, all-inclusive web development tool that is easy to use but still powerful enough to deliver the advanced features used by websites today.

Additional Resources

Download WebMatrix http://www.microsoft.com/web/webmatrix/

Learn more http://www.microsoft.com/web/category/learn

More tutorials http://www.asp.net/webmatrix

Twitter http://twitter.com/mswebplatform

Facebook http://www.facebook.com/WebPlatform

For any questions or comments about this tutorial please contact the Aeshen team at http://www.twitter.com/aeshen

You can discuss this article using the adjacent Facebook talkback.

For technical questions please visit our discussion forums, where we have a vibrant community of developers like you, as well as Microsoft engineers who are ready to answer your questions!