2010-04-16

Moved to www.selfelected.com

I have moved this blog to http://www.selfelected.com/

Happy hacking!

2010-04-12

Visual Studio 2010 installation

If you get
---------------------------
Microsoft Visual Studio 2010 Ultimate Setup
---------------------------
Some components must be installed in c:\Program Files\Microsoft Visual Studio 10.0\ directory. Check that you have write permissions and enough space in that directory.
---------------------------
OK
---------------------------
when you try to install Visual studio 2010; don't despair.
There is a big chance you try to install from a mounted virtual disc.

The resolution is to copy the files in the mounted disk to real files and run it from there. One could possibly also assign the mounted disk a letter but I haven't tried this.

I have learned that there is also some problem when installing from a network share. The symptom is something about a .cab file with a faulty digital signature.

2010-03-16

Coderush and camelCase and select

I am a long time fan of DPack. Some time ago Coderush stepped up to a must-have.

The other day I noticed that Coderush did camel case selection. It is like this:
Open the Vsnet editor with your favourite project and go to a camelCased or PascalCased word. Select it with ctrl-shift-right/left. This is old news.
Now instead use alt-shift-right/left; only a part of the word is highlighted. Perfect when copy-pasting variables like CustomerName and SerialNumber.

Coderush comes both in gratis and pay versions.

2010-03-15

Aspnet MVC 2 starter project compilation error

When starting your first Aspnet MVC2 project you might immediately run into compilation errors like these:

Error 1 The type or namespace name 'Controllers' does not exist in the namespace 'MvcApplication1' (are you missing an assembly reference?) C:\myprojectpath\MvcApplication1.Tests\Controllers\HomeControllerTest.cs 8 23 MvcApplication1.Tests

Error 3 The type or namespace name 'Models' does not exist in the namespace 'MvcApplication1' (are you missing an assembly reference?) C:\myprojectpath\MvcApplication1.Tests\Controllers\AccountControllerTest.cs 10 23 MvcApplication1.Tests

Error 4 The type or namespace name 'AccountController' could not be found (are you missing a using directive or an assembly reference?) C:\myprojectpath\MvcApplication1.Tests\Controllers\AccountControllerTest.cs 317 24 MvcApplication1.Tests



The origin of the problem is that the test project doesn't reference the web project. Just add the reference and you're good to go.

I haven't found the solution on google yet so I write this here to someones possible future aid.

2010-03-04

Checking events in VBNet

Due to some reason unknown to man the team behind VBNet decided that the developer should not be able to see if someone listened to your event or not. It is good in most cases but very bad in another.

In Csharp raising an event goes something like this:
var ev = MyEvent;
if( null != ev ){ ev( this, args ); }


Just look through the snippets (look in the context menu in the editor) and you will find the correct way to raise an event in Csharp.

VBNet on the other hand hides the if statement and the temporary variable from the developer. It is enough to write
RaiseEvent Me, args
and the event will be raise if there is someone listening - no need to check for null.

But what if you want to check if someone is listening. In my case I needed to know if the custom control was properly wired into the scaffolding of the application; the user control sometimes whished for more information and I had to know if someone was listening.
In Csharp this would have been easy with a check for null. But VBNet...

The solution is hidden. Just check the variable "MyEventEvent". This means that your MyClick event has a hidden variable MyClickEvent that you can check for like this:
If MyClickEvent IsNot Nothing Then

I don't like to use hidden and unoffical solutions but this is the only way I know of.

Honor those who should.

Selfelected - ideas

I just started another blog which only presents ideas yet to be implemented.
http://selfelected.wordpress.com/
Feel free to implement anyone of them.

2010-02-04

DesignMode in Visual Studio, inheritance, process name and a work around

The text and code below is only tested for Winform. WPF might behave differently; hopefully behaves differently.

I won't go into any details on why the ISite.DesignMode is good and sometimes even crucial to have. It is much better done in the link at the bottom.

First out there is unfortunately a caveat with DesignMode, it doesn't work with inherited forms and user controls. This is a problem since I always inherit from the base form in my projects and tell others to do the same. It also doesn't work inside the form's or the user control's constructor and then by any method that is called by the constructor. Long call chains to might make this hard to track down.
Secondly there is another way to check for design mode and that is to check for the LicenseManager.UsageMode but this in turn doesn't work in event handlers.
Thirdly one can set a flag in the base Form and base UserControl. But this doesn't solve the problem since we cannot be sure with what to set this value.
Fourthly is a workaround where one can check for the name of the process itself which is Visual Studio's process name (devenv) in case of design mode. This process name might change in future releases of Visual Studio and is also different for other IDEs.
Fifthly is other process information like the name of the module and stuff. Check into the Process and you'll see that the app is called MyApp.vshost.exe while being debugged.

The fourth solution (processname=devenv) seems to be the most viable but I believe there is something useful in the fifth (other process information). There must be a way to notice that the name of all your code doesn't match the name of the running environment; namespace, assembly name, whatever. I still haven't figured out how though.

Below is some code to copy-paste.
It is not 100% correct though since the DesignMode property isn't virtual. This might end with some really tough-to-track-down bugs where one iterates the forms but don't get the overloaded DesignMode flag. The code also doesn't promise to work forever since there is a magic string naming the name of the Visual Studio process.


public partial class MyAppForm : System.Windows.Forms.Form
{
protected new bool DesignMode
{
get
{
return HelperMethods.IsDesignMode(this);
}
}
}

public partial class MyAppUserControl : UserControl
{
protected new bool DesignMode
{
get
{
return HelperMethods.IsDesignMode(this);
}
}
}

class HelperMethods
{
public static bool IsDesignMode(System.ComponentModel.Component x)
{
var site = x as System.ComponentModel.ISite;
return
( null == site ? false : site.DesignMode ) ||
System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime ||
System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv";
}
}
The code above is also in pastebin for easier copy-paste.
A good article is here: http://dotnetfacts.blogspot.com/2009/01/identifying-run-time-and-design-mode.html
There is a description of how to debug this here: http://brennan.offwhite.net/blog/2006/08/30/design-time-debugging-aspnet-20-in-visual-studio-2005/

2010-01-28

Share a file in Visual Studio

I didn't think it was possible but it has been for years; to share a file between projects in a solution.

Add a file the normal way but instead of pressing Open, use the little dropdown arrow next to.  Then you have the possibility to "link" instead of "add".

This makes it possible to have one and only one file for many places.  It can be a source code file or a readme or anything really.
I have yet to try it with TFS and SVN to make sure it doesn't mess upp the version management.

Honor those who should.

On a side note: Sourcesafe has linking ability within itself.  I miss it in TFS.  Though: It is easy to lose the master file and keep copies wich makes strange icons.  It also doesn't play well with the VB6 editor when a file will be checked out and another not, but they should be, but the VB6 ide doesn't understand it and you have to do an explicit checkout and... never mind.  It was a long time ago.

2010-01-24

Changed keyboard settings

In Windows 7 (and possibly Vista) the keyboard layout is sometimes changed back to some sort of default.

The problem shows itself like this - I use the 1337 keyboard layout in Visual Studio.  Then without warning the keyboard layout changes to US layout; a layout I don't even have installed.  The 1337 layout is based on US though so somehow it shines through.

To get back to 1337 I choose "Open the language bar" in the systray context menu.  The language bar then pops up in another place (top of screen for me) and I can then choose keyboard layout.

The problem will reappear more times until I reboot again.

2010-01-16

Get calling method's name automatically in dotnet

Way too many times have I written

void MyFunction( int aNumber)
{
MyHomemadeLogClass.Logg( "MyFunction", "aNumber=" + aNumber.ToString());
...
}
to get logging functionality.

It would be so nice to just write

void MyFunction( int aNumber)
{
MyHomemadeLogClass.Logg();
...
}
It is no hard to do. Use reflection to get the call stack to get to the method and the parameters. Convert all this to a readable string.
Unfortunately it is not that easy to log the contents of the parameters, one has to get into some sort of debugger area to do that.

class ReflectionUtility
{
private static System.Reflection.MethodBase GetCallingMethod()
{
return new System.Diagnostics.StackTrace().GetFrame(2).GetMethod();
}
public static string GetCallingMethodFullNameReturnParametertypes()
{
return MethodFullNameReturnParametertypes(GetCallingMethod());
}
private static string MethodFullNameReturnParametertypes(System.Reflection.MethodBase method)
{
return string.Format("{0} {1}.{2} ({3})",
((System.Reflection.MethodInfo)method).ReturnType, // System.Void, System.Int32 etc.
method.DeclaringType.FullName, // MyNamespace.MyClass.
method.Name, // MyMethod.
string.Join(",", method.GetParameters().Select(p => p.ParameterType.ToString() + " " + p.Name).ToArray()) // () or (int) or (int,string) etc.
);
}
}
To use this in a Logging class one must implement a GetCallingCallingMethod or even worse, but it would make this example hard to read.

One can use the Conditional attribute to avoid the call when not debugging.

I also put the code on pastebin to make the copy-paste easier. (I have yet to find a good way to present code.)

2010-01-09

This is my visual setup of Visual Studio.

Notice how the real estate is used for tools I use and not for buttons that just happens to be there by default.

shift-alt-return maximises the window so not even the caption bar is visible.  I know which program I am working in so I don't need to waste the whole top for this.

I have removed all toolbars.  The buttons I need I have put to the right of the menu.

There are also two macros in the menu bar, one for connecting the bugger to nunit and ditto to IIS.

I have set all toolbars to auto hide.  When I debug, the call stack and autos (unfortunately hard to find among the menus with C# projects - open a VBNet project and see what it looks like), toolbox are visible.

I have also moved all toolbars to the right.  When one is working heavily with the forms designer it is good to have the Toolbox toolbar constantly open on the left but only then, and for the 2% of the project I handle the forms I can move it there manually.  The rest of the time I hack code and need nothing but code and debug tools.

I know shortcuts to almost all toolbars.  Those I don't know I don't use that often anyway.  I don't know why some banjo player at Microsoft decided that underlines and shortcut tips should be invisible as default.  Fix it through Tools->Customize.

This way I use all of the precious display area for stuff I have use of.



2010-01-06

Catch property, field and method name changes compile time in dotnet

When you want to populate a dropdown listbox with customers

class Customer
{
int Id;
string Name;
...
}
and have to write

myDropdownListbox.DisplayMember = "Name";
myDropdownListbox.DataMember = "Id";
or

myGridColumnCustomerName.DatatMeber = "Name";
you really get a sour taste in your mouth.

Having magic strings like above spread in your code is really bad since it always compiles but might fail runtime. This means more manual tests. Which in turns means a certain friction against renaming properties while refactoring.
I have been in way too many projects where one table has a field ItemNumber when it should have been ItemCount and where some fields are called Nr while another Number and these names are spread up in the layers to reach the presentation layer where they surface as magic strings like the examples above.

Luckily there is a solution in Dotnet 3 with LINQ. It isn't the prettiest but it fails compile time when it should and that is considered a good thing.

( I won't bother with explanation - just read the code. )

// The Code.
class ReflectionUtility
{

public static string GetPropertyName<T,TReturn>(Expression<Func<T,TReturn>> expression)
{
MemberExpression body = (MemberExpression)expression.Body;
return body.Member.Name;
}

public static string GetMethodName<T,TReturn>(Expression<Func<T,TReturn>> expression)
{
var body = expression.Body as UnaryExpression;
var operand = body.Operand as MethodCallExpression;
var argument = operand.Arguments[2] as ConstantExpression;
var methodInfo = argument.Value as System.Reflection.MethodInfo;

return methodInfo.Name;
}

}

// The test code.
class MyClass
{
public int MyField;
public int MyPublicProperty { get; set; }
public string MyReadonlyProperty { get { return string.Empty; } }
public int MyMethod() { return 0; }

private MyClass() { } // To make sure the class doesn't need a default constructor.
}

class Program
{
static void Main(string[] args)
{
string fieldName = ReflectionUtility.GetPropertyName((MyClass x) => x.MyField);
Console.WriteLine(string.Format("MyClass.MyField:{0}", fieldName));
Debug.Assert("MyField" == fieldName);

string propertyName = ReflectionUtility.GetPropertyName((MyClass x) => x.MyPublicProperty);
Console.WriteLine(string.Format("MyClass.MyPublicProperty:{0}", propertyName));
Debug.Assert("MyPublicProperty" == propertyName);

propertyName = ReflectionUtility.GetPropertyName((MyClass x) => x.MyReadonlyProperty);
Console.WriteLine(string.Format("MyClass.MyReadonlyProperty :{0}", propertyName));
Debug.Assert("MyReadonlyProperty" == propertyName);

string methodName = ReflectionUtility.GetMethodName<MyClass, Func<int>>((MyClass x) => x.MyMethod);
Console.Write(string.Format("MyClass.MyMethod:{0}", methodName));
Debug.Assert( "MyMethod" == methodName);

Console.Write(Environment.NewLine + "Press any key.");
Console.ReadKey();
}

}
Honor those who should.

Update: When copy-pasting through manoli.net some angle brackets got dropped. This is, hopefully, fixed now.  Otherwise - get the source here: http://selfelected.pastebin.com/f77563a02

2009-12-29

US vs French vs Swedish vs 1337 keyboard layout aka 1773 keyboard

Most programming languages I have tried work better with a US keyboard layout than a Swedish.  For instance my current language, C#, is riddled with {s and [s and these are a pain to use.  One has to press the right Alt-button (labeled alt-gr) and then 7 or 8 respectively.  Try this, it really twists your hand.

The US keyboard has {, [, ], } to the right of P and it works much better than the Swedish keyboard.

But then we have (, ), =, & and the rest above the number keys.  Most languages use plenty of parenthesises and even though you don't have to twist your hand it is still awkward to use two keys (and hands with a "proper" finger setting) to write these common characters.  The French keyboard has solved this by flipping the number keys/shift setting.  Press the key to get an ! and shift-key to get 1.  If one write lots of number there is always the proper number keyboard to the right.

So the French keyboard is better for some other characters.

Then we have the Swedish characters å,ä and ö.  Even though I usually hack in English I write text, outputs and user information in Swedish so these cannot be left out.

Thinking that there was no reason to have a second rate keyboard layout I fired up MSKLC from Microsoft and hacked together the 1337 keyboard layout.  I have used it for a couple of years now in WinXP, Vista and Win7.

For almost all use other than programming I keep the Swedish layout so I have set leftshift-leftalt for a fast keyboard layout toggle.

Lastly: I do use touch typing and I recommend learning this for all serious software developers.  I also have noticed that I have very little problem with switching keyboard layout, the fingers need a second to adjust and are then hitting the right key.

(For problems 1337 reverting to US see here.)

2009-12-14

String.IsNullOrEmpty

Instead of

    if( null == myString || string.Empty == myString ){...

one can use

    if( string.IsNullOrEmpty( myString ) ){...

There is nothing magic about it, just a more readable, and hence less error prone, syntax.

It would be nice of someone could solve the

    if( null == myCustomer.Address || null == myCustomer.Address.City || null == myCustomer.Address.City.Name ){...

-problem.

In Dotnet4 there will be a method similar to IsNullOrEmpty which also checks for whitespace.  It should come in handy.

2009-12-08

Database versioning

Since I have abandoned Visual studio database edition because of it not being able to handle tables with data I have returned to my old, proven, way; checking in/committing the update scripts and storing a database version number in a Setting table.

In Microsoft SQL Server Management Studio (or whatever it was called earlier) there is a setting to always create update scripts whenever a change is saved.

Then whenever a change is done, store the update scripts with consecutive version numbers.  These versions are not the same as the release versions but one version number per commit.

013_01_S_Customer_Added the CompanyColour field.sql
013_02_D_Customer_Set the CompanyColour to red except blue for McCarthysen.sql
013_03_S_Customer_Set CompanyColour to notnull and no default value.sql
013_99_D_Setting_Updated database version.sq
l

013 is the version number.  Next commit is 014 etc.
01, 02, 03 are consecutive numbers.
99 is the final number for this commit.  It always contains an update in the Setting (or whatever you call it) table and sets the version number record to 13.
S and D are Schema and Data respectively.  I have learned that it is good to see this already in the script's filename.
Customer and Setting are the names of the main manipulated tables.
The rest is free text that explains what the script does.

It is now very easy to see how far a database is in the development flow.  Select the the row from the Setting table and notice its number.  Then run all scripts with higher version numbers in the right order.  The scripts are easy to order by their names directly in the version manager or in the file explorer after a checkout/getlatest.

This technique works well with several developers.  Store the scripts locally until they you are ready to commit the code.  Update the version number if someone already used the version number.  Commit.

A tool like SQL compare does approximately the same job.  If you have only a few updates with a few databases it is way faster to just create a diff-script and run it.  Contrary to VSDatabase edition SQLcompare handles tables with data.  It costs money but 1) there is a trial version and 2) it is way cheaper than hacking the code yourself.
There are other tools as well and I have used one but I cannot remember the name of it.  It was not as easy to use as SQLcompare if I recall correctly.

If you have to handle several versions while developing the procedure I have described here is good since it is so easy to check the version of the database.

(I just stumbled upon a situation where saving a view and only updating the output fields from lower to upper case (customername -> CustomerName) did not result in a script file.  In this case there was no problem in scripting a drop/create script through the Object explorer tool box though.)

2009-12-01

Virtual PC under Windows7

If one wants to run a virtual machine on Windows 7 Windows Virtual PC is the official way to go.
It requires hardware supported virtualization though, which means not everyone's machine can do it.  On my HP 8510w it meant a cold reboot - just restarting and changing the BIOS was not enough.

The older VirtualPC2007 doesn't need any hardware virtualization stuff and a small text about how to install it is found here: http://blogs.msdn.com/virtual_pc_guy/archive/2009/08/19/running-virtual-pc-2007-on-windows-7.aspx

It looks like Microsoft wants everyone who installs Windows Virtual PC to also install Windows XP Mode by some reason unknown to me.  I am a developer and I am hesistant to installing apps that might tweek the OS.
The whole page at http://www.microsoft.com/windows/virtual-pc/download.aspx pushes you into installing Windows XP Mode but if one selects a system at step 3 two buttons pop up and one of them says "Windows Virtual PC".




Download and install.  But instead of the usual application GUI one gets a view of a folder under C:\Users\username\Virtual Machines prepared for virtual machines.  This might be good for people who backup what is under their personal account but as a developer I don't want to tie my data to an account and instead prefer something like C:\DATA\VMACHINE\.
Come to think of it - is it good for anyone?

It also took me a while to find out how to create a new virtual machine.  Instead of having an app with a button or menu as is de facto standard someone has decided to hide the button in the toolbar or extra menu system ( I have never figured that out. )


Don't bother to cut and paste the .vmcx file to some other place.  It will be copied but not removed so you end up with the original .vmcx file in the original place and a not functioning copy of it in your target directory.
The .vmc file can be run though.

Mount an ISO with your preferred OS on the virtual D: drive.  The virtual machines chews through your NICs and DHCP.  I had my WLAN card turned of in the host OS, but the virtual machine seemed to first look for my WLAN card and then my regular one.

The rest looks just like ususal.

2009-11-29

IsNot in vbnet - a more readable way to check for Nothing

When I have written Vbnet and checked for Nothing I have chosen between 

    If Not( o Is Nothing ) Then
        ...

and

    If False = o Is Nothing Then
        ...

and

    If o Is Nothing Then
        '    NOP.
    Else
        ...

all ugly and/or hard to read but in their own way.

Some days ago I stumbled upon IsNot and since then my code looks nicer like so:

    If o IsNot Nothing Then
        ...

I have been writing Vbnet for years without finding IsNot so I thought there are more out there with the same problem.

2009-11-28

Edit project file in VSNet

There are mainly 3 ways to get to your Vsnet project file to edit it.  (disclaimer: I am running Vsnet2008 and haven't tried earlier nor later versions)

1) Open windows explorer and navigate to your project folder.  Open the project file (.csproj/.vbproj/...) in your favourite xml editor.

2) Install a tool that gives you an "Open folder in windows explorer" context menu item in the Solution explorer.  If I recall correctly the tool I am referring to is Microsoft's Team foundation server power tools.  Please correct me if I am wrong.

3) Unload the project.  Use the context menu in Solution explorer to edit the project file.  Load the project again.

2009-11-04

Traverse Corporate Firewalls

Sometimes a solution is so secure it becomes insecure.  The primary example of this is requirements for passwords that are so complex that people write them on a note and stick them under their keyboard.

I have several times been locked into a corporate network where the possibility to cooperate with the outside has made my work more complex and expensive.
Limited email storage and chat protocols that don't make it through the router are things that might hinder my work all the way to effectively stopping it.  A limit of 100 megs of email storage makes it impossible to send large emails without risking filling the mail box of a colleague.  Without chat my communication with competence peers is severed.

A slow internet connection makes every search take longer time or give less thorough result.

Then there are hinderances like forbidden FTP, an email washer that stops binaries and source code, or the stopping of youtube in the firewall.

I live in a world, a community, and we communicate.  A big part of my work is to gather information and spread it to interested parties.  Too many times the rules of a corporation network limits this.  Hence workarounds that don't always play well with security but makes my customer happy.  And that is what it is all about, helping your Customer.

Wired has an article http://howto.wired.com/wiki/Traverse_Corporate_Firewalls that explains some workarounds from the dead simple to way more complex.

2009-10-18

Unable to open the physical file Operating system error 5: "5(failed to retrieve text for this error. Reason: 15105)". (Microsoft SQL Server, Error: 5

Try to attach a database with Management Studio when using Windows 7 and SQLServer 2008 developer edition and one might get an error message similar to the title of the article.

Whether this is a bug or not is beyond my knowledge but the solution/workaround is to connect as SA and not as windows authentication.