Interfacing flash with dot net
Often you come across nice tutorials and comments on interfacing actionscript with php,ruby,java etc:
probably cause they are pretty much open source in nature. However not much is available over the Internet
on interfacing actionscript with dot net. Although its not a big deal but though many people like me would sometimes come across the need. Having said that, there are certain methods available to industry standards that implement open source dot net remoting like: fluorinefx and weborb dot net. However not taking things to that level of complexity, we will just discuss about the basic way of interacting with an asp dot net server script.
Tools:
1. Visual studio 2008 (you can use any version of dot net i guess
)
2. Flex Builder 3 (don’t worry about this being a flex example, its not, you can try it out in flash cs3/cs4 too)
3. Pre-requisite for asp dot net: IIS server should be healthy and running
Part 1: – Preparing the fontend
Fire Up flex builder and create a new project by the name: “Dot_net_communications”.
Next we create the user interface as we want to be able to show different aspects of data sending. We therefore create 5 labels and 5 buttons.
- “Say Hello” for string testing
- “calculate” for number testing
- “Send xml” for  xml testing (sent as string)
- “Send image as binary”
- “Send image as upload”
Now the code and some explanations:
import mx.controls.Image;
import flash.net.*;
import mx.controls.Alert;
import flash.utils.ByteArray;
import com.adobe.images.PNGEncoder;
//
private var __urlLoader:URLLoader;
private var request:URLRequest;
private var variables:URLVariables;
private var xml:String = '<main>sample data</main>';
private function sendToServer(param:*,operation:String):void
{
__urlLoader = new URLLoader();
__urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
__urlLoader.addEventListener(Event.COMPLETE, onComplete);
request = new URLRequest("http://localhost:4731/WebSite1/Handler.ashx");
variables = new URLVariables();
variables.data = param;
variables.operation = operation;
request.data = variables;
logger.text += '\n';
logger.text += "Sending "+param+" for "+operation;
logger.text += '\n';
try{
__urlLoader.load(request);
}catch(e:Error){
Alert.show(e.toString());
}
}
private function sendImageBinaryToServer(img:Image,operation:String):void
{
var bmp:BitmapData = new BitmapData(img.width,img.height,true);
bmp.draw(img);
var ba:ByteArray = PNGEncoder.encode(bmp);
__urlLoader = new URLLoader();
__urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
__urlLoader.addEventListener(Event.COMPLETE, onBinaryComplete);
request = new URLRequest("http://localhost:4731/WebSite1/Handler.ashx?operation="+operation);
request.contentType = "application/octet-stream";
request.data = ba;
request.method = URLRequestMethod.POST;
logger.text += '\n';
logger.text += "Sending "+img.toString()+" for "+operation;
logger.text += '\n';
try{
__urlLoader.load(request);
}catch(e:Error){
Alert.show(e.toString());
}
}
private function sendImageUploadToServer(img:Image,operation:String):void
{
var bmp:BitmapData = new BitmapData(img.width,img.height,true);
bmp.draw(img);
var ba:ByteArray = PNGEncoder.encode(bmp);
var urlRequest:URLRequest = new URLRequest();
urlRequest.url = "http://localhost:4731/WebSite1/Handler.ashx?operation="+operation;
urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = UploadPostHelper.getPostData("gita.jpg", ba, "FileData", null);
urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
__urlLoader = new URLLoader();
__urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
__urlLoader.addEventListener(Event.COMPLETE, onBinaryComplete);
logger.text += '\n';
logger.text += "Sending "+img.toString()+" for "+operation;
logger.text += '\n';
try{
__urlLoader.load(urlRequest);
}catch(e:Error){
Alert.show(e.toString());
}
}
private function onComplete(e:Event):void
{
__urlLoader.removeEventListener(Event.COMPLETE, onComplete);
logger.text += '\n';
logger.text += "Reply from dot net "+ e.target.data.response;
logger.text += '\n';
}
private function onBinaryComplete(e:Event):void
{
__urlLoader.removeEventListener(Event.COMPLETE, onBinaryComplete);
logger.text += '\n';
logger.text += "Reply from dot net "+ e.target.data;
logger.text += '\n';
}
// -
]]>
The function – “sendToServer” is called from three places by passing different values for parameters. for example when it is called with the parameters ‘Say hello’ and ‘reply’, we construct  a new URLLoader object for communication with server side script. Then we create a new URLRequestVariables object calles variables and attach the two parameters as two variables to it. We then set a asynchronous call to asp dot net with “__urlLoader.load(request)” command.
The same method is used to send number and xml (as string). why we use  two variables ? we will see when we have a look at the server side script.
Next the – “sendImageBinaryToServer” function is used to send binary data to server. we create URLLoader object just as we did before. But this time we are not sending variables. so we need not create the URLRequestVariables object. also note that – “ __urlLoader.dataFormat = URLLoaderDataFormat.BINARY” means we are specifically sending binary data which was  - “__urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES” previously.
We use the adobe corelib libraries to encode the image as a binary data. (if you want to read more on image encoding, refer here)
request.data = ba;
request.method = URLRequestMethod.POST;
we mention the content to be of other than text/variables. so the server knows the content type its dealing with.Then we send the data to server by the standard URLLoader , load method.
Finally we see the  - “sendImageUploadToServer” function which sends the image to asp dot net as a image upload. this requires you to use  the  UploadPostHelper class. This will be used to create the boundaries that need to be defined in a post header for a file upload to server.
urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = UploadPostHelper.getPostData("gita.jpg", ba, "FileData", null);
urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
The content type now tells the server that this is a file being uploaded as from the standard html file upload. We now build the binary data to be sent along with correct header information. The UploadPostHelper class builds the entire post body with necessary information for the server. We then push in the headers. and then call the load method of the URLLoader class. if you notice we are sending the second parameter as a HTTP GET Object by appending it to the query string. we do this because when sending binary data we cannot send variables by standard URLRequestVariables.
now that we are done here lets move on to see what goes on at server end….
Part 2: – Preparing the backend
In your existing asp dot net “web site” add a generic handler.
File > New > File > Generic Handler
This new file (handler) will be your url to target in URLLoader’s request url. This will process all incoming request from the front end we just made. now lets dig into the code.
using System.Web;
using System.IO;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string response="";
string operation = context.Request.QueryString["operation"];
switch (operation)
{
case "reply":
response = "Hi flash!";
break;
case "increment":
int num = int.Parse(context.Request.QueryString["data"]);
num++;
response = num.ToString();
break;
case "parse":
response = parseXML(context.Request.QueryString["data"]);
break;
case "binary":
BinaryReader br = new BinaryReader(context.Request.InputStream);
BinaryWriter bw = new BinaryWriter(new FileStream("c:/data.png",FileMode.Create));
bw.Write(br.ReadBytes(context.Request.TotalBytes));
bw.Close();
response = "binary recieved";
break;
case "upload":
context.Request.Files[0].SaveAs("c:/data_uploaded.png");
response = "upload recieved";
break;
}
context.Server.UrlEncode(response);
context.Response.Write("response="+response);
}
public string parseXML(string data)
{
return "parsed";
}
public bool IsReusable {
get {
return false;
}
}
when you add the new handler vs auto generates the ProcessRequest function. So we will be kind enough to write our code inside it
.
We initialize the response variable that we will send back to actionscript after we are done here.Now the “operation” variable that we sent by appending to query string becomes our key for selection. Means we use it to choose what needs to be done with the data using a simple switch case statement.
Note how we catch that parameter:
Note: This way we extract url variables sent from actionscript.
Now we analyse our switch case statements.
1. case 1 – says we just need to reply politely, so we set response to “Hi flash !” and come out of the switch case.
2. case 2 – says we need to increment this number. so we parse the data as a integer and increment it.
then we set response to the incremented number.
3. case 3 – says the data is binary so we ask dot net to read data directly from the inputstream.
next we initialize a writer for the binary data we are reading:
We then write the bytes that we read from the input stream.
Finally we close the writer’s stream and set response to “binary recieved”.
4. case 4 – is the simplest cause we know what we are looking for. so does dot net.
so dot net has a global files array in context of web. this is where it finds all the files uploaded.
so we simply take the first file in the array, as probably that’s ours cause we didn’t sent anything else. Then we save it to a location on disk with a name for it.and there we have it image received.
Finally we need to keep one thing in mind. actionscript will be expecting urlencoded stuff in return. so we need to urlencode the response variable before we return it.
then we reply back to actionscript:
Coming back to actionscript you may choose to display this data returned or use it …that’s up to you.
this was the basic of communicating easy to dot net without any gateway or remoting stuff. the best part you don’t need to have admin rights on server to do this.
Source code for this tutorial is provided here
August 27, 2009
Posted in: Actionscript 3.0, Dot net






Leave a Reply