Logo Subtitle Subtitle

Extension Methods in Javascript

Download the demo project

One of the biggest development boosts is having a decent boilerplate code base you can use when starting new projects. One way to encourage re-use of code is the use of .NET extension methods. I like them so much, me and Fons Sonnemans made a website dedicated to them. My favorite methods are Chris Meijers IsFilled() and IsEmpty(). I use them all the time to avoid checking for !String.IsNullOrEmpty() which is a lot harder to read.

I am currently working on a HTML5 website that uses KnockoutJS, jQuery and a bit of MVC3 and need to check if a string has a value. I know Javascript should just support:

if (value) {
   // you are here if value != null and value.length>0
}

but for some reason it did not work for me in combination with a Knockout Observable so I created a function that returns true when the string is filled. Then I wondered if Javascript has support for extension methods. And it has!

Javascript Extension Methods

The following code is a js file (/ExtensionMethods/String.js) that you can include in your project:

String.prototype.IsFilled = function () {
    if (this && this.length > 0) {
        return true;
    }
    return false;
}

String.prototype.IsEmpty = function () {
    return !this.IsFilled();
}

Include and use the extensionmethod like this:

<!DOCTYPE html>
<html>
<head>
    <title>Javascript ExtensionMethods</title>
    <script src="Extensionmethods/String.js"></script>
    <script type="text/javascript">
      //<![CDATA[
        var name="Loek van den Ouweland";
        document.write("name.IsFilled(): "+name.IsFilled());
        document.write("<br/>");
        document.write("name.IsEmpty(): "+name.IsEmpty());
      //]]>
    </script>
</head>
<body>
  <h1>ExtensionMethods in Javascript</h1>
  <h2><a href="http://loekvandenouweland.com/">http://loekvandenouweland.com/</a></h2>
</body>
</html>

Silverlight Solid Validation Talk @Sixin

Tonight I will talk at the second Sixin meeting of 2012 in Amersfoort about creating the best user experience with Silverlight databinding and validation.

You can download my presentation and finished demo project

The program is as follows:

17:45 – 19:00 Eten, drinken en socializen
19:00 – 19:10 Welkomstwoord Timmy Kokke, bestuurslid Sixin
19:10 – 20:10 How not to design your Windows Phone apps, door Matthijs Hoekstra
20:10 – 20:30 Pauze
20:30 – 21:30 Silverlight Best Practices, door Loek van den Ouweland
21:30 – 22:00 Borrel

Hope to see you tonight!

Knockout.js for Silverlight Developers

Download demo project

One of the best Silverlight features is the support for MVVM. Recently I played a bit with Knockout.js and am very impressed with it. Knockout.js is an MVVM javascript library that has features like data binding, dependency tracking and templating. And all that goodness in 13 kilobytes!

Note

The Knockout website contains a lot of demo’s. It’s not my goal to re-do what they did. My goal is to show how I used my Silverlight/MVVM knowledge and best practices with Knockout. For example: I will use Model and ViewModel folders and put classes in separated files instead of dumping all the code in the View.

In our Silverlight Training we show how to bind a list of employees to a listbox. Let’s re-create that with Knockout. We will use an unordered list to show the employees like this:

Watch a live demo

Project anatomy

I like the convention with separate folders for models, viewmodels and recreated this in my project:

Create an employee class: Employee.js

var Employee = function (id, name) {
    this.id = ko.observable(id);
    this.name = ko.observable(name);
    this.displayInfo = ko.computed(function() {
    	return this.name() + " (" + this.id() + ")";
    },this);
}

Using Knockouts computed function I can return a concatenated string of Id and Name. This property (displayInfo) will be updated every time Id or Name is updated. Yes, that’s cool!

Create a viewmodel: EmployeeViewModel.js

var employeeViewModel = {
    employees: [
        new Employee("1","Vera"),
        new Employee("2","Chuck"),
        new Employee("3","Dave")
    ],
};

Tie together in the View: index.html

<!DOCTYPE html>
<html>
  <head>
  <meta name="author" content="Loek van den Ouweland">
  <meta name="description" content="Employee list with Knockout.js">
  <title>Employee list with Knockout.js</title>
  <link rel="stylesheet" href="css/html5reset-1.6.1.css?v=1">
  <link rel="stylesheet" href="css/screen.css">
  <script src="Library/jquery-1.7.1.min.js"></script>
  <script src="Library/knockout-2.0.0.js"></script>
  <script src="Models/Employee.js"></script>
	<script src="ViewModels/EmployeeViewModel.js"></script>
  <script type="text/javascript">
      //<![CDATA[
      jQuery(function () {
          ko.applyBindings(employeeViewModel);
      });
      //]]>
  </script>
  </head>
	<body>
		<div id="canvas">
      <h1>Employee list with Knockout.js</h1>
	    <ul id="employees" data-bind="foreach: employees">
	        <li><span data-bind="text: displayInfo"></span></li>
	    </ul>
		</div>
	</body>
</html>

After including the helper scripts (jquery and knockout), we include the model and viewmodel classes. When the DOM is ready, we need to apply the bindings with the applyBindings method. I’ve noticed a lot of people do this in script at the end of the page but I prefer applying them in the jQuery ready function.

The view has an unordered list that is bound to the employees list. Each item has a span with a text binding to the displayInfo property.

And that is all. A quick overview of binding a list of employees to an unordered list.

Download demo project

Split Generic.xaml in Silverlight Applications

If you work with Templated controls in a big Silverlight project, your Generic.xaml might grow fast. Here’s a quick tutorial on how to split the Generic.xaml into multiple resource files.

Step1: Find the resource

You will typically have the control code:

public class TemplatedControl1 : Control {
    public TemplatedControl1() {
        this.DefaultStyleKey = typeof(TemplatedControl1);
    }
}

and the XAML in the Generic.xaml:

<Style TargetType="local:TemplatedControl1">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:TemplatedControl1">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Step2: Create a new resource file

Create a copy of Generic.xaml and rename to TemplatedControl1.xaml.
Delete the TemplatedControl1 style from Generic.xaml.
So Generic.xaml looks like:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SilverlightApplication1">
</ResourceDictionary>

and TemplatedControl1.xaml looks like:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SilverlightApplication1">

    <Style TargetType="local:TemplatedControl1">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:TemplatedControl1">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Step3: Create reference in App.xaml

Open App.xaml and add the resource:

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Class="SilverlightApplication1.App"
             >
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source='/SilverlightApplication1;Component/Themes/TemplatedControl1.xaml'/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

If you open the project in Expression Blend you will see that you can edit the template as usual:

Seven Silverlight snippets you can not live without

One of the best Visual Studio features is the ability to create code snippets. During our Silverlight Training we use many of them. Here is a selection of the ones we use the most. You can download a zipfile with snippets and copy them to:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Visual C#

or

c:\Users\You\Documents\Visual Studio 2010\Code Snippets\Visual C#\

1 clsObservableObject

Creates an ObservableObject class you can use to subclass your Models from. Each model that subclasses ObservableObject can call a typed or untyped OnPropertyChanged method.

Output code:

public class ObservableObject : INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName) {
        var handler = PropertyChanged;
        if (handler != null) {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    protected virtual void OnPropertyChanged<TViewModel>(Expression<Func<TViewModel>> property) {
        var expression = property.Body as MemberExpression;
        var member = expression.Member;

        if (PropertyChanged != null) {
            PropertyChanged(this, new PropertyChangedEventArgs(member.Name));
        }
    }
}

2 event

Event declaration and a helper method to raise it.

Output code:

public event EventHandler DoubleClick;

protected virtual void OnDoubleClick() {
    EventHandler handler = DoubleClick;
    if (handler != null) {
        handler(this, EventArgs.Empty);
    }
}

3 loremIpsum

Creates a string with lorem ipsum text.

Output code:

var loremIpsum="Lorem ipsum dolor sit amet, Toverstudio consectetuer...

4 propds

Creates a Silverlight dependency property

Output code:

public string Text {
    get { return (string)GetValue(TextProperty); }
    set { SetValue(TextProperty, value); }
}

/// <summary>
/// Identifies the Text dependency property. This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty TextProperty =
    DependencyProperty.Register("Text",
                                typeof(string),
                                typeof(MyControl),
                                new PropertyMetadata(null, OnTextPropertyChanged));

/// <summary>
/// Text changed handler.
/// </summary>
/// <param name="d">MyControl that changed its Text.</param>
/// <param name="e">DependencyPropertyChangedEventArgs.</param>
private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
    var source = d as MyControl;
    if (source != null) {
        var value = (string)e.NewValue;
        //TODO: Handle new value.
    }
}

5 propds_nocallback

Creates a Silverlight dependency property without a callback method

Output code:

public string Caption {
    get { return (string)GetValue(CaptionProperty); }
    set { SetValue(CaptionProperty, value); }
}

public static readonly DependencyProperty CaptionProperty =
    DependencyProperty.Register("Caption",
                                typeof(string),
                                typeof(MyControl),
                                new PropertyMetadata(null));

6 propNotify

Uses the OnPropertyChanged with a string parameter (“”) from ObservableObject.

Output code:

private string name;

public string Name {
    get { return name; }
    set {
        if (name != value) {
            name = value;
            OnPropertyChanged("Name");
        }
    }
}

7 propNotify_typed

Uses the typed OnPropertyChanged method from ObservableObject.

Output code:

private string name;
public string Name {
    get { return name; }
    set {
        if (name != value) {
            name = value;
            OnPropertyChanged(() => this.Name);
        }
    }
}

You can download a zipfile with the snippets