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 Tutorial – Base Repository/Business Logic wrapper

Posted on by Joe in C#, Linq | 2 Comments

Before Linq to SQL I always separated out my Entities, Data Access Layer and Business Logic Layer.  With Linq to SQL it’s a little different as I feel the generated classes are kind of like the Entity and Data Access Layer combined.  Rather than using the generated entities directly it is still good practice to have a Business Logic Layer.  In this example I am using the term Repository which is an aspect of Domain-Driven Design.

Each entity will likely need it’s own repository object, as there will business logic that is specific for that entity, but there will be logic that is shared between all entities so it is worth creating a base object for this.

I have created a generic abstract class called RepositoryBase which has a constraint for EntityBase which is the base entity class I created in my Set inheritance modifiers with SQLMetalpost.  This ensures that the repositories can only be used with the objects created by Linq to SQL.

To handle my DataContext I am creating an instance of it in the constructor and keeping this instance for the life of the object.  For this reason my base repository implements IDisposable to handle disposing the DataContext.

Here is the code for my base repository:


public abstract class RepositoryBase<T> : IDisposable where T : EntityBase
{
    private UniversityDataContext _context;

    public RepositoryBase()
    {
        _context = new UniversityDataContext(ConfigurationManager.ConnectionStrings["UniversityConnectionString"].ConnectionString);
    }

    public UniversityDataContext Context
    {
        get
        {
            return _context;
        }
    }

    public List<T> GetAll()
    {
        return _context.GetTable<T>().ToList();
    }
    public T GetByID(int id)
    {
        return _context.GetTable<T>().FirstOrDefault(e => e.ID.Equals(id));
    }

    public int Count()
    {
        return _context.GetTable<T>().Count();
    }

    public void Save(T entity)
    {
        if (entity.IsNew)
        {
            _context.GetTable<T>().InsertOnSubmit(entity);
        }
        else
        {
            _context.GetTable<T>().Attach(entity, true);
        }

        _context.SubmitChanges();
    }

    public void Delete(T entity)
    {
        if (!entity.IsNew)
        {
            _context.GetTable<T>().Attach(entity);
            _context.GetTable<T>().DeleteOnSubmit(entity);
            _context.SubmitChanges();
        }
    }

    public void Dispose()
    {
        if (_context != null)
        {
            _context.Dispose();
        }
    }
}

You can see it contains methods that are relevant for all entities.  A method to get all entities, a method to get all entities by ID which I can do due to ID being a virtual member in my EntityBase class which is overridden by each entity.  It also has generic methods for saving and deleting which will work for any of the entities.  There will be a lot more logic that could go into this base class, but for now this just shows the basics.

Using this class you can derive separate repositories for each entity. I have a public property for the Context which allows any derived classes to use the DataContext instance.  Here is my implementation for StudentRepository which adds a couple of student specific methods:


public class StudentRepository : RepositoryBase<Student>
{
    public List<Student> GetByForename(string forename)
    {
        return Context.Students.Where(s => s.Forename.Equals(forename, StringComparison.CurrentCultureIgnoreCase)).ToList();
    }

    public List<Student> GetBySurname(string surname)
     {
        return Context.Students.Where(s => s.Surname.Equals(surname, StringComparison.CurrentCultureIgnoreCase)).ToList();
    }
}

Using this derived class I could use any of the base methods:

StudentRepository rep = new StudentRepository();
Student s = rep.GetByID(1);
s.Forename = "Joseph";
rep.Save(s);
gvStudents.DataSource = new StudentRepository().GetAll();
gvStudents.DataBind();

I could also use any of the entity specific methods:

StudentRepository rep = new StudentRepository();
List<Student> students = rep.GetByForename("Joseph");
foreach (Student s in students)
{
    rep.Delete(s);
}

To explicitly dispose of the object and the underlying DataContext I could do the following:

using (StudentRepository rep = new StudentRepository())
{
    List<Student> students = rep.GetByForename("Joseph");
    foreach (Student s in students)
    {
        rep.Delete(s);
    }
}

Move wordpress.com blog to other hosting provider

Posted on by Joe in Personal | Leave a comment

Yesterday I moved my blog from wordpress.com to my own hosting provider giving me greater control over my blog. This was quite an easy process but thought I would document the steps I took here incase it helps anyone else.

Firstly I installed wordpress on my new host. I then used the Import and Export options in Tools to import all my posts, categories, images etc into my new blog. I then opened up the SQL Admin tool provided by my host and ran some update queries to update any links and image references to use my own domain instead of the wordpress.com domain.

At this point the blog was running but was using the default theme so I downloaded the theme I was using on wordpress.com and installed it.

Now everything looked okay apart from my source code samples. I tried quite a few plugins that provide source code markup but I really wanted to find the one wordpress.com used as I liked the format it used, and I didn’t want to have to replace all my source code tags to use those of another plugin. After a bit of hunting around I found SyntaxHighlighter Evolved, which looks to be an updated version of the plugin wordpress.com uses.  After installing it all my source code example worked without having to update the tags, whoop!

Something else I liked on wordpress.com was the stats plugin they have, which uses Open Flash Chart written by my brother-in-law.  Doing a quick Google search brought up the wordpress.com Stats plugin.  It requires a wordpress.com API key but as I’m moving from wordpress.com that’s not a problem.  When activating the plugin it asks for the API key which can be found on the account page of wordpress.com.  It then asks you to confirm you want to link the new blog to the wordpress.com account.

Now my blog looks and works pretty much like my wordpress.com one, but they are two separate blogs which I don’t want.  What I really wanted to be able to do was forward all the posts on the old blog to the new blog as I didn’t want google search results going through the old one.  I found this post which has a handy tutorial on how this can be done.  It requires switching your name servers to the wordpress.com ones and adding your domain via the wordpress.com admin panel, costing you USD10.  Once that is done you can set your new domain to be the primary domain for the blog, then switch the name servers back and voila, the old blog redirects to the new one.

All in all this was quite painless, I’m now on the hunt for a decent theme!

Open Flash Chart

Posted on by Joe in Personal | Leave a comment

Open flash chart is on open source project written by my brother-in-law.  It is actually used by WordPress to show the Stats charts.

http://teethgrinder.co.uk/open-flash-chart/

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.

Linq To SQL Tutorial – Set inheritance modifiers with SQLMetal

Posted on by Joe in C#, Linq | 12 Comments

I have created an base class which my entities inherit from that gives a property called IsNew which returns true if the the value of ID is 0; all of my tables use ID for the identifier.

 

public abstract class EntityBase
{
    public virtual int ID { get; set; }

    public bool IsNew
    {
        get
        {
            return ID == 0;
        }
    }
}

For this to work each of my entities need to use the override modifier for the ID property.  Using the O/R Designer it is possible to set the inheritance modifier for each property, but this is not possible using SQLMetal and I need to use SQLMetal to set the base class.

To overcome this I have a batch file that first creates my .dbml file using SQLMetal:

SQLMetal.exe /server:localhost /database:University /dbml:University.dbml /namespace:Entities /context:UniversityDataContext /pluralize

I then run a console application to find column nodes with the name of ID, and add the Modifier attribute:

EntityProcessor.exe University.dbml

The code for EntityProcessor looks like this:

 

static void Main(string[] args)
{
    try
    {
        //Ensure there is an argument for the DBML file
        if (args.Count() == 0)
        {
            throw new ApplicationException("DBML path expected.");
        }

        string dbml = args[0];

        //Load the DBML file
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(dbml);

        //Loop through the tables
        foreach (XmlNode node in xmlDoc.GetElementsByTagName("Table"))
        {
            //Loop through the nodes for the type
            foreach (XmlNode child in node.FirstChild.ChildNodes)
            {
                //Find the ID column node
                if (child.Name.Equals("Column") && 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);
                }
            }
        }

        //Save the updated DBML file
        xmlDoc.Save(dbml);

        Console.WriteLine("Processing complete");
    }
    catch (Exception ex)
    {
        Console.WriteLine("An error occured: {0}", ex.Message);
    }
}

Finally I use SQLMetal again to create my entities from the updated .dbml file:

SQLMetal.exe /code:University.cs /entitybase:EntityBase /namespace:Entities University.dbml

My new entities now have an ID property with an overrides modifier that looks like this:

[Column(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public override int ID
{
    get
    {
        return this._ID;
    }
    set
    {
        if ((this._ID != value))
        {
            this.OnIDChanging(value);
            this.SendPropertyChanging();
            this._ID = value;
            this.SendPropertyChanged("ID");
            this.OnIDChanged();
        }
    }
}

I can now call IsNew on any of my entities to check if they have been inserted into the database.

Linq To SQL Tutorial – EntityBase – Base class for entities

Posted on by Joe in C#, Linq | 3 Comments

When using Linq To SQL you may often find yourself in a position where you want each of your entities to inherit from a base class.  As generated classes are partial classes you could create a second partial class for each entity which inherits a base class, but this is impractical.  The O/R designer does not give you the option for a base entity class but it can be achieved using the SQLMetal command line tool.

SQLMetal allows you to create a .dbml file or a code file containing your entities.  SQLMetal Builder provides a simple user interface for the command line tool and also generates batch files.

I have created an abstract class called EntityBase which I want all of my generated entities to inherit. I can use the following arguments with SQLMetal in order to create my entities that inherit this class.

<br />
SQLMetal.exe /server:localhost /database:University /code:University.cs /namespace:Entities /context:UniversityDataContext /entitybase:EntityBase /pluralize<br />

SQLMetal will look at server localhost and the database University.  It will create the entities in an file called University.cs with the namespace Entities.  The DataContext will be called UniversityDataContext and all entities will inherit EntityBase.  I am also using the pluralize argument which plurlises the table names, for example Student become Students;  I find this is more intuative when writing queries.

Linq To SQL Tutorial

Posted on by Joe in C#, Linq | 25 Comments

Check out some of my other Linq to SQL posts:

This is a basic tutorial for using Linq To SQL introducing some of the concepts behind it.

For this tutorial I have created a simple database for a University.  I will probably use this database and expand on it for any future posts where a database is required.  Below you can see the structure of the database.

ERD

Create a new website called Universities and add a second project called DAL to the solution.  This is the Data Access Layer where we will create the Linq To SQL classes.

Universities Solution

Right-click on the DAL project and select Add > New Item.  From the dialog choose ‘LINQ to SQL Classes’ and call the file University.dbml.

New Linq to SQL file

The .dbml extension stands for Database Markup Language.  The file itself is essentially an XML file that describes the database which is used to generate our classes.  When you add your new dbml file the Object Relational Designer (O/R Designer) should launch which is a visual tool for creating your model.  There is also a command-line tool called SqlMetal which gives you further control over how your model is created.  In this instance we will use the O/R Designer.

Locate your database in the Server Explorer window (View > Server Explorer), and drag and drop the tables to use onto the surface of the O/R Designer.  The result should look like this:

Object Relational Designer

Save and close the the O/R desinger.  In solution explorer you should see the University.dbml file, expanding this shows two other files, University.dbml.layout and University.designer.cs.

Solution Explorer

Examine University.designer.cs and you will find your DataContext which inherits System.Data.Linq.DataContext, and your model classes which were generated from the dbml file.  These classes are all partial classes which allows you to easily build them out to add extra functionality which won’t be affected if you need to regenerate from the dbml.

At this point we are now ready to use the generated classes.  In the website create a reference to the DAL project, and to System.Data.Linq.

linqtosql_referencelinq

Create a simple form to add a new Student with a GridView to display the current students. It should look something like this:

Student Form

Firstly we want to bind the data from the Title table in the database to the Title DropDownList on the form.  Manually add some data to this table such as Mr, Mrs and Miss.  In the Page_Load event handler put a (!Page.IsPostBack) condition and call the following method:

private void PopulateTitles()
{
using (UniversityDataContext context = new UniversityDataContext())
{
ddlTitle.DataSource = context.Titles;
ddlTitle.DataTextField = "Name";
ddlTitle.DataValueField = "ID";
ddlTitle.DataBind();
}
}

This method first creates an instance of our DataContext to use.  We then set the DataSource of the DropDownList to context.Title which is of type System.Data.Linq.Table.  We can query this object further, but in this instace I want all rows from the table.  The DataTextField and DataValueField properties are set to the relevant properties of the Title object.  Run the application and the Title dropdown will be populated with the values from the database.

The next step is to create a new student and save it to the database.  Call the following method from the Save button event handler.


private void SaveStudent()
{
using (UniversityDataContext context = new UniversityDataContext())
{
Student newStudent = new Student()
{
TitleID = Convert.ToInt32(ddlTitle.SelectedValue),
Forename = txtForename.Text,
Surname = txtSurname.Text,
DOB = Convert.ToDateTime(txtDOB.Text),
EmailAddress = string.IsNullOrEmpty(txtEmail.Text) ? null : txtEmail.Text,
Phone = string.IsNullOrEmpty(txtPhone.Text) ? null : txtPhone.Text
};

context.Students.InsertOnSubmit(newStudent);
context.SubmitChanges();
}
}

We are creating a new Student object and setting the properties of that object based on the form values.  We are using an Object Initializer which allows setting the properties of the object without having to explicity envoke a constructor.  The penultimate line adds our newly created object to the table in a pending state, then calling the SubmitChanges method on the DataContext submits any pending changes in the context.

Now that there is data in our Student table it would be good to be able to see it.  Add the following method to our code and call it from the Page_Load event handler.


private void PopulateStudents()
{
using (UniversityDataContext context = new UniversityDataContext())
{
var students = from s in context.Students
select new
{
Title = s.Title.Name,
Forename = s.Forename,
Surname = s.Surname,
DOB = s.DOB.ToShortDateString(),
EmailAddress = s.EmailAddress,
Phone = s.Phone
};

gvStudents.DataSource = students;
gvStudents.DataBind();
}
}

This method uses a Linq query to assign an Anonymous Type using the var keyword.  We could bind context.Students to the GridView as we did with the Titles, but in this instance I want the Name of the Title for the student using context.Student.Title.Name and I also want to show the DOB without the time.  The Linq query is selecting all rows in the Students table, and creating a collection of the Anonymous Type setting each of its properties.  We then set the datasource of the GridView to this collection and call DataBind.

I hope this tutorial gives a good overview of Linq To SQL for anybody new to it.  In the real world you would probably not access your object model directly from the page, but write a repository model that handles all the data access and DataContext.  I will write more about how to do this at a later date.

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

Enum description using reflection and extension methods

Posted on by Joe in C# | Leave a comment

I don’t take credit for this as it was written by another developer on the the project, but I thought it was good and worth writing about.

On the current project I’m working on we use a lot of enumerations for statuses which are shown in drop-down lists and grids. It can get a bit ugly from a UI perspective when simply using the ToString method as enumeration values cannot have spaces and are usually shortened for ease of use when coding.

One way to overcome this is to add a description attribute to each enumeration value and write an extension method that uses reflection to obtain the value in the description attribute.

The description attribute is part of the System.ComponentModel namespace so we need to import this.  The attribute value can then be set on each enumeration value:

public enum Status : int
{
    [Description("Application pending")]
    Pending = 0,
    [Description("Application received")]
    Received = 1,
    [Description("Application processing in progress")]
    Processing = 2,
    [Description("Application processed")]
    Processed = 3
}

The next step is to create the extension method.  Extension methods were introduced in  C# 3 and allow you to easily add new methods to existing types.  Scott Guthrie has a good blog post on them here.  Extensions methods need to be static, and contained in a static class.  In the method signature the ‘this’ keyword is used to indicate which type the extension method is for.  Below is the extension method that will get the description attribute for an enumeration using reflection.

public static string Description(this Enum enumeration)
{
    string value = enumeration.ToString();
    Type type = enumeration.GetType();
    //Use reflection to try and get the description attribute for the enumeration
    DescriptionAttribute[] descAttribute = (DescriptionAttribute[])type.GetField(value).GetCustomAttributes(typeof(DescriptionAttribute), false);
    return descAttribute.Length > 0 ? descAttribute[0].Description : value;
}

Any enumeration will now have a method called Description that will try to return the value of the description attribute, and if the attribute is not present return the result of calling ToString.  For example:

Console.WriteLine(Status.Processing.Description());

 
Will display:

exmethod1

As the extension method is for Enum, and not just the Status enumeration I created, we could do this:

Array values = Enum.GetValues(typeof(Status));
foreach (Enum e in values)
    Console.WriteLine("{0} - {1}", e, e.Description());

The result here would be:

exmethod2

There are lots of uses for extension methods which are used extensively with Linq, but I particularly like this idea to provide a more readable value for an enumeration.

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.