Monday, 30 May 2011

Simple XAML fade

Getting a control in WPF or Silverlight to fade in on a specific event is a doddle.

Here’s an example of a menu control I created that fades in when the StackPanel has loaded. 

The StackPanel contains multiple menu item controls, each of which comprises of an image and some text.

The key points here are:

  • EventTrigger RoutedEvent which tells the animation to start on the StackPanel.Loaded event
  • Use a double animation, double being the opacity value data type
<StackPanel x:Name="MenuContainer" Orientation="Horizontal" HorizontalAlignment="Center">

<StackPanel.Triggers>
<EventTrigger RoutedEvent="StackPanel.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="MenuContainer"
Storyboard.TargetProperty="Opacity"
From="0.0"
To="1.0"
Duration="0:0:3" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</StackPanel.Triggers>

</StackPanel>

Full source:  http://stevenhollidge.com/blog-source-code/Silverblade-Prism.7z

Tuesday, 24 May 2011

Dependency Objects vs INotifyPropertyChanged

WPF and Silverlight user interfaces are all about data binding. 

To allow your POCO (plain old CLR objects) to take advantage of two way data binding, your object needs to raise the change event.  This can be done by either specialising from DependencyObject or by implementing the INotifyPropertyChanged interface.

Here is a simple example of both in action.

DependencyObject

INotifyPropertyChanged

You can then bind your UI controls to your objects by setting the DataContext and ItemsSource of the control:

Now you may have noticed I’ve added some validation for the Age property.  In my next blog article I’ll show why I find INotifyPropertyChanged a more flexible solution and gives the ability for contextual validation.

Garbage Collector

This blog post demonstrates how the garbage collector generations work.

Our simple example does the following:

  • Creates an object
  • Calls a method to bloat the object
  • Releasing the object from memory

Between each step we check the memory used by our application and the GC generation level for our object.

ScreenShot048

We can see after the GC.Collect(0) is called the GC pushes our bigObject from the first generation (0) into the next GC generation (1).

Finally we set the object to null, meaning it’s memory can be reclaimed.

Monday, 23 May 2011

UI Design

Here is a nice example of what can be achieved with WPF and Silverlight for a line of business application.

StaffLynx from Tyler Bullock on Vimeo.

Debugger Canvas

There’s a cool new addition to the Visual Studio Power Tools that gives developers a more visual ride when debugging their applications.  Introducing the Debugger Canvas:

What a great new addition to the Visual Studio power tools!

For further details visit the Microsoft Research website:

http://research.microsoft.com/en-us/projects/debuggercanvas/

Common Tasks using the TPL

Want a quick way to remember how to spin up tasks in .Net 4.0?  Here’s a few examples:

Saturday, 21 May 2011

WCF RIA Services Overview

Deborah Kurata gave an excellent session at the recent TechEd 2011 that serves as a great introduction to WCF RIA Services in Silverlight. I see this as an excellent resource that can be used to bring up to speed members of the team that have been focused on other technologies in the past.

To view or download the video direct you can visit the Channel9 website:

http://channel9.msdn.com/Events/TechEd/NorthAmerica/2011/DEV210

C# RSS Feed Burner

This simple article demonstrates how to take RSS feeds from the internet and bring the data into your application.

output

1. Create a console application:

create-project

2. To access the RSS Syndication goodness within .NET you’ll need to add a reference to the System.ServiceModel assembly:

add-refererence

3. Paste the following code into your Program.cs file:

This code stores the RSS feeds in a dictionary, iterating through to output the feed items to the console window.

You can download this source code:

http://stevenhollidge.com/blog-source-code/RssFootballFeeds.zip

Friday, 20 May 2011

Silverlight MEF modularity loading

When designing an architecture for Silverlight applications it’s important to break down your application into loosely coupled modules, which can then be composed to create your system.

ScreenShot028

In this example you can see our solution contains our main Silverlight application, the web hosting project and a further six loadable modules named A - F.  There is also a ninth project called ModuleTracking which tracks the state of the loadable modules e.g. ModuleE 39% downloaded.

vs

The main application project can discover these modules through either direct project references or, more importantly, through a configuration file or directory sweep. When using the configuration file (ModulesCatalog.xaml in the example code) you can define dependencies so that a working module is always provided.

 

To download the source code please visit the PRISM website and select active releases v4:

http://msdn.microsoft.com/en-us/library/ff648465.aspx

Best free Silverlight menu control

Having search high and low across the internet my favourite free “desktop” style menu control for Silverlight is from VIBlend.

The menu is fully customisable and comes with a wide variety of themes out of the box.

You also get a nice context menu for your right click scenarios:

For more information visit the VIBlend website:

http://www.viblend.com/products/net/silverlight/controls/silverlight_menu_control.aspx

Thursday, 19 May 2011

C# Dispose Pattern

Here is an example of how to correctly implement the C# Dispose pattern, ensuring all your unmanaged resources are efficiently cleared from memory.

using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;

internal class HowToImplementTheDisposePattern
{
private static void Main()
{
const string filename = "data.xml";

if (!File.Exists(filename))
CreateXmlFile(filename);

// the using statement implicitally calls the dispose on exit
using (var myDisposableObject = new MyDisposableClass(filename))
{
//do some work here with your object
}
}

public class MyDisposableClass : IDisposable
{
private XmlTextReader reader;
private bool disposed = false; // to detect redundant calls

public MyDisposableClass(string filename)
{
reader = new XmlTextReader(filename);
}

#region IDisposable Members

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

#endregion

protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (reader != null)
{
((IDisposable)reader).Dispose();
}
}

disposed = true;
}
}

~MyDisposableClass()
{
Dispose(false);
}
}

private static void CreateXmlFile(string filename)
{
var xml = new XDocument(
new XComment("This is a comment"),
new XElement("Root",
new XElement("Child1", "data1"),
new XElement("Child2", "data2"),
new XElement("Child3", "data3"),
new XElement("Child2", "data4"),
new XElement("Info5", "info5"),
new XElement("Info6", "info6"),
new XElement("Info7", "info7"),
new XElement("Info8", "info8")
));

xml.Save(filename);
}
}

C# Create Xml File Programmatically

Here is a simple example of creating an XML file programmatically in C#:

Multi threaded apps with Tasks

Here is an example of running multiple methods simultaneously:

ScreenShot026

The Task Parallel Library will decide whether new threads are required, and spin them up from the thread pool as required.

Chain of Command pattern with Tasks

You can create a new thread and that can run a series of sequential methods, with the result of each passed onto it’s successor using Tasks and the ContinueWith keyword. 

The example below uses a fluent interface to chain each method together:

image

Tasks vs Threading

With the introduction of the Task Parallel Library (TPL) within .NET 4.0, creating a Task rather than a Thread is now the preferred way to create multithreaded applications.

Here is an example showing the creation of a thread using the old style Threading vs the new Tasks:

ScreenShot024

Why chose Task over Threading?

Behind the scenes, tasks are queued to the ThreadPool, which has been enhanced with algorithms (like hill-climbing) that determine and adjust to the number of threads that maximizes throughput. This makes tasks relatively lightweight, and you can create many of them to enable fine-grained parallelism. To complement this, widely-known work-stealing algorithms are employed to provide load-balancing.

Threading Locks and Synchronisation

Locks

The usual pattern for locking a piece of code so that other threads cannot enter at the same time is:


Which internally is the same as using the Monitor keyword:


Synchronisation

To cause a thread to block you can use the AutoResetEvent. The WaitOne method will block until the Set method is called:

Or you can use the Monitor class with a lock to achieve the same result:

Wednesday, 18 May 2011

MVVMLight Messenger for Loosely Coupled Events

The Messenger class within MVVMLight gives developers the ability to publish an application wide event using messages that allow a subscriber to react without either the publisher or subscriber knowing anything about each other.

As always with MVVMLight it’s really simple to do.

In this example, I wanted a user to be able to click on the main menu of my application, shown on the left hand side of the screenshot below, which would update the content pane on the right hand side.

image

The main menu is a user control whilst the content pane is a navigation frame located within the MainPage.xaml.

To allow two pieces of code to communicate with each other, without knowing anything about each other, I will use the Messenger class in 3 simple steps.

1 Create a strongly typed message

 

2 Register a subscriber to the message type

Register the MainPage as the subscriber so that when the message is received the Uri within the message will be passed to the NavigateTo method to update the content pane.

 

3 Lastly, publish the message

 

When the TreeView menu is clicked the code behind checks for a Uri within the selected TreeViewItem then creates a message containing the Uri and publishes it to your application.

Summary

Using messages within your application can be a great way for your components to communicate whilst maintaining a loosely coupled architecture. This is important because you don’t have any nasty hard coded dependencies. Hard coded dependencies result in brittle, inflexible systems that can be hard to extend in the future.

The Messenger class in MVVMLight provides similar functionality to the EventAggregator class in PRISM.

You can download the WCF RIA sample application here:

http://www.stevenhollidge.com/blog-source-code/Silverblade5-WCF-RIA-MVVMLight-Messenger.zip

Please note that for demo purposes only menu options “Home > Search” and “Client > Details” have views that can be displayed within the content pane.  All other menu options will return an error.

Sunday, 1 May 2011

Debugging JavaScript in a Silverlight Project

In Visual Studio, you can set breakpoints in your managed Silverlight code and also in JavaScript code within the host Web page. However, as mentioned earlier in this topic, you cannot debug Silverlight code and JavaScript code at the same time. To debug JavaScript using Internet Explorer, you must first configure the browser to enable script debugging. In Internet Explorer, on the Tools menu, select Internet Options. Then, on the Advanced tab, do the following:
  • Clear the Disable Script Debugging (Internet Explorer) check box
  • Clear the Disable Script Debugging (Other) check box.
  • Select the Display a notification about every script error check box.
  • Clear the Show friendly HTTP error messages check box.
When you use F5 to debug your Silverlight-based application, Visual Studio will attach the Silverlight debugger by default. JavaScript breakpoints will display a ToolTip with the message "The breakpoint will not currently be hit. No symbols have been loaded for this document." You can debug your JavaScript code in one of two ways:
  • Use CTRL+F5 to start your application without the debugger. You can then attach the debugger to the browser process using the Script code type as described earlier in this topic. After you attach the debugger, you can refresh the browser to reload the Silverlight plug-in. This is necessary to debug your application startup code.
  • When your solution includes a Web project, disable the Silverlight debugger. In Visual Studio, select the Web project, and then on the Project menu, select ProjectName Properties. Then, on the Web tab, in theDebuggers section, clear the Silverlight check box. You can then use F5 to start your application with the script debugger attached.
When the script debugger is attached, the breakpoints in your managed Silverlight code will be disabled.