Tag Archives: Code

T-SQL Transactions

I do not confess to being a database expert, nor a guru in T-SQL, which is why I have only just found out how crap transactions in T-SQL on SQL Server 2000 can be.  Take a look at the following piece of T-SQL:

CREATE TABLE #Foo
(
PK int NOT NULL
)

CREATE TABLE #Foo2
(
PK int NOT NULL
)

BEGIN TRANSACTION

INSERT INTO #Foo (PK) VALUES (1)
INSERT INTO #Foo2 (PK) VALUES (NULL)

COMMIT TRANSACTION

SELECT * FROM #Foo

DROP TABLE #Foo2
DROP TABLE #Foo

The above script creates two temporary tables, attempts to insert a value in the first, and then a NULL in the second table.  Since #Foo2.PK does not allow NULL values, the second insert fails.  I naively assumed that because I have wrapped the insert statements in a transaction, the commit will only complete if no error occurs.  This is not the case.  The commit statement commits the first insert but not the second – not exactly what I had in mind.  

The problem experienced above, is partially due to bad coding on my part because I did not initially understand the intricacies of how SQL Server 2000 manages transactions – the user is responsible for managing the roll back of a transaction after a statement error. The correct approach would have been to check the @@ERROR value for non-zero after each statement in the transaction block to see if a roll back was required. This can be a real chore if a transaction has many statements, and especially annoying if the error number of any one statement be reported, and the transaction aborted upon an error (typical behavior).  Fortunately, SQL Server 2005 comes to the rescue with try-catch – similar to that of how ADO.NET deals with transactions.  The following code will produce the desired results in SQL Server 2005:

CREATE TABLE #Foo
(
PK int NOT NULL
)

CREATE TABLE #Foo2
(
PK int NOT NULL
)

BEGIN TRANSACTION

BEGIN TRY

INSERT INTO #Foo (PK) VALUES (1)
INSERT INTO #Foo2 (PK) VALUES (NULL)

COMMIT TRANSACTION

END TRY
BEGIN CATCH

ROLLBACK TRANSACTION
PRINT ‘It broke’

END CATCH

SELECT * FROM #Foo

DROP TABLE #Foo2
DROP TABLE #Foo

From C++ to C#

I have gone back in time this week to work on a legacy ISAPI
application.  The ISAPI application is being developed in C++ and
makes use of MSXML to read an XML configuration file.  Below is
some code in C++ to open the XML file and read two text values,
contained in element nodes:

BOOL GetConfigDetails(string &userName, string &domain)
{
BOOL result = FALSE;
if (0 != configFilename && _tcslen(configFilename) > 0)
{
try
{
// Create a DOM Document.
// CComPtr smart pointer will release our COM handle.
CComPtr pItfcDoc = 0;
HRESULT hr = pItfcDoc.CoCreateInstance(__uuidof(MSXML2::DOMDocument60));
if (SUCCEEDED(hr))
{
// Load the config file.
if (VARIANT_TRUE == pItfcDoc->load(configFilename))
{
// Look for the username and domain nodes.
CComPtr pItfcNode = 0;
pItfcNode = pItfcDoc->selectSingleNode(_bstr_t(“/ISAPIStub/username”));
userName = 0 != pItfcNode ? pItfcNode->Gettext() : _bstr_t(“”);
pItfcNode = pItfcDoc->selectSingleNode(_bstr_t(“/ISAPIStub/domain”));
domain = 0 != pItfcNode ? pItfcNode->Gettext() : _bstr_t(“”);
result = TRUE;
}
}
}
catch (_com_error)
{
result = FALSE;
}
}
return result;
}

Now, here is the code in C#:

public bool GetConfigDetails(out string userName, out string domain)
{
bool result = false;
userName = domain = String.Empty;
if (!String.IsNullOrEmpty(configFilename))
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(configFilename);
XmlNode node = doc.SelectSingleNode(“/ISAPIStub/username”);
userName = (null != node) ? node.InnerText : String.Empty;
node = doc.SelectSingleNode(“/ISAPIStub/domain”);
domain = (null != node) ? node.InnerText : String.Empty;
}
catch
{
result = false;
}
}
return result;
}

Much easier huh?  See how far we’ve come as developers. 
Whilst writing my ISAPI application I had to remember to go back and
clean up my memory allocations because there is no friendly garbage
collector doing it for me – doh.

Multicast Delegate Events as Properties

The saying goes “you learn something new every day”, and today is no
exception.  I’m not sure how I missed this, but never less, this
post shows how to gain finer control over adding and removing of event
handlers to public multicast delegate events.

Typically, most C# developers are used writing event code as follows:

using System;
public delegate void MyDelegate(); // delegate declaration

public interface I
{
event MyDelegate MyEvent;
void FireAway();
}

public class MyClass: I
{
public event MyDelegate MyEvent;

public void FireAway()
{
if (MyEvent != null)
MyEvent();
}
}

public class MainClass
{
static private void f()
{
Console.WriteLine(“This is called when the event fires.”);
}

static public void Main ()
{
I i = new MyClass();

i.MyEvent += new MyDelegate(f);
i.FireAway();
}
}

The above code exposes a public multicast delegate event, which client callers subscribe to by adding handlers using the +=
operator.  However, it is possible to define a multicast delegate
event as a property, where the developer can control the adding and
removal of event handlers with add and remove accessor
decelerations. 

The example below defines properties for each event, and the accessor
decelerations on each property manages the storage of event handlers
using a private hash table. This approach is usually undertaken when a
class defines many events, where the developer expects most of the
events to be unimplemented, thus saving some overhead in creating
multicast delegate event instances that are never assigned a handler.

using System;
using System.Collections;

public delegate void MyDelegate1(int i);
public delegate void MyDelegate2(string s);
public delegate void MyDelegate3(int i, object o);
public delegate void MyDelegate4();

public class PropertyEventsSample
{
private Hashtable eventTable = new Hashtable();

public event MyDelegate1 Event1
{
add
{
eventTable[“Event1”] = (MyDelegate1)eventTable[“Event1”] + value;
}
remove
{
eventTable[“Event1”] = (MyDelegate1)eventTable[“Event1”] – value;
}
}

public event MyDelegate1 Event2
{
add
{
eventTable[“Event2”] = (MyDelegate1)eventTable[“Event2”] + value;
}
remove
{
eventTable[“Event2”] = (MyDelegate1)eventTable[“Event2”] – value;
}
}

public event MyDelegate2 Event3
{
add
{
eventTable[“Event3”] = (MyDelegate2)eventTable[“Event3”] + value;
}
remove
{
eventTable[“Event3”] = (MyDelegate2)eventTable[“Event3”] – value;
}
}

public event MyDelegate3 Event4
{
add
{
eventTable[“Event4”] = (MyDelegate3)eventTable[“Event4”] + value;
}
remove
{
eventTable[“Event4”] = (MyDelegate3)eventTable[“Event4”] – value;
}
}

public event MyDelegate3 Event5
{
add
{
eventTable[“Event5”] = (MyDelegate3)eventTable[“Event5”] + value;
}
remove
{
eventTable[“Event5”] = (MyDelegate3)eventTable[“Event5”] – value;
}
}

public event MyDelegate4 Event6
{
add
{
eventTable[“Event6”] = (MyDelegate4)eventTable[“Event6”] + value;
}
remove
{
eventTable[“Event6”] = (MyDelegate4)eventTable[“Event6”] – value;
}
}
}

LCG Performance

The following are the results of a performance test performed against
LCGs, direct function calls, and reflection API invokes.  Each
test ran for a number of iterations and produced a mean average time in
milliseconds. 

The efficiency of the dynamic method delegate (LCGs) calls are
calculated as the direct method call time divided by the DMD time.
The efficiency of the reflection API Method.Invoke calls are calculated
as the direct method call time divided by the reflection API Invoke
time.


== Testing performance of dynamic method delegates:
== Test call type: static method with boxing on return value
Results for 5 tests on 500000 iterations:
Direct method call: 6ms
Dynamic method delegates: 39ms (Efficiency: 0,15)
MethodInfo.Invoke: 4616ms (Efficiency: 0,001)

== Testing performance of dynamic method delegates:
== Test call type: static method without boxing on return value
Results for 5 tests on 100000 iterations:
Direct method call: 8ms
Dynamic method delegates: 14ms (Efficiency: 0,57)
MethodInfo.Invoke: 894ms (Efficiency: 0,009)

== Testing performance of dynamic method delegates
== Test call type: virtual method without boxing on return value
Results for 5 tests on 10000 iterations:
Direct method call: 10ms
Dynamic method delegates: 13ms (Efficiency: 0,77)
MethodInfo.Invoke: 166ms (Efficiency: 0,06)


Results obtained from Alessandro Febretti in an article at CodeProject.

Reflection and LCG

Anyone who has played with .NET long enough will tell you that
Reflection is a really cool feature.  Essentially, reflection
enables the developer to query the type system (CLT – Common Language
Type system), dynamically invoke methods, and dynamically create types
at runtime, using meta-data stored in the .NET assemblies. The reflection
API is built into the framework.  The only snag with using
reflection is paying the performance cost.

This post is not about dodging the performance pitfalls with
performance – Joel Pobar, a program manager on the CLR (Common Language
Runtime) team at Microsoft, has written a great article,
which is
extensive and covers the topic of reflection performance.  
Instead, I would like to take this opportunity to mention Lightweight
Code Generation (LCG) in version 2.0 of the .NET Framework.

What is LCG?

LCG is all about generating code on the fly at runtime, which can be
executed.  A good use for LCG is avoiding the performance bloat
associated with method invocation in reflection.  How many times
have you seen the following code?

Type t = typeof(Console);
t.InvokeMember(“WriteLine”, BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, null, new object[] { “Hello World” });

The above example code gets a Type object (t) for the Console class,
and then invokes the WriteLine method, using the InvokeMember
method.  Of course, this example is not a good representation of a
real world scenario, because it is unlikely that a developer would call
the static WriteLine method of the console class in this way. 
However, imagine that the type (t) was obtained dynamically via
reflection, perhaps as a result of querying custom attributes of a
property or class (GetCustomAttributes).  The developer may intend
a method call on the type (t) during runtime without knowing the class
type at compile time.  Regardless of how a Type object (t) is
obtained, calling InvokeMember is bad for performance (see Joel’s
article for reasons why).

A better approach to the above example would be to obtain a MethodInfo
instance for the dynamically called WriteLine method and then call the
MethodInfo.Invoke method.  This approach is faster than using
Type.InvokeMember, but still not that fast.

Type t = typeof(Console);
MethodInfo method = typeof(Console).GetMethod(
“WriteLine”, BindingFlags.ExactBinding | BindingFlags.Public | BindingFlags.Static, null,
new Type[] { typeof(string) }, null);
method.Invoke(null, new object[] { “Hello World” });

Version 2.0 of the Framework introduces LCGs, which is a half way
compromise between early bound invocation (invocation determined at
compile time) and late bound invocation (invocation determined at
runtime).  LCGs are about creating IL (Intermediate Language)
code, similar to what the compiler would generate as early bound
invocation, at runtime, and then calling the generated IL code from
your application infrastructure.  Joel touches on LCGs in his
article, and explains them further on his blog, the MSDN is also a good
resource for knowledge on this subject.

Below is a helper class (written with the help of examples from Joel on
CodeProject), which contains two public methods.  The Create
method is a replacement for MethodInfo.Invoke, which dynamically
invokes a method on a class (static) or object (non-static) using an
LCG.  The second method – CreateInstance – will create an instance
object from a Type class by using emitted IL in an LCG.  Both of
these helper methods are faster performing than the aforementioned
Type.InvokeMember and MemberInfo.Invoke API methods (perhaps I’ll post
evidence of this later).

///
/// Factory class to invoke a method on a type using Dynamic Methods in C# 2.0
///
public class DynamicMethodFactory
{
///
/// Factory returns a delegate instance for the invoked method.
///
/// Target object (null if invoking the constructor).
/// Arguments.
/// Return type of some sort.
public delegate object DynamicMethodDelegate(object target, object[] args);

///
/// Create a delegate for a dynamically invoked method that will create an instance of a type.
///
/// Constructor info for the type to create.
/// Delegate for the dynamic method.
public static DynamicMethodDelegate CreateInstance(ConstructorInfo ctor)
{
// Get the parameter details.
ParameterInfo[] parameters = ctor.GetParameters();
// Create the dynamic method, parameter is just an array of objects.
Type[] parameterTypes = { typeof(object), typeof(object[]) };
DynamicMethod dMethod = new DynamicMethod(String.Empty, typeof(object), parameterTypes, typeof(DynamicMethodFactory), false);
// Create the IL for the method (the meat in the sandwich) we just created.
ILGenerator il = dMethod.GetILGenerator();
// Check the parameters.
CompareArgsIL(il, parameters);
// Emit IL for the parameters before creating a new instance.
EmitArgsIL(il, parameters);
il.Emit(OpCodes.Newobj, ctor);
// Return object.
il.Emit(OpCodes.Ret);
// Return the delegate.
return (DynamicMethodDelegate)dMethod.CreateDelegate(typeof(DynamicMethodDelegate));
}

///
/// Create a delegate for a dynamically invoked method.
///
/// Method info.
/// Delegate.
public static DynamicMethodDelegate Create(MethodInfo method)
{
// Get the parameter details.
ParameterInfo[] parameters = method.GetParameters();
// Create the dynamic method.
Type[] parameterTypes = { typeof(object), typeof(object[]) };
DynamicMethod dMethod = new DynamicMethod(String.Empty, typeof(object), parameterTypes, typeof(DynamicMethodFactory), false);
// Create the IL for the method (the meat in the sandwich) we just created.
ILGenerator il = dMethod.GetILGenerator();
// Check the parameters.
CompareArgsIL(il, parameters);
// Push the target object on the stack if not static.
if (!method.IsStatic)
{
// Argument of our dynamic method is the target instance.
il.Emit(OpCodes.Ldarg_0);
}
// Emit IL for the parameters before our method call.
EmitArgsIL(il, parameters);
// Call the method, process return value and return from call site.
// If method is not final then we need to call it as a virtual method call.
if (method.IsFinal)
{
il.Emit(OpCodes.Call, method);
}
else
{
il.Emit(OpCodes.Callvirt, method);
}
// Check for return type.
// if return type is non-void reference type then use the last parameter on the eval stack from
// the last call statement.
if (typeof(void) != method.ReturnType)
{
// Box returned value types.
if (method.ReturnType.IsValueType)
{
il.Emit(OpCodes.Box, method.ReturnType);
}
}
else
{
il.Emit(OpCodes.Ldnull);
}
// Return object.
il.Emit(OpCodes.Ret);

// Return the delegate.
return (DynamicMethodDelegate)dMethod.CreateDelegate(typeof(DynamicMethodDelegate));
}

///
/// Emit IL code to check parameters.
///
/// IL generator.
/// Parameters defined for a dynamic method.
private static void CompareArgsIL(ILGenerator il, ParameterInfo[] parameters)
{
// Check the number of arguments in the array with this accepted by the method being invoked.
// Define a label for successful arg count checking.
Label argsGood = il.DefineLabel();
// Check input arg count.
il.Emit(OpCodes.Ldarg_1); // Loads argument at index 1 onto evaluation stack.
il.Emit(OpCodes.Ldlen); // Pushes number of elements of a zero based, one-dimentional array on the stack.
il.Emit(OpCodes.Ldc_I4, parameters.Length); // Push Int32 on evaluation stack.
il.Emit(OpCodes.Beq, argsGood); // Transfer to target if both arguments are equal.
// Argument is wrong, thrown an exception.
il.Emit(OpCodes.Newobj, typeof(TargetParameterCountException).GetConstructor(Type.EmptyTypes));
il.Emit(OpCodes.Throw);
// Mark label into IL, which is the skip point if args are good.
il.MarkLabel(argsGood);
}

///
/// Emit parameter IL for a method call.
///
/// IL generator.
/// Parameters defined for a dynamic method.
private static void EmitArgsIL(ILGenerator il, ParameterInfo[] parameters)
{
// Add args. Since all args are objects, value types are unboxed. Refs to value types are to be
// converted to values themselves.
for (int i = 0; i < parameters.Length; i++)
{
// Push args array reference on the stack , followed by the index.
// Ldelem will resolve them to args[i].
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldc_I4, i);
il.Emit(OpCodes.Ldelem_Ref);
// If param is a value type then we need to unbox it.
Type paramType = parameters[i].ParameterType;
if (paramType.IsValueType)
{
il.Emit(OpCodes.Unbox_Any, paramType);
}
}
}
}

The above helper methods can be called using the example code below:

// Late bound instance creation using LCG.
Type t = typeof(ArrayList);
ConstructorInfo cInfo = t.GetConstructor(Type.EmptyTypes);
DynamicMethodFactory.DynamicMethodDelegate del = DynamicMethodFactory.CreateInstance(cInfo);
object listRef = del.Invoke(null, new object[] { }) as ArrayList;

// Late bound invocation using LCG.
MethodInfo mInfo = t.GetMethod(
“Add”, BindingFlags.Instance |BindingFlags.ExactBinding | BindingFlags.Public, null, new Type[] { typeof(object) }, null);
del = DynamicMethodFactory.Create(mInfo);
del.Invoke(listRef, new object[] { “a string” });
mInfo = t.GetMethod(“Count”, Type.EmptyTypes);

Tech Preview: LINQ

This morning I’ve been checking out LINQ – Language Integrated Query from Microsoft, on Channel 9. LINQ enables developers to query any IEnumerable<T> collection  with a simple query, much like that of SQL.

Check out the following piece of LINQ code, which queries all the
non-static methods supported by System.String, and displays the number
of overloads for each method:

var q = from m in typeof(string).GetMethods()
where !m.IsStatic
order by m.Name
group by m.Name intp g
select new { Method = g.Key, Overloads = g.Group.Count() };

foreach (o in q)
Console.WriteLine(“{0} {1}”, o.Method, o.Overloads);

The code above defines a query q, which queries the collection,
returned by GetMethods.  The query orders on the method name,
selects only methods that are no static (notice how LINQ is strongly
typed – m.IsStatic works because m is strongly typed to the MethodInfo
class), and groups the results into a collection of objects defined on
the fly.  The count of overloads is defined by the number of
methods in each group. Lastly, the code iterates the over the
collection of objects in the query collection and displays the method
name and overloads count.

Also read about DLINQ – Language Integrated Query for Databases – and XLINQ – Language Integrated Query for XML.

LINQ was announced at PDC ’05, and is only a tech preview for
now.  The above code is likely to change before it ever reaches
production.

C# 2.0 and the ‘yield’ keyword

Another nice addition to C# 2.0 is the yield keyword. Yield enables iterator blocks to provide values to an enumerated result, see the following example.

// yield-example.cs
using System;
using System.Collections;
public class List
{
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while(counter++ < exponent)
{
result = result * number;
yield return result;
}
}

static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach(int i in Power(2, 8))
Console.Write(“{0} “, i);
}
}

What does this mean in English? Essentially, iterator blocks can
implicitly create an array of results, which supports IEnumerable,
without having to declare an array data type and populating it.

The following line will signal the end of the iteration.

yield break;