Archive for CSharp tag
Experimental LINQ to SQL template
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 :)
- 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
- Watch a screencast about T4 in action (download, embedded player is awful)
- Grab T4 Editor for IntelliSense within T4 and T4 Template Items for Add New Item… support
- Check out Oleg Sych’s blog for great T4 articles including how to enable the 3.5 compiler for templates
- Learn about T4 debugging
[)amien
Using LINQ to foreach over an enum in C#
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
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
This 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
Extension methods illustrated
Extension methods are a great new feature in the .NET Framework 3.5 that let you write new methods that appear to be part of existing classes without the need to subclass or modify them.
We can explain this in simple terms with an example. Here is a useful routine that takes a string and returns what it finds between two other strings that works just fine with .NET 2.0 and .NET 1.1.
public static string Between(string value, string start, string end) {
int startIndex = value.IndexOf(start, StringComparison.CurrentCultureIgnoreCase);
if (startIndex == -1)
return "";
startIndex += start.Length;
int endIndex = value.IndexOf(end, startIndex, StringComparison.CurrentCultureIgnoreCase);
if (endIndex == -1)
return "";
return value.Substring(startIndex, endIndex-startIndex);
}
If this method belonged to a static StringUtilities class then you could use it like this:
string newString = StringUtilities.Between(inputString, startingString, endingString);
The problem is knowing that the StringUtilities class within the project you are working on and until you know that IntelliSense can’t even kick in. What would be nice is to add this to the String class but of course we can’t because String is sealed and besides methods everywhere create String classes and not instances of your subclass.
What would be really cool is if Visual Studio and .NET could just realise that this method is static and takes a string parameter as it’s first parameter and let it just appear as another method on the String class and just call StringUtilities behind the scenes.
That is exactly what the extension methods in .NET 3.5 achieve.
All we need to do is put this in front of the first parameter which will let VS and the compiler know that this method should appear as if it is a method against the type of that first parameter. The method must be static and visible to the code and curiously the class itself must also be static. Our signature now appears as:
public static string Between(string this value, string start, string end)
To call the method we simply press . after our string and IntelliSense displays all the usual methods and properties of the String class and any extension methods it can find in your project too which now includes our Between method giving us:
string newString = inputString.Between(startingString, endingString);
Nice but bear in mind the extension method can only access the public parts of the class it will appear with – there is no privileged access to protected properties or methods that would be available with subclassing!
[)amien