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
Simple HTTP Post Request [Flash 9, AS3] (23.5 KiB, 4,554 hits)
Simple HTTP Post Request [Silverlight 2, C#] (844.2 KiB, 5,225 hits)
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();
});
}

October 14th, 2008 at 2:49 am
Actually for this particular sample, I think the use of WebClient in Silverlight would be much simpler and cleaner code to read.
July 21st, 2009 at 11:19 pm
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.)
August 31st, 2009 at 3:01 am
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″);
September 9th, 2009 at 10:11 am
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
September 28th, 2009 at 7:13 am
[...] 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 [...]
October 2nd, 2009 at 9:31 am
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?
November 5th, 2009 at 4:40 am
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..
February 3rd, 2010 at 10:19 am
that is because silverlight like any other MS crap sux ass
February 3rd, 2010 at 2:41 pm
@gugirugi.
Aswesome dude/dudette! You rock! Now stop trolling and get a real job :)
July 14th, 2010 at 2:40 am
[...] Flash Silverlight Download [...]
August 18th, 2010 at 5:11 am
Wow this is a terrible comparison in an attempt to make silverlight look bad. Kinda sad..
September 2nd, 2010 at 8:36 am
thanks for your article.
How to create an HTTP post using flash AS2 ?
thank you for your help
September 21st, 2010 at 7:16 pm
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”);
September 21st, 2010 at 7:21 pm
(That second line was kinda big, however ! hehehehe). Learn how it works and open your eyes to a real nice language - c#.
October 20th, 2010 at 4:53 pm
Thanks geesh…
but this code is on C#… I need it for flash As2
October 27th, 2010 at 3:54 pm
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
October 29th, 2010 at 6:30 am
@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
December 11th, 2010 at 9:45 pm
published view of the topic. published it, i love to read thoughts that enlightening helpful anyway.
April 3rd, 2011 at 11:19 am
As in the poem, I “hope your road is a long one, full of discovery, full of adventure.”
May 7th, 2011 at 1:09 pm
This was novel. I wish I could read every post, but i have to go back to work now… But I’ll return.
May 8th, 2011 at 2:50 am
FWACi0 http://gdjI3b7VaWpU1m0dGpvjRrcu9Fk.com
June 2nd, 2011 at 2:12 am
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.
June 3rd, 2011 at 11:37 pm
[...] Flash Silverlight Download [...]
June 5th, 2011 at 12:42 pm
Ребята , посоветуйте , кто знает или сталкивался.
Хочу купить украшение с бриллиантом массой более карата, но понимаю , что это стоит очень дорого и мне не по карману.
Но слышала , что есть облагороженные бриллианты, которые ничем не отличаются от обычных, но стоят дешевле в
три раза.
Кто-нибудь вообще держал такие в руках, они правда великолепны ?
June 23rd, 2011 at 7:42 am
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 :)
August 30th, 2011 at 9:54 pm
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.
September 24th, 2011 at 3:36 am
thanks
January 4th, 2012 at 4:29 pm
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!