Timmy Kokke

Expression Blend for Developers

On April 28th I was given the opportunity to speak at the Microsoft DevDays in The Hague in the Netherlands. My session about Expression Blend for Developers was chosen by the community to fill one of the Wildcard slots.

The idea for this session came when I saw a coworker tinker with XAML in visual studio to create an animation when he had Expression Blend available through his MSDN subscription. It turned out that a lot of Silverlight, WPF and Windows Phone 7 developers didn’t know they could use Expression Blend. “Expression Blend is for designers”, they thought.

imageThe first part of the session I explained Sample Data. I demonstrated how to create it and how to use it to create bindings. I demonstrated how to use the Visual State manager and set them by using behaviors. In the last demo I showed a couple of my favorite features of Expression Blend (including the gradient picker).

The recording of my session is available online and for download at Channel9. Although the slides are in English, the session itself is spoken in Dutch.

The slides contain all content shown in the demos. You can download them here.

Last but not least I would like to thank everyone for coming to my session. I hope I was able to send you home with little more knowledge that you had when you came in and inspired you to start using Expression Blend in your job.

First Windows Phone 7 Application

Duck’n’Cow

My first Windows Phone 7 application is available in the marketplace, Duck’n’Cow. Feel free to download and play with it (and rate it of course Winking smile).

background1

I build the application to try some of the features of the Windows Phone. In this application I focused mainly on the accelerometers.

The application shows a Duck and a Cow, hidden in a circle. When you shake the phone the duck pops up and you hear it quack. When you turn the phone upside down, you’ll see the cow pop up.

Screenshot4Screenshot5

Idea

I wanted to create a funny looking application that could be used to express your feelings about something when attending a presentation. A positive, cheering and green, action when you like something and a negative, red, action when disliking what is being told. But with a wink. Just a simple thumbs up or down wasn’t fun enough. So I decided to go for a moo and a quack, which automatically led to duck and a cow.

Gestures

The application uses to gestures, shaking and turning upside down. The turning upside down reminds of the nostalgic cow-in-a-box toys. But the gesture also resembles turning your thumb down to express dislikeness. The shaking motion is inspired by cheering and applauding.

I started off by reading the accelerometer data myself. By calculating the change of the accelerometers in X,Y and Z directions I was able to detect a shaking motion. By reading the Y accelerometer I was able to tell if the phone was turned upside down. Very soon I ran into issues whit this method, because the raw data returned by the accelerometers was too course (?!). I needed some kind of filtering to smooth things out a little. When looking around to find the best approach I came across the ShakeGesture library, which is build on the AccelerometerHelper library. Both these libraries helped my abstracting out the raw accelerometer data and use filtered events to get the data right.

Graphics and Xaml

As soon as I knew I was going to use the concept of a duck and a cow I started sketching. Below is the original sketch.

Sketch

I’ve digitized the sketch in Adobe Illustrator to be able to scale it to any size so I could use the same image for all the places where tiles were needed, like the live-tile or the tile in the marketplace.

The first version of the application only contained this image. I’ve added it as .png in expression blend. A couple of people I’ve showed the app to told me they’d rather see some animation. So I took the image apart and separated into a circle, the duck and the cow. And added the animations in Expression Blend.

Screenshot3

I’ve created a UserControl to make the switching between states a little more convenient. The control contains 4 states, duck, cow, both and none.

Wrap-up

That’s it about the app for now. If you’ve got a windows phone yourself, feel free to try the app. You can download it through here.

To stay up-to-date about the application you can follow the app on twitter: @DuckAndCow . For comments, bug or feature requests, send me an email at DuckAndCow[at]hotmail[dot]nl.

To be informed about anything else that’s going on my blog, follow me on twitter (@sorskoot) or subscribe to the RSS feed.

Mix11- just a bunch of links

Here’s just a quick list of some of the links to stuff shown in the first Mix11 Keynote.

IE10 preview: http://ie.microsoft.com/testdrive/

ASP.NET MVC 3 Tools Update: http://bit.ly/huiRE8

Modernizer: http://www.modernizr.com/

NuGet  1.2: http://bit.ly/dNe0oG

Webmatrix, Orchard, ASP.NET MVC 3 Tools Update and more in the Web Platform Installer: http://www.microsoft.com/web/downloads/platform.aspx

Have fun!

Customizing Silverlight properties for Visual Designers

When building custom or user controls you probably end up with a large amount of properties on that control. When using the control in a visual designer like Blend or the Visual Studio designer these properties just show up. Adding a bit of structure in this can be done very easily by adding a couple of attributes to the properties.

The attributes to let the visual design know what to do can be found in the System.ComponentModel namespace. There’s a WPF version of this namespace also.

For the sake of simplicity I’ve created a UserControl and set the background color of the LayoutRoot grid to red to be able to spot it in the designer. I’ll add properties with attributes to that control and show you what happens in Visual Studio and Expression Blend.

Categorizing

By default all properties on UserControls are grouped together in the Miscellaneous section at the bottom of the properties Panels in Blend and or in the Others section in Visual Studio.

The first property I’ve named CategoryDemo1 and it’s of type string. It doesn’t have an attribute to go with it.

When adding the control to the MainPage the properties look like this:

image

image

To add a property to an existing category add a Category Attribute to the property and give it the name of the category you would like to have you property added too.

For example, this adds the property Category2 to the Layout category:

[Category("Layout")]
public string CategoryDemo2 { get; set; }

imageimage

Your property might need a category of its own. This can be done just as easily as adding to an existing category. Just use a category name that doesn’t exist yet.

[Category("CustomCategory")]
public string CategoryDemo3 { get; set; }

imageimage

You might have noticed that some categories are named differently in Visual Studio and Blend, there might even be some localization used. Take for example the Common category in Visual Studio. It is called Common Properties in Expression Blend. The CategoryAttribute class contains a couple of static properties that return the CategoryAttribute for a default category. Unfortunately the static properties can’t be used when placing an attribute on a property. In part 2 of this tutorial I’ll talk about how this can be done. In the meantime you’ll have to guess a little.

The common properties category can be used like this:

[Category("Common Properties")]
public string CategoryDemo4 { get; set; }

imageimage

Description

Often you might want to add a description to a property, like you would do in code. You can use the DescriptionAtrribute for this purpose.

[Category("CustomCategory")]
[Description("This is a description")]
public string DescriptionExample { get; set; }

imageimage

Default Value

Often you would like to set a default value for a property. Numeric or a string or whatever. When the value is reset in the designer the property should show the default value. You can accomplish this by adding a DefaultValueAttribute to the property.

[Category("CustomCategory")]
[DefaultValue("Hello")]
public string DefaultExample { get; set; }

imageimage

Hide properties

There are situations where you have properties that you do not want to expose through the UI. In cases like this you can set the BrowsableAttribute to false.

[Browsable(false)]
public string NotBrowsable { get; set; }

 

(intentionally left blank: can’t make a screenshot of something that’s not there)

AlternateContentProperty

The last thing I would like to show is the AlternateContentPropertyAttribute. I’m still not sure what it is used for, but it lets Expression Blend know to display the property in a different way. The property is shown in the Objects and Timeline panel. The charting controls in the Silverlight Toolkit do this too. Visual Studio doesn’t seem to do anything with this property.

[Category("CustomCategory")] 
    [AlternateContentProperty]
public string AlternateExample { get; set; }

image

Wrap up

As you can see there are various possibilities on how to display your properties in the design surfaces. But there is more. Have you ever notices the .design.dll files that came with Silverlight and the Silverlight Toolkit? I’ll continue this article in part 2 about these.

To be the first to know when it’s done, please subscribe to the RSS feed or follow me on twitter (@sorskoot).

What’s new in the Expression Design January 2011 preview?

imageThis week Microsoft released the January 2011 preview of Expression Design 5. The preview can be downloaded here: http://bit.ly/gPxBMr.

The January 2011 preview contains only two new features:

  • EPS import
  • Multiple selection in the Layers panel

 

EPS Import

LabIconI’ve found this image in my Image Library.

It’s in .EPS format and I would like to use it in one of my designs. With the new Expression Design preview I can import it directly without having to convert it to another format first.

To do this, go to the “File” menu and select “Import Encapsulated Postscript File…”.

image

An open-file dialog appears where you can select the .EPS file you would like to open. After hitting “open” a progress bar shows at the bottom right of Expression Design for a moment.

image

And done. The .EPS file is opened in your .design file.

image

Multiple selection in layers panel

In the current version of Design, Expression Design 4, it is possible to select multiple layers by holding the Shift key. When doing this you can add layers to the selection.

In the new Expression Design January Preview this process has changed and works in the same way you might be used to in other programs like Windows Explorer for example.

By selecting a layer and pressing the Shift key while selecting another layer you can select a range of layers.

image

By selecting layers while holding the Control key you can add individual layers to the selection.

image

Conclusion

Only two features are added in the preview. I hope the Expression Design team will add a lot more features, so the final version of Expression Design 5 can match up to Adobe Illustrator. At least I am glad that Expression Design is still alive. 

Expression Blend Tips and Tricks at Mix11?

I was a bit surprised when I got an email from the Mix11 team congratulating me on my session proposal making the first cut. So now it’s up to the you to vote on your favorite sessions. After voting for mine, you can vote on 9 other sessions Winking smile. The entire list can be found here. The voting period ends on February 4, 2011.

 

My session will be focused on Expression Blend. I’ll be talking about the Visual State Manager, Sample Data and Behaviors. And I show some helpful features along way.  

 

So go and vote now, and I hope to see you at Mix11!

 

Expression Blend Tips and Tricks

Learn how Expression Blend can help you when building WPF, Silverlight or WP7 applications. Find out how to use behaviors and how to build them. See how sample data can be used and created. And how you can use the visual state manager to set and animate the properties of the controls in your applications.

 

300x250_Mix11_011011_US_b

Dependency Injection, MVVM, Ninject and Silverlight

Intro

The MVVM patterns is pretty popular these days. In Silverlight and WPF it is used a lot. Dependency Injection is also used very often. In this tutorials I would like to show you how to use Dependency Injection when building a Silverlight application using the MVVM pattern.

There are numerous Dependency Injection Frameworks. For this tutorial I’ve chosen Ninject. The main idea on how to implement DI in your application is pretty much the same for all frameworks. In this tutorial I hope I can give you a small introduction in using Ninject in you projects.

Ninject is an open source project which can be found at www.ninject.org. Ninject is also available through the NuGet tool in Visual Studio. Have look at my NuGet tutorial on how to get it through that.

Demo project

The demo project is a very simple game. The objective of the game is to guess a number. There will be a web service that can be requested to provide a random number. The game consists of three screens or Views. The first, StartView, asks the player for the maximum number. The second screen, GameView, ask the player to guess a number between 0 and the maximum number given on the first screen. The last screen, ResultView, shows whether the guess number equals the randomly chosen number and provides the user with two options, try again or restart. These views are displayed inside a fourth view, ShellView, that handles the navigation.

Each view contains one or more commands and one or more properties to handle interaction with the user. The views contain only the most basic controls to interact. On the StartView there’s a textbox to set the maximum number to guess for and a button to start playing. The GameView contains a textbox to get the guess from the user and a button that triggers navigation to the ResultView. The ResultView contains a styled checkbox to show if the guess was correct and two buttons. One to navigate to the GameView, to try guessing again, and one to navigate to the StartView, to start the game all over.

The generation of a random number takes place on the server. A proxy class is placed between the calls to the service and the caller of the methods. This implementation of the custom IProxyService interface will be replaced when unit testing to be able to use a dummy implementation.

The navigation works by calling a method on shared class between the viewmodels.The INavigator interface contains the method. It also contains an event the ShellViewModel is listening to. Calling the method would fire the event and causes the ShellViewModel to update the visible view.

Setup the IOC

Ninject uses a Kernel to setup the Inversion of Control, or IOC, container. The IOC container is filled with classes and interfaces that go together. We the program asks the Kernel for a specific type, this will be returned by the container. By default you can instantiate the StandardKernel class. The constructor of the StandardKernel class takes a NinjectModule as a parameter.

To separate the construction of the Module and the construction of the Kernel, the NumberGameModule class is created. The class inherits from the NinjectModule class. It has to implement the abstract Load method.

private IKernel Kernel;
...
Kernel =
    new StandardKernel(new NumberGameModule());

The binding of classes together for the IOC container happens in the Load method of the NumberGameModule class. The method is called automatically when the Kernel is created.

public class NumberGameModule : NinjectModule
{
    public override void Load()
    {
        //todo: Inititialize the IOC.
    }
}

Often an interface is bound to a class that implements that interface. This way alternative uses of that interface can be used if needed, when Unit Testing for example. The binding uses a fluent syntax and looks like this:

this.Bind<IServiceProxy>().To<ServiceProxy>();

This literally Binds the IServiceProxy interface To the ServiceProxy class. This means that every time you need a ServiceProxy you call the Get method on the kernel, like this:

kernel.Get<IServiceProxy>();

In this case the kernel instantiates a new ServiceProxy for you. If, in case of testing for example, you bind a TestServiceProxy to the IServiceProxy interface. The TestServiceProxy will be returned, without changing the call to the Get method. In the next section you will see the true power of this.

Sometimes you don’t want to use an interface for a class. You just want to have an instance when asking for it. In situations like this you can bind a class to itself. The syntax for this is straight forward again:

this.Bind<GameViewModel>().ToSelf();

This sounds pretty useless, but to get all the nice features of dependency injection you’ll have to let the framework instantiate your classes, and never use the new keyword.

Lifetime

One of these features is using singletons. There a lot’s of reasons not to use the singleton pattern, they are hell to unit test for example. When using dependency injection you can have the framework manage the singletons. Which means that every time you ask the kernel to give you a specific type, you always get the same instance. But, in case of unit testing you can have it return a new instance every time. Without any changes to the code under test. For example, say you want to bind the INavigator interface to the Navigator class using a Singleton scope:

this.Bind<INavigator>().To<Navigator>()
    .InSingletonScope();

Without specifying a scope the InTransientScope() variation is used. If you need it, you can also have Ninject instantiate a new instance once every thread by using the InThreadScope() method.

Context

Often you find the need to use different implementations of classes in different contexts. For example, when using Expression Blend to create your views. You don’t want to call web services and do complex calculations, but only a simple implementation to work with. You can have Ninject create different instances based on the context. In this example the normal implementation is created in Singleton scope. When using this class in a designer, like Blend, a new instance is created on every call. A delegate method is used. The method should return a boolean. In the example below a lambda is used to shorten the syntax.

bool designContext =
    DesignerProperties.GetIsInDesignMode(
        App.Current.RootVisual);

this.Bind<IGame>()
    .To<Game>()
    .When(x => !designContext)
    .InSingletonScope();

this.Bind<IGame>()
    .To<AlternativeGame>()
    .When(x => designContext);

 

Constructor Injection

When having Ninject instantiate your classes Ninject automatically resolves the parameters of the constructor. This means that if your constructor takes two interfaces and Ninject knows how to resolve these, the implementation of the interfaces is injected into the constructor. For example, the constructor of the ResultViewModel takes two parameters. The IGame interface and the INavigator interface. Both these interfaces are known to Ninject and therefore can be resolved when a ResultViewModel is created.

public ResultViewModel(IGame game,
                       INavigator navigator)
{
...
}

Without using Dependency Injection you probably would new a game and a navigator inside the constructor, and thus create a dependency on these classes. When using injection you only have a dependency on an interface, and can use different implementations when needed. Which makes testing a lot easier.

There are occasions however where you want to have control over which constructor is used for injection. Ninject looks for the constructor that takes the most known parameters and tries to use that when resolving the class. If it can’t find any it will use the default parameterless constructor.  You can mark a constructor with the Inject attribute to force Ninject to use that one when resolving. Marking multiple constructors with the attribute will result in an exception. 

Binding the VM to the V

The last step would be to glue it all together. The kernel must be build and filled somewhere, and the viewmodels must be bound to the Views somehow. To do all this one could use the View Model Locator pattern. The ViewModelLocator class contains properties that represent the viewmodels used. The class has a static constructor so it can be constructed in Xaml. By doing this the ViewModelLocator can be defined a resource and be used throughout the application. The implementation of the constructor is described earlier. Only a null-check is added. The ViewModelLocator looks like this:

public class ViewModelLocator
{
    public ShellViewModel ShellViewModel
    {
        get {
            return Kernel.Get<ShellViewModel>();
        }
    }

    // other ViewModels are defined
    // the same way.

    private static readonly IKernel Kernel;

    static ViewModelLocator()
    {
        if (Kernel == null)
        {
            Kernel = new StandardKernel(
                new NumberGameModule());
        }
    }
}

To get the ViewModelLocator known in Xaml you’ll have to define it as a resource. The best place to do this is directly in your App.xaml. In the Resources section define a new resource with and use a key like “ViewModelLocator”, like this:

<Application
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:Common="clr-namespace:NumberGame.Common"
  x:Class="NumberGame.App">

    <Application.Resources>
        <Common:ViewModelLocator
            x:Key="ViewModelLocator"/>
    </Application.Resources>
</Application>

When the application is started the resource is created, and the static constructor is executed. You can use the ViewModelLocator as a StaticResource now.

To get the right viewmodel in a view the DataContext of that particular view has to be bound to a property of the ViewModelLocator resource. In case of the ShellView you would like use the ShellViewModel property of the ViewModelLocator. Add a line like below to the definition of your view in xaml:

DataContext="{Binding ShellViewModel,
    Source={StaticResource ViewModelLocator}}"

All this is saying that you would like to set the path of the binding to the ShellViewModel property of the ViewModelLocator StaticResource.

 

Wrap up

There are a lot of situations where you might want to have Ninject do more than what is explained in this tutorial. Ninject can do a lot more, which is left out for the sake of simplicity. Sometimes you’ll need specific custom factory methods to create your objects or you might have separated your classes into a different assembly. Ninject can be used in situations like this too. If something isn’t supported right out of the box, Ninject is extensible and open source. 

You can find the demo project that goes with this tutorial here.

If you have any questions, suggestion or just want to leave a comment you can use the area below, feel free to send me an email or contact me through twitter. To be the first to know when there’s a new tutorial online you can also subscribe to the RSS feed.

Unit testing MVVM in Silverlight – SDN Event–Code and Slides

Yesterday I gave a talk at the SDN Event in Zeist about Unit testing MVVM in Silverlight. I talked briefly about how MVVM works in Silverlight and dove deeper into the Unit Testing Framework which is available in the Silverlight Toolkit. After going through the various attributes used in the framework I gave a demonstration on how to use StatLight, a command line tool for running tests.

I would like to thank anyone who attended my session for coming and SDN for organizing and hosting this great and informative day.

 

HTML5 – An Introduction – Code and Slides

Today I gave a talk about HTML5 at the UNIT4 DevDay. Thanks to UNIT4 for giving me this opportunity and thanks to everyone who attended my session!

Although HTML5 far from completed, it is a lot of fun to work with. Not all tags used in HTML5 are supported by the browsers. You can try the demos on different browsers to see if they work.

  • Download the code here.
  • Download the slides here.

For those at UNIT4 who missed this presentation, I will repeat it at UNIT4 Internet Solutions and at UNIT4 Oost Nederland.  So maybe I’ll see you there. The dates this will happen follow as soon as they are known.

If you have any questions, ideas, suggestions or a shout-out, just let me know by writing a comment below this post, sending me an email or contacting my though twitter @Sorskoot.

197328470

Technorati Tags:

NuGet

If you often use open source libraries you probably have a large library with various tools, like I do. NuGet is an extension for visual studio that enables you to install, uninstall and upgrade open source packages into your application very easily. Say for example you want to use MvvmLight or Ninject in your project, with NuGet it’s nothing more that tell it to add the package to your project.

NuGet

NuGet (formerly known as NuPack) is a free, open source developer focused package management system for the .NET platform.

You can download the .vsix extension at http://nuget.codeplex.com.

image

After installing it you can start adding packages to your project in two ways. The first is by right clicking in the Solution Explorer and selecting the Add Library Package Reference… option.

image

This will present you with a dialog where you can find and install a package. To see the package available, select the Online option from the list on the left. You can use the text box on the top right to filter the list to get to the package you want to use. Hit the install button to add the package to your project.

image

To remove a package, go to the same window. The installed packages are shown on the first page. Hit the uninstall button next to the package you would like to remove from your project.

image

Another way of managing packages is thru a powershell like interface, using the keyboard. You can get to the console window by going to the View menu and selecting Other Windows –> Package Manager Console.

image

The following window will show up (the coloration might be different based on your personal color scheme settings in Visual Studio). 

image

You can manage your packages by using a few simple commands.

  •  
    • List-Package
    • Install-Package
    • Update-Package
    • Uninstall-Package

These do exactly what can be expected. The Install, Update and Uninstall need at least the name of the package as parameter. You can type help before each of these commands to get information on the other parameters.

image

One last thing. You can use the Tab key to auto-complete commands and even parameters.

Shout it

Twitter