Friday 23 March 2012

Accessing C# Enumerations on the client side

So you spend all of that time carving out beautifully detailed Enums in your C# code but when you come to write your JavaScript code find yourself rewriting them all from scratch. Wouldn't it be nice if you could easily have them available in the client side scripts without too much effort... Well here is a solution that just does that:

First of all create an extension method for Enums which converts the Enum into a JSON string:


///
/// Serialize an enum's values to a JSON string returning a snippet of JavaScript
/// code that can be used to access the enum's values on the client side with out
/// duplicating the enum in your JavaScript code.
///

/// Enumerated type to serialize to JSON.
/// {"enum_value_1": "enum_value_1", "enum_value_2": "enum_value_2", ...};
public static string ToJson(this Enum en)
{
StringBuilder json = new StringBuilder();
json.Append("{");

List enumFields = new List();

Type type = en.GetType();

foreach (var value in Enum.GetValues(type))
{
enumFields.Add("\"" + value.ToString() + "\": \"" + value.ToString() + "\"");
}

json.Append(string.Join(", ", enumFields.ToArray()));
json.Append("}");

return json.ToString();
}


Then whenever you are creating a page on the server side just write this Enum into the JavaScript using:


Enum.ToJson()


Prototyping the result to an object you can access on the client side and voila! You have made your server side Enum's available on the client side!

Thursday 16 June 2011

C# Stack and Heap

Understanding memory management is a key weapon in a developers arsenal. After developing in Java for many years, I progressed to C# which adds a few of its own nuances to memory management.

What goes on the Stack/Heap?

On the stack - value types (int, float, struct, etc) + references to reference types. Typically this is the data structure which stores access to variables used in currently executing code.

The stack is split into "stack frames" - each containing all variables relating to the current executing method.

(LIFO data structure - Last In First Out)

The heap - contains the values of reference types. Does not keep track of execution state, instead is more of a data store.

Value types as references

When new methods are called with value types as their parameters, those value types get copied into the stack frame of that new method. Obviously if you are doing this with large value types, you can run into potential problems (general performance, stack overflow, etc). To reduce the copying over head C# allows you to pass the value type as a reference instead.

For example, if we have:

struct testStruct{
float one, two, three, four, five, six, seven;
}

Each time we pass this struct to a new method as follows:

testStruct T = new testStruct();
exampleMethod(T);

The entire struct is copied on the stack as explained above, however, if we do the following:

exampleMethod(ref T);

We just pass a pointer/reference to the method, and only this pointer is copied on the stack. The side effect is that any changes made within the exampleMethod to the testStruct will also be reflected in the calling method. We are accessing the value itself as opposed to a copy of it.

Reference types by reference

Not only can we obtain references to value types in C# but it also allows us to obtain references to reference types! The same terminology is used as explained above with the "ref" keyword.

A reference reference (better name suggestions on a postcard!) not only gives us access to change the values of the original reference object, but also change the original pointer to that object. So we could point it to a different object or we could change the type of the pointer (from say String to Object - making the reference more general).

It is interesting to see that C# gives us this additional power on top of Java - I don't think it is necessarily something that will be required all the time, however, when it comes to performance tuning an application I see that these language additions will be of great benefit.

Deep copies

As with Java, C# also undertakes just shallow copies of objects (not copying any child objects) just references and primitives. In order to copy child objects too we need to implement the ICloneable interface in C# which includes the clone method e.g.

public class TestObject : ICloneable{

public string ParameterOne;

public object Clone(){
TestObject object = new TestObject();
object.ParameterOne = ParameterOne.Clone() as string;

return object;
}
}

I always wondered why this kind of method wasn't provided as standard within C# or Java, however, it appears that the concept of a true deep copy of any arbitrary type is not something easily (or even safely) achieved in a reference-based object-oriented language. While simple classes would be trivial to copy, reference loops, classes without parameterless constructors, and immutable types present challenges.

Wednesday 23 March 2011

Visualising the join

Throughout my life I always found it much more simple to remember ideas if I could represent them as some kind of visual entity. For a long time the varied world of SQL joins never quite sat perfectly in my mind until I found the below useful article:

http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

Admittedly it there is still the slightly awkward case of the Cartesian join which doesn't quite lend itself to the Venn diagram construct, however, I am happy to leave that unique character in a corner on it's own for now. Since it took me a while to figure out why I might ever use one... until I found this rather interesting content on Stack Overflow:

"If you have a "grid" that you want to populate completely, like size and color information for a particular article of clothing:
select
size
,
color
from
sizes
CROSS JOIN colors

Maybe you want a table that contains a row for every minute in the day, and you want to use it to verify that a procedure has executed each minute, so you might cross three tables:

select
hour
,
minute
,
second
from
hours
CROSS JOIN minutes CROSS JOIN seconds

Or you have a set of standard report specs that you want to apply to every month in the year:

select
specId
,
month
from
reports
CROSS JOIN months

The problem with maintaining these as views is that in most cases, you don't want a complete product, particularly with respect to clothes. You can add MINUS logic to the query to remove certain combinations that you don't carry, but you might find it easier to populate a table some other way and not use a Cartesian product.

Also, you might end up trying the cross join on tables that have perhaps a few more rows than you thought, or perhaps your WHERE clause was partially or completely missing. In that case, your DBA will notify you promptly of the omission. Usually he or she will not be happy."

To be honest though I am still not carried away by the concept of the Cartesian/Cross join as there often seem much better and more elegant solutions.