Using KnockoutJS with SignalR in ASP.NET MVC

KnockoutJS is a MVVM implementation for JavaScript written by Steve Sanderson, in my opinion the author of the best ASP.NET MVC textbooks available. Simply put it lets you bind a JavaScript object model to your HTML UI using a Read more

A MongoDB Tutorial using C# and ASP.NET MVC

In this post I'm going to create a simple ASP.NET MVC website for a simple blog that uses MongoDB and the offical 10gen C# driver. MongoDB is no NOSQL database that stores information as Binary JSON (BSON) in documents. I Read more

Linq To SQL Tutorial

Check out some of my other Linq to SQL posts: EntityBase Inheritance Modifiers with SQLMetal Linq to SQL with WCF Services Linq to SQL Framework (Repository/Business wrapper) ObjectDataSource binding with server side paging and sorting Load Options Generic Framework using reflection This is a basic tutorial for Read more

Setting the SelectedItem in a Silverlight TreeView

Posted on by Joe in Silverlight | 1 Comment

I wanted to select a specific item in my Silverlight TreeView programatically.  Looking at the TreeView.SelectedItem property the setter is not public so it cannot be done this way.

If you are simply adding TreeViewItems to the TreeView you can cast the item you want to select in the Items collection to a TreeViewItem and set the IsSelected property to true. The following example will grab the first item and set it to selected.

TreeViewItem item = tvDirectories.Items[0] as TreeViewItem;
item.IsSelected = true;

If you are binding a list of business objects to the TreeView this will not work as the Items collection will be a list of your object.  In this scenario you can use the ItemContainerGenerator property of the TreeView to get the underlying TreeViewItem.  In this example I have a collection of Gallery objects bound to my TreeView and am using the ContainerFromIndex method to get the TreeViewItem at position 0.

TreeViewItem item = tvDirectories.ItemContainerGenerator.ContainerFromIndex(0) as TreeViewItem;
item.IsSelected = true;

The ItemContainerGenerator class also has a ContainerFromItem method that will get the TreeViewItem by passing it an instance of the business object you want to select.

Gallery gallery = GetGallery(); //Some method that gets the object you want to select in the TreeView
TreeViewItem item = tvDirectories.ItemContainerGenerator.ContainerFromItem(gallery) as TreeViewItem;
item.IsSelected = true;

In my application I want to select the TreeViewItem based on the ServerPath of the Gallery object so I’m using some of the nifty Linq extension methods (Cast and Single) to get my business object.

public void SelectGallery(string serverPath)
    Gallery gallery = tvDirectories.Items.Cast<gallery>().Single(x => x.ServerPath.Equals(serverPath));
    if (gallery != null)
        TreeViewItem item = tvDirectories.ItemContainerGenerator.ContainerFromItem(gallery) as TreeViewItem;
        item.IsSelected = true;

Disable enter submitting form with JavaScript

Posted on by Joe in JavaScript | Leave a comment

On a project I was working on I was asked to disable the enter key submitting the form.  Usually it would be better just to ensure that hitting enter performed the correct action but if you do want to disable this you can do so with JavaScript.

I created a JavaScript function called disableEnterSubmit which takes in the event as a parameter as shown below.

function disableEnterSubmit(e)
    if (e.keyCode)
       return (e.keyCode != 13); //IE
        return (e.which != 13); //FireFox

The event has different properties for the code of the pressed key for Internet Explorer and FireFox. In Internet Explorer we use e.keyCode and for FireFox it’s e.which.  The function simply returns false if the key is enter (key code 13).

I then just need to set the onkeydown event in the body tag of my HTML to call the method.

<body onkeydown="return disableEnterSubmit(event)">

Xbox 360 – Project Natal – No controller gaming?

Posted on by Joe in Xbox 360 | Leave a comment

Microsoft have announced Project Natal for Xbox 360.  It boasts controller-less gaming with face and voice recognition.  Obviously influenced by the Wii, the concept video does look interesting.  As a fan of the Skate and Skate 2 games the use of full motion body capture could be cool when it comes to skateboarding games, or it could be a complete flop. Will have to wait and see…

Alert, confirm and input message boxes in Silverlight

Posted on by Joe in Silverlight | Leave a comment

To use alert, confirm and input message boxes in Silverlight you need to import the following namespace.

using System.Windows.Browser;

You can then show an alert box by doing…

HtmlPage.Window.Alert("This is an alert")

Or a confirm dialog by doing…

if (HtmlPage.Window.Confirm("Are you sure you want to do something?"))
    //Do something

Or an input prompt by doing…

string name = HtmlPage.Window.Prompt("What is your name?");

Passing a byte array to a WCF method from Silverlight – The remote server returned an error: NotFound

Posted on by Joe in Silverlight | 8 Comments

My Silverlight application calls a method to get an image from the server as a byte array. When adding my Service Reference the ServiceReferences.ClientConfig automatically generated the binding’s MaxBufferSize and MaxRecievedMessageSize as 2147483647 which is a lot bigger than I want to I changed them to 5242880 (5MB).  When the application calls the service to bring down an image these values are used to limit the size of the response message.

I also set the MaxBufferSize and MaxRecievedMessageSize to 5242880 in the web.config file of the web application hosting my service.  At this point when I call the method in my service to upload an image passing a byte array I get a The remote server returned an error: NotFound error message, which really isn’t very helpful.

In this instance the problem is that the maximum array length for the XML reader has been exceeded. This can be fixed by expanding the binding section to insert a readerQuotas section and increase the maxArrayLength.

    <service behaviorConfiguration="GalleryServiceBehavior" name="GalleryService.GalleryService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpLargeMessage" contract="GalleryService.IGalleryService" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

        <binding name="basicHttpLargeMessage" maxReceivedMessageSize="5242880" maxBufferSize="5242880">
            <readerQuotas maxArrayLength="5242880" />

I can now upload and download files up to 5MB through my service.

Set Silverlight Image Source from byte array

Posted on by Joe in Silverlight | 12 Comments

I’ve been playing around with Silverlight and WCF services and I came across the need to set the Source of an Image control in Silverlight from a byte array. I have a service method which returns an image from the server as a byte array which I want to show in the Silverlight application.

My service method is simple and looks like this:

using System.IO;

public byte[] GetImage(string serverPath)
    return File.ReadAllBytes(serverPath);

In the Silverlight application I create a MemoryStream from the byte array, then a BitmapImage from the MemoryStream and set the image source to the BitmapImage.

using System.IO;
using System.Windows.Media.Imaging;

void proxy_GetImageCompleted(object sender, GetImageCompletedEventArgs e)
    MemoryStream stream = new MemoryStream(e.Result);
    BitmapImage b = new BitmapImage();
    imgImage.Source = b;

proxy_GetImageCompleted is the event handler for when my asynchronous call to GetImage completes, where e.Result is the byte array.

Wrapped Listbox items in Silverlight and WPF

Posted on by Joe in Silverlight, WCF | Leave a comment

I wanted to display a list of image thumbnails similar to how Windows Explorer does it so they are displayed horizontally and wrap onto the next line. The ListBox allows you to choose a template for the panel used to display items. The following XAML uses the WrapPanel for the ItemsPanelTemplate and gives the functionality I wanted.

<listBox x:Name="ImageList" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
            <usrcntrl:Image ImageName="{Binding Name}" ServerPath="{Binding ServerPath}" />
            <controls:WrapPanel />

I have also disabled the horizontal scroll bar so the images wrap to the next line.

Visual Studio closing when trying to choose items for the toolbox

Posted on by Joe in Visual Studio 2008 | Leave a comment

The other day I was trying to add new items to my toolbox in Visual Studio 2008 and each time Visual Studio would close itself without reason. I tried the Reset Toolbox option which didn’t solve the problem.

I then tried running Visual Studio in safe mode by choosing run from the start menu and typing ‘devenv /safemode’. In safe mode I was able to get the Choose Items dialog so I just flicked through all the tabs to make sure it was working. I then closed Visual Studio and loaded it normally and everything worked as expected.

Not sure why it happened but this seemed to fix it :)

WCF Services and Silverlight

Posted on by Joe in Silverlight, WCF | Leave a comment

After looking at WPF the other week I thought being a web developer it would be beneficial to look at Silverlight.  One of the first things I was interested to try was to access the server’s file system from the Silverlight application. I quickly found out that this wasn’t possible so I decided to create a WCF service hosted in the web application running my Silverlight application to access the file system for me.

To use a WCF service in Silverlight it must use basicHttpBinding. In Visual Studio you can add a ‘Silverlight-enabled WCF Service’ from the Silverlight category which creates a service using basicHttpBinding as default.

I created a simple service method called GetDirectories which returns an array of directory names within a given location.


public string[] GetDirectories()
    string path =  ConfigurationManager.AppSettings["GalleryDir"];
    IList<string> directories = new List<string>();

    foreach (string directory in Directory.GetDirectories(path))

    return directories.ToArray();

After adding my service reference and creating an instance of my proxy I noticed that it did not contain the method GetDirectories. Instead I have GetDirectoriesAsync and an event called GetDirectoriesCompleted. This is cool as all service calls with Silverlight are asynchronous.


public Directories()

    GalleryContractClient proxy = new GalleryContractClient();
    proxy.GetDirectoriesCompleted += new EventHandler<getDirectoriesCompletedEventArgs>(proxy_GetDirectoriesCompleted);

void proxy_GetDirectoriesCompleted(object sender, GetDirectoriesCompletedEventArgs e)
    foreach (string directory in e.Result)

The Result property of GetDirectoriesCompleteEventArgs has the response from the request.

WPF Community Workshop – Sydney

Posted on by Joe in Personal | Leave a comment

Last weekend (23rd May) I attended the WPF Community Workshop in Sydney put on by Microsoft and run by a colleague of mine, Deepak Kapoor.

I had never looked into WPF as I am predominantly an ASP.NET developer although I did use Windows Forms for several years. I thought this would be a good opportunity to see what WPF was all about and I was impressed.

The workshop featured several labs which quickly taught the basics of WPF and XAML and went on to data binding.

We also looked at Expression Blendwhich is written with WPF. I really liked how easy it was to change the appearance of the standard controls and make them look however you want.

Will definitely be looking further into WPF in the near future…