Jeff Griffin

Clay+MVVM Part II: Look Mom, Interactive Blogging!

Posted on May 19, 2011

Your Mom: That's nice, dear. What's blogging?
You: It's...never mind.

The following example illustrates the use of Clay with NotifyPropertyChangedBehavior to indirect control of a text value to a dynamic context. Said Context happens to be DLR via IronPython. It has no concept of the interface that the TextBox is binding to, but it must set the value to a property called "TextValue". Check out the example scripts under the "Script">"Script Examples..." menu, and write your own!  Use the "NotificationClay" constructor to instantiate Clay.

Install Microsoft Silverlight

This Python Console implementation had it's own set of challenges that I may address another day if I decide to use it again.

The NotificationClay class is a temporary fixture that keeps me from needing to implement my own ClayFactoryBehavior right this minute, though I'm not really crazy about subverting Clay's factory functionality.  I think a cooler, more permanent solution might (or will, if I get around to it) use MEF to resolve available behaviors and inject them into a MEFClayFactoryBehavior.

Links & Aknowlegements:
Clay+MVVM Part I
Awesome Famous Quotes RSS Feed: http://www.quotedb.com/
Clay: http://clay.codeplex.com/
http://weblogs.asp.net/bleroy/archive/2010/08/16/clay-malleable-c-dynamic-objects-part-1-why-we-need-it.aspx
My Clay Fork: https://hg01.codeplex.com/forks/griffinscs/clay/
Scott Hanselman: http://www.hanselman.com/blog/
http://www.hanselman.com/blog/NuGetPackageOfTheWeek6DynamicMalleableEnjoyableExpandoObjectsWithClay.aspx

Clay+MVVM, Part I

Posted on May 19, 2011

So earlier this month, the illustrious Scott Hanselman talked about a library called Clay.  Since nothing is on my radar until Scott Hanselman says it is, *wink*, I checked it out.  Actually Clay seemed like exactly what I had been needing.  First of all, ExpandoObject is great, especially for rapid prototyping of ViewModels, but they can't be extended.  So as my applications get more complex, Expandos either become relegated to the leaves of my object hierarchy, or need to be replaced with statically implemented code.  Now, I can't recommend making a fully dynamic ViewModel hierarchy.  The lack of Intellisense and Type safety will start to become agonizing.  But I'd like to decide for myself when it's time to stop expanding the dynamic aspect of my applications.

So before, when I said Clay sounded like exactly what I had been missing, it turned out that I was wrong.  Expando's are MVVM-ready out of the gate.  They use IDynamicMetaObjectProvider to serve up property metadata for binding, and fire property notifications when necessary.  Clay objects can be cast to an interface using a Castle DynamicProxy implementation, but don't implement INotifyPropertyChanged.  So let's look at how Clay objects can be extended.  I started by looking at the implementation of ClayFactory:

using ClaySharp.Behaviors;

namespace ClaySharp {
    public class ClayFactory : Clay {
        public ClayFactory() : base(new ClayFactoryBehavior(), new ArrayFactoryBehavior()) {
        }
    }
}

...well that's...terse. The ClayFactory is, itself, a Clay object. And Clay objects are nothing but containers for ClayBehaviors. As a result, I was a able to write NotifyPropertyChangedBehavior, which can implement INotifyPropertyChanged on Clay's behalf. Property notification is now a cross cutting concern.

The source code for NotifyPropertyChangedBehavior, as well as my Silverlight build of Clay, can be found in my Clay fork.

See why I needed a Silverlight Clay build in the next post, Clay+MVVM Part II: Look Mom, Interactive Blogging!

SecureString: Soup to Nuts, Part II

Posted on April 11, 2011

My last post, SecureString: Soup to Nuts, Part I, dealt with some basic rules around using the SecureString class in .NET and how to prepare the secret stored inside for persistence, without exposing the clear text to a CLR type.  In the second part, I'm going to discuss my solution for maintaining SecureString best practices, without sacrificing our MVVM design principles.  The XAML and code provided is in WPF, but it's applicable to Silverlight, as well with minimal tinkering.

First let's talk about PasswordBox.  The PasswordBox was designed to obscure the user-entered text, both visually and in memory.  That is to say, visually, it's much like the old Windows Forms MaskedTextBox, except it's specifically designed for secret data, and will only expose said secret in a clear text string if asked to do so,via the Password property.  It's important to understand that the Password property is only a helper that accesses the encrypted data member.  For this reason, it is not exposed as a DependencyProperty.  This is a source of frustration to developers who have no designs on a SecureString solution.  Alas, there's no pleasing everyone, and a Password DependencyProperty would make an acceptable SecureString implementation impossible with PasswordBox.  If you Google "PasswordBox MVVM" (without the quotes) you will find that the generally accepted solution for the CLR string camp, makes use of an attached property to expose a CLR string for binding.  This effectively takes the MaskedTextBox functionality of PasswordBox, and passes on memory security.

We want an MVVM solution that hands us a SecureString, so let's look at the SecurePassword property.  More frustration, as this is also not a DependencyProperty.  Before you go angrily writing an attached property to expose the SecureString, understand that this is by design, not neglect.  The first commandment of SecureString is to dispose of it when you're finished right?  The SecurePassword property gives us a SecureString to use one time, then dispose of it.

The MVVM way to do this is now staring us in the face.  We need to bind the event we're going to use to execute our users' credentials to an ICommand.


<PasswordBox x:Name="_passwordBox" ...>
        …
        <PasswordBox.InputBindings>
                <KeyBinding Key="Enter" Command="{Binding ExecuteCredentialsCommand}"
                                 CommandParameter="{Binding ElementName=_passwordBox}" />
            </PasswordBox.InputBindings>
</PasswordBox>
<Button Content="Login Button Text" …
        Command="{Binding ExecuteCredentialsCommand}"
        CommandParameter="{Binding ElementName=_passwordBox}"/>

In this example's ViewModel, I'm using Prism's DelegateCommand implementation of ICommand.


public ViewModelClassConstuctor(IRegionManager regionManager,
	IProxyDataProvider dataProvider)
{
	ExecuteCredentialsCommand = new DelegateCommand(
	//execute method
	delegate(object parameter)
	{
		SecureString securePassword = parameter as SecureString;
		if (parameter is PasswordBox)
			securePassword = ((PasswordBox)parameter).SecurePassword;
		try
		{
			//authentication/persistence model code
		}
		finally
		{
                    		securePassword.Dispose();
		}

                },
	//can execute method
	delegate(object parameter)
            {
		SecureString securePassword = parameter as SecureString;
		if (parameter is PasswordBox)
                        	securePassword = ((PasswordBox)parameter).SecurePassword;
		return securePassword != null && securePassword.Length > 0 &&
			!string.IsNullOrEmpty(UserName);
	});
	CredentialsChangedCommand = new DelegateCommand(
	delegate
	{
		ExecuteCredentialsCommand.RaiseCanExecuteChanged();
	});
}

public DelegateCommand ExecuteCredentialsCommand { get; private set; }
public DelegateCommand CredentialsChangedCommand { get; private set; }

There you have it. With the code from the previous entry, you can generate a nice authentication prompt with password persistence, without sacrificing memory security or your MVVM design. I hope this has been a helpful guide. Please leave a comment if you liked it, have something you'd like to share, or if you thought it could have been more comprehensive.