Matt Casto's .NET Journal RSS 2.0
 Friday, June 15, 2007
If you've ever been annoyed about having to activate a window, or part of a window, in order to scroll with your mouse wheel, then KatMouse is for you. KatMouse is a free application that allows you to scroll the window below your mouse cursor, even if it's not the active window or is behind other window(s). It's so simple that it's a no-brainer install.

I heard about this app from Roy Osherove's recent utilities post. Roy also mentions AutoHotKey, which is an excellent little open source keystroke/scripting app. The cool thing about AutoHotKey is that you can create automation scripts, compile them, and then run them on client machines without installing any software.

Labels:

Friday, June 15, 2007 6:43:00 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
tools
 Friday, May 25, 2007
While coding this morning, I needed to quickly find an entity object in an array, so I used the generic List's Find method.
Entity match = new List<Entity>(someEntityArray).Find(
delegate(Entity test) { return test.Id = someId; } );

Later, when I tried to build, I was getting a very unhelpful compiler errors.
error CS1502: The best overloaded method match for 'System.Collections.Generic.List.Find(System.Predicate)' has some invalid arguments
and
error CS1503: Argument '1': cannot convert from 'anonymous method' to 'System.Predicate'


These errors didn't make sense to me, but I tried creating a Predicate object, then passing that into the Find method by moving some code around.
Predicate<Entity> pred = delegate(Entity test) { return test.Id = someId; };
Entity match = new List<Entity>(someEntityArray).Find(pred);

At this point, I'm getting the compile errors
error CS1662: Cannot convert anonymous method block to delegate type 'System.Predicate' because some of the return types in the block are not implicitly convertible to the delegate return type
and
error CS0029: Cannot implicitly convert type 'long' to 'bool'


"Ah, now we're getting somewhere," I thought to myself, "but why would the anonymous method be converting long to bool? D'oh!"

I bet a good portion of other developers reading this blog (assuming anyone does) probably noticed the problem at once. The old single equals sign instead of double equals sign in a comparison. Going back to my original code and adding an equals sign compiles fine.
Entity match = new List<Entity>(someEntityArray).Find(
delegate(Entity test) { return test.Id == someId; } );

This all got me wondering why the compile error was so far off. I did a quick google for the original error message and came across this blog post where Avner Kashtan had a similar problem and he ended up getting feedback from Microsoft that this is the correct behavior, although misleading, and things should be improved with lambda expressions.

Labels:

Friday, May 25, 2007 10:19:00 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
c#
Patrick Cauldwell has posted an excellent general purpose manifesto for developers on any project - This I Believe ... the Developer Edition.

The post a very nicely condensed list of development guidelines and practices. I think it would be useful for every project to have a manifesto like this for developers to reference and keep everything on track.

Labels:

Friday, May 25, 2007 7:09:00 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
methodologies
 Thursday, May 24, 2007
I was writing some code today for a utility method to format names. You know, one of those functions that you find yourself writing even thought you've probably done it lots of times in the past, but you can't find the previous versions.

I got to the part where it returns different values if other values are available, and realized something as I wrote the following code.

if (!string.IsNullOrEmpty(lastName))
return lastName;
else if (!string.IsNullOrEmpty(firstName))
return firstName;
else if (!string.IsNullOrEmpty(middleName))
return middleName;
else
return string.Empty;

I realized that I could probably condense that into one line if I could chain together the variables with null coalescing operators. "What the hell," I thought, "I'll give it try and see if it compiles."

return lastName ?? firstName ?? middleName ?? string.Empty;

Sure enough, it compiles. And it works!

It's always a nice feeling to write beautiful code.

Labels:

Thursday, May 24, 2007 11:57:00 AM (Eastern Standard Time, UTC-05:00)  #    Comments [6] -
c#
 Saturday, March 31, 2007
The support for extending existing types with custom methods in Orcas is something I've been fairly excited about for a while. Extension methods provide way to inject your static own method into someone else's type, where it will appear as if it was an instance method defined on that type.

A Simple Example

In many of my projects, I have enumerations decorated with a description attribute and a static method in a utility class which will return the description of an enum value. This provides a way to have a user friendly description of an enum value. Now I can take that method in the utility class, modify it slightly to be an extension method, and have better looking, more intuitive and highly discoverable code.

Let's say we have an enumeration of report titles.

public enum ReportTitle
{
[EnumDescription("TPS Report")]
TPS,
[EnumDescription("Summary Report")]
Summary,
[EnumDescription("Expense Breakdown Report")]
[EnumDescription("Expense Report")]
ExpenseBreakdown,
Unknown
}

My .NET 2.0 utility method to get enum descriptions looks like this:

public static string GetEnumDescription(Enum enumValue)
{
if (enumValue == null)
return string.Empty;

Type enumType = enumValue.GetType();
Type descType = typeof(EnumDescriptionAttribute);
FieldInfo fi = enumType.GetField(enumValue.ToString());
object[] descAttrs = fi.GetCustomAttributes(descType, false);

// concatenate multiple descriptions
string desc = string.Empty;
foreach (EnumDescriptionAttribute descAttr in descAttrs)
desc += (desc.Length == 0)
? descAttr.Description
: ", " + descAttr.Description;

if (desc == string.Empty)
desc = enumValue.ToString();

return desc;
}

I don't think I really need to show the EnumDescriptionAttribute code or code that gets report titles, because there are no surprised there. As an aside, if anyone wonders why I'm not using System.ComponentModel.DescriptionAttribute, its because that attribute doesn't support multiple decorators on a single type.

This example code re-written with Visual Studio Orcas March CTP looks like this:

public static string Description(this Enum enumValue)
{
if (enumValue == null)
return string.Empty;

var enumType = enumValue.GetType();
var descType = typeof(EnumDescriptionAttribute);
var fi = enumType.GetField(enumValue.ToString());
var descAttrs = fi.GetCustomAttributes(descType, false);

// concatenate multiple descriptions
var desc = string.Empty;
foreach (EnumDescriptionAttribute descAttr in descAttrs)
desc += (desc.Length == 0)
? descAttr.Description
: ", " + descAttr.Description;

if (desc == string.Empty)
desc = enumValue.ToString();

return desc;
}

And the enum value's description is easily found through intellisense:

report.Description()

I can also take it a step further by refactoring my code to include a generic extension method that returns all custom attributes from a value's type, and another that joins an array of strings into one comma delimited string.

public static string Description(this Enum e)
{
var attrs = e.CustomAttributes<Enum, EnumDescriptionAttribute>();
var descs = new List<string>(attrs.Count);
attrs.ForEach(a => descs.Add(a.Description));
return descs.Join();
}

public static List<TAttr> CustomAttributes<T, TAttr>(this T obj)
where TAttr : System.Attribute
{
var fi = obj.GetType().GetField(obj.ToString());
var attrs = fi.GetCustomAttributes(typeof(TAttr), false);
return new List<TAttr>((TAttr[])attrs);
}

public static string Join(this List<string> values)
{
return values.Join(", ");
}
public static string Join(this List<string> values, string delimiter)
{
string result = string.Empty;
values.ForEach(v => result += (result.Length == 0) ? v : delimiter + v);
return result;
}

Of course, the custom attributes method still needs to be refactored to support other types.

Useful For More Than Utility Methods

Since extension methods can be used on sealed classes, they could also be used to hide methods from a publicly distributed assembly by putting extension methods in a non-distributed assembly. Of course, you could also accomplish this with a partial class. Sure, there are probably plenty of reasons why this would be a bad idea, but I get hyper over syntax additions, even if they're not really offering anything that you couldn't do before with more mundane code.

There seems to be a lot of controversy over whether extension methods are a good practice and should be part of object oriented programming. Some of the reasons I've seen people use to not use extension methods are that they complicate code discoverability, they will make code reviews more difficult, they don't follow object oriented principles, or even that they contradict best practices published previously by Microsoft. I think Scott Wisniewski of the VB Compiler Team does a great job addressing the benefits of extension methods in his introduction to an excellent series of in depth blog posts, which are also a good read to get a VB.NET perspective on the new feature.

Labels: ,

Saturday, March 31, 2007 2:08:00 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
betas | c#
 Friday, March 30, 2007
Every good developer knows that you don't want to spend too much time optimizing code as you're writing it. Premature optimization is Eric Gunnerson's 4th deadly sin of programming. I don't think that's over-exaggerating the problem.

But how do you know when you're going too far? Let's say you're writing a class that will be transferring data to or from somewhere else. When you find yourself thinking something like, "What if there's a ton of data being transferred? I need to change the format and consolidate information to make sure we send as little as possible." you're optimizing prematurely. You don't know that you'll run into that situation, and if you fix it now you're spending time fixing a problem that may never exist.

I recently ran into a situation like this, but instead I was thinking something more like, "According to the customer, there will possibly be tons of data to work with." Now I know that there will be a lot of data, so it's not premature to think about how that will affect performance. However, I don't know how bad my code will perform with the amount of data we'll have at production, so I don't know for sure that I need to spend time on the issue. There actually isn't an issue yet, even though the likelihood of a problem is much higher. Do I want to optimize in this case?

The feedback I got from my team was to not spend any time on optimization until the problem actually exists. I think there's a fine line between premature optimization and optimization based on known factors. I'm still not sure if I'm doing the right thing, but I'm going to follow the methodology and see how it works out.

Labels:

Friday, March 30, 2007 6:43:00 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
methodologies
 Monday, March 12, 2007
I made my first attempt at TDD last week and I definitely like the results. I feel like writing a test first lead me to a much more structured way to writing my code. I felt more in control of where I was going since I already knew what my code would ultimately need to do. Also, having a list of build errors (because of methods being called that don't exist) kept me focused on what I needed to be doing next. I think I still have a lot to learn about this, but I'm happy about my experience so far.

One thing I need to work on is code coverage, but I still have that nagging feeling that spending too much time writing test cases is slowing me down.

Labels:

Monday, March 12, 2007 8:14:00 AM (Eastern Standard Time, UTC-05:00)  #    Comments [2] -
methodologies
 Tuesday, March 06, 2007
I was about to post about how upset I was that the March CTP of Orcas was only available as an over 4GB! Virtual PC image. Then, when searching for a link for this blog post, I found "Orcas" Related CTP Downloads, which has a link for a self-extracting installation to use instead of an image. Huzzah!

Labels:

Tuesday, March 06, 2007 11:22:00 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
betas
 Thursday, February 01, 2007
I just received the copy of Windows Developer Power Tools O'Reilly sent me as thanks for my participation on Windows Developer Tools Day two weeks ago. It's a massive book, but seems to be organized so well that it will be easy to read a chapter or two each evening.

In fact, after seeing Jim Holmes' post about the WinDevPowerTools Rollout, I went there and set up my own profile. As tools are added to the site, and as I'm able to check out more tools that I read about on the book, I'll update my profile there.



A lot of the tools that I use regularly either haven't been added to the list or aren't covered by the book. I'm not sure about what's covered by the book yet because I haven't had any time to dig into it yet. I would love it if I could add tools that I use that might not have been covered by the book.

Labels:

Thursday, February 01, 2007 10:07:00 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
tools
Central Ohio Day of .NET

About the author/Disclaimer

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

© Copyright 2008
Matt Casto
Sign In
All Content © 2008, Matt Casto
Theme based on DasBlog theme 'Business' created by Christoph De Baene (delarou)