# Thursday, May 29, 2008

It has been almost one year since the last public release of CoolStorage.NET ("cool" open-source object mapper for .NET 2.0), but this doesn't mean the product was dead. A lot of people regularly downloaded the latest builds from CodePlex and I received a lot of great feedback, which finally lead to the release of version 1.2.

Besides a bunch of bug fixes and performance improvements, the new features in this release are:

  • Support for prefetching of many-to-one, one-to-one and one-to-many relations (marked by the [Prefetch] attribute at compile-time or by using the .WithPrefetch() method). This change results in a spectacular performance improvement in most cases where lists of objects with related objects are retrieved from the database.
  • Support for paging at server level. Use the Range() method on the CSList class to get a specific range of records
  • Support for GUID fields (server-generated and client-generated)
  • Support for specifying a context when calling generic CSDatabase.RunQuery() methods
  • New method ToList<T> on CSList
  • New method ThenBy() on CSList (in line with the LINQ methods)
  • New attribute [ClientGenerated] for GUID fields
  • New attribute [NotMapped] for fields that are not mapped to a database column
  • Support for VistaDB 3.x database

Databases currently supported are:

  • MS SQL Server 2000/2005
  • MS Access
  • SQLite v3
  • VistaDB 3.x
  • MySql 5.x
  • IBM DB2

The latest release can be downloaded from CodePlex.

In case you have no idea what CoolStorage.NET is:

CoolStorage.NET is a fully typed Object Relational Mapping library for .NET 2.0.

The main strength of CoolStorage.NET is the ease of use. Most ORM tools still require a lot of type casting and other plumbing to be written, CoolStorage.NET is designed to relieve the programmer from these tedious and error-prone tasks, making it very intuitive to use. It is "session-less", meaning you don't have to keep a connection or session object lying around to access objects in the database.

The main features are:

  • Supports SQL Server 2000/2005, MySQL, IBM DB2, SQLite, MS Access, VistaDB
  • Any existing relational data model can be mapped to CoolStorage objects with minimal effort
  • All relation types are supported: One-To-One, One-To-Many, Many-To-One and Many-To-Many
  • Completely typed object model (no type casts required)
  • Full support for transactions, including .NET 2.0 TransactionScope
  • Nullable columns can be mapped to .NET 2.0 nullable fields or any other value
  • Delayed (lazy) loading of data to minimize database access
  • Selective pre-fetching of all relation types for improved query performance.
  • Powerful and intuitive database-independent object query language
  • Flexible event framework to intercept any event
  • Identity (auto-increment) keys are supported for all database types
  • Support for server and client generated Guid keys
  • Sessionless data access
  • Objects can be mapped to different databases, even across object relations
  • Pageable object collections
  • Extensive support for retrieving aggregate values on collections (count, sum, average, ...)
  • Collections implement IBindingList so they can be used by controls (grids) as a data source
  • Underlying database engine uses optimized and parameterized SQL queries. SQL injection is impossible
  • Built specifically for .NET 2.0, taking full advantage of generics and nullable variables
  • Raw SQL and/or stored procedures can be called on the underlying database without the need for a separate database connection
  • Small footprint (less than 120 KB)
kick it on DotNetKicks.com
Thursday, May 29, 2008 11:28:58 PM (W. Europe Daylight Time, UTC+02:00)  #    Comments [0] -

# Monday, May 26, 2008

Am I the only one who believes a great programming font can boost your productivity and increase your coding joy?

Personally, when I'm using a nice, clean font for my coding, I feel happy about my code. The code just looks better. And I don't mean it "looks" better, but it looks better (catch my drift?)

I have tried a lot of fonts, and for the last few years I've always gone back to Damien Guard's excellent Envy Code R font. It is (IMHO) the perfect font for source code.

Today Damien released "Preview #7" of his font, which is a big step forward: the font looks almost perfect at all sizes. I really recommend it to anyone. And it's free! (he does accept donations, which he really deserves)

The link to his announcement: Envy Code R Preview #7 released

kick it on DotNetKicks.com
Monday, May 26, 2008 12:13:51 PM (W. Europe Daylight Time, UTC+02:00)  #    Comments [7] -

First some basics: in .NET there are reference types and value types. Reference types are always accessed through a reference (a pointer actually) while value types, well, are not.

The .NET documentation tries to sum it up in one sentence:

A data type is a value type if it holds the data within its own memory allocation. A reference type contains a pointer to another memory location that holds the data.

This means several things:

  • You cannot set a variable of a value type to null. It's not a pointer. It's just there.
  • When returning a value type from a method, a copy is made and the whole value is returned, not just a reference.
  • Creating a variable always initializes it to "something".

All primitive numeric types are value types (Int32, Double, Int64, Boolean, ...), as well as DateTime, enums and structs. Examples of reference types are String, all arrays (even when they contain value types) and all classes.

So far nothing new, but to make it interesting, let's create a small sample application using a custom struct, which is a value type:

Struct declaration:

struct MyStruct
{
  public int Value = 0;
  
  public void Update(int i) { Value = i; }
}


Code sample:

MyStruct[] list = new MyStruct[5];

for (int i=0;i<5;i++)
  Console.Write(list[i].Value + " ");
Console.WriteLine();

for (int i=0;i<5;i++)
  list[i].Update(i+1);

for (int i=0;i<5;i++)
  Console.Write(list[i].Value + " ");
Console.WriteLine();


The output of this code is:

0 0 0 0 0
1 2 3 4 5


Now let's do the same, but substitute the array for a generic List<>:

List<MyStruct> list = new List<MyStruct>(new MyStruct[5]); 

for (int i=0;i<5;i++)
  Console.Write(list[i].Value + " ");
Console.WriteLine();

for (int i=0;i<5;i++)
  list[i].Update(i+1);

for (int i=0;i<5;i++)
  Console.Write(list[i].Value + " ");
Console.WriteLine();


The output is:

0 0 0 0 0
0 0 0 0 0


Suprised? I was too, at first, but the explanation is very simple. No, it's not boxing/unboxing...

When accessing elements from an array, the runtime will get the array elements directly, so the Update() method works on the array item itself. This means that the structs itself in the array are updated.

In the second example, we used a generic List<>. What happens when we access a specific element? Well, the indexer property is called, which is a method. As I mentioned earlier, value types are copied when they are returned by a method, so this is exactly what happens: the list's indexer method retrieves the struct from an internal array and returns it to the caller. Because it concerns a value type, a copy will be made, and the Update() method will be called on the copy, which of course has no effect on the list's original items.

What should we learn from this?

Always make sure your structs are immutable, because you are never sure when a copy will be made. Most of the time it is obvious, but in some cases it can really surprise you...

kick it on DotNetKicks.com
Monday, May 26, 2008 1:27:05 AM (W. Europe Daylight Time, UTC+02:00)  #    Comments [3] -

# Thursday, May 22, 2008

Generated code is great... if it was generated by you,or you fully understand the generated code!

Imagine the following situation:

You have been working on a large project that has been around for years and you need to make a small change. The change seems insignificant so you dive in the code only to find out that the code change has to be done in code that was generated by a "tool". Now there are several possibilities:

1. The code was generated but changed by hand afterwards
2. The code should not be changed by humans, but should be regenerated
3. All of the above

Case 1:

the code that was generated is probably pretty big (otherwise it wouldn't have been generated by a tool), contains a lot of duplicated code and is incomprehensible for any human being. So you're making a change to code that you don't understand, which is by definition "programming by coincidence".

In other words, you're screwed, because you have no idea what you're changing and even if you get it working, you have a bad feeling about it because you don't know why it works.

Case 2:

Cool, you just have to run the tool that generated the code, change some settings or configuration, re-generate, and you're done. Only, where is the tool? Does it still run on my machine? (it used to run fine in 2001 on a Windows NT machine, but will it run on my Vista workstation?). OMFG!

In other words, chances are that you're screwed.

Would you trust your mission-critical application to a code generator that may no longer work in 7 years time? I'll let you answer that question for yourself.

Case 3:

The worst case scenario is a combination of case 1 and 2: code that should never be changed by hand has been changed. You should really re-generate the code, but that would overwrite all manual changes.

Now you're really screwed. Welcome to software maintenance hell...

Which leads to the title of this post: "Wizards are evil". Inspired by a piece in the book "The Pragmatic Programmer" (a must-read for any developer). It all comes down to this one statement:

Don't Use Wizard Code You Don't Understand

A snippet from the book:

"Some people feel that this is an extreme position. They say that developers routinely rely on things they don’t fully understand—the quantum mechanics of integrated circuits, the interrupt structure of the processor, the algorithms used to schedule processes, the code in the supplied libraries, and so on. We agree. And we’d feel the same about wizards if they were simply a set of library calls or standard operating system services that developers could rely on. But they’re not. Wizards generate code that becomes an integral part of Joe’s application. The wizard code is not factored out behind a tidy interface—it is interwoven line by line with functionality that Joe writes.[1] Eventually, it stops being the wizard’s code and starts being Joe’s. And no one should be producing code they don’t fully understand."

I couldn't agree more.

Let's say I needed a data access layer and I found this great, fancy tool(*) that generates all the data access code for me with one click of a button. Sure, it created 100,000 lines of (duplicated) code, but it worked perfectly.

Knowing that this application would have to be maintained for several years, and my business depended on it, would I feel safe?

NO. I would constantly worry about what would happen if any of the above 3 cases would occur in the future.

(*) Although some people will think I am referring to LLBLGen, I am not. LLBLGen is a superb tool (I even own a license), and it does have the problems I'm describing here, but there are lots of other products that generate data access layers that are a lot worse (does LINQ for SQL ring a bell?)

kick it on DotNetKicks.com
Thursday, May 22, 2008 12:15:39 PM (W. Europe Daylight Time, UTC+02:00)  #    Comments [1] -

# Tuesday, May 20, 2008

This is another one in the series "heck, I never thought of that"... Like most of these articles, if you already knew this trick, ignore me...

Let's say you have a generic class with a new() constraint on the type parameter. This means that you are allowed to create new objects of the generic type, like this:

class GenericClass<T> where T:new()
{   
   public void SomeMethod()   
   {      
      T obj = new T();
      ...
   }
}


Pretty straightforward stuff, BUT there is a possibility that type T implements IDisposable, meaning that you should clean up after using any object of type T (using the Dispose method or a "using" block.

The trivial way of solving this problem is:

class GenericClass<T> where T:new()
{
   public void SomeMethod()
   {
      T obj = new T();

      ...

      if (obj is IDisposable)
         ((IDisposable) obj).Dispose();
   }
}

 

Not too bad, but we can do better:

class GenericClass<T> where T:new()
{
   public void SomeMethod()
   {
      T obj = new T();

      using (obj as IDisposable)
      {
         ...
      }
   }
}


Pretty neat, don't you think? What actually happens is that the using block creates a "hidden" variable of type "IDisposable" and will call Dispose() on it when exiting the scope of the using block. If T does not implement IDisposable, the hidden variable will be null, and the compiler will not try to call Dispose().

kick it on DotNetKicks.com
Tuesday, May 20, 2008 11:29:08 PM (W. Europe Daylight Time, UTC+02:00)  #    Comments [5] -

Many of you know me from some open source projects that are hosted on CodePlex:

The next project has been in development for quite a while and is closely related to the other projects, as it is being used in ProMesh.NET and it is based on the LazyParser.NET expression parsing engine.

So I'd like to introduce SharpTemplate.NET, a lightweight general-purpose template engine for .NET 2.0. It allows you to incorporate template parsing in your .NET applications. Perfect for code generators, reporting tools, mass-mailing applications, etc..

The syntax of SharpTemplate.NET is not fixed, unlike other engines (NVelocity, StringTemplate, ...). The syntax is fully configurable with just a few lines of code and some regular expression magic. Currently, the following syntaxes are built in:

  • SharpVelocity (Velocity-like syntax)
  • ProMeshHtml (syntax used by ProMesh.NET)
  • XML
  • "DoubleCurly"

To give you an idea of how it works, here is an sample of a template (using Velocity syntax):

<table>#foreach (product in Products)
   <tr><td>$product.Name</td>
   #if (product.Stock > 0)
      <td>In stock</td>
   #else
     <td>Backordered</td>
   #end
  </tr>
#end
</table>


The same template in "ProMesh.NET" syntax:

<table>
<!--$[foreach product in Products]-->
   <tr><td>$[product.Name]</td>
   <!--$[if product.Stock > 0]-->
      <td>In stock</td>
   <!--$[else]-->
     <td>Backordered</td>
   <!--$[endif]-->
  </tr>
<!--$[endfor]-->
</table>


The code to parse and render the template:

SharpTemplate template = new SharpTemplate<Velocity>();
 
ParserContext data = new CSharpContext();
 
data["Products"] = GetProducts();

string renderedFile='template.RenderFile("template.htm", data);


Well, you get the idea. If you want to play with it, the code can be downloaded on CodePlex

kick it on DotNetKicks.com
Tuesday, May 20, 2008 10:26:17 PM (W. Europe Daylight Time, UTC+02:00)  #    Comments [4] -