Easy way to edit Visual Studio’s project file using XML editor

There are times one needs to edit a project file (csproj, vbproj or others) in XML editor or just text editor because all settings are not available through UI or perhaps it is easier. I usually right clicked on project node in solution explorer to open the folder (in explorer) where project file resides  and then edited the file using Notepad2.

Watching Hanselman’s podcast on MVC 2 I found that there is an easier way to do it. Right click on the project, do the unload project, re-click on, now unloaded, project node and pick edit yourproject.XXproj context item. There you go. After you’ve done editing, save it and pick reload project to continue working.

Adding features to Visual Studio 2008 SP1

While trying to compiling nVidia CUDA kernels on my Windows 7 x64 I realized that somehow I didn’t install the Visual Studio 2008 C++ x64 compilers and tools.

image

So I tried updating Visual Studio by going to Control Panel/Programs And Features bla bla only to get this error dialog showing up:

A selected drive is no longer valid.  Please review your installation path settings before continuing with setup.

Huh? I did have the ISO image mounted. Once more Google found Mike Eshva’s solution to the problem: uninstall SP1, add feature and reapply SP1. I am sure I’ve read this solution before but I never needed it. Later on I’ve found a bug report on Microsoft Connect with exact same motivation, the problem and the workaround as well.

The funny thing is that it didn’t work exactly like that for me. I’ve uninstalled SP1 and then I couldn’t get into uninstall/change dialog anymore. Ooops. But I wasn’t too worried because right before the process I’ve made a backup to my trusty Windows Home Server. Just in case. I didn’t need it though. Anyway I’ve reapplied SP1 and then it started working as it should – I was able to add the x64 feature just as it should be. Except for one additional obstacle during add process:

Setup is looking for file SQLSysClrTypes.msi.

Argh. This one I’ve solved with help from this blog post.

I guess one or more of the updates/hotfixes after SP1 was causing the original problem (and was uninstalled with SP1), which one I’ll never know.

Bottom line

I hope that Visual Studio 2010 will handle better the updates. The way Visual Studio 2008 handles the updates looks like one big mess and it is scary to change anything within updates, service packs and hotfixes.

The slides and code from my “Making asp.net mvc applications strong typed” presentation

Yesterday I held a presentation (as the part of Bleeding Edge 2009 conference) on how to make ASP.NET MVC applications strong typed by using CodeSmith and CodeRush (actually by using its free DXCore part). Attendees were great and the presentation went well. Attached are the slides in Slovene and source code in C#.

If you are interested in the topic you might read my previous blog posts as well:

Thanks everybody for attending the presentation.

Powerful and easy installation authoring of .net applications with Advanced Installer

Lately I’ve built a .net class library that supports COM as well. To make setup file I usually use Visual Studio’s Setup Project because I rarely do anything complicated during the installation ant Setup Project does the work fine for me.

This time the setup was a bit different, more complicated, because I needed to register my COM stuff during the installation. So I’ve built the setup file and tried the installation inside VMWare Workstation’s guest as I always do. COM objects were registered fine but type library (TLB) wasn’t registered at all when setup project is built on Vista/Visual Studio 2008. The later isn’t strictly required for running the code but it surely helps developers with strong typing support. There are several options to solve the issue ranging from building on XP to coding the post install/uninstall actions. Well, none of them looks very appealing to me thus I’ve decided to try the Advanced Installer from Caphyon this time.

I can say that creating a setup file for my .net application with Advanced Installer was a breeze – I had a working MSI setup in 10 minutes. The process consisted of importing the Visual Studio Setup Project (which I already had – I could start from scratch or by importing the library project) and adjusting few properties. Truth, mine wasn’t a complicated one but it surely solved type library registration with a click on the checkbox. It actually solved my problem in 10 minutes. Any other option would be either more annoying or it would take more time.

Advanced Installer is not just easy to use. It looks like a powerful and flexible authoring tool as well and certainly not limited to (simple) .net applications only.

A better call to Control.Invoke

Whenever one needs to interact with WinForms UI from within another thread (the one that didn't create the UI controls) one has to rely on the Control.Invoke (or BeginInvoke/EndInvoke pair) method. Otherwise one gets an InvalidOperationException exception with message “Cross-thread operation not valid: Control ‘name here’ accessed from a thread other than the thread it was created on”. This happens because WinForms (and .net framework in general) isn’t thread safe.

Let’s say I want to know how many controls are on the form. I’d do it like this (Form f holds the instance of the Form created in some thread):

public static int GetControlsCount(Form f)
{
if (f.InvokeRequired)
return (int)f.Invoke(new Func<Form, int>(GetControlsCount), f);
else
return f.Controls.Count;
}
...
int count = GetControlsCount(f);

This way the method GetControlsCount is thread safe. That’s fine. But what should I do if I require to access many methods in such a thread safe way (I’ll blog about the reason I need it in a future post)? Creating this kind of wrapper for every different method I need to call would be kind of boring at best and difficult to maintain, don’t you think?

So I created a generic method instead, like this:

public static TRet InvokeSync<TRet>(Control control, Func<TRet> func)
{
if (control.InvokeRequired)
return (TRet)control.Invoke(func);
else
return func();
}
...
int count = InvokeSync<int>(f, () => f.Controls.Count);

This is much better because I don’t need to create a wrapper for each method – instead I merely provide a delegate (of type Func<int> in my case). There are two drawbacks to this approach.

1. It won’t work with different number of parameters nor it will work with methods (= actions) that don’t return a value. The only workaround is to create various similar methods that accepts different argument number and return either a result or no result (void). Here is a bunch of such variations:

public static void InvokeSync(Control control, Action action)
{
if (control.InvokeRequired)
control.Invoke(action);
else
action();
}
public static void InvokeSync<T>(Control control, Action<T> action, T argument)
{
if (control.InvokeRequired)
control.Invoke(action, argument);
else
action(argument);
}
public static TRet InvokeSync<T, TRet>(Control control, Func<T, TRet> func, T argument)
{
if (control.InvokeRequired)
return (TRet)control.Invoke(func, argument);
else
return func(argument);
}
public static TRet InvokeSync<T1, T2, TRet>(Control control, Func<T1, T2, TRet> func, T1 argument1, T2 argument2)
{
if (control.InvokeRequired)
return (TRet)control.Invoke(func, argument1, argument2);
else
return func(argument1, argument2);
}

2. Passing Control parameter (which is required to do the synchronization) is such pre .net 3.5-ish. Instead extensions methods can be used, like this:

public static class Extender
{
public static TRet InvokeSync<TRet>(this Control c, Func<TRet> func)
{
if (c.InvokeRequired)
return (TRet)c.Invoke(func);
else
return func();
}

public static void InvokeSync(this Control c, Action func)
{
if (c.InvokeRequired)
c.Invoke(func);
else
func();
}
}

So the final version of the call to InvokeSync looks even nicer:

int count = f.InvokeSync<int>(() => f.Controls.Count);

That’s it.

InvokeSyncExtender.zip (572.00 bytes)

Packing assemblies to a single file for Righthand.Dataset.Visualizer

A while ago I’ve created Righthand.DataSet.Visualizer, an advanced DataSet visualizer. Today I’ve added support for displaying a single table as well. It wasn’t a big deal but I guess people will find it useful.

Now, there is one things I weren’t too happy about until today: I reference a lot of DevExpress assemblies and I have to redistribute all those assemblies along mine two (my visualizer comes in form of two assemblies). Which makes a lot of assemblies in total and even worse, if two visualizers use slightly different DevExpress versions you are in for a trouble.

So I’ve decided to pack everything to a single file. ILMerge, a free assembly merging tool from Microsoft, won’t work for me since it has problems with reference to Microsoft.VisualStudio.DebuggerVisualizers even though I don’t want to redistribute it. So I tried Xenocode Postbuild for .NET which does all sort of hacky things with .net assemblies, it even allows to create a setup that doesn’t require .net framework installed at the target machine. Among other features (obfuscation, optimization, etc.) it provides an assembly merging option that I successfully used in my case. Here are the required steps for my case:

1. Start Xenocode Postbuild for .NET, click on Application tab. Use Add… button to add required assemblies to pack together (you can add assemblies individually or pick most important ones and then use Scan Dependencies button to add referenced ones):

application

2. If you want only to pack assemblies then use Null – For test and debugging purposes or any other preset you want, just make sure you set other options appropriately.

presets

 

 

 

3. On the Protection tab I did uncheck all metadata obfuscation (since I am not after obfuscation here) by right clicking on the root node and selecting Unselect Tree menu item. I don’t use any Disassembler Suppression either. I left moderate code obfuscation (level 3 in scale 0..4), just for testing – this option shouldn’t cause any trouble since it should keep functionality the same. If there are problems with the later it means that the tool sucks heavily.

protection

4. Clear all checkboxes in Optimize tab.

5. On the Output tab I made sure that Single application executable option in Link and Code Generation group is selected and Righthand.DebugerVisualizer.Dataset.Visualizer assembly is the main one. I also selected .\Setup for the output folder.

output

6. By clicking Xenocode Application button the final, single file, output is written to the disk.

And that’s it. I got a single file with all required assemblies packed together. Just that easy. Note that I intentionally used only a fraction of Postbuild power.

If you use frequently Postbuild you should also consider using Final Builder tool, an automated build and release management tool that supports Postbuild out of the box (I am sure other such tools support Postbuild as well).

And finally, here is the updated visualizer:

RightHand.DebugerVisualizer.Dataset.Visualizer 0.9.14.zip (7.60 mb)

Let me know if there are any problems or if you have any improvement wish.

Autoimplement base class constructors with CodeRush

How often do you derive a class and re-create all of the base constructors? This is not an uncommon task, let's take a custom exception class for example:

public class MyException: Exception { }

If you right click on Exception and pick Go to Definition from the context menu you'll see that the Exception class has four constructors:

public class Exception : ISerializable, _Exception { public Exception(); public Exception(string message); protected Exception(SerializationInfo info, StreamingContext context); public Exception(string message, Exception innerException); }

And you better re-create all four in your derived MyException class if you want to follow the design guidelines. This is how MyException should look like (without custom code that is):

public class MyException: Exception { public MyException() { } public MyException(string message) : base(message) { } public MyException(string message, Exception innerException) : base(message, innerException) { } protected MyException(SerializationInfo info, StreamingContext context) : base(info, context) { } }

This is a straightforward derived Exception class definition and needless to say it is quite boring to create all those constructors again and again. That's why [CodeRush] has a one-click base constructors recreation feature. Position the caret somewhere on the Exception word and invoke [CodeRush] with keyboard shortcut (by default the shortcut is Ctrl+CEDILLA) and instantly all of those boring-to-recreate constructors appear from nowhere. Brilliant.

Using extension methods to make code less cluttered

Here is an example where an extension method is useful. Take this [LGP] code for example:

public EntityCollection<CustomersEntity> GetCustomers() { using (DataAccessAdapter da = new DataAccessAdapter("Data Source=[SERVER];Initial Catalog=Northwind;Integrated Security=True")) { LinqMetaData context = new LinqMetaData(da); var q = from c in context.Customers select c; EntityCollection<CustomersEntity> result = ((ILLBLGenProQuery)q).Execute<EntityCollection<CustomersEntity>>(); return result; } }

It is a simple LINQ to LLBLGenPro select against (we all love) Northwind database. Pay attention at result assignment. To have data returned as a native [LGP] EntityCollection you have to resort to ILLBLGenProQuery interface. You have to use ILLBLGenProQuery.Execute method on IQueryable<T> q. A cast is obviously required because IQueryable<T> doesn't know anything about ILLBLGenProQuery. While this code works it is not exactly elegant - I am referring to the later cast of course.

So, the idea is to have something like this instead:

EntityCollection<CustomersEntity> result = q.Execute<EntityCollection<CustomersEntity>>();

Possible? Sure, just add this static class with a single extension method and you are good to go:

public static class Tubular { public static TResult Execute<TResult>(this IQueryable q) where TResult : IEntityCollection2 { return ((ILLBLGenProQuery)q).Execute<TResult>(); } }

Or perhaps, we can further reduce the cluttering by introducing this extension method:

public static class Tubular { public static EntityCollection<TEntity> Execute<TEntity>(this IQueryable q) where TEntity : EntityBase2, IEntity2 { return ((ILLBLGenProQuery)q).Execute<EntityCollection<TEntity>>(); } }

to achieve this, even less cluttered, line:

EntityCollection<CustomersEntity> result = q.Execute<CustomersEntity>();

Isn't this or former de-cluttered line more readable and more elegant than the original?