Programming in C#, Java, and god knows what not

Trimming Text in AfterLabelEdit

Editing text of ListView item is quite easy. Just set LabelEdit = True and you are good. This will allow user to change text of item and it will even let us validate it in AfterLabelEdit handler. But can we additionally adjust edited text?

Most obvious choice would be setting e.Label to some other value. That will unfortunately never compile since Label property is read-only. Next guess will be just hijacking AfterLabelEdit and editing text in code. Something like this:

if (e.Label == null) { return; }
var text = e.Label.Trim();
if (string.IsNullOrEmpty(text)) {
    e.CancelEdit = true;
} else {
    list.Items[e.Item].Text = text;
}

And this works - almost.

Editing label at this point does not really matter. Whatever you write into Text property will be overwritten with e.Label once AfterLabelEdit handler is returns.

In order to handle things our self we just need to pretend that we canceled original edit:

if (e.Label == null) { return; }
var text = e.Label.Trim();
if (string.IsNullOrEmpty(text)) {
    e.CancelEdit = true;
} else {
    list.Items[e.Item].Text = text;
    e.CancelEdit = true;
}

Full code is here.

Visual Studio Update 1

Illustration

Service pack is forbidden word these days in Redmond. Therefore we got Visual Studio 2012 Update 1. Initial download is only 1 MB with rest of data collected upon setup. Real fun if you need to update multiple computers.

As far as update goes there just aren’t any major improvements. Mostly it is just bug fixes and stuff that ought to be in initial release.

One thing that I do like is how fast this update came after initial release. If they keep up this speed we might get next service pack update in a few months. With obvious stuff gone that means that some goodies will be there. We can only hope.

Which Rule Set?

Illustration

Static code analysis is a beautiful thing. For a while now Visual Studio has it embedded and it is only a right click away.

By default each project gets assigned “Microsoft Managed Recommended Rules” as baseline for analysis. In my opinion this is really good choice for most of projects. It does include quite a few checks (61 to be exact) and whatever you get is almost certainly something you want to improve.

I would argue that most projects would benefit from setting bar quite a bit higher at “Microsoft Extended Design Guidelines Rules”. This ruleset gets annoying pretty fast when you run it on existing project. You can almost be sure that code will be peppered with CA1704: Identifiers should be spelled correctly and CA1062: Validate arguments of public methods.

First one can be sorted with small code analysis dictionary and second one will need few ifs here and there. All other warnings can also be sorted with similar level of effort since they are not real errors nor something that will cause immediate problems (e.g. double dispose). If project is old this can take ages and it is for little or no practical value.

Biggest beast is “Microsoft All Rules” setting. This one will complain for anything and everything and it will be really hard to satisfy it in any GUI project. Yes, it is possible but this purity brings no value to customer and I usually keep my main assemblies away from it.

I have quite a simple personal rules which level to use. If assembly is intended to serve as a framework that will be written in stone once it is released I go with “Microsoft All Rules”. It is annoying at times but users of your framework will be thankful because it forces really tidy external interface.

If assembly is intended for sharing between projects I go with “Microsoft Extended Design Guidelines Rules”. It forces me to keep design guidelines close to mind and to avoid some potential bugs that can just creep in code (e.g. returning internal array directly). All externally visible members should be held to higher standards since you never know when you or someone else might reuse them.

If given assembly contains GUI, I usually just stick to default Microsoft Managed Recommended Rules. GUI assemblies are not intended to be called directly and bunch of warnings will be just annoyance (e.g. localization warnings when localization is not even planned).

Your mileage and opinion might differ but one thing is for sure - any project has to have at least minimum code analysis enabled.

PS: As number of rules increases so will number of false warnings. Suppressing code analysis warnings is sometime only way to go around it. Just make sure you have really good reason. If you have too much (valid) suppressions that might as well mean that you selected wrong code analysis level for your project.

PPS: It is not always clear which rule belongs to which ruleset. Therefore I have prepared small Excel file with this information.

Sometime 'D' Is Not a 'D'

Converting from date to string in C# is really easy. Basic components are y M d H m s and you go from there:

var date = new DateTime(2008, 3, 1);
Console.WriteLine(date.ToString("yyyy-MM-dd")); //2008-03-01
Console.WriteLine(date.ToString("yyyy")); //2008
Console.WriteLine(date.ToString("MM")); //03
Console.WriteLine(date.ToString("dd")); //01

Of course you can also use format without leading zeros:

var date = new DateTime(2008, 3, 1);
Console.WriteLine(date.ToString("yyyy-M-d")); //2008-3-1
Console.WriteLine(date.ToString("M")); //March 1 (or something similar) - WTF?
Console.WriteLine(date.ToString("d")); //2008-11-01 (or something similar) - WTF?

Looking at first line one would expect d and M to give day and month without leading zero. In .NET these characters lead double life. For example, if d is given alone it really means standard date and time format specifier. Similar goes for M.

Solution is quite simple. If you really need to use them alone, just prepend percent character (%):

var date = new DateTime(2008, 3, 1);
Console.WriteLine(date.ToString("yyyy-M-d")); //2008-3-1
Console.WriteLine(date.ToString("%M")); //3
Console.WriteLine(date.ToString("%d")); //1

VisualHg in Visual Studio 2012

Illustration

I am big fan of Mercurial and I keep all my private projects under its control. Quite a big portion of them is done in Visual Studio so I needed something a bit more integrated than TortoiseHg. Best solution I have found was VisualHg. And I was happy user until Visual Studio 2012 came out.

No matter how many times I would install and reinstall, it would not appear under Plug-in Selection. It seems that VisualHg installation is broken a bit so it does not signal Visual Studio to refresh list of source control plugins.

Solution is actually easy. Install VisualHg as you would usually do. When you start Visual Studio 2012 just go to Tools -> Extensions and Updates. In online section there you can find HgSccPackage. I actually don’t like this one but installing it does refresh plugin list. After HgSccPackage install is done, VisualHg is once more available for selection.

DotPeek

Illustration

Almost two years ago .NET Reflector went into freeware history. First it was $35 but price has gone since to $95 these days. For something that was freeware once this is quite an increase.

Strictly speaking I was not really affected. Microsoft released source code for basic .NET libraries quite a long ago so most of my snooping needs were covered. But setting that up was pain-in-the-ass compared to the pure simplicity of .NET Reflector.

JetBrains, creators of ReSharper tool, created new tool called dotPeek. For all practical purposes we can view it as long lost cousin of .NET Reflector. Best of all it is completely free (at least in version 1.0).

Product is not without fault. On Windows 8 I could not get document search to work; source produced has extra spaces here and there; it does not support Visual Basic; there is no option to save a file; project export is not possible; it sometime breaks Alt-Tab behavior… Those are just biggest complaints that show it is definitely not without fault.

But I like it nevertheless!

It worked perfectly on all code that I gave it and has always produced acceptable code. Stack trace browsing allows to track function calls across assemblies with ease and it is feature that I never thought of before but it seems so logical now.

Browsing though code is probably as good as it gets once you get used to keyboard shortcuts. And editor support for code folding is fantastic. Since that is what you actually need 95% of time, all bugs / forgotten features are easily forgotten.

It is tool that is worth its place in toolbox of every C# programmer.

P.S. No, it does not have stupid time restrictions that drove me crazy even in freeware .NET Reflector.

Deleting Team Foundation Services Project

As you try new service, one is bound to make a lot of mess. I did the same with my Team Foundation Services account. After initial testing was done I decided to make a clean start and delete a project.

It took me quite a while to give up on finding delete. It seems that somebody forgot to take his pills during design phase and thus delete button does not exist.

Fortunately, this is just an Team Foundation Server so good old command line will do nicely:

CD "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE"

TFSDeleteProject.exe /collection:https://jmedved.visualstudio.com/DefaultCollection/ Test
 Warning: Deleting a team project is an irrecoverable operation. All version control, work item tracking and Team Foundation build data will be destroyed from the system. The only way to recover this data is by restoring a stored backup of the databases. Are you sure you want to delete the team project and all of its data (Y/N)? Y
 Deleting from Build ...
 Done
 Deleting from Version Control ...
 Done
 Deleting from Work Item Tracking ...
 Done
 Deleting from TestManagement ...
 Done
 Deleting from ProcessManagement ...
 Done
 Deleting from LabManagement ...
 Done
 Deleting from ProjectServer ...
 Done
 Warning. Did not find Report Server service.
 Warning. Did not find SharePoint site service.
 Deleting from Team Foundation Core ...
 Done

Of course, if you want to create new project with same name, do not forget to visit File -> Source Control -> Advanced -> Workspaces in order to remove last traces.

Solving Case of Missing Tests

Illustration

I was quite surprised when Visual Studio 2012 could not run any unit tests for one project of mine. Every time I would hit rebuild, same output would appear “Exception has been thrown by the target of an invocation.” and Test Explorer would stay empty.

Solution that worked for me was just deleting whole TestResults directory. One rebuild after, Test Explorer was full once more.

How did this corruption occur is different matter completely. Since this project was converted from Visual Studio 2010 it might be something in conversion process gone wrong. Or it might have been some disk error. Or my habit of interrupting build process finally got me. I will probably never know.

Team Foundation Service

Illustration

Source control is something that every project needs. I do not care whether it is simple Hello World app or next Office. If you don’t have it under source control, you are doing it wrong.

For a while now I have been advocate of Mercurial. Nice distributed source control with acceptable UI under Windows and with lot of options for online storage (BitBucket being most popular choice). And it integrates nicely in Visual Studio (VisualHg plugin).

If your work completely revolves around Visual Studio, there was always option of using Team Foundation Server. It is good centralized source control system deeply integrated into Visual Studio. As a bonus it also offers quite a good deal of bug ticket management and scrum planning. It tries to be one solution for all project needs, and it is rather successful in that.

Downside is infrastructure. Installing Team Foundation Server is not too difficult but it does require separate server, setting up backup plans and at least though about access. This is not too difficult when dealing with local team but if you have someone outside of your network everything gets painful and expensive pretty soon. Not a problem for organization but usually unscalable obstacle for someone setting it up at home.

Things change a bit with new Team Foundation Service. Sales department boost it as “cloud-powered source code management” but developers can really just look at it as Team Foundation Server on Internet. That means that most difficult part of work is done for us. Server is up, somewhere where everybody can reach it and someone else takes care of backup.

Features include centralized source code management model that is really easy to use and almost anything any scrum team would need for managing project. Yes, that includes tasks, backlogs and all that beautiful stuff. Of course, bug management comes out-of-box too. Really no difference to standalone Team Foundation Server.

Thing that I like the most is fact that it is free for up to 5 users without any additional limit on number of projects. That makes it really viable for hobby project done by single person or even really small teams. Paid plans will be announced in 2013. Before that time even huge teams can get some of a free action.

Yes, BitBucket offers same amount of free users and you can get free scrum and bug management systems also. However, Team Foundation Service really shines in level of integration. I am not aware of any other solution that offers all this and that is so easy to setup.

If your development world is rooted in Visual Studio, life can hardly be better.

ListView Iterations

If there is need to iterate through ListView items, I often see following code:

foreach (var item in listView1.Items) {
    var itemX = (ListViewItem)item;
    //do something with itemX
}

Unfortunately C# compiler is not smart enough to notice that item is actually ListViewItem so it keeps it as Object. And thus we need to cast it to our desired type.

Well, actually there is no need to do this. One just needs to remember live before implicit typing with var came:

foreach (ListViewItem item in listView1.Items) {
    //do something with item
}

This still works and it definitely looks nicer.