Tuesday, December 29, 2009

Unit testing losse flarden

Wanneer je start met unit testing, zijn er diverse handvaten die je kunt gebruiken om unit testing te gebruiken in je applicaties.
In de test logica mag je geen gebruik maken van
- IFs statements
- Switch of case statements

- Vervolgens moet de test code die je opstelt herhaalbaar uitgevoerd kunnen worden.
- Vermijd Multiple Asserts.
- Integration test en een unit test moet je scheiden
Alle testen in de solution runnen, wanneer een test failed dan is er een probleem. Dus -> betere test
-> integration test
-> er is geen configuratie maar je moet de test vertrouwen
Een verschil tussen een unit test en integration test is dat bij een integration test configuration noodzakelijk is. (gebruik de postfix unittest en integrationtest voor de desbetreffende testen)

Bij 'gewone' code geldt al gebruik GEEN magic numbers, en dit gaat ook op voor test code.

Syntax method names (bij testen
- method name
-state undertest
- expected behavior
-> dat leidt tot 'Add_LessThanZero_ThrowException'.

Helper methods
- '_make' -> create
- '_change' -> update
- '_assert_'

- Alleen public testen. DIt is een contract naar buiten toe. Private/protected is voor intern gebruik en meer verandelijk.
- Incremental work! (stapje voor stapje)
- [setup] attribut, dit is uitgevoerd voor ELKE test
- start een fail test, de test mag niet blijven 'falen' als de productie code is aangepast
- TDD -> vind de bugs sneller
- Simple code kan bugs bevatten
- Test names zijn lang maar dit is readabily (documentatie)
- Duplicated de logic in de test is een probleem, je test de logica niet. Het eindresultaat is niet gecontroleerd de bug wordt gewoon opnieuw gecreereerd in de Assert.AreEqual. Unittest mag geen logica bevatten, zelfs geen string.Format etc.
- Verander nooit een test. Als een test niet goed is (failuing test). Tegenstrijdige requirements vraag na welke requirement geldig is.
- Code coverage

Saturday, November 7, 2009

SQL datetime headaches

I'm always hassleing with datetimes in the SQL Server database to get the correct datetime format that i want. It seems that most of this stuff you can do with specifying a format when converting it:
Usefull page for that

But it did not realy have what i wanted from it.

So the final solution was the following
to get a format like this:
2008-11-13 17:29:00

I needed to do the following

SET generated = cast( getdate() - 8 as smalldatetime)

WCF service error contract name not found

I had a stupid error a few weeks back which involved a WCF service, A end of the day configuration issue and some totaly unrelated error message. In short after googleing i came across the solution and i decided it was one to remember.

solution on the blog of :

The contract name xxxxxxx could not be found in the list of contracts implemented by the service

So what you need to do:
Check names of interfaces
Check namespaces
Check the service attributes (

What is Inversion of control and Dependency injection

recently we started to use Unity for projects. Unity is a way to facilitate dependency injection into you code.

And we where using some of the terms often related to this topic and it was confusing me. I decided to get my facts straight.

Inversion Of Control
Inversion of control article that i have found usefull
This article states that inversion of control is a priciple.
a short statement that signifies the base principle:
"Don't call us, we will call you"

the principle comes down to the following:
A Control gets all his data and events from the outside and itself does not know anything about the context it is being used in. This results in lousely coupled Code/controls which in turn should make them more reusable.
Dependency Injection
Dependency injection is a way to achieve Inversion of control



Inversion of control is a principle with the goal to help you create better, more reusable code

Dependency injection is a specific method of achieving inversion of control.(Unity is a method for dependency injection)

Path resolution through IUrlResolutionService

When developing for a web application you often come accross the scenario where you need to generate a path to a different page and all you have is a app relative path. To resolve this path to a usable client path i have often used different methods to resolve a path.

When working on a project at work i saw a colleage use the following interface

I had never seen that one before and i looked it up
MSDN page

Quote from the page:
Defines a service implemented by objects to resolve relative URLs based on contextual information.

This interface defines the service that is used to resolve URL paths. The IUrlResolutionService interface is used for resolving relative paths and paths that contain the ~ operator. Server controls that reference resources can define the paths to the resources through the ~ operator, which represents the root of the current application. A path containing the ~ operator will not work if passed to the browser. The server control must convert the path to an absolute or relative path before passing it to the browser.

Control implements this interface. A control that derives from Control could override this implementation to provide customized resolution of URLs.

This interface is implemented by the Control, among other classes, which means that Controls like Page, etc all have a method to resolve the path.
you can pass along controls or the page deeper into your code using this interface to resolve app relative paths for you. For example "~/foo/bar.aspx" would get resolved properly by the control to a path the client can use based on the current context of the control/page.

I myself are using this more often these days it seems a nice way to do it.

Steps until failure

This is a piece of code i came accross that i thought that was interesting. I came accross this piece of code and i thought i should remember it for future reference

on Found on the website:

void Process(){

Func<bool>[] steps = {



void ExecuteStepsUntilFirstFailure(IEnumerable<Func<bool>> steps)
steps.All(step => step() == true);

The All operator is documented as stopping as soon as a result can be determined, so the above code is equivalent to the following:

void ExecuteStepsUntilFirstFailure(IEnumerable<Func<bool>> steps)
foreach (var step in steps)
if (step() == false)

Thursday, October 29, 2009


When you create a string with must have multiple line use the option Environment.NewLine and not the escape characters.

Friday, October 23, 2009

Some Anti campaigns

Most programmers use the 'if' and 'loop' statements very much. But when you use this too much, your code can be less readeable. So some blogs have campaigns to minimize the usage of these statements:
- Reduce FOR
- Reduce IF.

Convert VB.NET to C#

Since my new job I have to work a little bit more with VB.NET. So here some tips for converting C# (.NET) and VB.NET and the other way around.

On this site some links can be found, for quick links for converting VB.NET to C# and vice versia.

Further there are some difference between those two languages. Some of these differences can be readen here.

Nested repeater programmatically

On this site I have found some information for creating Nested repeaters programmatically.

Create PDF in ASP.NET

Earlier I have created PDF file from a .NET (web) application with the help of XSL:FO. But my experience was not very good. So I have found a Tutorial for creating PDFs. With this tool you can create PDF files with OO technics, this sounds much better.

Tuesday, October 13, 2009

Tip: Linq to SQL

When you are using Linq to SQL, you have to read (and use) these tips.
I mostly use Linq to Objects, but when I am going to use Linq to Sql is will read these tips again:)

Monday, October 12, 2009

Tool SourceCodeOutliner

I have read something about the SourceCodeOutliner tool. This is a plugin for Visual Studio which organize your class file in a tree. So you can quickly navigate to a field or property.

I am not yet using it. But I think I will give it a try for a couple of weeks.

Sunday, October 11, 2009

.NET Versions

With System.Environment.Version the version of the Common Runtime Language is returned.

In the next switch statement an example of using the Version property:

case "1.0.3705.000" :
Response.Write(" (.NET 1.0)");
case "1.0.3705.209" :
Response.Write(" (.NET 1.0 SP1)");
case "1.0.3705.288" :
Response.Write(" (.NET 1.0 SP2)");
case "1.0.3705.6018" :
Response.Write(" (.NET 1.0 SP3)");
case "1.1.4322.573" :
Response.Write(" (.NET 1.1)");
case "1.1.4322.2032

Overview of .NET versions from the Framework.

Friday, October 9, 2009

Reading attribute with ConfigurationElementCollection

I was programming a part of a configuration file like this

I will use the ConfigurationElementCollection.... so the elements are not very difficult. Create a class for the element with the properties name and url and use this in a class which derived from the ConfigurationElementCollection.

But getting the value of the title attribute on the element is more difficult. I have not yet found a nice way to do does. For now I am use a dirty hack.

Wednesday, October 7, 2009

Google Webelements

With Google Webelements you can create a web element for your web site. On the page you can customize the web element and when you have entered all the settings you simply copy the html in your web site and your web element can be used on your web site.

Design conventions properties and methods

On the blog of Wesley Bakker I have read the following article. Most of this stuff is really basic, but it is always usefull to repeat this. So conform your code to the design conventions for properties and methods, when you do not some other developers which use your code can make wrong assumptions.

Monday, October 5, 2009

XMLSerializer and invalid XML

On the blog of Raj Kaimal I have read the following article about xml serialization.
The conclusion of this article is the existence of the System.Xml.XmlWellFormedWriter class which can be created with the XmlWriter.Create method.

Friday, September 25, 2009

Friday, September 11, 2009

.NET Framework 1.1. on Vista

When you want to install and use the .NET Framework 1.1. on a PC where Vista is installed read the following article.

Reset auto number from a SQL table after delete

When you have an auto number on a table and you deletes the rows in the table you have to reset the autonumber value.


The first lines throws all the rows in tblName away and with the second row the auto number is reset

read here more information

Thursday, September 10, 2009

Fill a dropdown with month names

On Jeff Widmer's Blog there is an >article about filling a dropdown with the month names. It sounds very simple to me, but when you digging into the code you will see that for months there is not a nice solution as for the DayOfWeek:(.

Tuesday, September 1, 2009

VS2010: Multi monitor

On the Blog of Scottgu he write about the support of mulit monitors in VS2010. This sounds very nice, I will try this when I have installed a version of VS2010...

Friday, August 28, 2009

Fun flow diagram

I have found a very funny flow diagram on xkcs. In this diagram non-computer people gets some instructions what do to when they getting an error on the pc BEFORE calling 'computer experts'.

Tuesday, August 25, 2009

Convert usercontrol to control

This article contains some instructions how to convert a UserControl to a Control.

.Root in Source Safe

Frustating everytime I created a project the postfix ".root" is added. Finally I have found a site with the same problem (or an the MSDN website and a SOLUTION.

You are running into a feature referred to as 'Solution Root' added
to VS2003 (and carried forward into VS2005). You can disable this behavior
via the following registry entry:


Builder versus Factory pattern

Copied from some other website, unknown which one...

Difference Between Builder pattern and Factory pattern
The factory pattern defers the choice of what concrete type of object to make until run time. E.g. going to a restaurant to order the special of the day. The waiter is the interface to the factory that takes the abstractor generic message "Get me the special of the day!" and returns the concrete product (i.e. Hawaiian or Spicy pizza)
The builder pattern encapsulates the logic of how to put together a complex object so that the client just requests a configuration and the builder directs the logic of building it. E.g The main contractor (builder) in building a house knows, given a floor plan, how to execute the sequence of operations (i.e. by delegating to subcontractors) needed to build the complex object. If that logic was not encapsulated in a builder, then the buyers would have to organize the subcontracting themselves ("Dear, shouldn't we have asked for the foundation to be laid before the roofers showed up?")
The factory is concerned with what is made, the builder with how it is made. Design patterns points out that Abstract factory is similar to builder in that it too may construct complex objects. The primary difference is that the Builder pattern focuses on constructing a complex object step by step. Abstract factory's emphasis is on families of product objects (either simple or complex). Builder returns the product as the final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.

_Blank variant

On old school tip... when you do not want to use "target=_blank", you can the use following javascript.

<a onclick="window.open(this.href,'_blank');return false;" href="http://some_oother_site.com">Some Other Site</a>

TemplateSourceDirectory invisible

TemplateSourceDirectory can be overridden in the following way:
new public virtual string TemplateSourceDirectory
return Page.TemplateSourceDirectory;

Now the property is invisible for other classes.

Set time-out-time

On the blog of Sujith K Jagini there is a article with some information about
Time out exceptions. How can the 'time-out-time' be set in a WCF service, web service or for (SQL) database.

Monday, August 24, 2009

Thursday, August 20, 2009

Not showing a login page

When you uses .NET web application authentication the user is automatically redirected to the login screen. Here there is an example how you can prevent this, and now you can show the 'Access denied' page.

SEO: Viewstate on top

The rules for better SEO on your website are not static. So it is better to set the Viewstate information at the bottom of your webpage. How you can do this can you read here.

Composited control

Here you can read something about composited controls. (with validators)

In Place Editing

With the control of AJAX.NET it is now (easy) possible to create a website where the user can update the content with a click on the content which must be updated.

On Misfit Geek there is a nice startup tutorial about Inplace editing.

Redirect Session Expiration

On Schnieds Blog I have read an piece of code about Redirecting when the session is expirated.

I have not yet used this, but it seems nice to integrate this in a webapplication which uses form authentication.

more info

Wednesday, August 19, 2009

Serialization in ASP.NET (2)

Starting with serialization....uhhh I always forget that... I have found a link with an easy example which can be used as startup code fragment.
Simple example for serializing and deserializing

Web Site or Web Application

When you start building a web appication with Visual Studio you must decide which type you use:
- a web application project
- a web site project (introduced in VS2005)

Some links with information about this discussion
- ASP.NET Resources - Web Site vs Web Application Project (WAP)
- ASP.NET Web Site Layout
- asp.net Web Site versus Web Application Project
- ASP.NET Website vs Web Application project
- Understanding Page Inheritance in ASP.NET 2.0 - Rick Strahl's Web Log
- Web Site or Web Application - Blog
- Website versus Web Application - Durban, South Africa

But the conclusion of most of these sites is: decide it by yourself!

Convert Website to Webapplication

When you want to convert a Website to a webapplication you can read
here some instructions for doiing this.

Parameters queries in Access

When developing websites for 'fun', mostly I will use an Access Database. In SQL server you have stored procedures and you can give values to them with params. This is also possible in Access, but Stored Procedures are called Queries and a nice example can be found here.

Tabs in Jquery

On Mikesdotnetting I have read the article about JQuery and Tabs.

I have sent a comment with the questing how to navigate directly to a specific tab? Example of navigate directly to a specific tab

Only IE7 in IE8

Force IE7 compatibility mode in IE8 with a single line in the header of each webpage.

<meta http-equiv="X-UA-Compatible" content="IE=7" />

Sunday, August 2, 2009

String.Empty vs empty quotes vs String.Length

The usage of String.Empty is more efficient that the usage of empty quotes.

When using empty quotes an object is created and this produces more assembly code on the execution stack and for string.Empty is NO object created.

The usage of String.Length == 0 is the best. Now there is a numeric compare applied instead of a string compararision, and numeric compare is quicker.

Only what if the string has the value null? So use string.IsNullOrEmpty method

More info: C# Shiznit, Vikram's Blog

Throw; versus Throw e;

In Coding Standards is the differents between throw and throw e explained.

What is the difference?
The difference is that 'throw;' the original stack trace persists and 'throw ex' truncates the stack trace after the method where the 'throw ex;' is called.

When using 'throw;'?
When in the try{...} a method is called then you must use 'throw;' to take care that you have the original stack trace.

// Bad!
catch(Exception ex)
throw ex;

// Good!

Another alternative is to create a new Exception and pass the current exception as inner exception. The stack trace is shown correctly (complete)

// Bad!
catch(Exception ex)
throw ex;

// Good!
Throw new NotImplementedException(“some extra information”, ex);

See for more information Fabrice's weblog, Signs on the Sand, Joteke's Blog

String.Compare or String.ToLower

// Bad!
Example: (ToLower() creates a temp string)
int id = -1;
string name = "lance hunt";
for(int i=0; i < customerList.Count; i++)
if(customerList[i].Name.ToLower() == name)
id = customerList[i].ID;

// Good! (but not for all cultures)
int id = -1;
string name = "lance hunt";
for(int i=0; i < customerList.Count; i++)
// The “ignoreCase = true” argument performs a
// case-insensitive compare without new allocation.
if(String.Compare(customerList[i].Name, name, true)== 0)
id = customerList[i].ID;

// Good! (now also for all cultures)
int id = -1;
string name = "lance hunt";
for (int i = 0; i < customerList.Count; i++)
// The StringComparison.OrdinalIgnoreCase argument performs a
// case-insensitive compare without new allocation and for several cultures.
if (String.Compare(customerList[i].Name, name, StringComparison.OrdinalIgnoreCase) == 0)
id = customerList[i].ID;

Een leuke referentie is de zogenaamde Turkey Test.

Wednesday, July 1, 2009

Refactoring methods

On Refactoring.com there is published a list with some refactoring rules.

I try myself to read this list and also use this list during programming. And when I optimize some code fragment I want to realize that I am using one of these refactoring methods.

Thursday, June 25, 2009

Byte array

Code snippet for converting a byte array to a string (or vice versa) with or without knowing the Encoding.

LINQ: Join

The Join operator is an extension method for the String object. With this you can easily create a comma separated string of a list from strings.

On Erwin's Blog you can read an example.

Tuesday, June 9, 2009

LINQ: Debug Visualizer

On the blog of Scottgu you will find some instructions for installing a Linq to SQL debug visualizer. With this visualizer installer you can see the relating SQL queries for the Linq statements.

Friday, June 5, 2009

SEO Toolkit

There is a new nice plugin for IIS 7, the SEO Toolkit. Scottgu describes on his blog, some nice features of the SEO Toolkit

Update 15 july 2009: Nice results of SEO Toolkit.

Tuesday, May 26, 2009

VS2010: Regular Expression Editor

A couple days ago the beta version of VS2010 is released.

I have not yet installed it on my PC, but I have read about the Regular Expression Editor and I found a Code plex: Editor Samples so maybe you can use this in the near future.

How to start with Unit Testing?

I do not know how to start with Unit Testing. And I still don't...

So there are several blog items about Unit Testing, see
Unit Testing ASP.NET ASP.NET unit testing has never been this easy - Stefan Sedich's Blog. But what is the best way to start.

Can someone give me a good suggestion?

Update 16 july 2009: I have found a nice list with suggestions on Bugfree.

Browser backbutton in ASP.NET

The backbutton from the browser does not work often in the way you want in ASP.NET applications. Below some links with information and tweaks relating the back button:

A back button for asp.net pages - Peter's Gekko - CodeBetter.Com - Stuff you need to Code Better!

ASP.NET Browser Back Button - Overclockers Australia Forums

Avoid Back button after logout. - ASP.net - Dotnet Fusion

back button of browser compitible with asp.net application - bytes

dotnetslackers Back Button in ASP.NET

Monday, May 25, 2009

Resource editors

On the blog entry there are two tools for editing the default resx files for the resources.

The Zeta Resource Editor is a Windows Tool and a Web Tool

Also a useful add-in is the automatically add to resource

Thursday, May 7, 2009

LINQ: Any() or Count()

Update 1 july: Also information about the ToDictionary method

When you have a collection and you want to check if there are items in the collection you can do this

Codefragment 1:

if (lCollection.Count() > 0) {
// do something

Codefragment 2:

if (lCollection.Any()) {
// do something

When the collection is also an ICollection the Count property is returned otherwise the collection is enumerated an counted for each element. The last one is an expensive operation.

The Any() method begins to iterate over the collection and stops when the condition is true. If you use the variant without the condition, the method iterates over the first element and stops. So code fragment 2 is a better solution qua performance.

LINQ and Deferred Execution

I was programming with LINQ and again I was forgotten the Deferred Execution of LINQ. I know the LINQ statement will executed when the program is running, but sometimes it is confusing, so I have read Charlie Calvert's Community Blog : LINQ and Deferred Execution
article and hopefully I will reminder it this time.

Wednesday, May 6, 2009

Difference between Convert.ToBase64String and HttpServerUtility.UrlTokenEncode?

There are two methods for converting a string to a Base64 value:

But what is the exact differnce between them? And when do you decide the use the Convert or the Encode?

When you are going to transmit a value via a URL the method to use is the: HttpServerUtility.UrlTokenEncode() method,

This method creates a url safe value.

The original base64 string encoding follows a standard definition which uses the following characters:



 Value Encoding  Value Encoding  Value Encoding  Value Encoding
0 A 17 R 34 i 51 z
1 B 18 S 35 j 52 0
2 C 19 T 36 k 53 1
3 D 20 U 37 l 54 2
4 E 21 V 38 m 55 3
5 F 22 W 39 n 56 4
6 G 23 X 40 o 57 5
7 H 24 Y 41 p 58 6
8 I 25 Z 42 q 59 7
9 J 26 a 43 r 60 8
10 K 27 b 44 s 61 9
11 L 28 c 45 t 62 +
12 M 29 d 46 u 63 /
13 N 30 e 47 v
14 O 31 f 48 w (pad) =
15 P 32 g 49 x
16 Q 33 h 50 y

Printable Encoding Characters
Table 1

As you can see there are a few characters in this set that are already used in normal urls. To create url save string the +, / and = characters are substituted for other tokens to create a value which is usable in a URL.

The System.Convert.ToBase64 does not display this behavior which might result in a value which isn't usable in a URL, So when you Encode a value to base64 data which you are going to use in a url use HttpSeverUtility.UrlTokenEncode to create safe values

Friday, May 1, 2009

Clipboard Ring

In Visual Studio you can use the Clipboard Ring. When you have copied multiple times something with CTRL+C, this is stored on the Clipboard Ring.

With CTRL+SHIFT+V can you browse through the Clipboard Ring.

Events in (Web)UserControls

On Mats Lycken - Posts about .NET related stuff I have read the following post about Events in (Web)UserControls.
I am a big fan of using (Web)UserControls, but often I forgot to use events... so may be I go use them more now;)

Webpage in the center of the screen

On Mikesdotnetting - Articles on ASP.NET and Web Development I have read some usefull HTML which I often forgot.

Html Snippet for creating a webpage in the center of the screen without tables.

Maybe there a better suggestions?

DateFormatting overview

(again)On Mikesdotnetting - Articles on ASP.NET and Web Development I have read a usefull post about DateFormatting.

Design Pattern: Lazy Loading

The design pattern Lazy Loading do I use without knowing this was called so.

The term Lazy Initialisation was known and that is a part of Lazy Loading. So in a property check if the field is not null and only when the field is null do your job.

Wednesday, April 15, 2009

Resharper 4.5 Released

I use the following tool for finetuning my code: Resharper

There is a new version released: "ReSharper 4.5 is more agile and robust than ever, with improved performance, memory usage and solution-wide analysis, as well as VB9 support"

I will report my experiences soon...

Update 22 april: I am using Resharper 4.5 a few days and it is really faster in VB.NET:) Further it is nice that the intellissence gives some suggestions for usage of fields-, variables names and so on. The rules for these name can defined by your own.

Tuesday, April 14, 2009

Always comment your code...

I was reading the
book about debugging and there was a very important part about commenting... I have summarized the following points:

Always document:
- your assumptions
- your approach
- the reasons why you have choosen for this approach

For each function or method:
- what does the routine?
- which assumptions have you made?
- what does every in- and output param contains?
- what are all the posssible return values or the routine?
- document every exception which is directly thrown in this routine

Always document bugfixes which you have made during development. (when available write down the bug number or reference where more information can be found about the bug/solution)

Always throw commented code away, because it is not clear what the meaning is of this in five years...

Always improve your code when you think "This is a hack"

Xml Comments
copied from winnershtriangle

exception: The exception tag allows a method's exception handling to be documented. The cref attribute allows the namespace of the exception handler to be included. Example: Throws an exception if the customer is not found.

permission: The permission tag can be used to describe any special permissions a specific object needs. The object to which the permission refers is included as the cref attribute. Example: Class needs to write to the file system, ensure user has appropriate access.

Run Kiss Llama on port 8000

Since a couple of years I own a Kiss DP 558 and when I had upgraded my OS to Vista64 the PC-Link doesnot work anymore.

But with LlamaKiss I still can watch movies from my KISS on TV.

But the programm doesn't start because there was already some other programm running on port 8000. The program starts with the following message "Error 10048: Only one usage of each socket address (protocol/network address/port) is normally permitted". You can analyse this with the command "netstat -a -b" from the command prompt.

Saturday, April 4, 2009

Tips for debugging in Visual Studio

Some tips when you are debugging in Visual Studio

I have not yet read them all... so I have no my best tips:)

UML associations

During my course on my job the topic UML associations was a short discussion. What is the difference between Composition, Aggregation and Assocation. In Dutch, read here for more details

Association: The object which have a relation with eachother are equal. For example a person drives a car.

Aggregation: One object is owner of the other object. For example a department and a person which is 'chief of the deparment'

Composition: One object is owner of the other object. But when the owner is deleted to other object is useless. For example a Room belongs to a house. When the house is destroyed the room doesnot exists anymore.

See for more details Wikipedia

ResolveUrl vs. ResolveClientUrl

The article which I have found, when I was "googling" for the difference between ResolveUrl and ResolveClientUrl

The difference between them is clear to me, but I do not yet really understand when to use the ResolveUrl instead of the ResolveCleintUrl...

Wednesday, March 4, 2009

Friday, February 27, 2009

Usage of keyword module?

During looking in the VB.NET code of my new Job I saw sometimes the keyword module. This keyword doesnot exist in C#.NET. The meaning of this keyword is the same as a class only all the members and methods are default shared. So the developer can become lazy;)

So my advise is to minimize the usage of the keyword module and use always the keyword class.

Friday, February 20, 2009

Some introduction links for Unity

From an previous colleague I have received the following links with some information about unity:

Reageer op externe events in plaats van zelf de touwtjes in de hand te houden. or the English variant “Don’t call us we will call you”

Thursday, February 19, 2009

How to nest web user controls dynamically?

When you use nested Web User Controls and you load them with the LoadControl method, add these controls in PlaceHolder.Controls collection (or other controls except the Page class)

Example code


protected void Page_Load(object sender, EventArgs e)
wucSub lMain = (wucSub)Page.LoadControl("Windows/wucSub.ascx");

<strong>Main</strong><br /><asp:ListBox runat="server" ID="lstItems" />


no code behind

<strong>Main</strong><br /><asp:ListBox runat="server" ID="lstItems" />

protected void Page_Load(object sender, EventArgs e)
wucMain1 lMain = (wucMain1)Page.LoadControl("Windows/wucMain.ascx");

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<form id="form1" runat="server">

When you build and run these pages, you will get the following error message
"Control 'ctl02_lstItems' of type 'ListBox' must be placed inside a form tag with runat=server."

How can you solve this?

Do not use Page.Controls.Add or Controls.Addd but specify to which Controls collection these these controls must be added and use there a PlaceHolder (panel or other control). So the correct implemention will be

protected void Page_Load(object sender, EventArgs e)
wucSub lMain = (wucSub)Page.LoadControl("Windows/wucSub.ascx");

<strong>Main</strong><br /><asp:ListBox runat="server" ID="lstItems" /><asp:PlaceHolder runat="server" ID="plhSub" />


no code behind

<strong>Main</strong><br /><asp:ListBox runat="server" ID="lstItems" />

protected void Page_Load(object sender, EventArgs e)
wucMain1 lMain = (wucMain1)Page.LoadControl("Windows/wucMain.ascx");

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<form id="form1" runat="server">
<asp:PlaceHolder runat="server" ID="plhMain" />

Saturday, January 3, 2009