Silverlight First Impressions

I’m a Flash & Flex Developer, and these are my first impressions of Silverlight. Silverlight is a rich media web browser plug-in that was recently released by Microsoft.

This is long. If you’re in a hurry:

…otherwise, just read the whole thing over coffee, beer, or pick a section.

Contents

Introduction

I felt the need to post for four reasons.

First, there are a lot of negative attitudes out there that I think potentially blind people from the cool technical features Silverlight has. Second, all the developer oriented posts written by people in Flash / Flex sphere are not as technical as I would like and wreak of Microsoft PR machine bs, or uber-idealism with no technical supporting data; well not enough for my taste. Engineers can be some mean, critical mofo’s and I’ve yet to see an article really rip into Silverlight from a technical perspective. Third, there are also some inaccuracies in the blog-sphere on how powerful Silverlight 1.0 is and what you can actually do with it compared to Silverlight 1.1. Fourth, my 3 4 5 6 day old (What frikin’ day is it!?) is finally asleep, but I can’t sleep.

Overall, I wanted to report my 3rd endeavor to learn Microsoft’s story on how they see this all working, and get a feel for the technology. To give some context, I am an Adobe kid; I use their design & development products in my career and for fun. I develop using Flash & Flex as a client architect at my full time job working at Multicast Media, a video streaming & Internet TV company. The views below, however, are my own and are not associated in any way with Multicast Media. We use a lot of technologies where I work, both client side and server-side such as PHP , Java, Ruby, C++, .NET, Flash, Flex, AJAX, and tons of HTML & JavaScript. I use both Mac and PC, and have drifted away from using Microsoft Office products on both machines now that I’ve become comfortable using Google Docs. I love to code, and love working with designers.

I am not an expert on Microsoft technologies, and am still a Silverlight n00b. I apologize for any inaccuracies below (feel free to correct me in the comments). These are my impressions.

TOP

What is Silverlight? My Version

Beyond being a browser plug-in to play rich media, Silverlight in my mind is definitely positioned as an application development platform for the web. In reading the SDK on how Silverlight works from a technical perspective, if she performs well under stress (hundreds of classes, code running combined with animation running without hiccups, code actually working as the docs say it does on both platforms), then I fully believe Microsoft has something really special here.

Don’t take my word for it; the 2 blog entries I found that were (mostly) not Microsoft lackey posts are from Richard Leggett, a very talented Flash Designer & Developer of both Flash and Flash Lite. Good stuff in the comments too. Another is from Satori Canton which he recently wrote to give a breakdown of what Silverlight really is and is comprised of. A sorely lacking blog post in the community, especially in the Flash in Flex sphere. Unfortunately, like them all, he’s too nice which makes me suspicious and angry because I want to know what sucks about it, where is it lacking, and what’s Microsoft’s story on improving those areas? Either way, both are great reads.

TOP

Here’s what I know, and like.

Silverlight 1.0 is a web plug-in that works on both Windows and Mac, and it works in Internet Explorer, Firefox, and Safari. Google Analytics used on users of a variety of my company’s products makes me not care. The data clearly is there to only need to support IE and Firefox; Safari’s a nice to have… for me alone, apparently.


Update: I still haven’t got the DLR & CLR parts totally correct yet; for better commentary, see the 3rd, 4th, and 5th comments at the bottom of this entry.

Silverlight 1.0 uses the JavaScript engine of the browser it’s in.

Silverlight 1.1 has will have a DLR, a Dynamic Language Runtime, that will run atop the CLR. This is similar to Flash Player’s ActionScript Virtual Machine, the AVM (AVM1, the one before Tamarin). As of today, you can write in JavaScript 1.0 style, from simple functions, to full blown classes via Object.prototype manipulation, similar to Flash Development circa Flash MX. This has some people excited because apparently enough of the DLR will be open sourced to allow other language implementations to compile to the DLR runtime, such as Ruby and Python. So, you can create animations and GUI’s in Silverlight and control them with code much like you did in the past in Flash using ActionScript 1.

TOP

The Silverlight DLR & CLR is not out yet; it is slated for the summer of 2008. This will be the release of Silverlight 1.1 which is currently in alpha. The CLR in .NET as I understand it is much like any runtime in taking bytecode or some other low level language and parsing/interpreting those instructions. Some are interpreted, some are compiled code. The way you get to that code is by compiling in Visual Studio 2008 (in beta currently called Orcas ). What is neat is that all the languages people currently use in .NET such as Visual Basic and C# can compile to compiled code, and thus the CLR. My guess is the speed increases one gets using the CLR vs. the DLR will be inline with what one gets using ActionScript 3 vs. ActionScript 2/1 in Flash Player. This is based on assumptions of seeing the online demo of TopBanana that Metaliq did, as well as my experience with reading about how you can only optimize dynamic, late bound languages so much compared to strongly-typed ones.

There are no native component sets for Silverlight 1.0. Building things in Silverlight currently is perceived by me as building things in Flash 4/Flash Lite. From scratch, each time, and small enough in scale because of your 1 week or less deadline. Hence, no need for a component framework. While I think this is just fine for a lot of design agencies looking to spruce up their usage of Windows Media as separate design elements on their branded portals, it’s frikin ‘ worthless to developers who want to start building something today. Building components frameworks are a lot of time & work.

TOP

Silverlight has a display tree much like Flash Player 9’s DisplayList. You can have display objects all attached to each other ( a Button control with a TextField attached to it). This is great because you can create GUI elements without them having to exist on the display tree, and thus drawn taking up CPU & RAM. This helps both Silverlight’s creators because they make sophisticated, efficient frameworks around this model, and it’s great for developers because they can not worry about the designs scaling if they have a bunch of screens.

Silverlight is built upon XAML. XAML looks and feels like XML, and is very low level. It’s low level because this is the XML that is parsed into machine instructions for WPF. XAML , however, is not software or hardware, it’s just an XML format, nothing more. You can edit it Notepad or any text editor, and easily create it in Design and Blend.

TOP

Comparing it to Flex’ MXML is really hard to do. MXML is very high level. The point of MXML is provide an easy way to build GUI’s with all the good things XML has to offer. It’s very high level, and abstracts a lot. This is good because the less code you have to write to get something done, the better in my opinion. Looking at the Silverlight / AIR / JavaFX Stopwatch example (HTML version here), you can definitely do custom controls, but they don’t seem to be built into the language as well as MXML is. The benefits of XAML , however, is you can pretty quickly (assuming you can find where the heck you’re going) change very low level properties on your XML document from the x position of an element to the 206th curve of a vector spline in a design.

It gets really interesting with animation. Unlike Adobe Flash which has a timeline, XAML has timelines, aka, plural. Each one is created for a property and/or object you can manipulate over time, and thus it’s a different type of timeline. So while Blend and Flash both have a timeline panel, Blend’s XAML is writing a specific type of timeline in XAML based on what you are actually animating. These can exist either as part of a set of objects, say a custom rectangle you built that immediately moves itself, or as a set of animations you can apply later. Flex has something similar with transitions which can be abstracted away from the GUI they are animating, much like XAML. So, to me, they got this part extremely right. The GUI’s responsible for creating and editing those timelines, however, suck. Blend’s animation timeline should just copy After Effects‘ and get it over with. I told Samuel Wan this over a year ago in Beta 1 of Blend, wtf. Either way, I still love time based, non-destructive timelines like After Effect’s has using key frames as more formal objects.

TOP

Most interesting of all is Sliverlight’s setup. In Flash & Flex, you make a SWF and shove it up to a web server with associated JavaScript to embed it in an HTML file. The tools usually generate these for you. In Silverlight, you don’t compile anything for using the DLR. You just upload your Silverlight.js file, a CreateSilverlight.js file, your own JavaScript, your XAML files, and your own HTML. All ASCII based. While this is irrelevant at development time because you can have an all ASCII based setup using Flex and Flash for source control, you cannot easily screw with SWF applications at runtime. Since SWF’s are binary files, you cannot simple open them in Notepad to see how they are made. My favorite new feature in Flex 2 allows you to easily publish your source code for all to see. In Silverlight using the DLR, this is native and allows tools like Greasemonkey to actually change the way Siverlight applications work at runtime, even ones that you didn’t create. You cannot do that easily using SWF’s mainly because of the strict cross-domain sandbox policies, and it’s next to impossible in ActionScript 3 SWF’s since you can’t hack the prototypes of the loaded classes.

Silverlight has an event model as well for all it’s display objects. Some of these events do event bubbling just like ActionScript 3 does. The JavaScript implementation is ok for writing an event handler, a function that receives the event. Your first parameter is the dude who sent the event, and the second is the arguments. ActionScript 3 has formalized this into 1 parameter only as a class that extends flash.events.Event. I agree with Silverlight 1.0’s implementation as it’s lighter weight, and you don’t need bloody classes when your trying to keep your applications’ file-size low. I despise the event registering, though. In Flex, you can opt-in to pass parameters to the event handler, effectively doing your own delegate like so:

TOP

This:

<mx:Button click=”click(event, ‘moo goo’)” />

Becomes this:

private function clickListener(event:Event):void

{

      click(event, 'some str');

}

Which at runtime will then call the function I defined when I click the Button:

public function click(event:Event, someStr:String):void

{

      throw new Error("someStr: " + someStr + ", event: " + event);

}

TOP

XAML is not compiled in the DLR, thus there is no code generation going on. I fail to see how Microsoft could do code-gen in the DLR, but they have no excuse to not have this ability in the CLR. Then again, there are 50 billion closet C# guys in the Flash world, so I’m sure they’ll be itchin’ to tell me how C# already has a better way, blah blah blah.

Bottom line, all you can do in XAML itself is someEvent=”someFunction”. Obviously you can do more in the code behind JavaScript. So, compared to MXML, XAML isn’t very flexible in this respect.

TOP

The mouse and keyboard events are pretty standard.

Fonts are neat, although, cumbersome. If you’re a Flex Developer, imagine not having a SWFLoader or Image component in the Flex SDK; that pretty much describes what the Downloader is used for in regards to font files. You have to manually download the font, whether a file or in a zip, and once downloaded you can then apply the font to text objects. It takes only 5 lines to download the font, and 1 to apply it, but still, this is all stuff developers are going to be writing; you might as well create a set of framework classes that simplifies these common needs for them. Either way, light years better than Remote Shared Libraries and font wars that last long into the night when using Flash/Flex. Assuming it works as advertised; haven’t used the feature.

It has full screen support, just like Flash Player 9.0.28.0.

It also has Ink support (aka stylus, pen input from tablet pc’s).

The last feature is that videos still support their embedded text tracks and time-codes. This allows messages to be played through the video at certain times, and JavaScript can handle these messages. It’s like cue points in Flash’s video players, or embedded NetStream events when you use Flash Media Server. The reason this is important is that those script tracks never worked well on the Mac. Thus, massive kludge code was written to poll the server if you were building synced slide web software for example. Nasty stuff. Now, Silverlight has this functionality working like it should on both platforms… so we’re told.

Linux has a version that seems to actually have Microsoft’s support called Moonlight.

TOP

Install Experience

When I tried the Beta 2 version of Silverlight on my Mac, I had pretty much the same experience as Sean Corfield. However, while I have seen 2 blog posts about Windows developers having issues installing the plug-in, I’ve been very impressed about the final release installation experience on both Mac and PC. It just works. That was one of the secrets to Flash Player’s early success, and was echoed by the swath of traditional developers who explained on their blogs why they chose Flex.

It needs to work for everyone, though, not just me.

TOP

Documentation

I installed the Silverlight 1.0 SDK, and read the entire .cfm file, stopping at the API. I glanced over the API to ensure it matched up with what I read, and it did for the most part. I found the documentation really good in explaining how Silverlight works. The fact Silverlight has changed so much from it’s early Alphas, Betas, and then final release made it have a few minor addendum’s that clearly spelled out corrections to earlier documentation. I did not read the earlier documentation (whatever was published at MIX 2007), so just took it at face value. These were usually in regards to performance bottlenecks and how to avoid them. While this is really cool to have that level of detail, and to ensure first apps built with Silverlight don’t get a bad rap for some developer who didn’t read the updated documentation, it wasn’t in depth enough. I want technical details like I can get from a variety of sources like Flash Player.

TOP

Business Decisions

The reason I even care about Silverlight is two fold. First, I wanted to learn something new.

Second, Windows Media doesn’t suck. Where I work, a huge portion of our customer base uses Windows Media streaming technologies, both live streaming and progressive using CDN’s. Yes real streaming, not fake streaming, hehe, nice on Ted. While the customer base is currently asking for Flash because it’s the latest greatest, there is no reason tomorrow they won’t start asking for Windows Media again, or even Quicktime when Apple fixes their severely broken Quicktime PR arm. Since we are in the business of video streaming and software solutions around them, it is in our best interest to know the ins and outs of all architectures… yes folks, even Real for the mere point of ripping it apart intelligently. Silverlight is not a video architecture like Windows Media Player; it’s an interactive runtime that allows you to create rich experiences with your Windows Media content. I’d argue Flash can do it better, not just from a technical angle, but from a community one. Keyword contraction “I’d”; I’m still learning, so while I doubt I’m wrong on the community angle since I don’t really hear much about people like Hillman Kurtis winning design awards for using Design/Blend/Silverlight together, it doesn’t mean I won’t be in the future. This is brand new software, barely out of the oven. I’m still learning Silverlight too, and Blend specifically; it took me years to get good at Flash & Flex, so I know it won’t happen overnight.

It also won’t happen without a project, either. While I’ll definitely do the responsible developer thing, and learn on my own personal projects at night, I do so knowing it’s not a waste of time. Clients will come a knockin’, I’m sure of it.

TOP

Further Validations

Silverlight has valid set of business needs. Previously, there was no easy way to brand Windows Media content easily online like you could with Flash. Now their is and to great effect. Designers can treat Windows Media content just like they can with Flash; as part of the page, not a “thing unto itself”. Granted, it’s still a plug-in, so things aren’t perfect, but plug-ins exist because browser evolution is too slow to do what businesses need to do today. One of those needs is to have a 100% branded image on some projects where millions were spent to ensure that customers are not confused about the brand image they are seeing. It’s really frustrating leading a design team to implement a new site, and customers mention in blogs “so and so brand used Microsoft video”. Dammit! No we didn’t, we used OUR video, for OUR brand! Silverlight remedies this. My video, my controls, all you need to do is design a video player around your brand, and you can then use Silverlight to show Windows Media as you want it to look and feel.

If you didn’t know, there was some hub-bub about a lot of online viewers petitioning the BBC to convert a lot of their online content to Flash solutions to better support audience needs. I use Flip4Mac WMV Player on my Mac, but it doesn’t work very well, so I definitely know what these audience members are talking about. Compare to CNN.com, and it’s pretty blatant.

TOP

The BBC’s retort was quite cool, actually. They said, no and explained why they couldn’t. Mainly, it was too expensive to remove all the massive investments they had made in Windows Media to just switch it over to Flash. They then put the ball in the communities court to help them figure out a way. I never really heard the resolution to this story, but I’ve heard derivatives before. For example, a company I work near has a box they send customers. This is an encoder box, and it streams Windows Media streams live, and later uploads them to be viewed progressively later. The amount of hardware & software development and testing, both client and server that went into that setup is immense. To just “start doing Flash” is unrealistic. One needs to consider the costs and the technological validity. These are 2 scenarios, one of which I can personally attest to, where Silverlight allows those who have invested serious capital into Windows Media to capitalize on it.

TOP

Silverlight 1.0 vs. 1.1 (aka, DLR vs. CLR)

While my exposure to the .NET blog-sphere is next to null, and those I’ve talked to in person and read about seem fine with either the DLR or the CLR. As long as Visual Studio 2008 supports the developer with code hinting, and other commonly accepted code tools, then a few don’t really seem to care if they are using JavaScript or C#. I don’t buy that in the long term, though. I think the .NET guys are just being patient. What I think will happen is the web geeks and the agencies will use the thenDLR, and all the .NET software shops will use managed code.

For the latter, I thought that the .NET guys would have the same problems that the traditional programmers who came to the Flex world would have with leveraging rich media. I was partially wrong. They all picked up Flex really quickly, were passionate, and are now producing a lot of great Flex work, both public, but mostly behind the firewall. I still get some emails requesting design talent for Flex specific projects which make me really happy to know that these software shops, once they see what’s possible, appreciate what good design can bring to the table. I’ve worked with some .NET’erz in my time at a large agency and at a mid-size software shop, and now at my new job. They all have appreciated good design. There is no reason these people, who have the tools, cannot do the same the non-.NET crowd did (Java/Ruby/ColdFusion, etc.) with Flash and Flex.

TOP

My concern stems from the fact that Design & Blend are 1.0. I’ve messed around only briefly with Design and it worked for me. My litmus test is if you support PNG, you get a passing grade right off the bat. However, supporting PNG and having industry standard design tools such as the Adobe & Autodesk suites are decades apart, both in software evolution and community evolution. Can a community really form around these design tools to push Silverlight in a direction it needs to go? Where does it need to go? Well, to me, it needs to go where Flash goes; pushing limits of designs, pushing web application envelopes.

I just feel like the .NET crowd is setup to fail with the design tools that Microsoft has provided. It does mean the tools are bad, nor that the .NET crowd is incapable of laying the visual funk. Rather, a DESIGNER has to learn those tools. The tools are new; they’re not like Photoshop which have gigantor communities and followings; atmospheres, attitudes, histories. That is a lot of ramp up time in an industry that already has Silverlight playing catch-up. Maybe more money will make it evolve faster?

TOP

What Sucks

If you view the tutorial videos on Siverlight.net, there is a WPF slant. The marketing Microsoft originally had made it sound like Sparkle (first of 2 Silverlight alpha/beta names) was this ground roots effort done in tandem with the WPF. However, after reading the docs, and using the tools, Silverlight seems extremely reactionary. Meaning, I believe that when you show me a video about using Blend about how I can create interfaces for Windows Vista programs, yet you place this video in the Silverlight tutorial section, this is misleading and contributes to the “reactionary” perception. Either you’re trying to leverage my Silverlight experience to create Windows Vista Destkop Applications for the same bizarre reason Adobe thinks we need to port well and good web apps to the desktop, or you’re low on content that shows how Blend can be used as an interface tool for creating web applications in Silverlight… because Blend is not a tool for creating web interfaces in Silverlight. Or both.

Heck, maybe it is. Maybe both Design & Blend are truly meant for building both desktop applications and web applications. You can do the same thing with Flex and Flash, so I can see the idea flying. Regardless, when Microsoft mention things in the SDK like “supporting most of XAML in Silverlight”, it only hammers home more of the idea that Silverlight was built atop WPF later rather than a tandem effort like the WPF/E original beta name tries to lead you in.

TOP

The lack of coding tools that work out of the gate, easily, is pretty bad. I never got Visual Studio 2008 (Orcas Beta 2) to actually work after downloading the 4 gigs twice in 1 weekend with the Silverlight JavaScript. I mean, if Aptana can do it in Eclipse, why can’t this greatest IDE on the planet I keep hearing about do it? I know it’s beta, so it’s all good, just curious. Just because I use a late bound language doesn’t mean I don’t like code hints. Besides, these things help me learn!

Blend’s timeline is bleh. It doesn’t mean it isn’t intrinsically good or powerful, but rather, my expectations from other tools such as After Effects, Flash, and Live Motion carry over to Blend. Maybe once I learn it, it’ll rock the mic. Once I found the bloody thing in Blend, I figured it out pretty quickly. The concept of an embedded animation vs. a resource was really hard to wrap my head around in the actual XAML syntax. The actual concept, though, makes perfect sense. MovieClip animation vs. a Flex transition tag; one is part of the object, the other can be borrowed. Got it. Uh… so… like, I don’t know, it seems to me that this should kind of be an important part of building RIA interfaces. Why not make this more a prominent part of the workflow? I don’t really know Silverlight workflow yet, so who knows. Flex Builder currently doesn’t have a very good one for transitions; states are good, but not animations. It seems both tools could improve on this front. Then again, Flex developers do just fine without them, so, maybe Microsoft thought it was acceptable since Adobe didn’t put it inFlex Builder . Glorious assumption, I know. Bottom line, I’d prefer Blend have their keyframe editing in place like After Effects does rather than having to use the global property inspector for everything. Relevant property inspectors on the timeline, not in a far away panel.

TOP

I know Blend isn’t really Silverlight, merely a tool in which you can create GUI’s for Silverlight. However, the end result is greatly affected by the tools used to create it. As such, improvements in Blend will have a direct impact in improvements in Silverlight content. For example, an under-utilized, yet powerful feature in Flex is transitions. If Flex Builder is improved in future versions, Flex content will be a lot better. The functionality is already there, it’s just tedious to create, not easy to undo, and thus hard to get “just right”. Same holds true for animating in Silverlight . Maybe if I did a full blown project, I’d change my mind. I just had high expectations from Beta 1 to Beta 2, and it doesn’t seem like much changed on that front.

There are no component frameworks that come with Silverlight. I’m sure some third party is nearly done based on the blogs I’ve read. For now, that doesn’t make Silverlight 1.0 valuable for large scale applications. Video players, however, that make Windows Media look good don’t need to be enterprise scale, so maybe that’s why. My guess is those types of things will be more polished in 1.1.

TOP

Conclusions

At the end of it all, Silverlight deserves more research. The biggest challenge for me is how to build a component framework around the createFromXaml method. In ActionScript 3, you can do:

var t = new TextField();addChild(t);

In Silverlight 1.0 JavaScript, it’s:

var xaml = "<textbock text='test'>";text = plugin.content.createFromXaml(xaml);

object.children.add(text);

Assuming you can create custom components this way, then I guess we’re off. If you read the SDK, the properties and methods are pretty easy to follow. I think Microsoft really has something here. Whether they do or not doesn’t really matter, though; there are tons of people who aren’t leaving Windows Media without spending mad bling, and Silverlight’s induction will help ease those frustrations. I think you’ll continue to see some losses in the Windows Media market as Flash continues it’s rise, but once Silverlight 1.1 gets out of beta, and more managed code applications come out of the woodwork, I’m sure the tide will change; or maybe not. I don’t care, I’m just glad Flash finally has some competition on the horizon.

In the interim, I know I’ll have Silverlight project soon, namely a customizable video player. There are tons of Flash jobs right now around building custom video players, and soon there will be more for Silverlight ones. A lot of video customers ask for Flash video by name. I have a feeling once the Microsoft marketing engine kicks into high gear, they’ll start to ask for Windows Media again, or even just “Silverlight”, not really knowing what it is, but they’ll have money proving they want it. Besides, there are a lot of people out there already who are deeply into Windows Media; it’s not going away, and Silverlight gives them all the opportunity to have better offerings. In short, that’s cool!

TOP

Flash Media Server 3 Feature Requests

Steve Wolkoff, Flash Media Server Product Manager, is asking the community for feature requests for the next version of Flash Media Server. I’ve put my comments there, but wanted to post them to myblog as well for reference.

1. A Remote SharedObject version with different licensing.

I don’t want video, I don’t want audio. I just want server-side scripting with Remote SharedObjects. I shouldn’t have to pay for things I’ll never use. There are a lot of multi -user, real-time data applications I’d like to create, and FMS is the best technology for those apps compared to XMLSocket, and yet to be released Binary socket alternatives. I’m down with Red5, but not all my clients will be.

It’s about empowering smaller markets. Think After Effects vs. Combustion / AVID; or Ruby on Rails vs. Java’s Spring & Hibernate. There is a lot of room for smaller scale, quicker to market applications that need the insane power FMS has in it’s data part. These apps don’t need video and audio.

If it’s a new product, so be it.

2. Streaming 3GP.

Being forced to use RealPlayer for streaming 3GP via Flash Lite is an f’ing joke. Give us an integrated solution! Or… I’ll keep RealPlayer on my phone, but at least allow the server to progressively stream them so I can not pollute my server. The reverse is true as well. 3GP conversion to FLV would allow better integration with this format from devices to desktop translation. A lot of weird, zombie-rific “solutions” are out there to allow clients to use cellphone video to be used on the web. 3GP to FLV server-side conversion could really be a nice niche here.

3. Backwards compatibility on Server-Side Scripting.

I’ve seen a lot of people ask for ActionScript 3 support, or even a move to a “mature” or “enterprise” language like Java. Whatever. Rhino’s ECMA 3 thing works great for me. If you move to a new language, fine, but keep it so I can still code in case-sensitive JavaScript like I have been. If you can’t expose the same API’s like they do for Flash 8 & 9 via AS1, AS2, and AS3, that’s fine; just make it so my old server-side code works in FMS 3. If not, at least allow some sort of scripting engine like .NET’s CLR where we can code in whatever we want.

4. SMS – Text Message Support

I’ve seen people wanting some form of VOIP bridge. It’d be nice to have some form of API for SMS too. If this is traditionally the forte of middle-ware, no problem.

Flash Media Server, Flex Builder 2, and ANT

Developing Flex 2 applications that talk with Flash Media Server is really fun.  I’m sure Adobe will tell you that Flex Data Services are the way to go, but that is overkill for a lot of the things I want to do.  If you want to create a set of widgets that support multiuser activity such as chat and sharing of real-time data, you don’t need the Enterprise data services that are FDS.  While Flash Media Server has real-time video and audio, I use it strictly for the real-time data via Remote SharedObjects , and the server-side scripting done in case-sensitive JavaScript.  The persistent data of Remote SharedObjects with a simple, yet flexible coding model makes them a very powerful way to get multi-user Flex 2 applications.  Combined with some simple server-side logic to maintain “data authority” as I like to call it, and you’ve got a really fun way to create real-time data, mult-user apps.

What are the alternatives?

XMLSocket ?  Parsing XML is more programmer friendly now with E4X, ECMAScript for XML , in ActionScript 3.  XMLSocket servers do not enforce XML, however… they are merely string servers that run on ports of 1024 or higher, thus making them flexible.  The cons?  They run on ports 1024 or higher… ONLY.  Client got a firewall?  Tough.  There are not a lot of big name XMLSocket hosting services.  Those that are out there are extremely expensive for what you get.  While the hosting might not be expensive, the license fee’s are.  A lot of the open source solutions aren’t finished.  Those that are assume you know PHP, Ruby, Perl, or Python well enough to finish it.  Assuming I could, where do I host these servers?  My host isn’t going to dig me having a PHP script stuck in a while loop…

FDS?  Sorry, can’t afford 60k for fun side projects that have the potential to go to extremely small commercial markets.

Some other TCP/IP binary server?  I’d like to create things today instead of getting burnt out writing something from scratch in ActionScript 3’s binary Socket API.

It’d be nice if Adobe would release a Remote SharedObject server, complete with server-side JavaScript on a totally different pricing and license scheme than Flash Media Server or Flex Data Services are.  There are a lot of use developing mulit-user Flash Player applications on FMS that have no need for real-time streaming video and audio.  I think the same crackheads that ran pre-Flex 2’s business unit took over Flashcom’s.

At any rate, there is no denying FMS is elegant to code with.  With a little work via the Observer pattern , you can implement FMS server-side components into Cairngorm 2 .  For ever server-side component you create, you merely create a client side equivalent as an Observer.  It listens for NetConnection or Remote SharedObject sync events and dispatches events.  These events run Commands which in turn set data… just like normal.  If your Views are bound to said data, boom, you’ve got a nice, clean separation.

One thing that sucks about the work flow, though, is:

  • you have to redeploy your .asc files, your server-side code (basically JavaScript written server-side components)
  • you have to restart your app via the Communication App Inspector, basically a small app written in Flash
  • you then toggle back to Eclipse (Flex Builder 2 )

That sucks.  The better way is to use some ANT tasks I’ve created along with a special SWF.  This SWF connects to the FMS Admin server, reloads the app, and then immediately quits.  I go into more detail below, or you can just download the source.  You could re-write the ActionScript 2 into ActionScript 3, but AS2 is just quicker than AS3 for this type of stuff.

Bottom line, you just double-click an ANT task in Eclipse, it does all that for you, and you don’t have to leave Eclipse.  That’s so hot!

First, the ANT tasks.

<project name=”DnDTools” default=”Deploy FCS” basedir=”.”>
   
    <description>
    by Jesse R. Warden
    jesterxl@jessewarden.com
    https://www.jessewarden.com
    jesse@universalmind.com
    http://www.universalmind.com
   
    A series of tasks to work with Flashcom.
    ************************************************   
       
    Start Flashcom will write out a bat file, and run it to start
    Flashcom as well as the Flashcom Admin service.
   
    Stop Flashcom stops both the Flashcom service and the
    Flashcom Admin service.
   
    Deploy FCS does a few things:
    * copies your .asc files to the FCS applications directory
    * writes a configuration XML file for the FCS App Reloader
    * runs the FCS App Reloader to reload your application instance on the FCS server
   
    </description>
   
    <!– ************************************************ –>
    <!– set global properties for this build –>
    <property name=”bin” value=”bin” />
    <property name=”localFCSDir” value=”../flashcom”  />
    <property name=”deployFCSDir” value=”C:\Program Files\Macromedia\Flash Communication Server MX\applications\fcsappdirectory” />
    <property name=”FCSAppReloader” value=”FCS_App_Reloader.exe” />
    <property name=”FCSAdminHost” value=”localhost” />
    <property name=”FCSAdminPort” value=”1111″ />
    <property name=”FCSAppName” value=”fcsappdirectory” />
    <property name=”FCSAdminUser” value=”myUsername” />
    <property name=”FCSAdminPassword” value=”myPassword” />
    <property name=”appWaitTime” value=”3″ />
    <property name=”bat” location=”bat” />
   
    <!– Copy files into the FCS app directory, write a config xml, and reload an FCS app –>
    <target name=”Deploy FCS”>
       
        <!– ************************************************ –>
        <!– Copy new FCS files to the applications directory –>
        <echo message=”Copying Flashcom files to application directory…” level=”info” />
        <copy file=”${localFCSDir}/Application.xml” todir=”${deployFCSDir}” />
        <copy file=”${localFCSDir}/asc/main.asc” todir=”${deployFCSDir}” />
        <copy file=”${localFCSDir}/asc/Chat.asc” todir=”${deployFCSDir}” />
       
        <!– ************************************************ –>
        <!– Write the config xml file for the FCS Reloader App –>
        <echo message=”Writing FCSAppReloader configuration xml file…” level=”info” />
        <!– Host –>
        <echo message=”&lt;config host=’${FCSAdminHost}’ “
            file=”${localFCSDir}/fcs_app_reloader_config.xml” />
        <!– Port –>
        <echo message=”port=’${FCSAdminPort}’ “
            append=”true”
            file=”${localFCSDir}/fcs_app_reloader_config.xml” />
        <!– App Name –>
        <echo message=”appname=’${FCSAppName}’ “
            append=”true”
            file=”${localFCSDir}/fcs_app_reloader_config.xml” />
        <!– Username –>
        <echo message=”username=’${FCSAdminUser}’ “
            append=”true”
            file=”${localFCSDir}/fcs_app_reloader_config.xml” />
        <!– Password –>
        <echo message=”password=’${FCSAdminPassword}’ “
            append=”true”
            file=”${localFCSDir}/fcs_app_reloader_config.xml” />
        <!– Hang Time –>
        <echo message=”hangtime=’${appWaitTime}’ /&gt;”
            append=”true”
            file=”${localFCSDir}/fcs_app_reloader_config.xml” />
       
        <!– ************************************************ –>
        <!– Launch the FCS Reloader App –>
        <echo message=”Re-loading the FCS application…” level=”info” />
        <exec executable=”${FCSAppReloader}”
            dir=”${localFCSDir}/”
            spawn=”false”
            resolveexecutable=”true” />
       
       
    </target>
   
    <target name=”Start Flashcom”>
       
        <echo message=”Starting Flashcom…” level=”info” />
        <mkdir dir=”${bat}” />
        <echo file=”${bat}/start_fcs.bat”>%SYSTEMROOT%\system32\net.exe start &quot;FlashCom&quot;
               
        </echo>
        <exec executable=”start_fcs.bat”
            dir=”${bat}”
            spawn=”false”
            resolveexecutable=”true” />
       
    </target>
   
    <target name=”Stop Flashcom”>
       
        <echo message=”Stopping Flashcom…” level=”info” />
        <mkdir dir=”${bat}” />
       
        <echo file=”${bat}/stop_fcs.bat”>%SYSTEMROOT%\system32\net.exe stop &quot;FlashCom&quot;
       
        </echo>   
        <echo message=”%SYSTEMROOT%\system32\net.exe stop &quot;FlashComAdmin&quot;”
            append=”true”
            file=”${bat}/stop_fcs.bat” />
       
        <exec executable=”stop_fcs.bat”
                    dir=”${bat}”
                    spawn=”false”
                    resolveexecutable=”true” />
       
    </target>
   
</project>

Now, the ActionScript 2 for the FCS Reloader App:

/*

FCS App Reloader
by Jesse R. Warden
jesterxl@jessewarden.com
http://www.jessewarden.com
jesse@universalmind.com
http://www.universalmind.com

This is release under a Creative Commons license.
More information can be found here:

http://creativecommons.org/licenses/by/2.5/

v 1.0.0
This app connects to your FCS server, and reloads
an application instance.  The typical use case is to
launch this app from ANT in Eclipse.

The alternative is to:
- toggle to the Communication App Inspector
- click the app instance and click "reload"
- if it's not there, type in it's name, and then click "load"
- toggle back to Eclipse

Now, you can just click once on your ANT task, and you're done!

This API assumes Flash Communication Server 1.0 and Flash Player 6.
I tested this in Flash Player 8, and the API should work
in Flash Media Server 2 per the livedocs.

*/
import mx.utils.Delegate;

function init()
{
	Stage.align = "TL";
	Stage.scaleMode = "noScale";
	Stage.addListener(this);
	
	createTextField("debug_txt", 0, 0, 0, 100, 100);
	debug_txt.background = true;
	debug_txt.backgroundColor = 0xFFFFFF;
	debug_txt.border = true;
	debug_txt.borderColor = 0x000000;
	debug_txt.html = true;
	debug_txt.multiline = true;
	debug_txt.selectable = true;
	debug_txt.wordWrap = true;
	var fmt:TextFormat = new TextFormat();
	fmt.font = "Verdana";
	fmt.size = 11;
	debug_txt.setTextFormat(fmt);
	debug_txt.setNewTextFormat(fmt);
	onResize();
	
	debugHeader();
	debug("Loading config xml...");
	
	NETCONNECTION_CALL_SUCCESS = "NetConnection.Call.Success";
	CONFIG_XML_FILE = "fcs_app_reloader_config.xml";
	
	TIMEOUT_WIDTH = 100;
	TIMEOUT_HEIGHT = 12;
	config_xml = new XML();
	config_xml.ignoreWhite = true;
	config_xml.owner = this;
	config_xml.onLoad = Delegate.create(this, onConfigLoaded);
	config_xml.load(CONFIG_XML_FILE);
}
function onConfigLoaded(success:Boolean):Void
{
	debugHeader();
	if(success == true)
	{
		debug("Config XML loaded, parsing...");
		var at:Object 		= config_xml.firstChild.attributes
		theHost				= (at.host == null) ? "localhost" : at.host;
		thePort				= (at.port == null) ? "1111" : at.port;
		theAppName 			= at.appname;
		theUsername 		= at.username;
		thePassword			= at.password;
		theHangTime			= (at.hangtime == null) ? 3 : parseInt(at.hangtime);
		if(isNaN(theHangTime) || theHangTime < 0 || theHangTime == null) theHangTime = 3;
		var tabs:String = "\t\t\t\t";
		debug("host: " 			+ theHost);
		debug("port: " 			+ thePort);
		debug("app name: " 		+ theAppName);
		debug("user: " 			+ theUsername);
		debug("password: " 		+ thePassword);
		debug("hang time: " 	+ theHangTime);
		
		connect();
	}
	else
	{
		debug("Failed to find " + CONFIG_XML_FILE + ", aborting.");
		lightFuse();
	}
}
function connect()
{
	debugHeader();
	debug("Connecting to FCS Admin...");
	
	nc = new NetConnection();
	nc.owner = this;
	nc.onStatus = function(info)
	{
		if(info.code == "NetConnection.Connect.Success")
		{
			debugHeader();
			debug("Successfully connected!");
			this.owner.onConnected();
		}
		else
		{
			debugHeader();
			debug("Problem connecting to FCS Admin, aborting.");
			this.owner.lightFuse();
		}
	};
	nc.connect("rtmp://" + theHost + ":" + thePort + "/" + theAppName,
		   theUsername,
		   thePassword);
}

function onConnected()
{
	//getActiveInstances();
	reloadApp("flex2test");
}
function reloadApp(str:String)
{
	debugHeader();
	debug("Reloading app...");
	nc.call("reloadApp",
		      new Responder(this,
				    reloadApp_result,
				    reloadApp_fault),
				    str);
}
function reloadApp_result(o)
{
	debugHeader();
	if(o.code == NETCONNECTION_CALL_SUCCESS)
	{
		debug("App successfully rebooted, exiting.");
	}
	else
	{
		debug("Failed to reboot the app!");
		debugProps(o);
		debugProps(o.level);
		debugProps(o.error);
		debugProps(o.code);
		debug(o.description);
		debugProps(o.description);
		debug("Exiting.");
	}
	
	//debugProps(o);
	lightFuse();
}
function reloadApp_fault(o)
{
	debugHeader();
	debug("reloadApp_fault");
	debugProps(o);
	lightFuse();
}

/*
function getActiveInstances()
{
	debugHeader();
	debug("getActiveInstances...");
	nc.call("getActiveInstances",
	      new Responder(this,
			    getActiveInstances_result,
			    getActiveInstances_fault));
}

function getActiveInstances_result(o)
{
	debugHeader();
	debug("getActiveInstances_result");
	if(o.code == NETCONNECTION_CALL_SUCCESS)
	{
		debug(o.data.length + " active instances.");
		debugProps(o.data);
	}
}

function getActiveInstances_fault(o)
{
	debugHeader();
	
	debug("getActiveInstances_fault");
	debugProps(o);
}
*/
function lightFuse()
{
	nc.onStatus = null;
	nc.close();
	nc = null;
	
	createEmptyMovieClip("timeout_mc", 1);
	timeout_mc.st = getTimer();
	timeout_mc.timeout = 3; // seconds
	timeout_mc.onEnterFrame = function()
	{
		var ct:Number = getTimer();
		var et:Number = ct - this.st;
		if(et > (this.timeout * 1000))
		{
			this._parent.boom();
		}
		else
		{
			var p:Number = et / (this.timeout * 1000);
			var w:Number = TIMEOUT_WIDTH * p;
			
		}
		timeout_mc.clear();
		timeout_mc.lineStyle(0, 0x000000);
		timeout_mc.lineTo(TIMEOUT_WIDTH, 0);
		timeout_mc.lineTo(TIMEOUT_WIDTH, TIMEOUT_HEIGHT);
		timeout_mc.lineTo(0, TIMEOUT_HEIGHT);
		timeout_mc.lineTo(0, 0);
		
		timeout_mc.moveTo(1, 1);
		timeout_mc.beginFill(0x666666);
		timeout_mc.lineTo(w, 1);
		timeout_mc.lineTo(w, TIMEOUT_HEIGHT - 1);
		timeout_mc.lineTo(1, TIMEOUT_HEIGHT - 1);
		timeout_mc.lineTo(1, 1);
		
		timeout_mc.endFill();
	};
	timeout_mc.onEnterFrame(); // draw immediately
	onResize();
}
function boom()
{
	delete timeout_mc.onEnterFrame;
	timeout_mc.removeMovieClip();
	fscommand("quit");
}

function onResize()
{
	debug_txt._x = 0;
	debug_txt._y = 0;
	debug_txt._width = Math.max(12, Stage.width);
	debug_txt._height = Math.max(12, Stage.height);
	
	var sx:Number = Math.max(6, Stage.width);
	var sy:Number = 6;
	timeout_mc._x = sx - (timeout_mc._width) - 6;
	timeout_mc._y = sy;
}
function debug(o)
{
	trace(o);
	debug_txt.htmlText += o + "";
}

function debugHeader()
{
	//debug("---------------");
}

function debugProps(o)
{
	if(o instanceof Array)
	{
		var len:Number = o.length;
		for(var i:Number = 0; i<len; i++)
		{
			trace(o[i]);
		}
	}
	else
	{
		for(var p in o)
		{
			debug(p + ": " + o[p]);
		}
	}
}

init();


Source Files – ZIP

Porting Flashcom Applications to ActionScript 3

Regardless if you Flex or Flash, I ran into a porting issue with a Flashcom app I wrote in Flex 1.5 & ActionScript 2. A lot of the server-side code, which is written in case sensitive JavaScript 1, utilizes the Flashcom Component Framework. This framework utilizes a namespace scheme to allow clients to identify server components, and server components to identify client components. This allows them to send messages to each other, and works really well…

…except in Flash Player 9. For some reason, the namespace mechanism doesn’t work for ActionScript 3 classes. This isn’t a big deal for playing existing content. All of my existing Flashcom apps I wrote in Flash MX 2004 & Flex 1.5 (Flash Player 7) still run just fine in Flash Player 9 in both Firefox & IE.

It’s when you have a server-side script do a NetConnection.call on an Flash Player 9 created SWF that things don’t work. You CAN call a method that your class has defined as public assuming you point the NetConnection’s client property to your class; protected and private don’t work. However, the namespace mechanism commonly used in ActionScript 2 doesn’t work with the server; it constantly reports method not found. You’d typically decorate the client side NetConnection object reference that you’re component got passed in via it’s loose interface “connect” method. This decoration with the namespaces pointing to your component allowed the server-side to find it. The server-side Flashcom Component Framework already has a built-in namespace mechanism that still works just fine.

You can emulate this by extending NetConnection, and making the class dynamic. Still, you’ll get the method not found error.

My only guess at the problem is I think it has to do with the lack of support of “slash syntax”. I’m not sure the new ActionScript Virtual Machine supports it. I know AVM does; it’s how Flash Player 4 SWF’s will work the same as they always have. However, it seems the FCS Component Framework utilizes this behind the scenes somehow. When you do this on the server-side:

nc.call ( this.callPrefix + "method" );

You’re basically going:

nc.call ( "YourComponent/InstanceName/method" );

…I guess. I gave up after 3 nights of trying to get it to work. I didn’t mind porting client code, but I didn’t want to port server-side code. Anyway, fix for me is to pass in the callPrefix as the first parameter to the method, and have the client side Observer class just parse out “who this message goes to”.

If you get it to work on your end, drop a note in the comments. I’m using Flex 2 & FCS 1.5 on Windows via Flash Player 9 in Firefox 1.5.