Friday, November 13, 2009

Friday Quickie: The *other* TemplateBinding syntax

Setting up the template for a new custom control in Silverlight is fraught at the best of times – the Silverlight runtime invariably swallows any error in the template and gives just a cryptic exception.

But stranger still is a limitation on how the {TemplateBinding ...} syntax can be used and the exception that is thrown when in error.

The {TemplateBinding ...} syntax provides a quick and simple way to bind properties within a control’s template to the properties of the control itself. According to the MSDN documentation, it’s a shortcut to the more full-featured {Binding ...} syntax. But what’s not clear from the documentation is that {TemplateBinding ...} can only bind a control property to a DependencyProperty on the control class.

If you try and use {TemplateBinding ...} against a normal property on the control, you get the strange exception shown right – confusing because the target control (WizardActionButton in the example) absolutely does have a State property.

The solution is to use the {Binding ...} syntax where the source property isn’t a DependencyProperty, and to use the {RelativeSource ...} syntax to specify that you’re actually binding to the control within its template.

Wrong:

<i4tControls:WizardActionButton x:Name="RetreatButtonPart"

Style="{StaticResource ActionButtonStyle}"

State="{TemplateBinding CanRetreat}"

Content="{TemplateBinding RetreatButtonContent}"

ContentTemplate="{TemplateBinding RetreatButtonContentTemplate}"

/>

Correct:

<i4tControls:WizardActionButton x:Name="RetreatButtonPart"

Style="{StaticResource ActionButtonStyle}"

State="{Binding Path=CanRetreat,RelativeSource={RelativeSource TemplatedParent}}"

Content="{TemplateBinding RetreatButtonContent}"

ContentTemplate="{TemplateBinding RetreatButtonContentTemplate}"

/>

Monday, September 14, 2009

Cometh The Gu

This should be old news to most readers (it was announced all of 3 days ago!), but bears re-posting.

Scott Guthrie is presenting in Manchester
on 29th September!

Why haven’t you registered already?

Gu’dness: http://developerdeveloperdeveloper.com/guathon/Default.aspx

Wednesday, September 09, 2009

Wednesday Quickie: Forcing event un-subscription

This is another really simple and obvious code snippet, but one well worth remembering – posted this morning by Fabrice MARGUERIE.

The crux is that event subscriptions can cause memory leaks – so ensuring they are un-subscribed is essential. The code snippet is designed to be used in the Dispose or Cleanup method on the publishing object, and forcibly disconnects any subscribers just before the publishing object is disposed.

if (SomeEvent != null)
{
foreach (EventHandler handler in SomeEvent.GetInvocationList())
SomeEvent -= handler;
}

Simple. Clean. Elegant. Use it!

Force your subscribers away: http://weblogs.asp.net/fmarguerie/archive/2009/09/09/forcing-event-unsubscription.aspx

Wednesday, August 05, 2009

Wednesday Quickie: Why Rounded Corners Work...

Came across this little article this afternoon via a tweet from @DaveSussman giving some background and justification for using rounded corners in your UI design. Well worth a read - I particularly like the examination of Apple hardware from a rounded corner point of view.

Round your rectangles: http://www.uiandus.com/2009/07/27/theories/realizations-of-rounded-rectangles/

Wednesday Tidbit: Smoooooooth scrolling a ScrollViewer

Spotted this great little article today on how to use the Mediator pattern to allow you to bind an animation to a scroll-viewer to get really slick scrolling.

Smooth as butter on a muffin: http://blogs.msdn.com/delay/archive/2009/08/04/scrolling-so-smooth-like-the-butter-on-a-muffin-how-to-animate-the-horizontal-verticaloffset-properties-of-a-scrollviewer.aspx

Monday, August 03, 2009

Monday Quickie: CSS Resources

This morning, @DaveSussman (http://blogs.ipona.com/davids) posted a link on Twitter to an excellent set of CSS resources:

http://is.gd/20qgs

This post is just an aide-memoire... and to share the CSS goodness.

Thursday, June 11, 2009

Thursday Quickie: Using the NULL pattern for event delegates

This little tweet turned up this morning in response to Mike Taulty wanting“the ability to fire an event without having to check it for null”.

richardblewett @mtaulty you can use the null pattern for this Mike, just do = delegate{}; on the event declaration
Thu, Jun 11 09:27:36 from Witty in reply to mtaulty


It’s pretty obvious when you think about it tho’...

public event EventHandler CriteriaChanged = delegate{};

Easy-peasey.

Update: Richard credits Andy Clymer the original idea (see comments). How far will the chain go?!

Thursday, May 21, 2009

Path animations in Silverlight

I attended the most-excellent NxtGenUG Manchester Launch event last night, where Richard Costall (@costall) gave a great overview of some of the new features in Silverlight 3.0.

One of the questions that came up was whether visuals could be animated on a non-circular path using the new Perspective 3D features. The answer was “No”, because the projection features just give rotation and offset in 2.5D space. I piped up that it MIGHT be possible to take a visual moving along a 2D animation path that is itself projected to give the required effect. Richard pointed out that Silverlight doesn’t have any PathAnimation support. 

A quick Google this morning, however, came up with an intriguing CodeProject post from  “Ineir” where he presents a PathAnimation framework for Silverlight that flattens the path into a set of line-segments suitable for use as Storyboard keyframes. With this, I think it WOULD be possible to have a complex path for visuals in 2.5D space. I’ll just have to try it at some point - this post is really just a “note-to-self”.

Moving in circles along curves: http://www.codeproject.com/KB/silverlight/PathAnimation.aspx

 

Tuesday, April 07, 2009

Getting Started with the Managed Extensibility Framework

Updated 2009-04-08 11:48

Thanks to Eric Nelson who included this as the Feature Article in today's MSDN UK Newsletter. (updated on the web soon, I hope!).

Also, and with perfect timing, the MEF Team have just released MEF Preview 5. Enjoy.

Joel


In this article, I will provide a basic overview of the Managed Extensibility Framework (MEF), and detail a practical sample of providing extensibility in your application.

But what is it? And why is using it a good idea?

According to its project web site, MEF is “a new library in .Net that enables greater reuse of applications and components.”[1]

MEF provides an engine that will dynamically extend your .NET application with plug-ins at run-time. You define the requirements to extend your application by decorating the classes in your core application with MEF’s attributes. Plug-ins can then be created as classes that will satisfy these requirements, again using MEF’s attributes to indicate what requirements the plug-in class will satisfy.

Currently in open development, the January 2009 release (Preview 4) is licensed under the MS-PL – which means you can use it right away for real projects. There is already a strong community grown up around MEF, including a Contrib project and plenty of articles on the web – but getting started with MEF can be a daunting prospect.

Glenn Block put it very succinctly:

“In MEF everything is an extension, everything is extensible (extensions themselves included).”[2]

Let’s look at a simple sample (download the code here) - a Login processing module which needs to allow extentions to the processing of a login request with custom code, without re-writing the login code and without the login module referencing the extensions.

To implement the extensibility for the login module, we define an interface that describes the functionality that a Login Extension should provide (ILoginExtension), an “extension point” in login code at the point where logically the checks should occur (in the sample this is in the LoginHelper class), and finally a LoginExtensions property (again in the LoginHelper) that will contain the extensions that MEF provides.

What makes MEF so easy is that the interface (ILoginExtension) exposed by the requirement is the only piece of shared information. MEF scans all assemblies in your application (and / or specific directories as you choose) for plug-ins that will satisfy the requirement and calls the setter for the LoginExtensions property, “injecting” the list of extensions so that the code at the extension point merely has to iterate the list and call the implementation method on each extension.

This magic happens when, in the LoginHelper’s constructor, we use MEF to generate a catalog of all extensions (classes decorated with an Export attribute) and requirements (classes with properties decorated with an Import attribute). Better still, the catalog can watch the file system for new plug-ins being added on the fly.

This catalog is then passed to the composition engine (an instance of the MEF CompositionContainer class) and the container statisfies all the requirements (Imports) found with the matching extensions (Exports).

Now we’ve looked at MEF in overview, let’s dive into our sample code, starting with the ILoginExtension interface:

    public interface ILoginExtension

    {

        void LoginEx(ref Session session);

    }

So our extension point will call the LoginEx method of any extensions, passing in a reference to the current user’s session. The LoginEx method can then do any additional checks it needs and throw an exception (or modify the session information) based on whatever its own requirements are.

Next the extension point itself:


public Session Login(string username, string password)

        {

            // Get a session - this is abstracted via MEF too.

            var session = SessionProvider.GetSession(username, password);


            // =============================================

            // EXTENSION POINT

            // =============================================


            // process all the extensions

            if (LoginExtensions != null)

            {

                Console.WriteLine(string.Format("LoginHelper: Found {0} extensions...",
LoginExtensions.Count()));


                foreach (var extension in LoginExtensions)

                {

                    extension.LoginEx(ref session);

                }

            }


            // =============================================

            // END EXTENSION POINT

            // =============================================


            return session;

        }

This code is as simple as it comes – after we do our initial login check and have a session, just iterate the extensions, calling them each in turn.

The LoginExtensions property is the point at which MEF will inject the extension instances:

        [Import(AllowRecomposition = true)]

        public IEnumerable<ILoginExtension> LoginExtensions { get; set; }

Note that MEF automatically understands that if a module requires an IEnumerable of a type, then it is to inject a list of class instances that satisfy that requirement into the property. If the requirement is for a single instance, then just the first matching extension will get injected. So we could also abstract how a session is created (for example, from a database, or via a web service), and the LoginHelper can indicate its need for a provider with a property for that:

        [Import]

        public ISessionProvider SessionProvider { get; set; }

In the sample, this composition logic is encapsulated in a static ExtensionHelper class that provides a single container of all the Imports and Exports, as well as a simple method to allow a module to compose itself.

    public static class ExtensionHelper

    {

...


        public static void Compose(object compositionTarget)

        {

            // configure our Imports so that we've loaded any plugins.

            var batch = new CompositionBatch();

            batch.AddPart(compositionTarget);


            using (var container = GetCompositionContainer())

            {

                container.Compose(batch);

            }

        }


...

    }

The Compose method is the heart of the helper – it retrieves the composition container from a helper method, then instructs that container to satisfy any requirements of the object passed into it.

We centralise our container generation so that the catalog of imports and exports is generated only once – parsing all the assemblies in a large project can take a little time.

    public static class ExtensionHelper

    {

        private static AggregateCatalog _catalog;


        private static object _padlock = new object();


        public static CompositionContainer GetCompositionContainer()

        {

            if (_catalog == null)

            {

                lock (_padlock)

                {

                    _catalog = new AggregateCatalog();

 

                    // Add the current executable

                    _catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));


                    // Add all the assemblies in the executable's directory

                    _catalog.Catalogs.Add(new DirectoryCatalog(".", false, "*.dll"));


                    // add any plugins assemblies

                    if (PlugInsDirectoryExists)

                    {

                        _catalog.Catalogs.Add(new DirectoryCatalog(PlugInsDirectory, true, "*.dll"));

                    }

                }

            }


            // finally, build the composition container

            var container = new CompositionContainer(_catalog);


            return container;

        }


...

    }

You will notice that we add three “sub-catalogs” to our application’s plug-in catalog:

  1. A catalog containing any imports and exports found in the current executing assembly
  2. A catalog containing imports and exports from any other assemblies found in the current working directory. This is a “static” catalog.

    Note: For windows services & ASP.Net, the working directory is NOT the executable’s installation directory, so you may need to compensate!.

  3. A catalog containing imports and exports from any assemblies found in a specific “plug-ins” directory.

    This catalog is “dynamic”, indicated by the true flag passed into its constructor, and will “watch” the plug-ins directory for any assemblies being added or removed. The next composition that happens would then automatically pick up any new plug-ins – a really powerful feature.

We cache the catalog so that the assembly resolution happens only once, but create a new composition container each time just to be on the safe side and avoid any interactions between objects being composed.

With this helper class available, the LoginHelper’s constructor becomes about as simple as you could hope for:

        public LoginHelper()

        {

            ExtensionHelper.Compose(this);

        }

Finally, we can implement an extension in a completely separate assembly if required, just by implementing the requirement interface (e.g. ILoginExtension) and decorating the class appropriately. So we can implement a FooLoginCheckExtension plug-in class thus:

    [CompositionOptions(CreationPolicy = CreationPolicy.NonShared)]

    [Export(typeof(ILoginExtension))]

    public class FooLoginCheckExtension : ILoginExtension

    {


        public void LoginEx(ref Session session)

        {

            Console.WriteLine(string.Format(" Foo: Processing {0}", session.Guid));

        }

    }

MEF also is recursive – if any extensions need providers, or have other extension points themselves, these too will be satisfied when the MEF composes the LoginHelper. This means you COULD write a completely interface-driven system, where every component is bound in dynamically using MEF.

Even for this simple case, the MEF provides an elegant and above all SIMPLE way of defining and implementing extensibility within your application. Use it once, and you’ll be using it again and again to implement extension points in your code that will make it much more flexible.

On a final note, it should be stressed that MEF is NOT an Inversion of Control container[3] - it targets purely one goal: Dependency Management. But it does this well, and as such is a worthy addition to any developer’s toolset.


[1] http://www.codeplex.com/MEF

[2] http://codebetter.com/blogs/glenn.block/archive/2008/09/25/what-is-the-managed-extensibility-framework.aspx

[3] http://ayende.com/Blog/archive/2008/09/25/the-managed-extensibility-framework.aspx

Wednesday, April 01, 2009

Excellent new library for .Net 4.1

@shanselman tweeted this morning about an incubator project from DevDiv that’s examining the problem of arbitrary input captured via strings. Eilon Lipton blogs about it here and it looks really useful for adding to the web app layer to help with string parsing, and draws on the concept of mutual exclusion of properties when observing a system.

It takes a bit to get your head around, but it’s well worth a look at this morning.

Check it out here: http://weblogs.asp.net/leftslipper/archive/2009/04/01/the-string-or-the-cat-a-new-net-framework-library.aspx

Wednesday, February 25, 2009

Configurationless WCF - Kinda

WCF 4.0 is shaping up to be quite an interesting release.

This morning, Jesus Rodriguez blogged about support for WS-Discovery in WCF 4.0, including a detailed basic “how-to” to get us started. What’s interesting is that this level of WS-Discovery support will allow for much more dynamicism in our WCF based systems.

For example, now we might use a Broker as a first endpoint that then provides a resolution mechanism for other services. Using this new mechanism not only can a client can use WS-Discovery to find all available Brokers, but the Brokers themselves can monitor the services available across a server farm and self-configure accordingly. Neato!

Discover yourself: http://weblogs.asp.net/gsusx/archive/2009/02/13/using-ws-discovery-in-wcf-4-0.aspx

 

 

 

Tuesday, February 24, 2009

Put out a contract on your code

I always read Somasegar’s postings with interest – nearly as much as I give to ScottGu’s – and today was no exception.

In a posting today, Somesgar announced the release of a Visual Studio companion product from the DevLabs called Code Contracts for .Net.

This is exciting because it provides a mechanism for us developers to employ design-by-contract techniques in our .Net code. I’d previously rolled my own (very basic) equivalents to this, but this tool seems much superior because it includes an IL rewriter and a static checker as well as the static library used to express the contract specification. The static checker even provides suggestions for contract specifications based on the code in a method – very cool.

Plan your hit by reading about it here: http://blogs.msdn.com/somasegar/archive/2009/02/23/devlabs-code-contracts-for-net.aspx

Pull the trigger and get it here: http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx

Friday, February 20, 2009

Friday Quick Tip: WPF Data Binding

@mtaulty tweeted with this cheat-sheet for WPF (and by extension Silverlight) data binding.

Handy.

Wednesday, January 28, 2009

Patterns & Practices

Eric Nelson (@ericnel) tweeted this morning about the patterns & practices Guidance Explorer tool.

Now I’d seen this before, but had missed the Visual Studio 2008 Guidance Explorer Add-In that brings guidance directly into VS.

I’d also missed that there’s a way to get the guidance in “bite-sized” chunks via an RSS feed for Outlook1.

Why is this relevant? Well, the p&p team’s guidance is a baseline for .net development – being at least aware of the best practice is certain to improve your own development. Time to do some configuration…

p&p Guidance Explorer: http://www.codeplex.com/guidanceExplorer

VS2008 Add-In: http://www.codeplex.com/GEVSAddIn

p&p Guidance RSS: http://blogs.msdn.com/alikl/archive/2008/01/03/consume-patterns-practices-guidance-explorer-via-rss-using-outlook-2007.aspx

 

1Disclaimer: Other RSS readers are available.

Friday, January 23, 2009

Quickie: Simulating DataContextChanged in Silverlight

One of the key line-of-business-app features of Silverlight is the ability to databind – and we use it everywhere.

So it’s slightly odd that the DataContextChanged event is internal in Silverlight (it’s public in WPF). How on earth can we then know if our data context has been changed?

The answer’s pretty simple, and is properly documented on The Problem Solver blog.

The solution is to create a custom DependencyProperty and explicitly bind it, thus:


public
partial class PersonHeader : UserControl
    {
        public PersonHeader()
        {
            // Required to initialize variables
            InitializeComponent();
            SetBinding(DataContextWatcherProperty, new Binding());
        }

        public static readonly DependencyProperty DataContextWatcherProperty =
            DependencyProperty.Register("DataContextWatcher",
                                        typeof (Object), typeof (PersonHeader),
                                        new PropertyMetadata(DataContextChanged));

        private static void DataContextChanged(object sender,
                                               DependencyPropertyChangedEventArgs e)
        {
            var personHeader = (PersonHeader) sender;
            // Update the control as needed
        }
        …
}

DataContextChanged Solution: http://msmvps.com/blogs/theproblemsolver/archive/2008/12/29/how-to-know-when-the-datacontext-changed-in-your-control.aspx  

Thursday, January 22, 2009

Simulating internal links in a Silverlight ScrollViewer

One of the unsung heroes of HTML is the ability to use internal links within a document for navigation within a page.

In HTML, this is achieved by placing name tags (e.g. <A Name=”top>…</A>) as invisible placeholders throughout the document, and then referencing them from internal hyperlinks (e.g. <A HREF=”#target”>Back to top</a>) wherever you want the navigation to appear.

In Silverlight, it’s common to use a ScrollViewer control to provide a scrolling viewport over some other set of controls, but there’s no analogue to the internal hyperlink to allow us to easily scroll that viewport. It’s easy enough to use HyperlinkButton controls to provide the navigation, but how to scroll the ScrollViewer?

My solution is a simple one – provide an extension method that commands a ScrollViewer to position itself so that a specific control is visible. The click event handler for the HyperlinkButton can then easily simulate internal links and position the ScrollViewer.

 

In the following Xaml source snippet I’ve used HeaderedItemsControls to contain my sections:

 

<!-- Navigation -->

<StackPanel Orientation="Horizontal" >

<TextBlock Text="Jump to" />

<HyperlinkButton x:Name="Section1Link" Content="First Section" Click=" Section1Link _Click" />

<HyperlinkButton x:Name="Section2Link" Content="Second Section" Click="Section2Link_Click" />

      …

</StackPanel>

 

<!-- Viewport -->

<ScrollViewer x:Name="Scroller”>

<StackPanel>

<HeaderedItemsControl x:Name="Section1">

</HeaderedItemsControl>

<HeaderedItemsControl x:Name="Section2">

</HeaderedItemsControl>

            …

</StackPanel>

</ScrollViewer>

 

By making sure the “target” HeaderedItemsControls have names, the click method for the HyperlinkButton is as simple as you could wish for:

 

/// <summary>

/// Handles the Click event of the NamesSectionLink control.

/// </summary>

/// <param name="sender">The source of the event.</param>

/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>

private void Section1Link_Click(object sender, RoutedEventArgs e)

{

DetailsScroller.PositionOnControl(Section1);

}

 

And finally, the extension method itself.

 

/// <summary>

/// Extension methods for ScrollViewer controls

/// </summary>

public static class ScrollViewerExtensions

{

/// <summary>

/// Extension method that positions the scroll viewer to show the specified control

/// </summary>

/// <param name="scrollViewer">The scroll viewer.</param>

/// <param name="targetControl">The target control.</param>

public static void PositionOnControl(this ScrollViewer scrollViewer, UIElement targetControl)

{

var transform = targetControl.TransformToVisual(scrollViewer);

            var offset = transform.Transform(new Point(0, 0));

            scrollViewer.ScrollToVerticalOffset(offset.Y);

}       
}

 

The only magic is in the transformation used to convert the origin coordinates of the target into a scroll offset for the ScrollViewer.

Enjoy!