Warning: Use of undefined constant wp_cumulus_widget - assumed 'wp_cumulus_widget' (this will throw an Error in a future version of PHP) in /var/www/kjeldby.dk/blog.kjeldby.dk/wp-content/plugins/wp-cumulus/wp-cumulus.php on line 375
C# and stuff - Patterns and best practices in software development ...
Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /var/www/kjeldby.dk/blog.kjeldby.dk/wp-content/plugins/ultimate_ga_1.6.0/ultimate_ga_1.6.0.php on line 524
Skip to content


First experience with Sitecore 6

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /var/www/kjeldby.dk/blog.kjeldby.dk/wp-content/plugins/ultimate_ga_1.6.0/ultimate_ga_1.6.0.php on line 524

I just started a new project, my first one in Sitecore 6. Sitecore have improved 5.3 in a number of ways.

The installation was not without its problem. The installer complained about a missing ASPNET user, although the user was clearly present. Hence I ignored the warning, and continued. After installing the files, I tried to install the databases via the installer, but for some reason it failed and rolled back the whole installation. So I installed again and reverted to my old procedure of attaching the mdf file manually, and creating a login for the Sitecore user.


But here came the first pleasant surprise: The number of databases have been reduced from 7 to 3, leaving only Core, Master and Web. This clearly simplifies the process of attaching and deploying databases. And in a environment like ours, where we host multiple Sitecore instances on a single Microsoft SQL server, the aesthetic aspect of not having 7 databases per instance popping up in the enterprise manager should not be underestimated.

Inline editing

Sitecore 6 features inline editing, a feature found in other Content Management Systems. The page can be edited directly on the page though editable panels, and not via the simple input forms used in the previous Sitecore versions administration interfaces. I predict that this feature will be very well recieved among our clients, and make it a lot easier for Sitecore to target not-so-technical administrators.

The interface

The overall impression of my administration interface of choice (desktop), is that the interface have been simplified a bit, and hence been made a little more responsive. A new detail that I greatly enjoyed was the icon that appears besides the titles of locked items. This makes it very simple to ensure that your work have been checked in.

Sitecore WebControls

Sitecore 6 ships with at collection of Sitecore .NET WebControls, located in the Sitecore.Web.UI.WebControls namespace. I you prefers sublayouts over renderings, these will come very much in handy. You can simple insert a Sitecore field value in the markup like any other WebControl – without writing a single line of codebehide. These WebControls are configured in the sc tagprefix. This collection includes WebControls for rendering ImageFields, TextFields and so on in the typesafe and intellisense enabled manner common to ASP.NET developers.

All said, Sitecore is not a ‘out of the box’ system, and  nor should it be (in my opinion): Sitecore advantage is that is a flexible platform for development more that a classic CMS. And you still need to manually tweak configuration files and permission to get the instance online. But my first experience in Sitecore 6 was definitely a positive one.

Posted in C#.

Tagged with , , , .

Overflow, checked and unchecked

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /var/www/kjeldby.dk/blog.kjeldby.dk/wp-content/plugins/ultimate_ga_1.6.0/ultimate_ga_1.6.0.php on line 524

The CLR supports both unchecked and checked integer arithmetics. This post explains how this is exposed in the C# language.

As default, C# does integer arithmetics in a unchecked context. In a unchecked context division by zero throws a exception, whereas overflow does not. Overflow happens when the range of a type is exceeded, e.g. by adding to the byte b, so that result exceeds the range of 0-255. When this happens, the CLR truncates the result, and simply count over from zero: 254, 255, 0, 1, 2 … Hence the following statement will not throw an exception:

for (int i = 0; i < 256; i++)

Checked context

But the CLR actually supports integer arithmetics with overflow checking. You can mark a portion of your code as checked, or use the /checked compiler option to make the whole code compile to in a checked context, causing the following code to throw an OverflowException:

    for (int i = 0; i < 256; i++)

But the overflow checking comes with a performance penalty – actual code like the above (when not overflowing) runs about 3.5 times faster in a unchecked context than in a checked. As an alternative, you can check for overflow youself, given that you know the precise circumstances under which a overflow will happen: 

for (int i = 0; i < 255; i++)
    if (b < 255) b++;

This check runs a bit faster than the all encompassing CLR check, and reduces the performance penalty to about 2.5.

Posted in C#.

Tagged with , , , , , , , .

Shared classes and Web Services

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /var/www/kjeldby.dk/blog.kjeldby.dk/wp-content/plugins/ultimate_ga_1.6.0/ultimate_ga_1.6.0.php on line 524

The Windows Communication Foundation Services have simplified the way you use classes in distributed application.

Windows Communication Foundation (WCF) expands the .NET WebServices technologies. One exciting feature is the Data Contracts abilities that enables you to marshall data structures more seamlessly through the service. The “classic” .NET WebService (as well as a WCF service) exposes a description in the WebService Description Language. The WSDL file describes the methods supported by the WebService, and the data structures (classes) used by these methods (parameters and results).

When a application consumes the WebService, Visual Studio creates a WebService reference – including a codefile that wraps the service. Each data structure is created as new a class inside the reference. Say you have a WebService with a single method GetPerson that returns a instance of you MyClasses.Person class. After consuming the WebService, the reference codefile will contain a new class, MyServiceReference.Person. This new class contains only the serializable public fields of the original class exposed the the WSDL file.

For a external consumer everything is fine. The external consumer have no knowledge of the original class (or the fancy methods and he/she might be missing). All the external consumer knows and needs to know is the data fields described in the WSDL file – Visual Studio have wrapped these structures in classes – everything is fine.

But in a distributed application, both the WebService and the consuming application may be part of the same application and codebase. But since the WebService still creates new classes in the WebService reference, you end up with two classes representing the same data: On the WebService side you will have your MyClasses.Person and on the consuming side of the WebService you will have your MyServiceReference.Person. And there is (to my knowledge) no easy way to cast the MyServiceReference.Person instance to a full fetched MyClasses.Person class.

This have changed in WCF services: You can now use the DataContract attribute to expose a class through the services WSDL. Likewise each public field must be marked the the DataMember attribute. Now, when you create a reference to the WCF, Visual Studio will (as default) reuse classes in shared assemblies: The result – you will end up with only one version of the applications classes.

Posted in C#.

Tagged with , , , , , , .

Paths in User Controls

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /var/www/kjeldby.dk/blog.kjeldby.dk/wp-content/plugins/ultimate_ga_1.6.0/ultimate_ga_1.6.0.php on line 524

This post is about the different way to write paths in User Control, and about the special ASP.NET Web Application root operator.

Ever wondered how paths in ASP.NET User Control are resolved when the control is being consumed by web pages in different locations? I did. So I made a simple control named MyControl.ascx in a folder called /UserControls. The UserControl displays an image called MyImage.jpg which is located in a folder called /UserControls/Images.

The challenge is that I want to use my control from different pages, located in different folders in my Web Application. (As an example here, I am using a page located in the root of the application and another page located in a folder called /Pages). So how should I refer to the image from my control?

One way to do this is by using a site-root relative path:

<img src="/UserControls/Images/MyImage.jpg" alt="">

This will work on both pages, but the obvious disadvantage of this approach is that the Web Application then needs to run in the webroot (or some other known path). And if I reuse my control in some other project, I need to keep the locations or change my mark-up. I could probably use the HTML base element to avoid some of these disadvantages though.

The second way to do it is by a “truly” relative path. Here I actually got two option: By using a ordinary (client side) HTML tag, the path will be embedded in the page as it is, and the relative path in my mark-up must be relative to the consuming page:

<img src="UserControls/Images/MyImage.jpg" alt="">

This is generally not a useful behavior, because all consuming pages must be placed in the same location. In this case, the page located in /Pages will not display the image.

As an alternative, I can render the img as a HTML server control. By doing this I tell ASP.NET to process the img tag (including the path) before sending it to the client. This will change a path relative to my control to a path relative to the consuming page. Hence

<img src="Images/MyImage.jpg" runat="server" alt="">

will be rendered as

<img src="UserControl/Images/MyImage.jpg">

in the HTML sent to the client. Notice that ASP.NET removes a empty alt attribute – not good. Otherwise this behavior it more what I am looking for: The relative path will be adapted as the control is consumed on different locations.

The third way is by using the Web Application root operator ~/. This operator will resolve to the Web Applications root, even is the application is running in some subfolder. The rendered HTML will include a relative path, resolved by ASP.NET. This means that the img tag must be rendered as a HTML control:

<img src="~/UserControls/Images/MyImage.jpg" runat="server" alt="">

will render as

<img src="UserControls/Images/MyImage.jpg" runat="server" alt="">

The disadvantage here is that I need to know the location of the resource relative to the Web Applications root, and change my mark-up if this location changes. This can happen here because the resource is tied to my control, and it may want to copy the control and its resources to another project/location.

All of these three (actually four) approaches will work, and to decide which one to use in your project, you may want to ask these questions: Will the control be used in other projects? Will the location of the application change, e.g. from the testing and staging environment to the production server? Will the locations of the resources (images) change. Is the resources logically tied to the control or tied to the current application?

Posted in C#.

Tagged with , , , , , .

Method signatures

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /var/www/kjeldby.dk/blog.kjeldby.dk/wp-content/plugins/ultimate_ga_1.6.0/ultimate_ga_1.6.0.php on line 524

With a few simple tricks, you can avoid those annoying changes in the method signatures in your application.

Method signatures are important point of integration in your application, and hence changes in your method signatures can be both annoying and error prone, and even break applications that consumes your code. So method signatures should be as stable and decoupled from the method implementation as possible. This can be done by e.g. defining interfaces, but I’ve learned that a few simple tricks can often make a huge difference.

A methods signature is its fingerprint: It’s name, parameters and return type. I am working on an application, where I search out segments of costumers in a database based on different segmentation options, e.g. zipcode, gender and last name. The method is called SearchCostumers. The gender is a enumerations called Gender, whereas the the zipcode and last name are strings. I return a generic collection of costumers from the method. So my methods signature is basically:

public List SearchCostumer(string zipcode, Gender gender, string lastName)

Now the name of this method is not likely to change, but the parameters are. Someday I will need to implement new segmention options like age, number of orders and so on. So oe way to avoid signature changes is by implementing a CostumerQuery object. The CustomerQuery is a simple container including the parameters, CostumerQuery.ZipCode, CustomerQuery.Gender and CustomerQuery.LastName. So before I do my search, I’ll simply populate an instance of my query object, and pass it to the search:

public List SearchCostumer(CostumerQuery costumerQuery)

The benefit is, that when I need to add new search parameters, I’ll simply add them to the query object, and specify som default value. This will prevent code from breaking, even code written for the old method.

Another way to decouple the method is by returning my collection of costumers as a IList. The IList is a generic interface available from .NET 2.0, implemented by the List object. It represents a collection of objects, that can be individually accessed by index, and supports the operations that I need to perform on the returned costumers. So instead of binding my application to Microsoft specific implementation of the IList interface, I return my list as a interface instead. Note that the actual collection returned is still a List – it is simply returned as the less specific interface IList.

public IList SearchCostumer(CostumerQuery costumerQuery)

Now, I’ll admit that not everybody will choose to return interfaces instead of the actual type, but the option exists. And to be hornest – In case mentioned above, it was not plausible that the returned type would ever change, so mainly due to lazyness I just returned the darn List.

Posted in C#.

Tagged with , , , .

Dynamic Compilation in a Web Application

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /var/www/kjeldby.dk/blog.kjeldby.dk/wp-content/plugins/ultimate_ga_1.6.0/ultimate_ga_1.6.0.php on line 524

With a simple trick, you can mimic the dynamic complilation of a Web Site in a Web Application.

Visual Studio 2008 comes with the Web Application project type build-in. As you may know, the main difference between a Web Application and a Web Site is that a Web Application must be compiled, whereas a Web Site uses dynamical compilation, where the page is compiled when a user first reach it. The compiled code is stored in the frameworks Temporary ASP.NET Files folder, until the codebehind is changed.

Hence the normal way to use a Web Site is simply to copy the mark-up and the codebehind to some webserver, and let the user do the compilling. But a Web Site can be precompiled: One way to do this is to use Visual Studios Publish function, where the Web Site is compiled to some destination, with the compiled code is stored in the Bin folder. You can choose to compiled the codebehind or the codebehind and the markup by selecting Precompile for Deployment or Precompile for Deployment and Update.

But my problem is the other way around: I often work on Sitecore projects, which are normally Web Applications. I must say, that while I generally prefer this project type, it can a pain when e.g. developing User Controls. This normally means that I have to recompile alot, but I found on that if I change the CodeBehind attibute in the Control directive, I could force the User Control to use dynamic complition.The same goes with pages by the way.

The codebehind is wired to the mark-up by a directive within the mark-up. For a control, it goes something like:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SomeFile.ascx.cs" Inherits="SomeClass" %>

So by changing this to

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SomeFile.ascx.cs" Inherits="SomeClass" %>

I can make SomeFile.ascx.cs dynamically compile upon changes. So how does it behave? I tried using two User Controls on the same page, the one using CodeBehind and the other using CodeFile, and it worked as expected: The CodeFile control dynamically compiled whereas the CodeBehind control used the compiled code from the dll. Now, except from the above, the two controls where actually identical, so I thought: What will happen if I inherits the same codebehind, but with CodeBehind in the first control and CodeFile in the second … they both used the dynamically compiled code, dropping the code in the dll all together.

I regard this as a kind of a hack, and I always change the references back to CodeBehind and compile the project before deploying. But for developing, it saves me a lot of compiling.

Posted in C#.

Tagged with , , , , , , , .

Strings the right way

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /var/www/kjeldby.dk/blog.kjeldby.dk/wp-content/plugins/ultimate_ga_1.6.0/ultimate_ga_1.6.0.php on line 524

In this post, I will show how you can optimize your string operations by using the StingBuilder class and the static class String.

I’ve done it tons of times: Concating string the wrong way. Concatenation is the process of joining strings. And if I have a string s1 = "Hello", and I want to append the string " world" to the string, so i’ll use the + operator overridden from System.Object.

string s1 = "Hello";
s1 = s1 + " world";

or equivalent

string s1 = "Hello";
s1 += " world";

So whats wrong with that. The problem is that a string is immutable: A string cannot change – it’s read-only. So the + operation does not change s1, but creates a new concated string, and then points s1 to the new strings location i memory. But the old string still lingers somewhere in the memory. And you string may be long, and you may append to it many times.

But how do we change a string, if a string is immutable. We don’t. We avoid creating the string until its completed, by keeping the “to-be” string in a StringBuilder until we are ready to copy the result to a real string. The StringBuilder is a mutable dynamic “string”. As a default, the builder holds 16 bytes of string data, but you can specify another length in the constructor – which you may want to do is you have an idea of how long the final string will be.

How many bytes you’ll need per characters depends on the kind of character. The UTF-8 uses 1-6 bytes per characters – the 127 ASCII characters only uses 1 byte per character. But most importantly: If your StringBuilder grows larger, it’ll simply expand as needed.

Actually, this is a pretty simple approach, not radical different that working with real strings:

using System.Text;

StringBuilder s1 = new StringBuilder();
s1.Append(" world");

A different, and less flexible approach is to use the static String.Concat method:

string s1 = String.Concat("Hello", " world");

This approach is useful when combining different parts of data, e.g. user input, but unlike the StringBuilder, you will need to know all the parts of the string when it is declared.

Posted in C#.

Tagged with , , , , , , .

Rotation around an vector in C#/XNA

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /var/www/kjeldby.dk/blog.kjeldby.dk/wp-content/plugins/ultimate_ga_1.6.0/ultimate_ga_1.6.0.php on line 524

This post show how you can rotate one vector around a arbitrary axis, represented by a second vector. This is done by defining a rotation matrix.

I was playing around with the Microsoft XNA framework, and needed a way to rotate a vector around a second vector. Now I know that the framework probably include functions to do that, but I thought that I would look into the thing myself, and implement my own custom rotation. This may be basic math to some, but not to me, and I thought that I would share the way to accomplish this.

First of all, you’ll need is a vector v = (x, y, z) and an axis of rotation a = (X, Y, Z). You will also need an angle of rotation r, measured in radians. By using a negative angle, you can rotate clockwise.

So what we want to do, is to rotate the vector v r radians around the axis a. The result is another (rotated) vector vr.  The way to do this, is by creating a “rotation matrix” A based on the axis a and the angle r, and then multiply matrix with the vector v. The result is a rotated vector.

Sound complicated – let me explain:

The rotation matrix is simply a table of numbers, 3×3:

We need to perform the multiplication Av, that is multiply the rotation matrix with the original vector. The way to do this is by matrix multiplication, that is by multiplying each row of the rotation matrix with the value of the original vector:

So you simply have to calculate the nine values of the rotation matrix, and multiply then on the x, y and z values of the original vector, and voila, you got the 3 coordinates of the rotated vector. Unfortunately, these nine values require some work (remember that X, Y and Z are the coordinates of the axis):

a1 = (t(r) * X * X) + cos(r)
a2 = (t(r) * X * Y) - (sin(r) * Z)
a3 = (t(r) * X * Z) + (sin(r) * Y)
b1 = (t(r) * X * Y) + (sin(r) * Z)
b2 = (t(r) * Y * Y) + cos(r)
b3 = (t(r) * Y * Z) - (sin(r) * X)
c1 = (t(r) * X * Z) - (sin(r) * Y)
c2 = (t(r) * Y * Z) + (sin(r) * X)
c3 = (t(r) * Z * Z) + cos (r)

The function t(r) is defined by t(r) = 1-cos(r).

Phew – at least the computer is going to do the work!

Now all we need to do is to express this math in C#, e.g. like this: rotate.cs [3kb]

Posted in C#.

Tagged with , , , , , , .

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /var/www/kjeldby.dk/blog.kjeldby.dk/wp-content/plugins/ultimate_ga_1.6.0/ultimate_ga_1.6.0.php on line 524

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /var/www/kjeldby.dk/blog.kjeldby.dk/wp-content/plugins/ultimate_ga_1.6.0/ultimate_ga_1.6.0.php on line 524