Archive for CSharp tag

Experimental LINQ to SQL template

June 2008 – October 2009 .NET, Microsoft (, , , ) • 3,137 views • 4 responses

A newer version of this LINQ to SQL template is available.

While SQL Metal does a good job of turning your SQL schema into a set of classes for you it doesn’t let you customize the code generation process.

Usefully there is now a templating system built into Visual Studio 2008 called Text Templates (T4 for short).

Here is a short (369 line) experimental proof-of-concept T4 template I wrote last night that will generate a data context and associated entity classes as a starting point similar to that produced by SqlMetal.

Download of this old version no longer available, see the newer article!

Once downloaded unzip and drop the DataContext.cs.tt into your project and edit line 17 to set the connection string. You can also edit lines 18 and 19 to set the namespace and class name. The lightweight wrappers around database, table and column can be found at the end of the file – they simply wrap the SQL Server Information_Schema views as briefly as possible.

Within seconds Visual Studio should have created a code-behind file for the DataContext named DataContext.cs.cs with your generated code ready to use :) If you don’t like the way the template generates your context you can change it :)

There are limitations with this experimental proof-of-concept including: 

  • Processes all and only tables in the database (no views or SP’s)
  • Foreign-key relationships are not implemented
  • Column attributes for IsDbGenerated, UpdateCheck and AutoSync not implemented
  • C# only (sorry Julie)
  • Plural and singular naming rules are incomplete
  • Can’t modify schema as you could with a designer stage
To learn more about T4: 

[)amien

Using LINQ to foreach over an enum in C#

April 2008 .NET (, ) • 20,140 views • 8 responses

I can’t be the only person in the world who wants to foreach over the values of an enum otherwise Enum.GetValues(Type enumType) wouldn’t exist in the framework. Alas it didn’t get any generics love in .NET 2.0 and unhelpfully returns an array.

Thanks to the power of LINQ you can do this:

foreach(CustomerTypes customerType in Enum.GetValues(typeof(CustomerTypes)).Cast<CustomerTypes>())

That is okay, but this is more concise:

foreach(CustomerTypes customerType in Enums.Get<CustomerTypes>())

The tiny class to achieve that is, of course:


using System.Collections.Generic;
using System.Linq;

public static class Enums {
	public static IEnumerable<T> Get<T>() {
		return System.Enum.GetValues(typeof(T)).Cast<T>();
	}
}

Great.

[)amien

Calculating Elf-32 in C# and .NET

November 2007 – October 2009 .NET (, , ) • 1,699 views • 4 responses

Because you can never have enough hashing algorithms at your disposal this one is compatible with the elf_hash function that forms part of the Executable and Linkable Format.

using System;
using System.Security.Cryptography;

public class Elf32 : HashAlgorithm {
   private UInt32 hash;

   public Elf32() {
      Initialize();
   }

   public override void Initialize() {
      hash = 0;
   }

   protected override void HashCore(byte[] buffer, int start, int length) {
      hash = CalculateHash(hash, buffer, start, length);
   }

   protected override byte[] HashFinal() {
      byte[] hashBuffer = UInt32ToBigEndianBytes(hash);
      this.HashValue = hashBuffer;
      return hashBuffer;
   }

   public override int HashSize { get { return 32; } }

   public static UInt32 Compute(UInt32 polynomial, UInt32 seed, byte[] buffer) {
      return CalculateHash(seed, buffer, 0, buffer.Length);
   }

   private static UInt32 CalculateHash(UInt32 seed, byte[] buffer, int start, int size) {
      UInt32 hash = seed;

      for (int i = start; i < size; i++)
         unchecked {
            hash = (hash << 4) + buffer[i];
            UInt32 work = (hash & 0xf0000000);
            if (work != 0)
               hash ^= (work >> 24);
            hash &= ~work;
         }
      return hash;
   }

   private byte[] UInt32ToBigEndianBytes(UInt32 x) {
      return new byte[] {
         (byte)((x >> 24) & 0xff),
         (byte)((x >> 16) & 0xff),
         (byte)((x >> 8) & 0xff),
         (byte)(x & 0xff)
      };
   }
}

[)amien

Dissecting a C# Application – Inside SharpDevelop

November 2007 .NET (, , , ) • 10,927 views • 5 responses

Cover of Dissecting a C# ApplicationThis great book shows you the process, thinking and code behind the open-source .NET IDE SharpDevelop that went on to branch into MonoDevelop.

It was not in print for very long but Apress bought Wrox when they closed down and made the book freely available on its site for download in PDF format.

Alas, with their most recent web redesign their free e-books section has disappeared so I am temporarily hosting it here after recommending it to somebody interested in writing their own syntax highlighting editor on the MSDN forums.

Download Dissecting a C# Application – Inside SharpDevelop (Adobe PDF) (3.9MB)

[)amien