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();
    });
}
Sep 13

I have organized all my previous samples and grouped into the Gallery.

You may now access the Gallery via the Tab above or though the link below:

Flash vs Silverlight Gallery

Enjoy it~

Sep 11

This is a simple demonstration on XML Parsing. It’s a primitive knowledge and I added a drop down effect to make it looks much more attractive.

The Silverlight version can only load the XML from the resources. It’s because I don’t have IIS right now and I couldn’t solve the cross domain security problem (Better don’t waste too much time on that first). Enjoy it.

Comparison

Flash implementation: 1 hour  
Silverlight implementation: 1 hour 30 minutes 
What’s the difference?

  • XML Prasing: XML [AS3] vs XDocument [C#]

Source codes

Flash

Silverlight

XML Prasing: XML [AS3] vs XDocument [C#]

XML is a very difficult topic in many languages, because there are dozen of methods to manipulate XML. If you want to learn something more, here is a good site: http://www.senocular.com/flash/tutorials/as3withflashcs3/?page=4. Anyway, let’s have a brief view how did I get all the titles from a RSS feed.

// AS3
// create a loader and load the XML
var loader : URLLoader = new URLLoader();
var request : URLRequest = new URLRequest(url);
loader.addEventListener(Event.COMPLETE, on_complete);
loader.load(request);

// after the request is completed
private function on_complete(e : Event):void{
	var loader:URLLoader = e.target as URLLoader;
	var xmlData : XML = new XML(loader.data);

	var titleList : XMLList = xmlData.channel.item.title;
	for(var i:int = 0; i < titleList.length(); i++){
		var node :XML =  titleList[i];
		// get the title
		var title:String = node.text();
	}
}

You may use LINQ query in C# and the data can be collected easily (if you really know how to use it.)

// C#
// url is the xml data from the xap resources
XDocument xDocument = XDocument.Load(url);
var v = from g in xDocument.Descendants("item")
        select new
        {
            title = g.Element("title").Value,
        };

foreach (var item in v)
{
    string title = item.title.Trim();
}