Blog

posts from 2007

ExtensionMethod.net

0 Comments
By Fons Sonnemans, 9-12-2007

Together with my friend Loek van den Ouweland I have created our new website: ExtensionMethod.net. 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

0 Comments
By Fons Sonnemans, 4-12-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.

I changed my web.config and added a system.diagnostics section. In this section I added the WebPageTraceListener tracelistner. In my project the LINQ to SQL Classes are placed in the App_Code folder and not in a referenced ClassLibrary. To enable diagnostics tracing for my web project I have to add the compileOption="/d:TRACE" to the c# compiler in the system.compilers section of the web.config. For ClassLibraries you only have to check the 'Define TRACE constant' Build Option in the Project Properties.

When you add tracing to the page you will see all LINQ queries in the Trace. This will give you a better understanding in what is going on behind the LINQ curtains

The TextToTraceWriter class can also be used for Windows Forms or Console Applications in which LINQ is used.

Click here to download a copy of the above sample in order to try it out on your own machine.

Tags: CSharp

NotificationFormTraceListener Assembly

0 Comments
By Fons Sonnemans, 26-11-2007

Download TraceForm.zip (VS2005 Solution, C# 2.0)

Introduction

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

Usage

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>
[STAThread]
staticvoid Main()
{
    // Initialize the TraceListener
    ReflectionIT.Diagnostics.NotificationFormTraceListener
        m_listner=new ReflectionIT.Diagnostics.NotificationFormTraceListener();

    // Add it to the Listeners collection
    System.Diagnostics.Trace.Listeners.Add(m_listner);

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

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

ContextMenu
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.

<configuration>
    <system.diagnostics>
        <traceautoflush="true"indentsize="4">
            <listeners>
                <addname="myListener"
type="ReflectionIT.Diagnostics.NotificationFormTraceListener, ReflectionIT.Diagnostics"
                     initializeData="Buffy.NET Demo Trace"/>
            </listeners>
        </trace>
    </system.diagnostics>
</configuration>
Sample: BuffyDemo.exe.config

Conclusion

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 Fons.Sonnemans@reflectionit.nl

Thanks to:

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

ConvertSelectedTextToAssociatedLabel Macro

0 Comments
By Fons Sonnemans, 9-10-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 Code Snippets

0 Comments
By Fons Sonnemans, 2-10-2007

I use Visual Studio 2005 Code Snippets a lot. Especially during trainings. I have created some snippets myself which I want to share. Download this zipfile and extract it in the "My Documents\Visual Studio 2005\Code Snippets\Visual C#\My Code Snippets" folder.

ASP.NET ViewStateParameter

0 Comments
By Fons Sonnemans, 30-5-2007

I like the ASP.NET 2.0 DataSource controls. They are very flexible and easy to use. It has some great parameters like SessionParameter and ControlParameter. It doesn't have a ViewStateParameter. I have written it myself to fill this gap.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace ClassLibrary1 {

    public class ViewStateParameter : Parameter {

        private String _key;

        public String Key {
            get {
                return _key;
            }
            set {
                _key = value;
            }
        }

        protected override object Evaluate(HttpContext context, Control control) {
            Type t = control.Page.GetType();
            System.Reflection.PropertyInfo pi = t.GetProperty("ViewState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            StateBag pageViewState = pi.GetValue(control.Page, null) as StateBag;
            return pageViewState[Key];
        }
    }
}

My solution uses Reflection to retrieve the ViewState out of the Page. You will need FullTrust to use the code, bummer.

Download the source + sample website here.
Tags: Web, ASP.NET

My First XNA Game

0 Comments
By Fons Sonnemans, 27-5-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.

I have used the XNA - Drawing Text in XNA article (Creator tool + XnaFont class) to fix a drawing text bug from Rob's code.

Download the source here.

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.