Dec 17

Loading external libraries is a very effective method to minimize the application file size. Through it’s useful, I found that it’s seldom discussed in the Internet.

I learned this a few days ago and I think that it’s important to share it immediately to al of you.

In the sample below, I have implemented a host application where it will download the assembly made from my sample “Simple Game System“. Once the assembly is downloaded, the application can initialize a a specific class from the assembly.

Vote for this sample

Flash is Better? (45 votes)
Silverlight is Better! (192 votes)

Comparison

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

  • LoaderContext [AS3] vs AssemblyPart [C#]

Source codes

Flash

Silverlight

LoaderContext [AS3] vs AssemblyPart [C#]

In Flash, there is no dll file. However, once a SWF file is complied, you can actually utilize the resources inside the swf file. Here is a simple demonstration.

// AS3
var _assembly:Loader = new Loader();
var _loaderContext:LoaderContext = new LoaderContext();

// download the swf file
function download():void{
	var request : URLRequest = new URLRequest( SWF_PATH);
	_assembly.contentLoaderInfo.addEventListener(Event.COMPLETE, on_download_completed);
	_assembly.load(request, _loaderContext);
}

// create an instance from the resources
function on_download_completed(e:Event):void{
	var className : Class = _loaderContext.applicationDomain.getDefinition(CLASS_NAME) as Class;
	var displayObject : DisplayObject = new className();
	addChild(displayObject);
}

The approach in Silverlight is different. We are not going to download xap file as the assembly. Instead, will need to use the dll file generated form a project as the assembly resources.

// C#
WebClient downloader = new WebClient();
downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(onDownloadCompleted);
downloader.OpenReadAsync(new Uri(DLL_PATH, UriKind.Absolute));

// Once the assembly is downloaded
private void onDownloadCompleted(object o, OpenReadCompletedEventArgs args)
{
    try
    {
        AssemblyPart ap = new AssemblyPart();
        Assembly assembly = ap.Load(args.Result);
	UserControl control = (UserControl) _assembly.CreateInstance(CLASS_NAME);
	LayoutRoot.Children.Add(control);
    }
    catch (Exception e){}
}
Dec 01

Sometimes, your application may need to save the user state or progress for various purposes. Rather than storing the information to server, both technology provided a very convenient way to store some temporary data into user computer.

However, the storage has it own limit size for security reason.

Vote for this sample

Flash is Better? (70 votes)
Silverlight is Better! (196 votes)

Comparison

Flash implementation: 30 minutes
Silverlight implementation: 2 hours (Implemented First)
What’s the difference?

  • flash.net.SharedObject [AS3] vs System.IO.IsolatedStorage.IsolatedStorageFile [C#]

Default local storage limit

  • Flash: 100 KB (Can be adjusted to unlimited by user)
  • Silverlight: 1024 KB

Source codes

Flash

Silverlight

flash.net.SharedObject [AS3] vs System.IO.IsolatedStorage.IsolatedStorageFile [C#]

Using Local Storage is pretty easy in Flash. It’s because you only have to deal with the shared data as if local Object.

Please note that you have to call the flush() method after updating the object. Just to make sure it is saved into file system.

// AS3
// get the shared object
var so: SharedObject = SharedObject.getLocal(OBJECT_NAME);

// load data from local storage
if(so.data.text){
	TextArea.text = so.data.text;
}

// save data to local storage
so.data.text = "New Text";
so.data.flush();

In Silverlight, the local storage is actually a predefined path of storage directory. You can read and save data as if reading and writing files.

// C#
// load data from local storage
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
if(store.FileExists(FILENAME)){
	isfs = new IsolatedStorageFileStream(FILENAME, FileMode.OpenOrCreate, store);
	StreamReader streamReader = new StreamReader(isfs);
        string s;
	while ((s = streamReader.ReadLine()) != null)
		TextArea.Text += (s + '\n');
	streamReader.Close();
}

// save data to local storage
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(FILENAME, FileMode.OpenOrCreate, store);
StreamWriter streamWriter = new StreamWriter(isfs);
streamWriter.Write("New Text");
streamWriter.Flush();
streamWriter.Close();
Oct 23

This is a simple example demonstrating how to load an external image (not embed). It will also detect the downloading progress and illustrate it with the progress bar.

The source file size of Flash is much larger than Silverlight. It’s because I used many components in this application which result in a increase in file size.

Vote for this sample

Flash is Better? (144 votes)
Silverlight is Better! (160 votes)

Comparison

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

  • Loading Image: Loader [AS3] vs BitmapImage[C#]

Source codes

Flash

Silverlight

Loading Image: Loader [AS3] vs BitmapImage[C#]

The approach in detecting image loading progress in Flash is different to that of Silverlight. The image has to be loaded completely before you can add the image to stage.

// AS3
var urlRequest : URLRequest = new URLRequest(URL);
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, on_complete);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, on_progress);
loader.load(urlRequest);

private function on_complete(e : Event):void{
	// bitmap image
	var bitmap: Bitmap = loaderInfo.content as Bitmap;
}

private function on_progress(e:ProgressEvent):void{
	// e.bytesLoaded
	// e.bytesTotal
}

While in C#, you have to add the image to the stage for triggering the loading process. It seems that the you can’t detect the file size if you use BitmapImage to download the image.

// C#
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.DownloadProgress +=
	new EventHandler(bitmapImage_DownloadProgress);
bitmapImage.UriSource = new Uri(URL, UriKind.Absolute);
Image newImage = new Image() { Source = _bitmapImage };

void bitmapImage_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
	int progress = e.Progress; // 0 = 100

	if (e.Progress == 100)
        {
		// finish
	}
}
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.

Vote for this sample

Flash is Better! (115 votes)
Silverlight is Better? (111 votes)

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~