Jesper Niedermann's .NET Blog
about .NET and related technologies RSS 2.0
# Tuesday, 31 August 2010

The new Guidance Automation Framework GAX 2010 and GAT 2010 which is installed through the Extension Manager in Visual Studio 2010, provides a nicer usability experience compared to the Visual Studio 2008 predecessor. It is installed using the new vsix installer. A vsix install is much nicer than the old msi install since it integrates into Visual Studio. You can uninstall using the Extension Manager and if a new version comes out it should appear on the Updates tab of the extension manager.

Another nice thing is that a generated factory template solution now only consists of one project which itself results in a vsix file. So the installer of your own generated factories will also be vsix files. Nice…

But nicest of all is the fact that it is automatically integrated with the Visual Studio 2010 Experimental Instance (formerly known as Experimental Hive). Before you had to manually edit your recipes to get them to register in the Experimental Hive. But know you just press Ctrl+F5 and the Experimental Instance is automatically launched with your factory installed. It is now almost easy to debug your recipes. :)

But apparently there are few weird bugs in GAX/GAT 2010. One I run into all the time is this error:

Unable to read the project file 'Something.csproj'.

C:\Something\Something\Something.csproj(354,3): The imported project "C:\Microsoft.Practices.RecipeFramework.Build.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.

Which happens when I try to open a Guidance Automation solution.

For some reason the declaration of the variable RecipeFramework in the project file is not provided. This I deal with by editing the Project file by hand and adding a declaration to the end of the first PropertyGroup like this:

 

  <RecipeFrameworkPath>$(DevEnvDir)Extensions\Microsoft patterns and practices\GAX 2010\2.0.20406.0</RecipeFrameworkPath>

After applying this fix I can open the solution.

I have read somewhere that it is important to adhere to the following install order:

    1. Visual Studio 2010 Ultimate or Professional (obviously)
    2. The Visual Studio 2010 SDK
    3. GAX 2010
    4. GAT 2010

And this might be what I have screwed up on the particular machine where I get the error.

Anyway the above mentioned fix works. And overall I am very satisfied with the new improvements in GAX/GAT.

Tuesday, 31 August 2010 17:31:11 (GMT Daylight Time, UTC+01:00)  #    Comments [1] -
.NET | GAX | Tips & Tricks | Visual Studio
# Wednesday, 12 May 2010

Windows developers who are used to click events in WinForms, WPF or Silverlight might miss click and double click events, but because of the game loop where everything is drawn and updated every few milliseconds an event based approach is probably not a good idea in most cases. Not so much because of the performance of an event based approach, but more because the complexity is overwhelming. If several users clicks and double clicks several keys on the keyboard simultaneously, how would you decide which of these are clicked and in which order, and further more it is not obvious to subscribers of the events that they are in the game loop, so they might do code which performs inadequately.

I have made a few generic classes that expands the MouseState, GamePadState and KeyboardState in order to make click “events” available. But of course I utilize the standard polling mechanism in XNA which is to call GetState() on each device.

The approach is that I call my own version of GetState() in the main game loop. My GetState() method first enqueues the state in a Queue, and then dequeues all states older than 500 ms, before the state is returned. In this way a historical map of user interactions is maintained at all times.

Now I can simply check if a key or button was clicked by checking if the key was pressed and then released “historically”. Similarly I can check for double click by checking if the key or button was pressed, then released, then pressed again and then released again.

Now you probably realize why I go back 500 ms. It is because this is the standard time in which a double click should be executed.

I have used this approach in the game Protect the Carrot at http://ptc.codeplex.com and it works like a charm (The url for the game does not work today, since the game will only be published in a few weeks).

Here is the implementation of the MouseExtended class which uses this approach:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;

namespace PTC.Input
{
public class MouseExtended : InputDeviceExtended<MouseState>
{
private static MouseExtended m_Current;
public static MouseExtended Current
{
get
{
if (m_Current == null)
{
m_Current = new MouseExtended();
}
return m_Current;
}
}

public MouseState GetState(GameTime currentTime)
{
DequeueOldStates(currentTime);
MouseState state = Mouse.GetState();
EnqueueNewState(currentTime, state);
return state;
}

private bool ClickCount(MouseButton checkButton, int requiredCount)
{
ButtonState found = ButtonState.Released;
int count = 0;
foreach (InputStateExtended<MouseState> stateExt in RecordedStates)
{
if (found == ButtonState.Pressed &&
ButtonStateToCheck(stateExt.State, checkButton) == ButtonState.Released)
{
count++;
if (count >= requiredCount)
return true;
}
found = ButtonStateToCheck(stateExt.State, checkButton);
}
return false;
}

private ButtonState ButtonStateToCheck(MouseState state, MouseButton checkButton)
{
switch (checkButton)
{
case MouseButton.Left:
return state.LeftButton;
case MouseButton.Middle:
return state.MiddleButton;
case MouseButton.Right:
return state.RightButton;
case MouseButton.XButton1:
return state.XButton1;
case MouseButton.XButton2:
return state.XButton2;
default:
return state.LeftButton;
}
}

public bool WasSingleClick(MouseButton checkButton)
{
return(ClickCount(checkButton, 1));
}

public bool WasDoubleClick(MouseButton checkButton)
{
return (ClickCount(checkButton, 2));
}

}
}

And here is the generic InputDeviceExtended class which MouseExtended inherits:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace PTC.Input
{
public class InputDeviceExtended<S> where S : struct
{
private Queue<InputStateExtended<S>> m_RecordedStates = new Queue<InputStateExtended<S>>();

public Queue<InputStateExtended<S>> RecordedStates
{
get { return m_RecordedStates; }
}

private Stack<InputStateExtended<S>> m_StatesForReuse = new Stack<InputStateExtended<S>>();

protected void EnqueueNewState(GameTime time, S state)
{
if (!state.Equals(m_CurrentState))
{
m_CurrentState = state;
m_RecordedStates.Enqueue(CreateState(time, state));
}
}

private S m_CurrentState;
public S CurrentState
{
get { return m_CurrentState; }
}

protected void DequeueOldStates(GameTime currentTime)
{
InputStateExtended<S> state = null;
if (m_RecordedStates.Count > 0)
{
state = m_RecordedStates.Peek();
}
if (state != null && state.StateTime < currentTime.TotalRealTime.Subtract(new TimeSpan(0, 0, 0, 0, InputDeviceConstants.ClickCountTimeMS)))
{
m_StatesForReuse.Push(m_RecordedStates.Dequeue());
DequeueOldStates(currentTime);
}
}

private InputStateExtended<S> CreateState(GameTime time, S state)
{
if (m_StatesForReuse.Count > 0)
{
//Reuses the object to fight of the GC
InputStateExtended<S> stateExt = m_StatesForReuse.Pop();
stateExt.StateTime = time.TotalRealTime;
stateExt.State = state;
return stateExt;
}
else
{
return new InputStateExtended<S>(time, state);
}
}
}
}

Notice that the Recorded States are reused. When dequeued from the queue the are added to a reuse stack. This is a standard trick to fight of the Garbage Collector, by always keeping a reference to objects on the heap they never become garbage + they are reused so the memory use will not explode.

I have also implemented the necessary extended classes for the Keyboard and the gamepad. I have included them in the attachment to this post. I have not tested the GamepadExtended class since I do not own a Gamepad, but it is implemented exactly as the keyboard and mouse classes and ought to work.

To wire up the new classes you just add the relevant Getstate() calls to the Update game loop like so:

protected override void Update(GameTime gameTime)
{
KeyboardExtended.Current.GetState(gameTime);
MouseExtended.Current.GetState(gameTime);
base.Update(gameTime);
}

And then you can check for click and double click “events”. For instance you check for double click of the left mouse button like this:

if(MouseExtended.Current.WasDoubleClick(MouseButton.Left)))
{
//Do double click reaction
}

Hope you like the stuff.And look out for the amazing “Protect The Carrot” game within the next month or so, at http://ptc.codeplex.com

In InputDeviceExtended.zip I have included the code for all the InputDevice classes.

Wednesday, 12 May 2010 21:38:51 (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
.NET | Tips & Tricks | XNA
# Friday, 13 November 2009

In the Day View project I needed to open a Windows 7 Sticky Note programmatically and write to it. Unfortunately I found out that there is not an API for the Sticky Notes application. At least not a managed one.

So I had to fake it and make my own API. I have made a small class that basicly uses Process.Start to open the program, and SendKeys to write to the Note.

Here it is:

using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace DayView
{
public class StickyNote
{
private const string m_ProcessName = "StikyNot";
private readonly string m_ProcessFileName = Path.Combine(Environment.SystemDirectory, "StikyNot.exe");
private event EventHandler m_Activated = delegate { };
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

public void Activate()
{
bool makeNewNote = true;
Process p = FindProcess();
if (p == null)
{
p = StartProcess();
if (!NoteContainsText(p.MainWindowHandle))
{
makeNewNote = false;
}
}
var state = new StickyNoteState();
state.MakeNewNote = makeNewNote;
state.StickyNoteProcess = p;
ThreadPool.QueueUserWorkItem(Activate, state);
}

private void Activate(object state)
{
var stickyNoteState = state as StickyNoteState;
if (stickyNoteState.MakeNewNote)
{
NewNote(stickyNoteState.StickyNoteProcess);
}
OnActivated();
}

private Process StartProcess()
{
var startInfo = new ProcessStartInfo(m_ProcessFileName);
Process p = Process.Start(startInfo);
Thread.Sleep(200); //This is an annoying hack. I haven't been able to find another way to be sure the process is started.
return p;
}

private void NewNote(Process p)
{
SetForegroundWindow(p.MainWindowHandle);
Signal("^n");
}

/// <summary>
/// Weird hack to find out if note contains text.
/// </summary>
/// <returns></returns>
private bool NoteContainsText(IntPtr handle)
{
string textOfClipboard = Clipboard.GetText();
Signal("^a");
Signal("^c");
Signal("{RIGHT}");
string noteText = Clipboard.GetText().Trim();
if (textOfClipboard == null)
{
Clipboard.SetText(textOfClipboard);
}
return !string.IsNullOrEmpty(noteText);
}

private Process FindProcess()
{
Process[] processes = Process.GetProcessesByName(m_ProcessName);
if(processes != null && processes.Length > 0)
{
return processes[0];
}
return null;
}

internal void OnActivated()
{
m_Activated(this, new EventArgs());
}

public event EventHandler Activated
{
add { m_Activated += value; }
remove { m_Activated -= value; }
}

public void Signal(string message)
{
SendKeys.SendWait(message);
SendKeys.Flush();
}
}

public class StickyNoteState
{
public bool MakeNewNote { get; set; }
public Process StickyNoteProcess { get; set; }

}
}

It works OK. The only really buggy thing in the code is in line 47, where I have to use a Thread.Sleep in order to make sure the note is loaded before I write to it. Unfortunately this is necessary because the Process class does not provide an event to signal when it has finished loading. I arbitrarily chose 200 milliseconds for the Sleep. Larger values might be necessary on slower computers.

In order to use the class you have to configure SendKeys in your app.config like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SendKeys" value="SendInput"/>
</appSettings>
</configuration>
Friday, 13 November 2009 23:28:10 (GMT Standard Time, UTC+00:00)  #    Comments [4] -
.NET | Tips & Tricks | Windows 7

I am currently developing the game Klimakonflikt with 5 other guys. It is a Retro arcade game, Pac-man style, with nice 2D Graphics and music. Here is a screenshot from the game:

klimakonflikt_screenshot

The current release, documentation and source code can be downloaded from here http://klimakonflikt.codeplex.com 

The game is inherently for 2 players but we are working on the single player edition. The AI in the current release is pretty daft, but in the next release it will be much improved. Also we are working on a WPF leveleditor, powerups and other fun stuff.

One of my co-developers Jakob has released a blog about the game and XNA development in general at http://xnafan.net

Friday, 13 November 2009 23:11:29 (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | Games & Puzzles | WPF | XNA
# Thursday, 18 June 2009

Here is my take on the Best practice Dispose pattern for most situations. It is heavily influenced by Juval Löwy from IDesigns book "Programming .NET Components", and some other sources which I no longer remember, since I made it a few years ago and have stuck to it ever since. Here it is:

public class Class1 : IDisposable
{
private bool m_IsDisposed;

~Class1()
{
Dispose(false);
}


[MethodImpl(MethodImplOptions.Synchronized)]
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

private void Dispose(bool isDisposing)
{
if (m_IsDisposed)
return;

if (isDisposing)
{
FreeManagedRessources();
}
FreeUnmanagedRessources();
m_IsDisposed = true;
}

protected virtual void FreeManagedRessources()
{
//Free managed ressources here. Typically by calling Dispose on them
}

protected virtual void FreeUnmanagedRessources()
{
//Free unmanaged ressources here.
}
}

Another thing is that you can inherit the class and override the FreeManagedRessources and FreeUnmanagedRessources as needed.

Thursday, 18 June 2009 21:38:51 (GMT Daylight Time, UTC+01:00)  #    Comments [6] -
.NET
# Sunday, 14 June 2009

I was using my codeplex project ManagedMenuExtensions recently when I realized that it threw an Exception, when clicking on a menu attached to a C# project under a solution folder. The reason was that the object which normally contained an EnvDTE.Project when a project was clicked contained null, when this project was contained in a solution folder.

I normally use this code to get at the selected project (m_VSStudio is the DTE object of the current solution):

private UIHierarchyItem SelectedItem
{
get
{
UIHierarchy uiHierarchy = m_VSStudio.ToolWindows.SolutionExplorer;
if(uiHierarchy == null)
return null;

object[] items = uiHierarchy.SelectedItems as object[];
if(items == null || items.Length == 0)
return null;

return items[0] as UIHierarchyItem;
}
}

The SelectedItem.Object of type object now contains a EnvDTE.Solution object if the solution is selected in the solution explorer, and guess what :O) it contains an EnvDTE.Project if a project is selected. It is this SelectedItem.Object that contains null, if the project is contained in a solution folder.

I googled this problem and found others who had the same problem, but none with a solution, so I had to come up with my own. I don't know if this behaviour is by design from Microsoft, or if it is a bug.

My Solution

Normally I would test if a project is selected with this code:

var project = SelectedItem.Object as Project;
if (project != null)
{
//Do something with the project
}

Now I use this code instead:

Project project = GetProject(SelectedItem.Object);
if (project != null)
{
//Do something with the project
}

Where I implemented GetProject(...) as:

private Project GetProject(object selectedItemObject)
{
var project = selectedItemObject as Project;
if (project != null)
return project;

var item = selectedItemObject as ProjectItem;
if (item == null)
return null;

return item.SubProject;
}

Not exactly beautiful, but that is to be expected when playing with Visual Studios AddIn model, and the kind of thing I try to hide in ManagedMenuExtensions. I haven't had a chance to look at Visual Studio 2010 yet, one could hope that they have done a better job of hiding the ugly underlying COM stuff.

 

Anyway, I hope this helps the next person who tries to search for a workaround for this rather weird behaviour.

Sunday, 14 June 2009 18:33:04 (GMT Daylight Time, UTC+01:00)  #    Comments [3] -
.NET | Tips & Tricks | Visual Studio
# Friday, 01 May 2009

If you want to Execute something on each element of the result of a Linq expression. You can either loop over the result using foreach(...) or turn the result into a List using .ToList(), and then use .Foreach(...) on the resulting list. Like this:

(from excep in ErrorList
where excep is ArgumentException select excep)
.ToList().ForEach(e => Console.WriteLine(e.Message));

This is ugly, and I prefer to make my own Extension method for IEnumerable<T> called Execute(...):

public static void Execute<T>(this IEnumerable<T> list, Action<T> action)
{
foreach(T element in list)
{
action(element);
}
}

This means you can do this instead:

(from excep in ErrorList
where excep is ArgumentException select excep)
.Execute(e => Console.WriteLine(e.Message));

Back in the days when I used Linq in a program for the first time, I wondered why there was no way to execute an action on each element of a list, so I implemented the Execute method.

It was only later that I discovered that the default way was .ToList().Foreach(...)

I must say I still prefer my original approach.

BTW: In a small none scientific test I have tested the two approaches.

With Linq To Objects iterating over 100000 integers and printing them to the Console takes about 21 seconds with the Foreach method and about 20 seconds with the Execute method, so it is even faster at least for this particular example. Though nothing to get excited about. :O)

The test was done in a Vista VPC with VS2008,

Small performance test: LinqPerfTest.zip

Friday, 01 May 2009 21:12:40 (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
.NET | Linq | Tips & Tricks
# Tuesday, 07 April 2009

I recently was in a company where I created the coding standard. Mostly by referring to the great standard from IDesign but with a twist of company specific things. When C#3.0 came out I couldn't find any coding standard material on the new stuff out there on the web. So I was forced to think...

My thoughts on the var keyword, is that it should be used extensively. But I place a restriction on it. You should only use it if the type of the object is explicitly readable from the line.

So this is allowed:

var person = new Person();

And this is not allowed:

var person = PersonFactory.Create();

And similar for a Linq expression.

Allowed (actually it is required because of the anonymous type):

var person = 
from c in Customers
select new { c.FirstName, c.LastName };

Not allowed:

var person = 
from c in Customers
select Person.Create(c.FirstName, c.LastName);

Otherwise I place no restriction on the use. This way you get maximum readability without comprising that you should always know the type of what you are dealing with. Even when not using intellisense.

At the meeting I mentioned in "The Missing Linq" I asked Anders Hejlsberg why var is not possible on member variables in C#. He told me that they are looking into parallelizing the compiler. And it would be impossible to infer the type across assemblies compiled by different threads of the compiler.

Tuesday, 07 April 2009 09:01:55 (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
.NET
# Wednesday, 18 March 2009

What is Linq ? You probably think you know the answer, Linq is after all already quite dated. Well in my experience chances are you only know part of the story. Most of the people I have met have a slight misconception of Linq which limits their use of this great technology.

Let me explain. Linq of course means "Language Integrated Query", we all knew that. This basically refers to the syntactic sugar that Microsoft has poured over the C#3.0 language. I.e the from, where and select keywords and a few more.

In practice Linq is more. It is also a set of Extension methods in a given Linq provider, and a new way of coding, and furthermore many of the C#3.0 features are there to make Linq more useful. Like the var keyword, and lambda expressions.

What I think is limiting the use of Linq is that most people think Linq is a database technology. It is true that Linq can be used for querying databases if you use a Linq provider for a database technology like The LinqToEntities, LinqToSQL or Linq to some other ORM. This is basically Microsoft's "fault", Linq can be used for querying databases, and that is how Linq was promoted, I guess because of the ORM hype.

I was so fortunate to talk to one of the creators of Linq, Anders Hejlsberg in October 2008 when he was giving a lecture in Hilleroed, Denmark. I presented my view to him, that I thought it was a pity that Linq was viewed only as a database technology. He agreed with me, and said that this was because database access was the driving force behind Linq to begin with, and for marketing reasons.

But what is Linq really then ? If you look at an old fashioned SQL query

SELECT SomeColumn FROM SomeTable

You query relational data (SomeTable), and in return you get relational data (A set containing SomeColumn). With Linq you have much more power. You can query anything that implements the IEnumerable<XXX> interface, and you can return one or more .NET objects of any type.

So therefore I think it is much more productive to look at Linq as a means to transform data. In some ways Linq can replace XSLT, I am no XSLT expert but I would guess that you can always write a Linq expression to replace any XSLT transformation, as long as you work in a .NET assembly. Of course an XML document can refer directly to an XSLT transformation, which is not possible with Linq.

Transformations of data are so common in a computer program that we don't even notice them. In fact we use them all the time. And consequently we can use Linq expressions all the time, and should use them most of the time. I would argue that a Linq expression is more readable than "normal" code most of the time. If it is less readable or performs badly you might choose another option.

Here are a few examples of transformations that we don't think of as transformations:

  • Outputting errors to a logfile, or the console, or an eventlog. In this case exceptions are transformed to lines of text.
  • Building a dynamic menu from data in an XML file. In this case the data in the XML file is transformed into menuitems.
  • Building a dynamic Xaml page from some input. The input data is transformed into Xaml.

I will know give you some concrete codefragments to show these types of queries.

Outputting errors

Let's say that you have collected error information in the form of a List of Exceptions. Assume in the following code that ErrorList is a List<Exception>:

(from excep in ErrorList 
where excep is ArgumentException
select excep).ToList()
.ForEach(e => Console.WriteLine(e.Message));

Now you have transformed your Exception data to Visual Data in the Console. In this example only ArgumentException's are printed. Of course you could easily print something better than just the message, e.g ToString() or perhaps a PrettyPrint() extension method for Exception that digs all InnerExceptions out, and prints everything in a nice readable format.

Building a dynamic menu

This example is from my WiiCursor project:

m_ConfigurationMenu = new MenuItem("Configure");
var confMenus =
from configuration in configurations
select Util.GetMenuItem(
configuration.Name,
(sender, args) => Configure((MenuItem)sender, configuration),
configuration.Default);
m_ConfigurationMenu.MenuItems.AddRange(confMenus.ToArray());

In the code shown 'configurations' is a List<WCConfiguration> where WCConfiguration is a class that corresponds to an XML file, and gets initialized by the file. The GetMenuItem(...) method basically "news up" the MenuItem and connects a click eventhandler to it by passing the lambda expression '(sender, args) => Configure((MenuItem)sender, configuration)' to the MenuItems constructor.

So when the user clicks the MenuItem what happens is that the Configure(...) method is called with the MenuItem and most importantly the correct WCConfiguration as parameters.

This might not be the most readable code in the universe. In fact I violate one of my own best practices. Only use the var keyword if the resulting type, here MenuItem, is readable in another way. In the original version I called new MenuItem(...) directly, so that is my (admittedly bad) excuse.

But still the code beautifully illustrates how a Linq expression can Transform the context of XML files to MenuItems that act upon the information in the corresponding file.

Building a dynamic Xaml page

In another project of mine, not yet published, I experiment with logging mouse moves to help me register the time I have used on different projects at the end of the week. A common task for employees around the world. I log the mousemoves in an XML file using a custom format.

<?xml version="1.0" encoding="utf-8"?>
<Activities>
<Activity Name="Activity" Start="10-03-2009 08:01:42" End="10-03-2009 10:01:54" />
<Activity Name="Activity" Start="10-03-2009 12:00:00" End="10-03-2009 16:01:05" />
</Activities>

To make it more appealing visually I transform it to a Xaml file that I load dynamically in a WPF project. The smart thing is that I can do it in a VB.NET assembly combining XML Literals and LinqToXML. Below is the first few lines of the Transformer class that contains the methods to create the Xaml file. Notice how the Xaml can be inlined easily in VB.NET since it is also XML.

Imports System.Linq
Imports System.Linq.Enumerable
Imports System.Xml.Linq
Imports <xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
Imports <xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

Public Class Transformer

    Private Const Column0Width As Integer = 50
    Private Const Column1Width As Integer = 50
    Private Const Column2Width As Integer = 70
    Private Const Column3Width As Integer = 170
    Private Const Column4Width As Integer = 40

    'Converts from a basic XDocument with Activities to a rich one using Xaml.
    'This is done with VB.NET because of the rich LinqToXML experience in VB.
    Public Shared Function ConvertToXaml(ByVal convertFrom As XDocument) As XDocument

        Dim months As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}


        Dim doc As XDocument = New XDocument( _
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Time Statistics" Height="302" Width="514">
    <Grid>
        <TabControl Name="ActivitiesTabControl">
            <%= From month In months _
                Select _
                <TabItem Header=<%= NameOfMonth(month) %> Height="20" Width="80" Selector.IsSelected=<%= SelectMonth(month) %>>
                    <ScrollViewer VerticalScrollBarVisibility="Auto">
                        <Grid>
                            <%= ColumnDefinitions() %>
                            <%= RowDefinitions(NumberOfRows(month, convertFrom)) %>
                            <%= RowHeaders() %>
                            <%= RowsOfMonth(month, convertFrom) %>
                        </Grid>
                    </ScrollViewer>
                </TabItem> %>
        </TabControl>
    </Grid>
</Window> _
                )
        Return doc
    End Function
    ...

XML Literals is the only reason why I sometimes use VB.NET, otherwise I am a C# guy. I would have loved C# to have this nice feature too, my guess is that it was impossible because angel brackets '<' are reserved for generics in C#.

Apart from giving an appealing visual look the code also makes calculations like summing up the time used in an entire day. Linq is ideal for this too.

Summing up

I hope I have convinced you that Linq is more than just a database technology. You knew it already of course, but did you live it and breathe it :O) In my opinion Linq is such an integral part of C#3.0 that there is no avoiding using it all the time.

Wednesday, 18 March 2009 21:49:20 (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | Linq
# Wednesday, 11 March 2009

Currently I am looking into taking over a huge enterprise legacy system written mostly in C#, but also some C++. The numbers are staggering several million lines of code, 1200 GUI screen, mostly WinForms, about 750 C# projects, 150 solution files, just to mention a few. In all about 4 times larger than the largest enterprise system I have previously been working on.

Just building and deploying the system is a pretty big task since due to events beyond my control I basicly only have the sourcecode and nothing else. Not quite true because there are some documentation, but buried in the thousands of files.

When I managed to modify a build file and build the entire monster with it, it took 2½ hours to complete.

I won't even try to include all projects in a single Visual Studio file. I wonder if it would load ? This gives me a problem though. How about debugging ? I cannot press F5 for any of the visual studio projects because the build process using the build file set up a ton of config files with IP adresses, connection strings and the like. So it doesn't make sense to run the thing from Visual Studio.

But if I start up the exe assembly how do I attach a debugger ? Well, I decided to use a simple trick. I added a line of code in the top of the main() method:

static void Main(string[] args) 
{
Debugger.Break();
...

Debugger.Break() is basicly a programmatic breakpoint, but it is more than that. If no debugger is attached it asks the user for a debugger. Smart! And for the process to debug I can just choose the Visual Studio process with the project containing the exe assembly. Henceforth the control is mine.

I could even consider writing this method and using it instead:

[Conditional("DEBUG")]
private static void DebuggerBreak()
{
if(!Debugger.IsAttached)
Debugger.Break();
}

This gives me the advantage that the IL code is only build in DEBUG mode and that the Debugger is only attached if one is not attached already.

Wednesday, 11 March 2009 06:23:39 (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | Tips & Tricks
# Sunday, 08 March 2009

When I post code blocks in this blog. It would be nice if they look like, well, code. So I looked at what Scott Hanselman had done, he is after all one of the creators of the blogengine I use: "Dasblog"

In this post Scott explains how to do it. He explains how to add Javascript from a project called SyntaxHighlighter and use a plugin called precode for Windows Live Writer. Well I use WLW too, so this is perfect for me.

But I had a few problems. I took me some time to figure out that the newest edition of SyntaxHighlighter didn't work with precode.

So I have now settled on SyntaxHighlighter version 1.5.1 and precode version 3.0.0

SyntaxHighlighter is nice because it has support for multiple languages, and it is easy to add support for more. The caveat is that it hasn't got any knowledge of the language. Which means that it just parses the text and looks for keywords. So stuff that looks like keywords will be color highlighted too. I consider this a minor problem.

I chose to add the Javascript in the scripts folder of my blog, and the SyntaxHighlighter.css file in template folder.

Know I could easily add the required code in the bottom of my homeTemplate.blogTemplate file, immediately before the closing <body> tag, like so:

<script class="javascript" src="scripts/shCore.js"></script>
<script class="javascript" src="scripts/shBrushCpp.js"></script>
<script class="javascript" src="scripts/shBrushCSharp.js"></script>
<script class="javascript" src="scripts/shBrushJScript.js"></script>
<script class="javascript" src="scripts/shBrushSql.js"></script>
<script class="javascript" src="scripts/shBrushXml.js"></script>
<script class="javascript">
dp.SyntaxHighlighter.ClipboardSwf = 'scripts/clipboard.swf';
dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

Of course if you don't use DasBlog you just put the code in the bottom of each page.

Furthermore you need to refer to the stylesheet in the top of each page.

The last thing I did was to modify the stylesheet to make the color scheme look a bit more like visual studio.

And now I can post code like this nice c# one-liner that shows the name of every file in the current directory:

using System;
using System.IO;
using System.Linq;

namespace ListNames
{
class Program
{
static void Main(string[] args)
{
(from file in Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)
select file).ToList().ForEach(file => Console.WriteLine(file));
Console.ReadLine();
}
}
}

A coworker of mine showed me a program that could do this, and I said well I can do that in one line - it is always nice to show off :) - (disclaimer:  I do not generally advocate to code in as few lines as possible. :) One issue you must always consider is readibility, though generally I must say that one of the great advantages of C#3.0/Linq syntax is that it tends to make stuff more readable when used correctly.

Speaking of Linq, as you can see the Syntaxhighlighter doesn't recognize Linq syntax. The "from" and "select" keywords are not highlighted (unless you read this when I have updated the shBrushCsharp.js script).

Sunday, 08 March 2009 12:07:11 (GMT Standard Time, UTC+00:00)  #    Comments [2] -
.NET | blog
# Tuesday, 24 February 2009

This is the first post of my new blog. Hope you will like it. My plan is to blog about my favourite topic - .NET and other more or less related technologies. I hope to post regularly but I will keep my ambitions low and plan only to post once every month ! Perhaps with a larger more in-depth blog post every second month. This is not for lack of subjects, but because I know myself. Work, family and fitness training often comes before late night programming and researching new stuff.

 

Though my mother-tongue is danish I plan to keep this blog in English to reach a wider audience.

 

Take care…

Tuesday, 24 February 2009 22:39:57 (GMT Standard Time, UTC+00:00)  #    Comments [2] -
.NET
Archive
<2017 December>
SunMonTueWedThuFriSat
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456
About the author/Disclaimer
I am a software architect with focus on Microsoft Technologies. I have been working with these in different large companies since 1995. I am currently employed at UVdata A/S.
Here is my View Jesper Niedermann's profile on LinkedIn

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Privacy policy
The privacy policy of this site.

© Copyright 2017
Jesper Niedermann
Sign In
Statistics
Total Posts: 28
This Year: 0
This Month: 0
This Week: 0
Comments: 32
All Content © 2017, Jesper Niedermann
DasBlog theme 'Niedermann' created by Jesper Niedermann, based on 'Business' created by Christoph De Baene (delarou)