Nov 05

C# 3.0 added lambdas to the language syntax. I wont go into details as to what those are as there is pleanty of information on the web, what I will show is how you can assign a lambda to a variable for later use.

I do a lot of work with LINQ and the Entity Framework and as such lambdas come in very useful when using LINQ expressions (I am not a fan of the query syntax), however it is sometimes useful to reuse a lambda. A lamda is simply a delegate that has a number of different prototypes all under Func.

[source:C#]
Func<TResult>
Func<T,TResult>
Func< T1,T2,TResult>
Func< T1,T2,T3,TResult>
Func< T1,T2,T3,T4,TResult>ÂÂ
[/source]

All of the lambdas take a result type and each varient adds an additional input type. 

How does this help us save a lamda? Well lets take an example piece of code
[source:C#]
model.Users.Count(u => u.UserName == username);
[/source]
Here I am searching through the Users collection for any users which have UserName equal to the username variable. The input type for the lamda is User as Users is actually an ObjectQuery<User> object, the return type is bool as I am comparing 2 values and returning the result.

To store this lamda I do the following:

[source:C#]
Func<User,bool> userExpression = (u => u.UserName == username);
model.Users.Count(userExpression);
[/source]
If your lambda uses say 2 input types your code would look something like this:

[source:C#]
Func<User,Ticket,bool> userExpression =
     ((u,t) => u.UserName == username && t.UserID == u.UserID );ÂÂ
[/source]

The main difference here being that the list of input types must be wrapped in parenthesis (u,t) followed by the => operator.

For more information on lamdas have a look at this InformIT Article

Jun 13

This may have just been a result of my PHP background trying to tell me how to do things and so it is quite possible that this post is common sense and obvious to others in the .NET / LINQ community.

I have been working on an ASP.NET MVC prototype application (Preview 3) and I ran into a very frustrating problem. Part of the system allows users who are logged in to vote a post up or down, a user can only vote once per post. There is a Posts table, a Users table and a Votes table and Votes contains a foreign key for both Posts and Users.

Now when a use submitted a vote the system created a new Vote object, passed in the PostID, the UserID of the current user and the result. LINQ then stuffed it in the data context and saved it back to the database. When a user came back to the post or a listing of posts, it didn’t display as having registered their vote although if they voted again the system blocked it which told me the data was there and LINQ could read it.

After quite a bit of head scratching and googling I came across Chris Rock’s post “LINQ TO SQL Caching Gotcha” which identified a similar problem and it did seem like mine was a caching issue. I tried his suggestion but to no avail so I ruled out caching.

So what was the solution? Well, let me do a before and after for you:

Before

[source:c#]
Vote vote = new Vote();
vote.PostID = id;
vote.Result = (result == “up” ? true : false);
vote.UserID = CurrentUser.UserID;
DBDataContext.Votes.InsertOnSubmit(vote);
DBDataContext.SubmitChanges();
[/source]

After

[source:c#]
Vote vote = new Vote();
vote.Post = DBDataContext.Posts.Single(p => p.PostID == id);
vote.Result = (result == “up” ? true : false);
vote.User = CurrentUser;
DBDataContext.Votes.InsertOnSubmit(vote);
DBDataContext.SubmitChanges();
[/source]

The key is on lines 2 and 4. In the first snippet I am assigning the numerical IDs to the foriegn key fields PostID and UserID, in the second I am passing in actual objects; the Post object found using the id variable and the User object found by using the CurrentUser property.

LINQ does not seem to connect the Vote to the User or Post if you directly assign the ID values, evidently you need to pass the object which is being referenced in order to get LINQ to recognise the connection and perform the required updates, despite the DB knowing exactly what is going on.

As I said before, perhaps this is well documented and I am just being slow to catch on but that took the better part of a week to find and fix.

Jan 02

New Year, new projects, new challenges and also some nice new upcoming technologies. So given this is a new blog I wanted to make my first post a bit of a reference post detailing a nice new ASP.NET 3.5 Extension Project which is currently in CTP. From the Extensions information page:

The ASP.NET 3.5 Extensions Preview is a new release that provides new functionality being added to ASP.NET 3.5 and ADO.NET in 2008. This release delivers a set of new features that target:

  1. Enabling High Productivity Data Scenarios – including MVC, Entity Framework, ADO.NET Data Services and dynamic data
  2. Supporting Test Driven Development – including a powerful and extensible MVC framework
  3. Creating the best server for Rich Clients – including Ajax history support and Silverlight controls for ASP.NET

Now the part that I have been very interested in is the MVC Framework for ASP.NET.

MVC stands for Model-View-Controller, it is a high-level design pattern which effectively separates business objects and data from presentation (explanation). MVC is by far a new concept in programming and it is not even new to ASP.NET. Projects like MonoRail have been developing a reliable MVC framework for quite some time so why am I interested in what Microsoft have brought to the table?

Well that is kind of like asking why use ASP.NET over PHP for me, I will happily use both but one has different features and functionality to the other. But reading through blogs from the likes of Scott Guthrie, Fredrik Normén and others I am impressed by the levels of functionality the frameworks brings.

There is little point discussing the details nor workings of the framework, I more wanted to raise awareness of it as I feel that it is a very useful and powerful development tool. However I realise that not everyone shares the view. Still it will be interesting to see how the project matures.

Links:

ASP.NET 3.5 Extensions Preview

Scott Guthrie’s 4 part tutorial

Fredrik Normén on ASP.NET MVC Framework