posts tagged with csharp

Generic BidirectionalAssociationCollection

By Fons Sonnemans, 25-mrt-2008

Bidirectional associations are easy to design but difficult to program. You must write lot's of synchronization code with the risk of making mistakes. Have a look at the following example in which there is a bidirectional association between Employee (Employer) and Company (Employees).

The synchronization code is implemented in the AddEmployee(), RemoveEmployee() and the (Set)Employer methods.

  class Employee {

    publicstring Name { get; set; }
    publicdecimal Salary { get; set; }

    private Company _employer;

    public Company Employer {
        get {
            return _employer;
        set {
            if (Employer != value) {
                // Remove from 'old' Employerif (Employer != null) {
                    Company old = _employer;
                    this._employer = null;

                // Set the Employer    this._employer = value;
                // Add to 'new' Employerif (Employer != null) {

publicclass Company {

    publicstring Name { get; set; }

    privatereadonly List<Employee> _employees = new List<Employee>();

    publicvoid AddEmployee(Employee emp) {
        if (!_employees.Contains(emp)) {
            emp.Employer = this;  // Synchronize

    publicvoid RemoveEmployee(Employee emp) {
        if (_employees.Contains(emp)) {
            emp.Employer = null; // Synchronize
Tags: CSharp


By Fons Sonnemans, 09-dec-2007

Together with my friend Loek van den Ouweland I have created our new website: This website is setup for finding and sharing .NET 3.5 ExtensionMethods written in C# 3.0 or VB.NET 2008.

I hope you will use it to publish your own extension methods. It is still in BETA but we hope to go live real soon.

Tags: CSharp


Trace LINQ to SQL Queries

By Fons Sonnemans, 04-dec-2007

ASP.NET Tracing is a powerful mechanism. LINQ to SQL doesn't support it out of the box. The DataContext class however has a Log property which can be set to a TextWriter object. This TextWriter object writes all SQL queries which are executed.

I have created a small class which derives from TextWriter to write all SQL queries to the System.Diagnostics.Trace class. I found out that I only had to override the WriteLine(string) and Write(string) methods.

The easiest way to assign a new TextToTraceWriter to the Log property of the DataContext object is by implementing the partial OnCreated() method in a partial class. See the following example in which also the Trace Category is set.

Tags: CSharp


NotificationFormTraceListener Assembly

By Fons Sonnemans, 26-nov-2007

Download (VS2005 Solution, C# 2.0)


During development, you can use the output methods of the Debug class to display messages in the Output window of the Visual Studio 2005 integrated development environment (IDE). For example:

' Visual Basic
Trace.WriteLine("Hello World!")
Debug.WriteLine("Hello World!")

// C#
Trace.WriteLine("Hello World!");
Debug.WriteLine("Hello World!");

Each of these examples will display "Hello World!" in the Output window when the application is run in the debugger.

The .NET TraceListners monitor trace and debug output. You use TraceListners to redirect this output to a specific medium. There are 3 TraceListners available: DefaultTraceListener, EventLogTraceListener and TextWriterTraceListener.

The NotificationFormTraceListener is a special TraceListner which allows you to monitor the output in a special TraceForm which can be activated using a Notification icon.

Sample: TraceForm used to monitor SQL statements


The NotificationFormTraceListener can be used in a Windows application. You have to create one and add it to the (static) Listeners collection of the System.Diagnostics.Trace class.

Don't forget to Dispose the listener when you exit the application. This is necessary because an extra Thread is used for the NotificationFormTraceListener. This Thread doesn't stop automatically.

/// <summary>
/// The main entry point for the application.
/// </summary>
staticvoid Main()
    // Initialize the TraceListener
        m_listner=new ReflectionIT.Diagnostics.NotificationFormTraceListener();

    // Add it to the Listeners collection

    // Run the MainForm
    Application.Run(new TraceFormTest());

    // Dispose all TraceListeners
    foreach (TraceListener l in Trace.Listeners){
Sample: static Main

The ContextMenu of the NotificationIcon makes it possible to Open the TraceForm, set the 'Always on Top' option and Exit.

Add Tracing using the Configuration file

You can add TraceListeners from your code but you can also add them by editing the configuration file that corresponds to the name of your application. Within this file, you can add a listener, set its type and set its parameter, remove a listener, or clear all the listeners previously set by the application.

type="ReflectionIT.Diagnostics.NotificationFormTraceListener, ReflectionIT.Diagnostics"
                     initializeData="Buffy.NET Demo Trace"/>
Sample: BuffyDemo.exe.config


TraceListers can help you to debug your code. The NotificationFormTraceListener helps you to monitor the Trace and Debug output in more convenient way.

Any suggestions and feedback for improving this article is most welcome. Send your suggestions and feedback to

Thanks to:

  • Damien Pitman who reported and solved a threading problem (bug).
Tags: CSharp


ConvertSelectedTextToAssociatedLabel Macro

By Fons Sonnemans, 09-okt-2007

I have created a new Visual Studio 2005 Macro which can be used to convert a literal text to an asp:Label that is associated to the next control. You first have to select the text and then Run the ConvertSelectedTextToAssociatedLabel Macro. In the example below the text Age: is selected.

The result is an asp:Label with the correct Text and AssociatedControlID attributes.

Download Zipfile


My First XNA Game

By Fons Sonnemans, 27-mei-2007

I finally found some time to play with XNA. I learned a lot from Rob Miles at TechEd 2006. He has some great samples on his website. Rob will also be presenting about this subject on the DevDays 2007 in the Netherlands. Fun is guaranteed.

My first game is a remake of a game I build 20 years ago on my Commodore 64. You must move around a bouncing ball using your joystick. The ball may not collide with the flying birds. It took me only a few hours to build and it was great fun.

XNA - Drawing Text in XNA


Updated my DAL article!

By Fons Sonnemans, 17-mei-2006

I have updated my DAL article which I wrote late 2002. This article was one of my first aricles and needed an update. The download project now also contains a .NET 2.0 project. It uses the new TraceSource class for tracing purposes. I hope you like it.

Tags: CSharp, SQL



By Fons Sonnemans, 19-feb-2006

I have just received mail from Pearson VUE informing me that have passed the Beta Exam 70-528 TS: Microsoft .NET Framework 2.0 - Web-Based Client Development (called 71-528 while it's in Beta). I also received a free Voucher for a next exam, thanks guys.

On Friday I will try the Beta Exam 70-551 UPGRADE: MCAD Skills to MCPD Web Developer by Using the Microsoft .NET Framework. One week later I will try the Beta Exam70-552 UPGRADE: MCAD Skills to MCPD Windows Developer by Using the Microsoft .NET Framework . Wish me luck.

Tags: CSharp, Framework


New VS2005 Macros

By Fons Sonnemans, 18-nov-2005

Three years ago I have written some useful Visual Studio 2003 macros: SortCode and CreateProperty. With the introduction of VS2005 it was time to upgrade them.

The new SortCode macro also supports VB.NET 2005. Totally new is the EncapsulateAllNonPrivateFields macro. It creates properties get/set for all non private (public, protected, internal) fields. By using the CodeDom I managed to supports VB.NET and C#.


After running the marco the 3 fields are private and there are 3 extra properties.


Avalon and ClickOnce demo

By Fons Sonnemans, 23-sep-2005

I have build my first Windows Presentation Foundation (WPF) application. It is a remake of my WinForms Minesweeper game. Go to the ClickOnce publisher page and install Avalon Minesweeper.

Make sure you have the Microsoft Pre-Release Software WinFX Runtime Components - September Community Technology Preview (CTP) installed on your computer.

To run this sample you must add '' to your Trusted Sites in Internet Explorer.

UPDATE 1-1-2006: Moved to my own provider and updated to the December CTP.

Tags: WPF, CSharp


All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.