Dealing with iterations over null lists in LINQ to Objects

by Miha Markič15. October 2009 10:41

Problem

If you used LINQ to Objects you have certainly come across iterations over null values resulting in an ArgumentNullException being thrown at you.

See this example:

int[] b = null;var query = from i in b select i;

In the case above the error is obvious but if the list comes as an argument of a method or some more complicated way it is hard to spot it. Sure, the obvious solution is an easy one. A simple if statement before will do it:

if (b != null)
var query = from i in b select i;

What about nested loops? Like this

class Tubo
{
public List<string> Strings;
}
...
IList<Tubo> tubos = ...;
var query = from t in tubos
from s in t.Strings
select s;

Sure, we could add guardian clauses like the if before:

if (tubos != null)
var query = from t in tuboswhere t.Strings != nullfrom s in t.Stringsselect s;

The problem with this approach is that it gets cluttered and it complicates the flow, specially the first if.

Solution

So, here is my proposal and I am sure it has been proposed before (I just couldn’t find it on Google, err, I mean internet).

public static class Extension
{
public static IList<T> Safe<T>(this IList<T> source)
{
if (source == null)
return new T[0];
else return source;
}
}

The extension method makes sure that query always gets a non-null list by making an empty one if it is null. The trick with extension method is that they can be invoked on null values which are passed as this argument.

And the last nested LINQ to Objects loop would look like:

var query = from t in tubos.Safe()
from s in t.Strings.Safe()
select s;

I am not sure that the extension method name Safe is adequate or not but it sure does help in code readability.

What do you say?

Tags:

.net | .net 3.5 | .net 4.0 | LINQ

.net reflector pro is awesome

by Miha Markič7. October 2009 09:20

.net reflector

I am sure we all know and love .net reflector originally developed by Lutz Roeder and took over by fine folks at Red Gate. If you don’t know what .net reflector is or what it does you must take a look. It is an indispensible tool for understanding how a certain assembly (i.e. from .net framework or 3rd party) works – .net reflector does that by disassembling assemblies into C#/VB/IL/whatever (whatever code is achieved through a right plugin) code you want. And based on all this information it can provide you a ton of useful data, i.e. who uses which type, what types are derived from a type, etc.

.net reflector pro

And now there is a PRO version with a kick ass feature – it lets you step through source code even for referenced assemblies without sources while debugging an application under Visual Studio 2005/2008/2010. The functionality is similar to using symbols for same purposes. But it is a lot better because you aren’t constrained to assembly vendor as vendor has to provide symbol files for you to debug them. .net reflector pro does the trick for any assembly, regardless of the origin. True, it is useless with obfuscated assemblies and it doesn’t provide comments but hey – AFAIK right now there is only Microsoft providing some, not all, symbol files. You are out of luck for other Microsoft and 3rd party assemblies in this case.

Let me tell you an example. I’ve been bugging Developer Express guys for a while to provide symbol files and they probably will, but who knows when because this task is a low priority one for them. Now, with .net reflector pro I don’t need those files anymore nor I need any other 3rd party vendor symbol files.

The question is why would I want this feature at all?

This question should be asked only by a beginner. Everybody that did some serious development knows how important is to understand how a certain feature in a certain assembly is working, specially when you are presented an exception dialog and you have to understand what happened, what went wrong. Normally if you try digging the call stack to show code some code below your methods

call stack

(double click on a method where you don’t have source code – almost all call stack is gray meaning there is no source code available) you are presented with this informative dialog:

no source code

Go ahead, if you are an assembler guy, click Show Disassembly. For mere mortals disassembler code is useless.

How to use .net reflector pro

Download early access program version from .net reflector pro forum, unzip it somewhere and run reflector.exe. By running the executable for at least once you will register the Visual Studio addin that integrates .net reflector pro into Visual Studio. Without the addin registered nothing will happen in Visual Studio.

Run Visual Studio. Take note that there is a new root menu entry - .NET Reflector. Next create a test application – mine will be a WinForms one hosting a single SimpleButton from DevExpress. I’ll implement its Click event and put a breakpoint there. No additional code.

Run the application. If you have turned on Just My Code debugging setting then you’ll be prompted by a .net reflector dialog like this:

turnoffjustmycode

You have to turn off Just My Code feature. This is the same restriction as with symbol files. Then you’ll be presented another dialog where you can select which assemblies are you interested in:

assemblyselection

Select all assemblies. Once you hit OK button .net reflector will start decompiling assemblies by using all available cores on the computer (note that there are many entries in “In progress” state running in parallel).

decompiling

This is the first application I use that actually use all of my Core i7 4+4 cores. Good job and very smart because decompiling so many assemblies even in parallel takes a around 10 minutes on my Core i7 920 computer. But don’t fear – the results are cached and next run there is almost no performance hit at the start. That’s it for configuration and single window application will finally run.

The application will present a default window with a single button. Click on the button and execution will hit a breakpoint you’ve put in button’s Click handler. Look at the call stack again - it isn’t gray anymore:

newcallstack

And double clicking on the BaseButton.OnClick call stack entry opens decompiled source code from DevExpress assembly with everything except the Edit&Continue feature.

kickass

Let me repeat. The code above comes from an assembly decompilation and it is almost as useful as normal source code in debugger. You can inspect the variables and step forth and back but, of course, you can’t change it. Or better, you can change it but it won’t be recompiled.

No more black boxes! Now, if this isn’t an awesome feature, a must must have one, I don’t really know what such a feature is.

There is a slight drawback though: pro version won’t be free, which isn’t a big surprise and not a big issue. The regular version will continue to be free but it won’t have the *feature*. Also currently, being in beta, there are some bugs here and there which should disappear by RTM I guess.

More (official) information on this Alex Davies' blog post.

Tags: , , ,

Visual Studio | Visual Studio | VS Add In | VS Add In | Parallel programming | Parallel programming | Red Gate | Red Gate

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

by Miha Markič2. October 2009 10:57

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.

Tags:

.net | VS 2008 | asp.net mvc | CodeRush | CodeSmith | DXCore | DXCore plugin | Presentation | Visual Studio

Putting sleepless Windows 7 to sleep

by Miha Markič21. September 2009 09:11

A while ago I had the problem with Vista. The thing was that it woke up randomly from the sleep state. The same problem reappeared when I’ve upgraded to Windows 7 x64. But the solution I’ve found previously didn’t work anymore. Even turning off all wake up features for each device didn’t make any difference. Computer would just wake up in the middle of night and stay awake. Besides unpleasant noise there is also unnecessary power consumption.

However it looks like I’ve found the solution once again and this time it is a much more clean and an obvious one. Go to Control Panel, Power Options and click on Change plan settings of the currently selected plan.

poweroptions

Next click on Change advanced power settings

balanced

And finally disable Allow wake timers in Sleep node.

final

That’s it. Your Windows 7 computer will sleep like a baby again.

Tags:

Windows | Windows 7

Reversing for loops with CodeRush

by Miha Markič17. September 2009 13:19

Imagine you have to delete a bunch of items from a list, something like this:

List<int> items = new List<int>();
...
for (int i = 2; i < items.Count; i++)
{
items.RemoveAt(i);
}

Will it work? Of course not because you are removing items while your are looping the entire list. That means sooner or later you’ll bump against out of index exception or items silently won’t be removed. And this is a common mistake we all do I suppose.

The solution is a pretty easy one – reverse the for loop, like this:

for (int i = items.Count - 1; i >= 2; i--)
{
items.RemoveAt(i);
}

However I find writing reverse loops harder than the former one. Not sure why but I guess that’s how I am used to do the maths – addition is always easier compared to subtraction.

Luckily there is CodeRush to the rescue. Just execute the Reverse For Loop code reformatting (not refactoring because you do change the meaning of the code with this one) and you are done.

cr

It works the other direction as well. Until today I didn’t even know that this trick exists. I just assumed it does and it sure did exist. This and a “million” of other features makes CodeRush really a must have coding tool.

Tags:

.net | CodeRush | DevExpress | Visual Studio

Investigating Windows BSOD cause for dummies

by Miha Markič13. September 2009 21:57

Does your Windows displays nice, we all love, BSOD once in a while or perhaps, god forbid, often? There are two most plausible suspects for this behavior. And no, it is rarely Windows fault. Instead it is either hardware or driver and I won’t even dig into the quality of drivers produced by various hardware companies.

But the big question here is, which one? Which driver? Which hardware? It is even harder to pinpoint the cause in case when BSOD occurs at random times. Luckily there is a tool that might shade some light on the mystery and point cyber finger at the offending driver: Microsoft Debugging Tools for Windows.

Recipe for using Debugging Tools

The recipe is shown on Windows 7 but it is very much the same for other Windows flavors.

1. Make sure your BSODs are producing memory dumps.

  1.  
    1. Right click on Computer, pick Properties
    2. On the left side click Advanced system settings
    3. Select Advanced tab, you’ll see this window
      dm1
    4. Click Settings… button in Startup and Recovery Group to see this window
      dm2
    5. Make sure that Kernel memory dump or at least Small memory dump (256KB) is selected (it should be on by default). That way Windows will store the forensic evidence of the crash.

2. Install appropriate (x86, x64 or Itanium) version of Microsoft Debugging Tools for Windows.

3. Run WinDbg debugger (installed as a part of package in previous step) as administrator (Right click/Run as administrator).

4. Setup symbols server path so the tool can output human readable information instead of hex codes.

Pick File/Symbol File Path… menu item and enter the following line into the text box:
SRV*c:\symbols*http://msdl.microsoft.com/download/symbols
This line instructs WinDbg where to download symbols from (in this case it will be public Microsoft server). Also note that c:\symbols is folder on my disk where WinDbg will cache the symbols. You are free to use whatever other folder.
Note: there are other ways for obtaining the symbols, this is just the easiest one.
d1

5. Now you are ready for some real action. If your BSOD produced memory dump you’ll find it in C:\Windows\Minidump folder (default location). Pick File/Open Crash Dump… menu item and search for a memory dump file. Once you open a file WinDbg will present you a window like this (note, the first time it make take a while because WinDbg will download symbols from the internet):
d2
Here you’ll find the first clue of the offender, see line which starts with Probably caused by. The text probably won’t tell you much more, so here is the magic wand command.

6. Either click on !analyze –v or type it into the command line at the bottom and press enter. A better description of the error will appear such as this one:
d3
Here is a much more (human readable) information you can use to understand the cause of the BSOD. There is an offending process or driver and even a call stack. Specially the former should give you a hint who is causing the problem. Or perhaps you’ll find it in the call stack among system functions. Unfortunately the given sample is not the best one because at the moment I don’t have any better since I didn’t run into BSOD for a long time except the given sample on my wife’s computer. Csrss.exe doesn’t tell me much because the real source is hidden probably by a hardware issue. But if it was soundblaster.dll or nvidia.dll or ati.dll it would be very obvious who is the cause, wouldn’t it.

Here is my advice: search for a known dll/exe on this screen and if you find one you probably found the cause.

Well, I am not a die hard debugging guy but I often did find the cause of my BSODs this way. I am sure skilled people can use WinDbg much better than me. However often you’ll be able to understand the BSOD cause by yourself simply running WinDbg and !analyze –v command. And you’ll agree that there is no better feeling than solving such an annoying problem by yourself.

Happy hunting!

Tags:

Windows

SLODUG and SLOWUG picnic today

by Miha Markič9. September 2009 12:05

SLODUG and SLOWUG members don't forget that today is the picnic day!

Tags:

SloDUG | Slovenia

Suppress system menu when right clicking on DevExpress skinned form's icon

by Miha Markič14. August 2009 16:36

Task

Today I've got a requirement from my customer to prevent showing the system menu when WinForm's icon (top left) is right-clicked. The form is painted by DevExpress skin. Here is how I've done it.

Solution

1. Intercept proper mouse messages

I had to intercept two mouse messages: WM_NCRBUTTONDOWN (0xa4) and WM_NCRBUTTONUP (0xa5). These two guys shows up when right click is performed on non client (NC) are of the form (where icon is located). That’s also the reason I couldn’t use Mouse* events which fire only for client area.

The interception is done by overriding Form's WndProc method and it looks something like this:

...
enum MouseMessage
{
WM_NCRBUTTONDOWN = 0xA4,
WM_NCRBUTTONUP = 0xA5
}
...
protected override void WndProc(ref Message msg)
{
switch ((MouseMessage)msg.Msg)
{
case MouseMessage.WM_NCRBUTTONDOWN:
case MouseMessage.WM_NCRBUTTONUP:
// code here
break;
}
base.WndProc(ref msg);
}

2. Finding icon bounds

If you are doing DevExpress form skinning it means that your form has to derive from XtraForm which does all of the skinning work for you. XtraForm holds a reference to FormPainter instance (which is responsible for painting the skin) through FormPainter property which in turn holds the icon bounds through its IconBounds property of Rectangle type. Now, the problem is that FormPainter.IconBounds property is protected and reflection has to be used to retrieve the value:

...
private PropertyInfo iconBoundsInfo;
...
public MyForm()
{
...
// store reference to IconBounds property to increase the performance
iconBoundsInfo = typeof(FormPainter).GetProperty("IconBounds", BindingFlags.Instance | BindingFlags.NonPublic);
...
}
protected override void WndProc(ref Message msg)
{
...
Rectangle iconBounds = (Rectangle)iconBoundsInfo.GetValue(FormPainter, null);
...
}

3. Figuring out if right click is within icon bounds and ignore such clicks

To get the click’s location I simply used Cursor.Position which is easier than retrieving the position from Message but less accurate – still enough for me.The position is in screen coordinates and they have to be transformed to form's coordinates. Form.PointToClient method won’t help because it transforms to form’s client area which border isn’t. The solution to this is rather simple – just Offset the position by Form’s –Left, –Top.

If click is positioned within icon bounds just return without delegating to base.WndProc. That’s it. Here is the complete code:

public IgnoreRightIconClickForm: XtraForm
{
enum MouseMessage
{
WM_NCRBUTTONDOWN = 0xA4,
WM_NCRBUTTONUP = 0xA5
}
private PropertyInfo iconBoundsInfo;

public IgnoreRightIconClickForm()
{
iconBoundsInfo = typeof(FormPainter).GetProperty("IconBounds", BindingFlags.Instance | BindingFlags.NonPublic);
}

protected override void WndProc(ref Message msg)
{
switch ((MouseMessage)msg.Msg)
{
case MouseMessage.WM_NCRBUTTONDOWN:
case MouseMessage.WM_NCRBUTTONUP:
// prevent showing system menu on window's icon rightclick
Rectangle iconBounds = (Rectangle)iconBoundsInfo.GetValue(FormPainter, null);
Point cursorPosition = Cursor.Position;
// offset to the raw window's coordinates (PointToClient transforms to window's client coordinates)
cursorPosition.Offset(-Left, -Top);
if (iconBounds.Contains(cursorPosition))
return;
break;
}
base.WndProc(ref msg);
}
}

Notes

This method works only for DevExpress skinned forms. If you want to use for normal forms the you should modify the icon bounds retrieval.

Tags:

.net | .net | DevExpress | DevExpress

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

by Miha Markič6. August 2009 19:06

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.

Tags: ,

VS 2008 | .net | Visual Studio | VMWare | Deployment

Microsoft Tag beta

by Miha Markič24. July 2009 15:26

It goes basically like this: Sign up, create one or more tags (the image is generated on the server), make a sticker with tag image and once people scan the image with a mobile phone or some other mobile device they get the action you associate with the tag (i.e. open an URL). Simple and effective.

Even on my lame HTC TyTN II Windows Mobile device all it takes is a click to start the application and pointing phone’s camera to the printed tag. (to install the Tag application on the mobile phone you should browse the http://www.microsoft.com/tag using your phone’s browser)

Here is an example that will redirect you to this blog. Note that images aren’t fixed sized.

Righthand's_blogYou can test Microsoft Tag for free.

Tags:

Windows Mobile | Beta

Miha Markic

About me
Righthand
 
Microsoft MVP
 
Developer Express' MVP
INETA Country Leader for Slovenia
INETA Country Leader for Slovenia

Slovene Developer Users Group Lead
Friends of Red-Gate
LLBLGenPro Partner

Miha currently works as a free lance consultant and software developer specialized in .net area.
He graduated in Computer and information science at the University of Ljubljana, Slovenia. He has accumulated experience in various programming languages such as Java, Visual Basic 3-6 (MCP), Visual C++, Delphi, C# and VB.Net through years.
He has experience in practically all (technical) stages of project development, including planning, framework development, user interface, business processes, as well as testing and documenting. He has worked on big and small projects in Slovenia and abroad (e.g. participated in completing level 3 IS for the Nucor steel plant, Hertford, USA).
Currently he enjoys programming in .net environment using C#. Since 2000 he has been active in Developer Express' DX Squad and has been ECDL trainer and tester. He also gives lectures on conferences and other events in Slovenia.

Month List

Tag cloud

Most comments

Richard Richard
1 comments
us United States
Filip Stanek Filip Stanek
1 comments
us United States
Manav Manav
1 comments
us United States

RecentComments

Comment RSS