Google Analytics Results Silverlight 2 Released (What a bad news for me)
Oct 14

Dealing with HTTP Web Services in Silverlight is really difficult for me. Many Google search results will ask you to use WebClient and HttpWebClient. But most of them simply doesn’t work. Anyway, after many attempts, finally I got it working properly.

The samples below demonstrate how to submit POST Data and get the corresponding results.

I think Microsoft should really allow the VS to have a choice to ignore cross-domain restriction during development. (Flash has this feature). That will definitely save a lot of development time.

Comparison

Flash implementation: 20 minutes (Implemented First)
Silverlight implementation: 60 minutes
What’s the difference?

  • Submit HTTP Request: URLRequest [AS3] vs HttpWebRequest [C#]

Source codes

Flash

Silverlight

Submit HTTP Request: URLRequest [AS3] vs HttpWebRequest [C#]

Getting HTTP Resources in Flash is easy. It is because the sample code provided in Help Page always work.

// AS3
// Create a Request Loader
var loader : URLLoader = new URLLoader();
var request : URLRequest = new URLRequest(POST_ADDRESS);

// pass the post data
request.method = URLRequestMethod.POST;
var variables : URLVariables = new URLVariables();
variables.key1 = "value1";
variables.key2 = "value2";
request.data = variables;

// Add Handlers
loader.addEventListener(Event.COMPLETE, on_complete);
loader.load(request);

private function on_complete(e : Event):void{
	// do your stuff here
}

Actually, to be fair, I usually use the Flash approach to deal with HTTP Request in Silverlight. It may be the reason that makes me wasting a lot of time in implementation. Anyway, let’s see how to submit POST data in C#.

// C#
// Create a request object
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(POST_ADDRESS, UriKind.Absolute));
request.Method = "POST";
// don't miss out this
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);

// Sumbit the Post Data
void RequestReady(IAsyncResult asyncResult)
{
    HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
    Stream stream = request.EndGetRequestStream(asyncResult);

    // Hack for solving multi-threading problem
    // I think this is a bug
    this.Dispatcher.BeginInvoke(delegate()
    {
        // Send the post variables
        StreamWriter writer = new StreamWriter(stream);
        writer.WriteLine("key1=value1");
        writer.WriteLine("key2=value2");
        writer.Flush();
        writer.Close();

        request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
    });
}

// Get the Result
void ResponseReady(IAsyncResult asyncResult)
{
    HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

    this.Dispatcher.BeginInvoke(delegate()
    {
        Stream responseStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(responseStream);
	// get the result text
        string result = reader.ReadToEnd();
    });
}

Shares and Enjoy~

Did you like this post?

Subscribe here:  

12 Responses to “Flash vs Silverlight: Simple HTTP Post Request”

  1. timheuer Says:

    Actually for this particular sample, I think the use of WebClient in Silverlight would be much simpler and cleaner code to read.

  2. dave Says:

    One feature of the silverlight option with WebClient (much less code) is that you don’t have to let it be asynchronous, and since a post in most cases (for example a contact form, or what have you) from what would be encapsulated in a flash or silverlight app would likely not take very long anyway, you can do it synchronously and eliminate more than half of the code shown above. Flash just does it the asynch ‘callback’ way all the time. Both are perfectly acceptable for this task, and really, the amount of code is about the same for each. The only benefit I see to Silverlight in this case is that you don’t have a new language to learn, and you do your client side code dev in the same tool as your server side. However, the clients are more likely to have the flash plugin than the silverlight one, so you win once and lose once either way. I like both tools, personally, but I will concede that Adobe’s CS integration between their entire suite does make development for flash a bit simpler. There is integration with the microsoft tools, sure, but you have to do your design work in a particular tool, and you can’t really import it from any of your favorite tools you’d use to do non-silverlight design (like you can with flash etc.)

  3. AaronLake Says:

    instead of using:
    writer.WriteLine(”key1=value1″);
    writer.WriteLine(”key2=value2″);
    i got the post variables to go through using:
    writer.Write(”key1=value1&key2=value2″);

  4. Lalit Says:

    You are using Silverlight as if it were Javascript/flash. Therein lies your real problem. If you approach Silverlight with a fresh set of eyes/mind, Silverlight implementation would be much smaller, cleaner, faster to implement, and easier to read.

    I have programmed in all 3, and I must say that programming wise, I prefer Silverlight

  5. Simple HTTP Post Request | Silverlike - A Free Microsoft Silverlight 3 Directory Says:

    [...] coding below demonstrated how can post data to the target remote server. Terence Tsang also provided a simple sample letting you to search the feed items of your blog (Only works for [...]

  6. Ben Says:

    Lalit, you say there is a better way to do this. I searched at google a long time but still I haven’t found a good example which works. Do you have an example which is smaller, cleaner and faster to implement and easier to read?

  7. Shrikster Says:

    The Sad Thing is that both of them are the same ..
    Same approach to declertive UI,url requests,loading data… animation,even in video displaying ..
    Instead of steeling from each other or fighting who is better .. why not collaborate on exploring new approaches . deciding on some standards .. and mutual benefit from each other so for us developers it will be easier and for our clients to have the best applications…
    I use both (Silverlight and FLEX/FLASH) and they are more the same then they are different - even in your example the look ,act,and response the same..

  8. gugirugi Says:

    that is because silverlight like any other MS crap sux ass

  9. Lalit Says:

    @gugirugi.
    Aswesome dude/dudette! You rock! Now stop trolling and get a real job :)

  10. Flash ve Silverlight karşılaştırması | AdobeHaber Says:

    [...] Flash Silverlight Download [...]

  11. Stephen Says:

    Wow this is a terrible comparison in an attempt to make silverlight look bad. Kinda sad..

  12. oliver the trader Says:

    thanks for your article.
    How to create an HTTP post using flash AS2 ?

    thank you for your help

Leave a Reply