Event Handling

There are different methods for reacting on events in C#.

The most common ones are demonstrated via s simple use case. In the following samples a timer is created and when the tick event occurs a message box shall be displayed.

The approaches to handle events can be transferred to any other event in dotNET.

The usual way by registering a function:

Timer myTimer = new Timer();
myTimer.Tick += new EventHandler(myTimer_Tick);

and later:

void myTimer_Tick(object sender, EventArgs e)
{
     MessageBox.Show("Tick!");
}

Using an anonymous function:

Timer myTimer = new Timer();
myTimer.Tick += delegate (object sender, EventArgs e)
{
     MessageBox.Show("Tick!");
};

Using an anonymous function without parameters:

Timer myTimer = new Timer();
myTimer.Tick += delegate
{
     MessageBox.Show("Tick!");
};

Using Lambda Expressions:

myTimer.Tick += (sender, e) => {
     MessageBox.Show("Tick!");
};

Note that in all examples the event is registered by ‘+=’, which ensures that existing registrations are not removed.

Customize the Tab Appearance of a WinForms TabControl

This article describes by a short example how to customize the tabs in a WinForms TabControl.
In order to customize the look and feel of a TabControl, the DrawItem event must be handled. Be sure to set the DrawMode of your TabControl to OwnerDrawFixed, otherwise your custom event handler will not be called.

#region tabControl1_DrawItem()
private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
{
	//this eventhandler is called only if:
	//DrawMode = OwnerDrawFixed

	//define how to handle which tabs
	var redTabIdxList = new List<int>() { 0, 1, 2, 3 };
	var orangeTabIdxList = new List<int>() { 4,5,6 };

	//customize the tabs
	if (redTabIdxList.Contains(e.Index))
	{
		var bshBack = new LinearGradientBrush(
			e.Bounds,
			Color.Gold,
			Color.Red,
			LinearGradientMode.BackwardDiagonal);
		e.Graphics.FillRectangle(bshBack, e.Bounds);
	}
	if (orangeTabIdxList.Contains(e.Index))
	{
		var bshBack = new LinearGradientBrush(
			e.Bounds,
			Color.YellowGreen,
			Color.Green,
			LinearGradientMode.BackwardDiagonal);
		e.Graphics.FillRectangle(bshBack, e.Bounds);
	}

	//also draw the text
	var fntTab = e.Font;
	var bshFore = new SolidBrush(Color.Black);
	string tabName = this.tabControl1.TabPages[e.Index].Text;
	var sftTab = new StringFormat();
	var recTab = new Rectangle(e.Bounds.X, e.Bounds.Y + 4, e.Bounds.Width, e.Bounds.Height - 4);
	e.Graphics.DrawString(tabName, fntTab, bshFore, recTab, sftTab);
}
#endregion

.NET WinForms Chart Control

With framework version 4.0 new WinForms controls were introduced. In this article I am going to play around with the ‘Chart’ control. By default it is located in the toolbox in category data.

Create a new WinForms project and simply drag the control onto the surface.

After playing around with the properties (ChartAreas, Legends, PaletteCustomColors and Series) the user interface looks like this:

dotNet WinForms Chart control

dotNet WinForms Chart control

#region UpdateChart()
private void UpdateChart()
{
	try
	{
		//update statistics
		double totalRepeatCount = 0;
		double totalRightCount = 0;
		foreach (DataRow statRow in this.QueryStatistics.Rows)
		{
			//obtain values
			var rightCount = Int32.Parse(statRow["RightCount"].ToString());
			var repeatCount = Int32.Parse(statRow["RepeatCount"].ToString());
			var queryID = Int32.Parse(statRow["QueryID"].ToString());

			//display values
			this.chart1.Series[0].Points.AddXY(queryID, rightCount);
			this.chart1.Series[1].Points.AddXY(queryID, repeatCount-rightCount);

			//update values for summary
			totalRepeatCount += repeatCount;
			totalRightCount += rightCount;
		}

		//summary
		if(totalRepeatCount > 0)
			this.chart1.Titles[0].Text = "Statistics: " + ((totalRightCount / totalRepeatCount) * 100).ToString("0.00") + "%";
	}
	catch (Exception ex)
	{
		MessageBox.Show("Error creating statistics graph: " + ex.Message);
	}
}
#endregion

The control´s properties remind a little bit of the Excel Chart wizard properties. After getting used to handling the control, it is a quite neat way to represent data managed in code.

Further Reading
http://www.codeproject.com/KB/miscctrl/graphcontrol.aspx

Code Generation and T4 Text Templates

Code generation can save a developer a lot of time. Therefore it becomes more and more important to automate recurring tasks.

Microsoft offers a convenient way to generate code (and any other text based artifacts) with its T4 Text Template engine which is fully integrated in up to date versions of Visual Studio.

In order to play around with it, I was writing a little test application with the following sample code.

1. Project Creation

Launch Visual Studio and create a new Project (I used C# WinForms, but it can be any other Project type).

Add a reference to Microsoft.VisualStudio.TextTemplating (I had to install Visual Studio SDK in order to have it present on my machine).

Right click your project node and choose Add/New Item. Then choose PreprocessedTextTemplate, give it a name (I called it: MyPreTextTemplate.tt)

To the PreProcessedTextTemplate file add the following (sample) content:

<#@ template language="C#" #>
<#@ parameter name="TestParam" type="System.String" #>
<html>
<body>
<h1>Some Header</h2>
Parameter: <#= TestParam #>
<table>
    <# for (int i = 1; i <= 10; i++)
       { #>
         <tr><td>Test name <#= i #> </td>
             <td>Test value <#= i * i #> </td> </tr>
    <# } #>
 </table>
</body>
</html>

2. Transforming Text via C#

The following code executes the text transformation of the above template providing a custom parameter called ‘TestParam’:

private string ExecuteProcessedTemplate()
{
	//create template
	var template = new MyPreTextTemplate();

	//create session
	var session = new TextTemplatingSession();
	session["TestParam"] = "paramValue";
	template.Session = session;
	template.Initialize();

	//execute transformation
	string textTemplateOutput = template.TransformText();
	return processedTextTemplateOutput;
}

This is the most simple way of transforming text of a text template including parameters. In order to do more sophisticated text generation, check out the ITextTemplatingEngineHost interface (which you need to implement, but there can be found a full working demo implementation in the MSDN).

private string ExecutePreProcessedTextTemplateUsingACustomEngineHost()
{
	string templateFile = this.Host.ResolvePath("MyPreTextTemplate.tt");
	string templateContent = File.ReadAllText(templateFile);

	CallContext.LogicalSetData("TestParam", "paramValue");

	Engine engine = new Engine();
	string generatedContent = engine.ProcessTemplate(templateContent, this.Host);

	CallContext.FreeNamedDataSlot("MyParameter");

	return generatedContent
}

Further Reading and References

Code Generation and T4 Text Templates
http://msdn.microsoft.com/en-us/library/bb126445.aspx
http://customtemplating.codeplex.com/

Blogs
http://www.olegsych.com/2010/05/t4-parameter-directive/
http://www.olegsych.com/2008/03/code-generation-with-visual-studio-templates/
http://stackoverflow.com/questions/4402011/t4-template-and-run-time-parameters

Visual Studio SDK
http://msdn.microsoft.com/de-de/library/aa985039.aspx
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=21307c23-f0ff-4ef2-a0a4-dca54ddb1e21
Reference: Microsoft.VisualStudio.TextTemplating
(C:\Program Files\Microsoft Visual Studio 2008 SDK\VisualStudioIntegration\Common\Assemblies\Microsoft.VisualStudio.TextTemplating.dll)
Installation FAQ
http://localdev.de/2011/03/vs-2010-sdk-you-must-have-microsoft-visual-studio-2010-installed/

ITextTemplating Interface
http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.texttemplating.vshost.itexttemplating.aspx

Invoking Text Transformation in a VS Extension
http://msdn.microsoft.com/en-us/library/gg586947.aspx

Creating Custom Text Template Hosts
http://msdn.microsoft.com/en-us/library/bb126519(v=vs.80).aspx

Useful .NET Development Tools

In this section there will be a collection of all the ‘must have’ or at least ‘should know’ freeware development tools for dotNET.

dotPeek
dotPeek is a new free .NET decompiler from JetBrains.
http://confluence.jetbrains.net/display/NETPEEK/dotPeek+Early+Access+Program

LinqPad
http://www.linqpad.net/

#develop (SharpDevelop)
… a free IDE for C#, VB.NET and Boo projects on Microsoft’s .NET platform. It is open-source, and you can download both sourcecode and executables
http://sharpdevelop.net/opensource/sd/

PowerCommands for Visual Studio 2010
http://visualstudiogallery.msdn.microsoft.com/e5f41ad9-4edc-4912-bca3-91147db95b99/

Productivity Power Tools
http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef

SoapUI
A tool for simulating and testing WebService requests and responses.
http://sourceforge.net/projects/soapui/files/

This list may grow as time goes by…
If you know further tools worth being mentioned, please leave a comment.