Just Quickly: jQuery and Silverlight

March 30, 2009

I love Silverlight and I love JavaScript. A very important part of any new technology is making sure it plays nice with existing technologies.

Silverlight has some great features when it comes to integration with the DOM and JavaScript. The ScriptObject and the way Silverlight proxies out POCOs (Plain Old CLR Objects) to JavaScript are a couple of my favourites.

Across the divide, JavaScript is also very cool, but lacks some power and compatibility when used in its bare form (well, compared to JS with a library over the top anyway).

This leads to a lot of web developers choosing to add a JavaScript library to add extra functionality and compatability to their sites. A common choice these days is jQuery.

Over the years a lot of code has been written against these various JS libraries. This means that Silverlight needs to play nice with existing code so that integration with existing sites is quick and pain free (and to reduce re-writes of existing code). Client code is client code and in .NET or not, it can still be very useful.

Nobody wants to re-write an entire site just to add some new existing tech. You want to reuse as much of your existing code as is possible.

jQuery rocks. It’s got some great features, like the jQuery object’s fluent interface, plugins and importantly the implementation of CSS style selectors. CSS selectors allow you do some cool stuff when searching the DOM based on CSS syntax. You can do stuff like “find me all the LI elements that are in UL elements that are in an element with a CSS class name of menuPanel -> “.menuPanel UL LI”. Check out the full power of jQuery selectors here.

jQuery is so cool and so powerful there is a case for using it even if you *don’t* have existing code based on it.

A potential case – CMS

I talked briefly about Silverlight playing nice with existing sites. It’s probably even more important that Silverlight plays nice with existing back end systems such as CMS. When Silverlight is used with a library like jQuery it becomes very easy to integrate.

Your new application can source data from the existing CMS without the CMS needing to know a single thing about Silverlight. And we’re not talking about integrating Silverlight with some existing API or web service.

You can use jQuery selectors with Silverlight to scrape the page both elegantly and simply.

Nitty gritty – jQuery in Silverlight

<Sample Code>

jQuery and Silverlight sample code

</Sample Code>

Using jQuery from Silverlight is very easy as jQuery (in all it’s awesomeness) has a single object to perform most operations -> the “jQuery Object”. Most people use jQuery by using the $ shortcut, but it’s also available on the JS global object (window) as a property called jQuery.

public class jQueryManager
{
	ScriptObject jQuery = null;
	void init()
	{
		//get the jQuery object from the JavaScript global object
		jQuery = HtmlPage.Window.GetProperty("jQuery") as ScriptObject;

		...

	}

}

Now the code is ready to chain up some jQuery operations.

public List<HtmlElement> GetElements(string selector)
{
	List<HtmlElement> result = new List<HtmlElement>();

	//this is like saying $(selector) in jQuery
	ScriptObject select = jQuery.InvokeSelf(selector) as ScriptObject;

	//Check the length property to see if there are any elements in the array
	//Keep in mind JavaScript objects are arrays
	int length = Convert.ToInt32(select.GetProperty("length"));

	if (length > 0)
	{
		for (int i = 0; i < length; i++)
		{
			//As I said, all objects are arrays, so you can call GetProperty like an indexer
			HtmlElement selElement = select.GetProperty(i) as HtmlElement;
			result.Add(selElement);
		}
	}

	return result;
}

The magic happens when the code calls InvokeSelf on the jQuery object. Keep in mind that objects in JavaScript can be functions (it’s a functional language). Once the selector has been passed in to the jQuery “function” a ScriptObject is returned. Also keep in mind that objects in JavaScript can be functions *and* arrays. So the ScriptObject in this case can be treated like an array and an object that has properties (like length etc).

The array is looped through and the elements are retrieved using the GetProperty(i) call… is like saying select[i] (remember that the calls are proxied back to JavaScript so that’s probably why raw indexers don’t work).

This code packages up the elements in to a List and returns the result.

List<HtmlElement> eleList = jQueryManager.Instance.GetElements("#someDataDiv ul li a");

List<SomeDataObject> result = (from e in eleList
							   select new SomeDataObject()
							   {
								   Link = e.GetAttribute("href"),
								   Text = e.GetAttribute("innerHTML")
							   }).ToList<SomeDataObject>();

return result;

The SomeDataManager class uses the jQuery helper class to find all the anchor tags that are in LI tags that are in UL tags that are in an element called “someDataDiv”. It does this by calling the jQuery selector “#someDataDiv ul li a”. Cool hey.

Once it gets the list of HtmlElements back it parses them out to get their Link and Text values and populates a simple business object class called SomeDataObject.

The SomeDataManager class also implements INotifyPropertyChanged so that it may raise an event when the data is ready. This means the class can be bound to using Silverlight DataBinding.

id x:Name="LayoutRoot" Background="White">
<ItemsControl Height="Auto" HorizontalAlignment="Left" VerticalAlignment="Top" Width="Auto" ItemTemplate="{StaticResource LinksTemplate}" ItemsSource="{Binding Data}">
	<ItemsControl.DataContext>
		<local:SomeDataManager/>
	</ItemsControl.DataContext>
</ItemsControl>

An ItemsControl in Page.xaml shows the result.

Finally – the HTML that this reads: a simple un-ordered list.

 <div id="someDataDiv">
	<ul>
		<li>
			<a href="http://www.sddn.org.au" title="SDDN Site">SDDN Site</a>
		</li>
		<li>
			<a href="http://blog.webjak.net" title="My Blog">My Blog</a>
		</li>
		<li>
			<a href="http://www.theage.com.au" title="The Age Website">The Age Site</a>
		</li>
	</ul>
</div>

There is something else cool about this

As you well know there are a lot of different browser and “plugin levels” out there. Someone might be on Safari 2 with no Silverlight, someone else might not have JavaScript enabled and the other person may have anything and everything installed.

It’s good practice to design your site in such a way to support all these groups -> a gracefully degrading site.

Build the site so that it works with HTML, JavaScript only and the full works Silverlight version. Using the techniques in this article and some extra sprinkles of ingenuity you can quite easily make your site work in all browser types and plugin installs. Stay tuned for more on this important aspect of web development!


Mix 09 – 10 from 10

March 23, 2009

I’ve just returned home from the Mix conference in Vegas… and wow I had a great time. It took me 31 hours to get from the Venetian Hotel in Vegas to my home in Bendigo, Australia :)

Let me start out by sending out a big thank you to the MSFT crew for a) putting on a *great* show and b) giving me so many new toys and tools to play with and add to my toolkit.

I’ve got to say I was very impressed with the announcements during the keynote. I’m not going to provide a news service on the announcements but I will go through some of my favourites.

Sketchflow (SF)

So if it was Designer Developer Workflow before, what’s it now? Designer/Developer/Client/Coffer/Manager/Stake Holder/CTO Workflow? DDCCMSCW? How many people do they want to invite to the workflow? As many as is possible = WIN. Lets call this SFDDW.

I loved this as it confirms Microsoft’s intentions when it comes to Workflows – you can bet Adobe (who neglected WF in their design tools) will be keeping a close eye on this one). I had a shiver down my spine when they showed the Sketchflow player in browser (to show the client your design).

Great points about SF:

  • I can use Sketchflow to visually demonstrate the concept of DDW from conception to demonstration to final product. Talking DDW to people can be difficult until they have an “AHA” moment. Sketchflow is a DDW sales tool.
  • It keeps with the “you are always working on assets that will be used in the final product” paradigm. Reuse of assets, animation, behaviour etc cuts down time “big time”. Huge in DDW, now still huge in SFDDW.
  • Client can comment, draw etc in the Sketchflow player. Designer sees this overlayed in Blend. Smooth.
  • Use of behaviours in SF. Now the client can see transitions and animations in the SF player. Gone are the days of PowerPoint and After Effects to demonstrate UI.

SF has huge appeal to me, even as a developer, as I am responsible for teaching people about DDW and how to reduce cost and maximise reuse… thank you :)

Out of Browser (OOB)

I was hoping this would be in there. I made the call, and was vindicated. There was doubt though – OOB Silverlight certainly puts a little pressure on other technologies such as WPF. When it was announced I was a little surprised.

There are a couple of highlights for me about OOB with Silverlight

  • Deployment is very simple. The same app runs in the browser as it runs on the desktop. A small change to the manifest file and the user can right click the app to install it. You can also deploy from any code that is a user initiated event (i.e. a button click).
  • The fact that the same app that runs in the browser also runs on the desktop is very cool. You can test for OOB mode and show a different interface on the desktop whilst showing the “install” interface in the browser.
  • Online and offline events. When you don’t have ‘Net access the app can look after itself. Why not download some content for later consumption in “on the bus” (OTB) mode.
    I ponder how cross domain access works on the desktop. Is the home domain the same as the downloaded XAP location. What about relative URI’s… I must test this out.
  • Cross O/S desktop applications written in .NET. Can customise the icon too.

3D and Pixel Shaders

I was a bit worried about 3D in Silverlight – mainly about learning cameras and meshes and all that. The 3D implementation in Silverlight is fantastically simple. You use an element’s Projection property and set a PlaneProjection to it. Then you start setting all sorts of properties (which can of course be animated or bound etc). Deliciously simple.

Check out Jesse Liberty’s video here.

This all makes 3D in Silverlight is a UX tool rather than a 3D modelling workshop.

Pixel Shaders in SL3 are based on HLSL which is created in a C style language then compiled using the Direct X SDK. SL shaders are “almost” compatible with the WPF ones. This means its quite easy to port them. The WPF Pixel Shader library has already been ported over (and works). See here.

Shaders and 3D rock – they allow for some very cool effects to be sure, but use them wisely… we don’t need a recreation of the early Internet please (think blinking backgrounds and cyan scrolling marquees). Shaders are implemented as “effects”. There are two built in: drop shadow and blur.

Navigation

The new navigation stuff is one of my favourite features. You now create pages which can be navigated between using the new navigation pattern. Using these pages also gives you automatic back and forward browser button access and deep linking!

You can also use special URI mapping to alter URL’s and to introduce parameters (like an ID) in the URL.

See Tim Heuer’s video here.

New Blend

I’ve not played with Blend 3 yet! Geese I’m slack. But, I’ve seen some sweet stuff in it.

  • Behaviours. Developers encapsulate behaviour in special classes and designers can then consume then in blend (they show up on the behaviours tab).
  • Better design time data experience. I still have to check this out but I swear I saw some cool stuff when it comes to design time data improvements.
  • Full support for Photoshop and Illustrator files. Import them and… MODIFY them! Sweet.
  • Intellisence
  • Support for code editing
  • Support for source code control (nice)

RIA Services

RIA Services formalises data centric patterns and practices for use with RIAs (i.e Silverlight). It provides a formalised way to bridge the gap between database, server and client code. RIA Services will make it A1 easy to teach people best practice when it comes to Silverlight.

Traditionally tooling pushes you down a contract based path. The only link between client and server is a contract. Now with RIA services the tooling encourages you to go past contracts and share behaviour metadata and even implementation between client and server.

See Nikhil’s post on this here.

Yes please

I’ll gladly take all these new tools and place them in my toolkit. Silverlight just got a heap better (and it was already damn good).

This post doesn’t even cover the half of it, so head over to http://sessions.visitmix.com/ and start watching… that’s what I’ll be doing.

For a sweet MIX session on most of these features check out Joe Stegman’s talk here.

Oh… and don’t forget element to element binding in the UI – YAAY!


Silverlight Hits Mainstream Media in Australia

March 6, 2009

The SMH site is today featuring a firetrucking load of past Sydney Madri Gras imagery – all powered by Silverlight.

More details can be seen on Delicate’s blog here. Delicate has done some great work here, both organising the feature and coding it! Making it even cooler is that it’s hosted on Azure!

It’s a good day for Silverlight in Australia – a good deal of people will see it in action. This app also clearly demonstrates some of the differences between Silverlight and other RIA technologies… deep zoom is seriously cool. Make sure you resize the window!

P.S. Jump in to IE8, crack open the direct URL to the IFRAME (here) and hook up the webslice… and resize that too. Wow it’s cool, well done Kordsy.