(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .

Getting ready for Microsoft Silverlight Exam 70-506 (Part 3)

(10 votes)
Gill Cleeren
>
Gill Cleeren
Joined Apr 02, 2010
Articles:   63
Comments:   6
More Articles
2 comments   /   posted on Feb 01, 2011
SilverlightShow and Gill Cleeren start a series of materials aimed at helping you get prepared for taking Microsoft Silverlight Exam 70-506. Through this series we will try to structure the resources available on the internet, grouping them by topic covered in the exam. Any feedback would be much appreciated! Thanks! 

This article is Part 3 of the series on Microsoft Silverlight Exam.

In the previous parts of this series on getting yourself ready for the Silverlight exam, we mainly looked at UI related items. In the very first part, we looked at how Silverlight could help with layout, navigation, media and the core controls. In part 2, we focused on the many features Silverlight has on board to create better user interfaces, such as the Visual State Manager, styling, templating and animations.

This third part is going to be more aimed at the code-side of things. We’ll start our journey by looking at specifics of Silverlight such as routed events (these also exist in WPF by the way and asynchronous communication with services. We’ll look at dependency and attached properties as well, these are very important to a deeper understanding of Silverlight. We’ll look at the ICommand interface as well, which forms the base of commanding support for the MVVM-pattern in Silverlight. As you can see, we’ll be spending more time looking at C# code this time!

For your convenience, the following list contains links to the other parts of the article series which have been finished already:

Part 3: Implementing Application Logic

Do you remember the name WPF/E (the E stands for Everywhere)? It was the name Silverlight was known by before it got its final name. The reason I bring this up here is that it shows that Silverlight has inherited from WPF (Windows Presentation Foundation). The original name gives this away. Much of the core development platform we have today in Silverlight found its origin in Silverlight. Things like dependency properties and attached properties were introduced in WPF and later were ported into Silverlight. Some of these implementations are identical in the 2 technologies, others are somewhat trimmed down in Silverlight. Still, the development model available in Silverlight is solid and ready to build all types of applications on. Let’s dive into writing some code for Silverlight applications!

Handle events

Working with events in Silverlight is not very different from any other technology (note that we’re not looking at MVVM/commanding here yet). When we have some control in the designer, we can select it and select an event in the event window. Visual Studio will generate the event handler for us then as well as generate the event on the control in XAML. Not very different from ASP.NET or WinForms indeed! We can also choose to attach the event handler in code-behind using a delegate or even a lambda expression.

Silverlight has the notion of routed events. An event raised on a control nested within another control will bubble into the parent control so this parent can handle the event. This model is easy because Silverlight promotes nesting. This way, a TextBlock and an Image inside of a container (such as a Grid), all nested within a Button, will raise the click event to the Button, instead of us having to wire the event for the Button and its children manually.

To learn more about event handling, take a look at the following links:

  • Handling routed events / Bubbling events:
    Bubbling of an event is a type of a routed event. At the time of writing, there’s only support for bubbling events in Silverlight. WPF also supports tunneling. Bubbling can be seen as a way to send an event higher in the hierarchy. Hence the name bubbling: it will bubble up in the XAML tree. Tunneling, which is only available for WPF, does the opposite, drilling down so to say in the XAML tree.
  • Implementing AddHandler:
    Using the AddHandler, we can add an event handler for a routed event to the handler collection of an element.
    • http://msdn.microsoft.com/en-us/library/ms598899(v=vs.95).aspx
Consume services asynchronously

Services are a vital building block for Silverlight applications. As business applications become more and more the focus of where Silverlight is going, data is needed in any app. Since out-of-the-box, Silverlight has no support for client-side database (I specifically said out-of-the-box, since there are some custom implementations such as Sterling database but these are not the focus for the exam), it has to access services for its data needs. Client-side databases would not be the solution for all problems either: if we build a shopping website in Silverlight, no developer would get it in his mind to transfer the entire product database to the client (let’s hope so at least!).

Luckily, Silverlight is well-equipped for working with all kinds of services. ASMX, WCF, REST, POX and RSS pose no problem for Silverlight. We can easily say that today, the default for building new services should be WCF or REST. However, if you have an existing implementation (legacy) in ASMX (plain web services), there’s no problem to consume these from a Silverlight environment.

When working with WCF or ASMX services, Visual Studio helps us out by generating a proxy class when adding a reference to the service. This proxy will make the actual calls to our service. This is not different from adding service references in other .NET technologies.

One big difference however is the fact that all communication happens asynchronously in Silverlight. No service can be communicated with in a synchronous manner. This would, while the Silverlight application waits for a response, lock the UI thread and therefore also the browser. Even in WCF RIA Services, where the async behavior is somewhat abstracted away, the communication still happens asynchronously.

(Shameless plug: in my book Silverlight 4 Data and Services Cookbook (Gill Cleeren – Kevin Dockx, Packt Publishing 2010), we have a very deep coverage of all things happening around accessing services).

Let’s look at some important information regarding working with services from Silverlight.

Work with background threads

Threading is the ability to push some long running task to a separate thread. By default, all the work is done on the single UI thread in Silverlight. If we launch for example a calculation that takes several seconds to complete in the main thread, the UI will be blocked and won’t be accepting any input until it has finished the calculation. By creating a separate thread to execute the work on, the UI thread won’t be blocked and the user can keep working with the application in the meantime. This is similar to what happens when connecting with a service: there’s also a time-consuming task that would block the UI if invoked synchronously.

Silverlight has a threading stack on-board. While it doesn’t contain all threading options available in the full .NET framework, there’s more than enough for scenarios where Silverlight is to be used. Silverlight also contains the BackgroundWorker class which makes working with threads easier.

One important thing concerning threading is that all code that executes on a separate thread has no access to the UI elements. It’s therefore not possible to write code in a callback that does something with a UI element (such as setting the Text of a TextBlock). There’s a workaround though in the form of the Dispatcher.BeginInvoke(), to which we can pass code that will be executed on the UI thread.

To learn more about threading, take a look at the following links and articles:

  • Spawning a background thread to execute code
    • Thread class on MSDN: http://msdn.microsoft.com/en-us/library/system.threading(v=VS.95).aspx
    • BackgroundWorker on MSDN: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(v=VS.95).aspx and http://msdn.microsoft.com/en-us/library/cc221403(VS.95).aspx
    • http://10rem.net/blog/2010/04/23/essential-silverlight-and-wpf-skills-the-ui-thread-dispatchers-background-workers-and-async-network-programming (also contains overview of the BackgroundWorker class)
    • http://www.silverlight.net/learn/videos/silverlight-videos/using-multiple-threads-with-the-backgroundworker/ (video)
  • Returning data to the UI thread by using the dispatcher object
    The Dispatcher allows to pass code to execute on the UI Thread. Without this, we wouldn’t be able to change anything on the UI elements from a background thread.
  • Implementing the DispatcherTimer
    The DispatcherTimer is a Timer which is integrated in the Dispatcher queue. It should be your default when using any timer in a Silverlight application.
    • DispatcherTimer class on MSDN: http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer(v=vs.95).aspx
    • http://blogs.silverlight.net/blogs/msnow/archive/2009/11/09/69731.aspx
Working with Dependency Properties

When I teach a Silverlight class, one of the hardest things to explain I think are dependency properties. Not because they’re that hard, certainly not. The thing is that dependency properties make something you know (the regular property system) to a new level. However, they do relieve us from writing a lot of code ourselves.

Dependency properties are the enabler for data binding, styling and animations. Without them, we would have to write a lot more code to get these things working. Most properties on UI objects in Silverlight (the FontSize property on a TextBlock, the Width property of a Rectangle…) are dependency properties, so in most cases, you’ve used them without even knowing it! When you start writing your own controls, you’ll need to start creating them as well, if you want your control to be able to take part in data binding, styling… It’s certainly recommended to do so, since other users of your custom-built controls will expect your controls to behave just like the default controls of Silverlight.

Let’s take a look at working with dependency controls:

  • Creating dependency properties / Specifying dependency property metadata / Getting and setting dependency property values
    Creating dependency properties is more complicated than writing regular properties. You have to declare the DP by registering it with the dependency property system (on the DependencyObject). Optionally, you have to write code in a PropertyChangedCallback that will trigger when the value changes. Finally, you have to write a public wrapper for your DP. You won’t be accessing the value of the DP directly: you’ll always use this wrapper which internally uses the GetValue/SetValue defined on the DependencyObject class. These methods will retrieve the exact value of the DP at the given time, taking into account all the current influences taking place on the value and their priorities.
  • The topic of dependency properties in Silverlight is inherited from WPF. There’s a lot of interesting material on DPs in WPF as well from the following links:
    • http://msdn.microsoft.com/en-us/library/ms752914.aspx
    • http://joshsmithonwpf.wordpress.com/2007/05/16/demystifying-dependency-properties/
    • http://www.wpftutorial.net/DependencyProperties.html
    • http://www.switchonthecode.com/tutorials/wpf-tutorial-introduction-to-dependency-properties
    • http://www.codeguru.com/csharp/.net/net_general/netframeworkclasses/article.php/c13449
Interacting with attached properties

Attached properties are properties defined on one control but used on a different control. Confused? Let me explain it with a simple example. Take the Row property on a Grid control. When we want to place a TextBlock in row #3 inside a Grid, we specify the Grid.Row property to have the value 3. However, the TextBlock does not have a “Grid.Row” property defined. Instead, the Grid has the Row property defined as an attached property. The attached property is defined as a global property, so that other control can use it. Most attached properties are defined on containers (Grid, Canvas…). This is because there needs to be some “communication” between the child control and the parent control. However, this is not required: your own control can too define attached properties if needed.

To learn more about attached properties, take a look at the following articles:

Implementing ICommand

The MVVM pattern is something you’ve surely heard about already. The ViewModel (aka View-Model-ViewModel) pattern promotes separation of concerns. The ViewModel is an abstraction of the View: the View mostly XAML-only and it’s the place where the designer is focusing on. The ViewModel contains state and operations for the View. State can be seen as properties, operations are commands. The View falls back on the concepts of data binding and the DataContext to bind to an instance of the ViewModel.

When executing an action in the UI, for example clicking a Button, we think of adding an event handler and writing some event handling code in the code-behind. MVVM promotes commanding, which comes down to writing a public command in the ViewModel and binding to this instance in the View. When the command fires, the related code in the ViewModel gets executed. Therefore, we don’t write an event handler, instead we create a command instance and the ViewModel and bind to it.

Commanding is possible in Silverlight 4 because of the introduction of the ICommand interface. When creating a command implementation, we have implement the ICommand interface. Once we have our implementation, we can instantiate it, expose it as a public property on the ViewModel and bind to it in the View. In Silverlight 4, commanding is only supported on the ButtonBase class though. (Note: in many cases, we don’t implement the ICommand ourselves but we’ll use an existing implementation such as RelayCommand of MVVM Light or DelegateCommand from Prism).

The following articles can helpful when exploring the ICommand interface:

Summary

In this part, we prepared ourselves for the code-side of Silverlight. Not everything is XAML so there are some really important things to understand that you need to know in this area. Aspects such as Dependency Properties, Attached Properties and the ICommand interface are tools you’ll surely want in your Silverlight toolbox!

In part 4, data will be our focus, when we look at things like data binding and validation.

About Gill

Gill Cleeren is Microsoft Regional Director (www.theregion.com), Silverlight MVP (former ASP.NET MVP), INETA speaker bureau member and Silverlight Insider. He lives in Belgium where he works as .NET architect at Ordina. Passionate about .NET, he’s always playing with the newest bits. In his role as Regional Director, Gill has given many sessions, webcasts and trainings on new as well as existing technologies, such as Silverlight, ASP.NET and WPF at conferences including TechEd Berlin 2010, TechDays Belgium, DevDays NL, NDC Oslo Norway, SQL Server Saturday Switserland, Spring Conference UK, Silverlight Roadshow in Sweden… He’s also the author of many articles in various developer magazines and for SilverlightShow.net. He organizes the yearly Community Day event in Belgium.

He also leads Visug (www.visug.be), the largest .NET user group in Belgium. Gill recently published his first book: “Silverlight 4 Data and Services Cookbook” (Packt Publishing). You can find his blog at www.snowball.be.

Twitter: @gillcleeren


Subscribe

Comments

  • shozayen

    Re: Getting ready for Microsoft Silverlight Exam 70-506 (Part 3)


    posted by shozayen on Jun 15, 2012 19:41

    Please fix this link:

    http://johnpapa.net/silverlight/5-simple-steps-to-commanding-in-silverlight/

    it have to be :

    http://johnpapa.net/5-Simple-Steps-to-Commanding-in-Silverlight

  • AjayBagra

    Re: Getting ready for Microsoft Silverlight Exam 70-506 (Part 3)


    posted by AjayBagra on Feb 12, 2015 09:00
    Great post! I am actually getting ready to across this information, is very helpful my friend. Also great blog here with all of the valuable information you have. Keep up the good work you are doing here.
    Visit This Site - Check This website - Site

Add Comment

Login to comment:
  *      *       

From this series