Thoughts on Software by Andrew Davey
| | Sun | Mon | Tue | Wed | Thu | Fri | Sat |
|---|
| 26 | 27 | 28 | 29 | 30 | 31 | 1 | | 2 | 3 | 4 | 5 | 6 | 7 | 8 | | 9 | 10 | 11 | 12 | 13 | 14 | 15 | | 16 | 17 | 18 | 19 | 20 | 21 | 22 | | 23 | 24 | 25 | 26 | 27 | 28 | 29 | | 30 | 1 | 2 | 3 | 4 | 5 | 6 |
Search
Navigation
Categories
Blogroll
|

Saturday, September 29, 2007

Thursday, September 27, 2007
Lazy Functions in LINQ
Imagine we have a set of complex expressions. A subset of these need to be evaluated at runtime, depending on some state external to the program (e.g. user input). If these subsets are not distinct from each other then the code will likely become messy and unstructured.
What we would like to so is define all the expressions first and then pick and choose those required. This would of course involve evaluating all of the them. This wasteful of time if only a few are required.
Enter lazy evaluation! From my rather limited exposure to Haskell, I hear that lazy evaluation is all the rage. :)
Using lambdas in C# 3.0 we can create code like this:
long x = 42;
var lx = Lazy.Eval(() => x * x * x * x * x * x);
if (some_boolean_expression)
{
UseNumber(lx);
}
where UseNumber is some function that takes a "long" as input.
Now this example is over-simplified, but it shows the mechanics. We use a call to Lazy.Eval to return a wrapper around the lambda. So at that point we have not calculated the expensive expression. Later in the program the variable "lx" is used. lx is of type Lazy<long> and there exists an implicit cast from Lazy<long> to long. At this point the original expression is evaluated and saved by the lazy wrapper. So next time the value is required the cached value is returned.
Here is the Lazy<T> class:
public class Lazy<T>
{
bool _gotValue;
T _value;
Func<T> _expr;
public Lazy(Func<T> expr)
{
_expr = expr;
}
public T Value
{
get
{
if (!_gotValue)
{
_value = _expr();
_gotValue = true;
}
return _value;
}
}
public static implicit operator T(Lazy<T> l)
{
return l.Value;
}
}
And to allow the C# 3.0 compiler to infer types for us, we use a separate Lazy class:
public class Lazy
{
public static Lazy<T> Eval<T>(Func<T> expr)
{
return new Lazy<T>(expr);
}
}
Whilst lazy evaluation may not be useful in everyday programming, this example does show some of what can be achieved with lambdas in C# 3.0.
Thursday, September 27, 2007 10:56:51 AM (GMT Standard Time, UTC+00:00)
.net | c# | linq | programming

Monday, September 24, 2007
Trial mode Facebook applications?
Why do most Facebook applications require me to add the application before being able to do anything with them? I would prefer to see a trial version first, or at least some screenshots! I rarely download an application for Windows without first looking at some screenshots.
Having to add a Facebook application just to evaluate effectively puts bad data into my news feed. I didn't add "Cool app 1.0" because I plan on using it. I'm only trying it out! I'd like to see Facebook applications have a demo/trial mode. Perhaps allow me to use it with reduced functionality, or implement a "demo user".
Monday, September 24, 2007 12:42:14 PM (GMT Standard Time, UTC+00:00)
facebook | thinking

Saturday, September 22, 2007
Why Script# Makes Sense
Check out Joel's post: Strategy Letter VI
He seems to make a lot of sense. It'll be interesting to see the JavaScript compiler coming with some future version of Silverlight. It should mean that I can generate JavaScript from C# using Script#, and send a compiled version to those web clients with support.
Let's face it, a few mini-killer apps written using Silverlight will soon get the numbers using the plug-in way up to near Flash levels. I wonder what politics would stop Microsoft pushing Silverlight down via Windows Update? Then again, the tiny download and easy install should not stop standard web-based deployment as well.
Saturday, September 22, 2007 4:31:38 PM (GMT Standard Time, UTC+00:00)

Monday, September 17, 2007
Client-side MVP with Script#
Have you seen Script#? It is very impressive cross-compiler from C# to JavaScript. The libraries make it simple to program against the HTML DOM and Silverlight among other technologies. I have been using them recently to program Silverlight 1.0 without having to actually touch JavaScript. Using high-level OOP concepts makes creating complex user interactions much easier.
The Model-View-Presenter pattern has been very popular on the server-side when creating HTML applications. However, it seems that not many people have considered using it within the browser. With AJAX techniques becoming the way to make interactive web applications, it seems a little odd that people are not using more high-level concepts client-side. Of course, this mostly applies to the .NET space. I am aware there are Java toolkits that generate JavaScript.
I am therefore going to look into using Script# to implement a client-side, MVP-style, web application. The Model will contain local data and communicate with the server (via XML HTTP requests). The View will be a simple object that can get and set values from HTML/Silverlight elements and raise events when the user clicks on buttons, etc. The Presenter object will then orchestrate the user interaction logic. All this will be done within JavaScript by using Script# to convert C# classes, etc, into JavaScript concepts.
By writing all the code C#, it should be possible to tier split the Model class into server-side and client-side pieces. Whilst the JavaScript on the client-side is drastically different from the C# server-side model, they will share a common set of data fields. So it should be possible to serialize between the two worlds.
Monday, September 17, 2007 4:24:00 PM (GMT Standard Time, UTC+00:00)
.net | c# | programming | silverlight | thinking

Friday, September 07, 2007

Wednesday, September 05, 2007
Assertions via Linq Expressions
When writing assertions it is annoying to write a string that basically mirrors what the code your testing says. For example:
Debug.Assert(input != null, "input != null");
Similar statements appear when unit testing with tools like NUnit.
With Linq it is now possible to avoid this by using expression trees. The basic idea is to take a boolean assertion function as an expression tree so that we can call ToString() to get the message for the assert.
void Assert<T>(T obj, Expression<Func<T, bool>> test)
{
System.Diagnostics.Debug.Assert(test.Compile().Invoke(obj), test.ToString());
}
This is then called like:
Assert(input, i => i != null);
Given this idea, we can play with the syntax a bit. Using an extension method:
static class Exts
{
public static void MustSatisfy<T>(this T obj, Expression<Func<T, bool>> test)
{
Debug.Assert(test.Compile().Invoke(obj), test.ToString());
}
}
We then have:
input.MustSatisfy(i => i != null)
Another syntax option would be something like:
Assert.That(foo).Satisfies(
i => i > 0,
i => i < 100);
Where we are now passing an array of assertions (using a params arg in the Satisfies method).
Wednesday, September 05, 2007 11:46:23 AM (GMT Standard Time, UTC+00:00)
.net | c# | linq | programming | syntax

Monday, August 27, 2007
Data Access Syntax Using Anonymous Methods
I have so far managed to avoid needing to use any fancy ORM tools. However, this doesn't mean I like writing all the standard ADO.NET code by hand. Using C# 2.0 anonymous methods I am able to write code like the following. (I'm not sure all of this is truly original work; if you have already done this then sweet! I just want to share the ideas with everyone.)
Customer c = With.Database<Customer>(delegate(Database db)
{
return db.ExecuteReader<Customer>(
"select Id, FirstName, Surname from Customer where Id = @id", // The SQL to execute
delegate(IDbCommand cmd) // This anonymous function is called before executing so we can add params.
{
db.AddParameter(cmd, "@id", DbType.Int32, id);
},
delegate(IDataReader reader) // The IDataReader returned from ExecuteReader is passed here.
{
if (reader.Read())
return new Customer(
reader.GetInt32(0),
reader.GetString(1),
reader.GetString(2));
else
return null;
});
});
My Database class manages the creation of a connection and optionally a transaction. It then exposes methods to invoke SQL commands (Reader, Scalar and NonQuery). A transaction can be automatically provided by calling With.DatabaseInTransaction( ... ) instead. This then wraps the inputted action in a try-catch-finally block, commit and rolling back in the usual places.
("With" is a static class that provides convenient access to the Database object)
public static T DatabaseInTransaction<T>(Function<Database, T> function)
{
using (Database db = new Database())
{
db.BeginTransaction();
try
{
T result = function(db);
db.CommitTransaction();
return result;
}
catch
{
db.RollbackTransaction();
throw;
}
}
}
There are generic and non-generic versions of the functions, depending on if we want to return a value.
For example, here is the non-generic ExecuteReader method from Database:
public void ExecuteReader(string sql, Action<IDbCommand> addParameters, Action<IDataReader> action)
{
Debug.Assert(sql != null, "sql cannot be null.");
Debug.Assert(action != null, "action cannot be null.");
using (IDbCommand cmd = CreateCommand(sql))
{
if (addParameters != null)
{
addParameters(cmd);
}
using (IDataReader reader = cmd.ExecuteReader())
{
action(reader);
}
}
}
The IDbCommand is created using the following method. Notice that we also handle assigning the transaction if we're in one.
IDbCommand CreateCommand(string sql)
{
Debug.Assert(_connection != null && _connection.State == ConnectionState.Open);
IDbCommand cmd = _connection.CreateCommand();
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
if (_transaction != null)
{
cmd.Transaction = _transaction;
}
return cmd;
}
The Database class implements IDisposable, thus allowing the "using" syntax in the With class methods. In Dispose() I close the connection, if the transaction is still open I rollback first.
I anyone wants the full Database and With classes drop me a line. I'm looking forward to C# 3.0 since the improved type inference and lambda syntax will slim down the amount of keyboard time even more!
Monday, August 27, 2007 9:41:09 AM (GMT Standard Time, UTC+00:00)
.net | c# | data_access | programming | syntax