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:  

28 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

  13. Geesh Says:

    Three lines of C# code:

    WebClient client = new WebClient();
    client.UploadStringCompleted+=new UploadStringCompletedEventHandler((sender,e)=>
    {
    string result = e.Result;
    });
    client.UploadStringAsync(new Uri(”http://some.server.com”), “POST”, “post=data&more=data”);

  14. Geesh Says:

    (That second line was kinda big, however ! hehehehe). Learn how it works and open your eyes to a real nice language - c#.

  15. oliver the trader Says:

    Thanks geesh…
    but this code is on C#… I need it for flash As2

  16. JR Says:

    Hi there. Great example. Just having trouble getting it running locally.

    Downloaded on VS2010 Windows7, hit F5, and got the following errror:

    {System.Reflection.TargetInvocationException: An exception occurred during the operation, making the result invalid. Check InnerException for exception details. —> System.Security.SecurityException —> System.Security.SecurityException: Security error.

    Any idea why?

    Cheers - Jonathan

  17. maximus Says:

    @JR, sounds like a cross-domain access issue. You need a clientaccesspolicy.xml file and should be fine. http://msdn.microsoft.com/en-us/library/cc197955(v=VS.95).aspx

  18. insomnia symptoms Says:

    published view of the topic. published it, i love to read thoughts that enlightening helpful anyway.

  19. Photoshop Says:

    As in the poem, I “hope your road is a long one, full of discovery, full of adventure.”

  20. Alanna Morten Says:

    This was novel. I wish I could read every post, but i have to go back to work now… But I’ll return.

  21. frenky Says:

    FWACi0 http://gdjI3b7VaWpU1m0dGpvjRrcu9Fk.com

  22. Ben Breland Says:

    I’m extremely impressed with your writing expertise as well as with the structure on your weblog. Is that a purchased idea or did you customise it yourself? Both way hold up the nice top quality creating, it is scarce to see a fantastic weblog like that one today.

  23. Flash vs Silverlight Gallery « Tam Quang Blog Says:

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

  24. Luna Says:

    Ребята , посоветуйте , кто знает или сталкивался.

    Хочу купить украшение с бриллиантом массой более карата, но понимаю , что это стоит очень дорого и мне не по карману.

    Но слышала , что есть облагороженные бриллианты, которые ничем не отличаются от обычных, но стоят дешевле в

    три раза.

    Кто-нибудь вообще держал такие в руках, они правда великолепны ?

  25. Lashon Locatelli Says:

    sama nie probowalam, ale rozmawialam z kumplem, ktory przy okazji ambitnej nauki do egzaminow;)postanowil sprawdzic brain wave generator wspomniany w tym artykule. podobno dziala. choc, jak stwierdzil, pomaga bardziej pod wzgledem pamieciowym, przy alnalizie - rozprasza. moze to kwestia indywidualna. powodzenia :)

  26. Lang Jimmison Says:

    I really required to create anyone An individual part of key phrase in order to lastly mention thank you cost-free all over again while using special concepts you may have supplied today. Might certainly generous on you for making unhampered what are the many you may have advertised for an at the direct to make quite a few gain in their own business, mostly seeing as you simply could have done the item inside special occasion you desired. The ideas in includeition difficult to turn to be beneficial technique to be aware that other individuals own equivalent eagerness the same as this private individual to learn extremely significantly additional connected for this establish a.

  27. c sections Says:

    thanks

  28. Zelegoawl Says:

    My partner and i don’t know about an individual individuals however for myself the format of the website is vital… I’d personally declare virtually as much as this content themselves. Moreover Now i’m ridiculous about videos… or even, goods simple fact, Any media content in any respect. Consequently, at any time My partner and i surf a similar write-up We simply want the actual OP embeds several Youtube online video media somewhere. Nowadays even though, a large amount of copy writers will not… I am unable to envision why?… My partner and i picture this may change conditional upon this content… However I nevertheless believe it would be well suited for practically any type of articles, as it would certainly be satisfying to determine a friendly as well as cozy deal with or even hear a new tone of voice to start with go to. Anyway, I suppose I’m a feel away subject using this type of?.. Precisely… That appears like it! He or she, They, They… We appreciate you enriching the world wide web using this type of placing!

Leave a Reply