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

Linq to SQL with WCF Services

Posted on by Joe in Linq, Silverlight, WCF | 5 Comments

I was interested to see how I could use Linq to SQL with WCF Services to load and save data using a Silverlight project.  In this post I will expand upon the database I created in my Linq to SQL Tutorial and the console application I wrote for my Set inheritance modifiers with SQLMetal post.

The first step is to enable serialisation on my Linq entities so that they can be sent over the wire. To do this in the O/R Designer you can select the white space of the designer and view the DataContext properties.  Set the property called Serialization Mode to Unidirectional:

Linq Serialization Mode Property

 

If using SQLMetal you can use the serialization command line argument:

SQLMetal.exe"/server:localhost /database:University /dbml:University.dbml <strong>/serialization:unidirectional</strong> /namespace:Entities /context:UniversityDataContext /pluralize

Enabling unidirectional serialization in either of these two ways adds the necessary DataContract and DataMember attributes to the generated entities and properties:

[Table(Name="dbo.Student")]
[DataContract()]
public partial class Student : EntityBase, INotifyPropertyChanging, INotifyPropertyChanged
{
    ....

    [Column(Storage="_Forename", DbType="NVarChar(50) NOT NULL", CanBeNull=false, UpdateCheck=UpdateCheck.Never)]
    [DataMember(Order=3)]
    public string Forename
    {
        ....
    }
}

The entities are now in a state where they can be serialised and sent down the wire.  In my WCF service I have a method that returns a list of my Linq to SQL Student entity:

public List GetStudents()
{
    using (_context)
    {
        return _context.Students.ToList();
    }
}

These entities can then be easily used by the client, in this case the Silverlight application:


UniversityContractClient _proxy = new UniversityContractClient();

private void PopulateStudents()
{
    _proxy.GetStudentsCompleted += new EventHandler(proxy_GetStudentsCompleted);
    _proxy.GetStudentsAsync();
}

void proxy_GetStudentsCompleted(object sender, GetStudentsCompletedEventArgs e)
{
    dgStudents.ItemsSource = e.Result;
}

Here I am using the list to populate a DataGrid:

Linq WCF Datagrid

This is all very straight forward, but the next step to update the data it a little more complex.  Here is my service method to save a Student entity created or updated by the client:

public void SaveStudent(Student student)
{
    using (_context)
    {
        if (student.IsNew)
        {
            _context.Students.InsertOnSubmit(student);
        }
        else
        {
            _context.Students.Attach(student, true);
        }
               
        _context.SubmitChanges();
    }
}

Here I am using the IsNew property I created in my Set inheritance modifiers with SQLMetal post to check if the entity is to be inserted or updated.  The insert code is simple enough, but for the update we have to attach the entity to the DataContext as it has been modified outside of the DataContext’s scope.  I’m at doing this using the Attach method of the Student table, passing true for the asModified parameter to state that the entity has been updated.

In my Silverlight application I have a DataForm which calls this method passing the updated Student entity:

Linq WCF DataForm

At this point inserting data will work, but when I try to update an entity the service method will throw the following error when trying to attach the entity:

An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.

This occurs because the entity was modified outside of the scope of the DataContext, so Linq to SQL doesn’t know what has changed about the entity and what to update.  To overcome this we can use a Timestamp column.  The Timestamp is a byte array which is used for versioning.  Linq to SQL knows to check this column to see if an object has been updated.  In my database I have changed the Student table so that it has a field called Timestamp, of type timestamp which doesn’t allow NULLs:

Linq WCF Timestamp Field

When adding the new column, the O/R Designer automatically knows this is a timetamp column and sets the Time Stamp and Auto Generated Value properties to true:

Linq WCF Timestamp Properties

 

SQLMetal will also detect a column with the timestamp type and set the necessary attributes.

With this timestamp column set up it will now be possible to successfully update an entity that was changed by the client.

In my example if I try to update the entity twice it will throw the following exception when trying to submit the changes:

Row not found or changed.

This is because the client doesn’t have the entity with the updated timestamp.  Also when adding a new entity the entity at the client won’t have the updated ID identity column so trying to update this will create another entity.  To resolve this I can change my SaveStudent service method to return the updated Student entity:


public Student SaveStudent(Student student)
{
    using (_context)
    {
        if (student.IsNew)
        {
            _context.Students.InsertOnSubmit(student);
        }
        else
        {
            _context.Students.Attach(student, true);
        }
               
        _context.SubmitChanges();
    }

    return student;
}

In my Silverlight application I then pass the hash code for the object as the userState when calling the asyncronus service method:

_proxy.SaveStudentAsync(student, student.GetHashCode());

This user state can then be obtained in the callback EventArgs class using e.UserState.  Using this I get the correct object from my collection, update it and reassign the source for my DataGrid and DataForm:

void _proxy_SaveStudentCompleted(object sender, SaveStudentCompletedEventArgs e)
{
    ObservableCollection students = (ObservableCollection)dgStudents.ItemsSource;
    Student student = students.Where(s => s.GetHashCode() == Convert.ToInt32(e.UserState)).First();
    if (student.ID == 0)
    {
        student.ID = e.Result.ID;
    }
    student.Timestamp = e.Result.Timestamp;
    dgStudents.ItemsSource = students;
    dfStudent.ItemsSource = students;
}

This is all well and good and works as expected but what I really wanted to do was have an UpdateDate column which holds the date of the last update which could be used as a timestamp.  I replaced my current Timestamp column with an UpdateDate column:

Linq WCF UpdateDate Field

The default for the new column is set to getdate() to automatically populate with the current date when creating a new record:

Linq WCF UpdateDate Default

Using the O/R Designer this field can be set to a timestamp by setting the Time Stamp property to True, which will automatically set Auto Generated Value to True.

As I am using SQLMetal I can update the console application I wrote in my Set inheritance modifiers with SQLMetal post to add an IsVersion attribute to the DBML XML as well as the Modifier attribute:


.... code omitted ....

//Find the column node
if (child.Name.Equals("Column"))
{
    if (child.Attributes["Name"].Value.Equals("ID"))
    {
        //Create the Modifier attribute to add to ID column
        XmlAttribute modifierAttribute = xmlDoc.CreateAttribute("Modifier");
        modifierAttribute.Value = "Override";
        child.Attributes.Append(modifierAttribute);
    }
    else if (child.Attributes["Name"].Value.Equals("UpdateDate"))
    {
        //Create the IsVersion attribute to add to UpdateDate column
        XmlAttribute versionAttribute = xmlDoc.CreateAttribute("IsVersion");
        versionAttribute.Value = "True";
        child.Attributes.Append(versionAttribute);
    }
}

.... code omitted ....

Doing this adds the following values to the Column attribute on the UpdateDate property in the Student entity.  You can see IsVersion=true which tells Linq to SQL this property is the timestamp.

[Column(Storage="_UpdateDate", AutoSync=AutoSync.Always, DbType="DateTime NOT NULL", IsDbGenerated=true, IsVersion=true, UpdateCheck=UpdateCheck.Never)]

At this point everything works okay, but the UpdateDate is not refreshed on update.  To fix this add a trigger that sets the date on update:

ALTER TRIGGER trg_UpdateDate
ON dbo.Student
FOR UPDATE
AS
    UPDATE      Student
    SET         UpdateDate = getdate()
    WHERE       (ID IN (SELECT ID FROM Inserted))

The UpdateDate is now set for each update and is used by Linq to SQL as the timestamp.

Resize image with Silverlight and FJCore before uploading to server

Posted on by Joe in Silverlight, WCF | 4 Comments

I have a Silverlight application which allows the user to select images from their local PC which are then uploaded to a server via a WCF Service.

It is easy enough to resize the image once it gets to the server, but this would still mean that the full image is being sent over the wire.

In Silverlight 2 there are no built in features that allow us to do the resizing at the client, but it can be achieved using an open source imaging library called FJCore.

To get the FJCore source from Subversion I use an open source plug-in for Visual Studio called AnkhSVN.  It is then possible to build the solution and add a reference to the FJCore library to my own solution.

In my application I allow the user to select multiple files using the OpenFileDialog which are then processed as byte arrays and sent to the server via the WCF Service.  Before doing the upload I am using FJCore to check if the image needs to be resized, and if so resize the image.

The resizing requires the following using statements.

using FluxJpeg.Core;
using FluxJpeg.Core.Decoder;
using FluxJpeg.Core.Filtering;
using FluxJpeg.Core.Encoder;

The following code shows how to use FJCore to take the files selected with the OpenFileDialog and do the resizing before calling the service method to upload to the server.  Here the maximum edge length is 640px, so if width or height is greater than 640px, the resize code is used to resize the maximum edge length to 640px while keeping perspective.


OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg";
ofd.Multiselect = true;

if (ofd.ShowDialog().GetValueOrDefault(false))
{
    //The path to upload the files on the server
    string serverPath = "d:\uploads";

    foreach (FileInfo image in ofd.Files)
    {
        FileStream stream = image.OpenRead();
        using (stream)
        {
            byte[] data;
                       
            //Decode image
            DecodedJpeg origJpeg = new JpegDecoder(stream).Decode();

            //Check if the image needs resizing
            if (ImageResizer.ResizeNeeded(origJpeg.Image, 640))
            {
                //Resize image
                DecodedJpeg resizedJpeg =
                    new DecodedJpeg(new ImageResizer(origJpeg.Image).Resize(640, ResamplingFilters.NearestNeighbor), origJpeg.MetaHeaders);

                //Encode resized image
                MemoryStream resizedStream = new MemoryStream();
                new JpegEncoder(resizedJpeg, 100, resizedStream).Encode();

                //Read resized stream to byte array
                resizedStream.Seek(0, SeekOrigin.Begin);
                data = new byte[resizedStream.Length];
                resizedStream.Read(data, 0, Convert.ToInt32(resizedStream.Length));
            }
            else
            {
                //Read original stream to byte array
                stream.Seek(0, SeekOrigin.Begin);
                data = new byte[stream.Length];
                stream.Read(data, 0, Convert.ToInt32(stream.Length));
            }

            //Upload image via service
            GalleryContractClient proxy = new GalleryContractClient();
            proxy.UploadImageCompleted += new EventHandler<uploadImageCompletedEventArgs>(proxy_UploadImageCompleted);
            proxy.UploadImageAsync(serverPath, image.Name, data);
        }
    }
}

Simple double click in Silverlight

Posted on by Joe in Silverlight | Leave a comment

I needed to pick up on a double click on an image in Silverlight but there is no event to handle this. It can be done quite easily using a DispatchTimer.  I am doing this for an image but you should be able to do it for any UIElement.

First I have imported the System.Windows.Theading namespace where the DispatchTimer lives.  In the constructor of the User Control containing the image I have instantiated the Timer and set its interval to 200 milliseconds, this is the amount of time allowed between clicks for it to be considered a double click.  I have also added a listener to the Tick event of the Timer which fires with each iteration.

 
using System.Windows.Threading;

public partial class Image : UserControl
{
    DispatcherTimer _timer;

    public Image()
    {
        InitializeComponent();

        _timer = new DispatcherTimer();
        _timer.Interval = new TimeSpan(0, 0, 0, 0, 200);
        _timer.Tick += new EventHandler(_timer_Tick);
    }
}

My event handler for the Image’s MouseLeftButtonDown will check if the Timer has already been started, and if so we know this is a double click, if not we start the timer.  The first time the event is raised the timer won’t be started, but the second time, on the second click it will be so this is our double click.

private void imgImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (_timer.IsEnabled)
    {
        MessageBox.Show("Double Click");
    }
        else
    {
        _timer.Start();
    }
}

Finally I handle the Tick event of the Timer, and simply stop the timer so that after 200 milliseconds the timer is no longer active, and any subsequent clicks are not counted as the second click of a double click.

void _timer_Tick(object sender, EventArgs e)
{
    _timer.Stop();
}

This is a fairly basic and not very reusable but does the job for what I need.  You could also use the GetPosition property of MouseButtonEventArgs to make sure that the mouse hasn’t moved between clicks.

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;
    }
}

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.

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

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

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();
    b.SetSource(stream);
    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">
    <listBox.ItemTemplate>
        <dataTemplate>
            <usrcntrl:Image ImageName="{Binding Name}" ServerPath="{Binding ServerPath}" />
        </dataTemplate>
    </listBox.ItemTemplate>
    <listBox.ItemsPanel>
        <itemsPanelTemplate>
            <controls:WrapPanel />
        </itemsPanelTemplate>
    </listBox.ItemsPanel>
</listBox>

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

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))
        directories.Add(directory);

    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()
{
    InitializeComponent();

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

void proxy_GetDirectoriesCompleted(object sender, GetDirectoriesCompletedEventArgs e)
{
    foreach (string directory in e.Result)
        tvDirectories.Items.Add(directory);
}

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