Method I Wish Was There: string.Contains

Sure, string has a member method of Contains, but its an exact comparison. What I really want is something that takes a StringComparison argument as well.

public static bool Contains(this string source, string search, StringComparison comparison)
{
  return source.IndexOf(source, 0, comparison) > -1;
}

Not much to this extension method, but it gives me the semantics that I want.

if (foo.Contains("bar", StringComparison.CurrentCultureIgnoreCase)) …

FOSDEM Videos Online 2

I’ve been watching more FOSDEM videos. They are very cool. Watching in 720p is awesome.

Alan McGovern on The Evolution of MonoTorrent – By far the best bittorrent library for .net. Alan talks about the challenges of writing a library that will handle things like hundreds (if not thousands) of simultaneous socket connections, why using threads to do so is wrong, and how good design and the async pattern made it easy and fast.

Stephane Delcroix on Image Processing – I was really looking forward to this one – Mono.SIMD is awesome – but the whole thing is code and the non-bold small font on a white background did not get picked up by the projector. Needless to say that Mono.SIMD is still awesome, but the talk isn’t really worth watching. I’ll be it was cool live though. If you don’t know Mono.SIMD is yet another Mono innovation that is Mono-only. It provides an object oriented api for the underlying SIMD instructions in modern cpus. These are the SSE instructions that you see listed in the spec about your Core2 CPU.

Jeremie Laval on Parallel Fx – This is NOT just another talk on Parallel Fx aka Task Parallel Library+PLINQ. Jeremie actually wrote Mono’s implementation of TPL. While its great to see Stephen Toub show use cases of TPL, the geek in me wants to see what is under the hood. Jeremie gets into some of the challenges in implementing the scheduler and library. He also mentioned that .NET4’s thread pool actually uses the TPL scheduler underneath. I didn’t know that. He also shows a demo of Future<> which I had never considered. Chaining Future<>’s in a tree like manner in order to create parallel delayed evaluation.

Andreia Gaita on Moonlight and You – Why moonlight is important to mono? WOW! They are working on XAML designers for MonoDevelop. I can’t imagine how awesome moonlight development will be on Linux in the future. Moonlight is super close to working in Chrome on Linux. mxap –desktop lets you create moonlight desktop apps launchable with the mopen command. Very cool. Desktop apps in moonlight. Very cool pixel shaders on video in moonlight 3.

Jim Purbrick on Building The Virtual Babel – Mono in Second Life – The virtual worlds in Second Life and how it has progressed for 7 years. Very cool to hear how an existing language LSL and existing virtual machine was moved to a new virtual machine, Mono. I’ve never heard of JavaGoX or Brakes so listening to the description of script migration was rather mind blowing.(very cool)

Joe Shields on OSCTool – learning C# and Mono by Doing – While probably not of interest to a lot of developers, this one hit close to home for me because I was in a position pretty close to Joe’s about 8 years ago. Of course I didn’t know .NET at the time and Mono was still very young, but I do recall playing with some ASMX web services to do things similar to what he was doing. Joe makes a point that python, perl, C and even Java have cross platform difficulties (think HPUX, Itanium, Tru64 etc) of which Mono seems to mitigate much. The audio goes out for a few minutes in the middle, just skip to about 17:00 and watch the demo.

Mirco Bauer on Smuxi – IRC in a modern environment – Just an irc client with some special features. I’ll definitely be looking into this because I’m an IRC junkie, and it also has the exact twitter client that I’ve been looking for since I started using twitter.

FOSDEM Videos online

As a .NET programmer in my day job targeting Windows desktop applications (winforms and wpf), I don’t get to stay on top of much ASP.NET or Mono. The ASP.NET stuff I feel like I have a good enough handle on via channels I use to stay on top of .NET in general (user groups, blogs, etc). Mono gets much less coverage there.

Luckily there are some awesome (720p quality) videos from FOSDEM 2010 of some Mono centric presentations.

Lluis Sanchez Gual on MonoDevelop – I knew MonoDevelop 2.2 had some awesome in it, but I didn’t know about some of the code generation things in it. Think R# mixed with CodeRush. It is very sweet.  Lluis’s Blog is always a good read too.

Ivan Porto Carrero on IronRuby – Poor Ivan had some demo troubles, but overall the presentation was excellent. It is VERY cool to see a Banshee add-in written in Ruby. I don’t think I was reading Ivan’s Blog before, but I am now.

Miguel on Mono – I think this is kind of Miguel’s “State of the Monkey” of the day. Its a status overview with a few deep dives into things. I especially thought it was cool that he went deep (well, deeper than most) into Expression<>.

The videos seem to be coming out slowly. I’m posting these brief summaries of the videos as I watch them, so expect me to link to more as I watch them.

LINQ Abuse with the C# 4 dynamic type

With C# 4 adding some support for dynamic typing one of the first thing that I wanted to do is use it with LINQ.

I want to do this:

dynamic x;
var h = from y in x where y == 1 select y.something;

But I get error messages on both where and select that says

Query expressions over source type ‘dynamic’ or with a join sequence of ‘dynamic’ are not allowed

Major bummer.

But surely there is something I can do. 🙂

*the title of this post starts with LINQ abuse… please don’t comment about how stupid and evil this is. I know it. Instead, consider this an exercise in getting to know C# a little better.

The dynamic type is just sugar for the object type and some attributes to which the compiler pays attention.

Lets use object…

object things = new[] { 0,1,2,3,4,5,6,7, };
var whatIwant = from thing in things
                            where thing % 2 == 0
                            select thing;
// or if you like longhand:
var wiw = things.Where(thing => thing%2 == 0).Select(thing => thing);

How does this compile? Well, by making Where and Select resolve to extension methods on object instead of extension methods on IEnumerable<T> (which is what people USUALLY think of when they think LINQ).

public static IEnumerable<dynamic> Select(this object source, Func<dynamic, dynamic> map)
{
    foreach (dynamic item in source as dynamic)
    {
        yield return map(item);
    }
}
public static IEnumerable<dynamic> Where(this object source, Func<dynamic, dynamic> predicate)
{
    foreach (dynamic item in source as dynamic)
    {
        if (predicate(item))
            yield return item;
    }
}

Extension methods on object, then cast to dynamic (extension methods aren’t allowed on dynamic).

It should be short work to fill out whatever LINQ methods are necessary to make whatever LINQ expressions you wish work against dynamic (object) and now you can use LINQ with a source that is typed dynamic.

Version Control Tools Is More Than Just The Tools

Martin Fowler has an excellent post on Version Control, and he almost got all of the way there, but for more than just a tiny development shop I think he missed a few important pieces.

http://martinfowler.com/bliki/VersionControlTools.html

Martin does say that Mercurial and git get most of the attention and that the choice between the two come down to “…the shadow of github.”

He is dead right, but I’d argue that this is where the recommendability starts. github is awesome. Ask anyone who has used it and I’ve rarely heard anything negative said. But for anything but the tiniest organization outsourcing your VCS to github is not a practical option. There could be IP requirements or legal requirements about keeping source private and just the over cautious nature of people is to want to run VCS in house. github is not open source. gitorious is.

http://gitorious.org/about

You can go checkout the source code to gitorious and run your own in your own internal organization. AWESOME!

I’d never heard of the Mercurial hosting project http://bitbucket.org/ until i read Martin’s post. That is great to know that it exists. But…

The most mature solution is something which is also open source, has the best project management implementation, has the best bug tracking implementation and integration and is just all around awesome. Its called Launchpad.

http://launchpad.net/

Yes, the same software that drives launchpad is open source and you can install and run it for your own team, company, organization or however you are structured.

Launchpad is written by open source volunteers as well as employees of Canonical. You can buy support for Launchpad from Canonical. Launchpad uses the lesser known bazaar DVCS. Martin kindly left out the DVCS which is used by the most prominent Linux distribution, ubuntu, and the most prominent open source database software, MySQL.

Just like GIT is not going away, because linux uses it, and Mercurial isn’t going away because python and google use it, bazaar is not going away, because ubuntu and mysql use it.

My point is that the web hub to your code and the tools surrounding how you get to your code is just as important as the base DVCS tool itself. SVN has always been good, but ViewVC makes it great. GIT is good. github makes it great. Launchpad makes bazaar great. It makes bazaar at least as good of a choice as either git or mercurial.

double.IsNaN is 100 times slower

Its not just your programming group that can’t get it right. I work in a semi-disfunctional group on contract for a client who, not matter how hard we try, doesn’t seem to listen to basic software engineering principles.

I feel a little better (and a great deal worse after thinking about it) when I see that the largest software company in the world deals with some of the same problems.

I found this gem in the WPFToolkit (it is MSPL) source.

// The standard CLR double.IsNaN() function is approximately 100 times slower than our own wrapper,
// so please make sure to use DoubleUtil.IsNaN() in performance sensitive code.
// PS item that tracks the CLR improvement is DevDiv Schedule : 26916.
// IEEE 754 : If the argument is any value in the range 0x7ff0000000000001L through 0x7fffffffffffffffL
// or in the range 0xfff0000000000001L through 0xffffffffffffffffL, the result will be NaN.        
public static bool IsNaN(double value)
{
    NanUnion t = new NanUnion();
    t.DoubleValue = value;

    ulong exp = t.UintValue & 0xfff0000000000000;
    ulong man = t.UintValue & 0x000fffffffffffff;
    return (exp == 0x7ff0000000000000 || exp == 0xfff0000000000000) && (man != 0);
}

 

My jaw was open pretty far for quite a few seconds as I read this.

My Whole App is a LINQ Expression

I just published an application which I consider useful over on codeplex with source hosted on launchpad.

http://wlanchannelinfo.codeplex.com/

https://code.edge.launchpad.net/~evarlast/+junk/WlanChannelInfo

I wrote this because Wifi in my home is very slow. Its so slow I’m tempted to run a network cable to my couch so that even when I’m couch surfing I can have fast access to my server.

In an effort to diagnose my slow Wifi, I tried to see if my neighbors were causing interference by running Wifi on the same or overlapping channel as me. I downloaded netstumbler; it didn’t work. I downloaded some other tool; neither did it.

So I wondered how hard it would be to write my own. It turns out Windows 7 added to the Wlan* api to expose all of the necessary data. After some digging I found the managedwlan project on codeplex. Now I got to play.

Once I figured out the api, I was able to write the entire application with pretty much one LINQ expression:

var client = new WlanClient();
var retval =
from wlanIface in client.Interfaces
from bssentry in wlanIface.GetNetworkBssList()
from network in wlanIface.GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags.IncludeAllAdhocProfiles)
where InterfaceService.GetStringForSSID(network.dot11Ssid) == InterfaceService.GetStringForSSID(bssentry.dot11Ssid)
select new WifiInfo
{
bssentry = GetStringForSSID(bssentry.dot11Ssid),
channel = Wifi.FrequencyChannelMap[bssentry.chCenterFrequency],
frequency = bssentry.chCenterFrequency,
linqQuality = bssentry.linkQuality,
strength = bssentry.rssi,
signalQuality = network.wlanSignalQuality,
wifitype = network.dot11BssType
};

The result of that expression is directly databound to a WPF DataGrid and I can now view the data that I want to.

I really love the platform (C#+.NET) on which I work.

I’m Lazy And I Need My Helpers

public static class NumericExtensions
{
public static bool IsZero(this byte number)
{
return 0==number;
}
public static bool IsZero(this short number)
{
return 0==number;
}
public static bool IsZero(this int number)
{
return 0==number;
}
public static bool IsZero(this long number)
{
return 0==number;
}
public static bool IsZero(this float number)
{
return 0==number;
}
public static bool IsZero(this double number)
{
return 0==number;
}
public static bool IsZero(this decimal number)
{
return 0==number;
}
}

I wanted something like this today as I was toggling between NUnit and MSTest. Sure, Assert.That( something, Is(0) ) is readable, but its not portable. Its NUnit only, and for this project, I can’t do that. I also like the english reading of IsZero() vs. Is(0)

I think I’ve stated before that any code on this blog (c) by me and licensed under the MIT/X11 License, but for certain bits of code, I see no point in that. So I’m going to start tagging code with CC0, Unlicense and/or WTFPL.

TFS is the new SourceSafe in cost

from :
http://blogs.msdn.com/bharry/archive/2009/10/01/tfs-2010-for-sourcesafe-users.aspx

this quote stuck out :

There are 3 main areas that we’ve focused on in 2010 to make TFS attractive to smaller teams:

1. Price – We’re not quite ready to announce the pricing and licensing for 2010 yet but I can tell you that it will be at least as easy and cost effective to get as SourceSafe has been.  Stay tuned for more info on this.

If this is true (and I don’t think it is) it will greatly change the face of .net development organizations over the next few years.

The Ugliest Code I’ve Written in a While

  1. private EventHandler<MyEventArgs> NameObscured1(IMyForm form)

  2. {

  3.             return new EventHandler<NameObscured2>((sender, eventArgs) =>

  4. {

  5.                 form.TabControl.Enabled = false;

  6.                 IAsyncResult iar = null;

  7.                 Action bg = null;

  8.                 bg = new Action ( () => {

  9.                     NameObscured3((s) => {

  10.                         form.StatusLabel.Owner.Invoke(new Action(() => {

  11.                             form.StatusLabel.Text= s;

  12.                             form.StatusProgressBar.Value +=2;

  13. }));

  14.                         return false;

  15. });

  16.                     NameObscured4(sender, eventArgs);

  17. });

  18.                 Action enableForm = () => { form.TabControl.Enabled = true; form.StatusProgressBar.Value = 0; };

  19.                 AsyncCallback callback = (_) => { form.TabControl.Invoke(enableForm); bg.EndInvoke(iar); };

  20.                 iar  = bg.BeginInvoke(callback, null);

  21. });

  22. }

The question is… How can I make this more readable, and is it worth spending the time to do so?

Nesting lambdas to 4 deep cannot be a good idea, but honestly, factoring each one out to a method might actually make this code LESS readable IMO. In this case, it is just a damned shame that some things can be done cross threads in a Windows Forms application.

I’m guessing this is a sign that I am too tightly coupled and should have some kind of mediator which will then Invoke property updates on the correct thread, but I don’t have that now.

Moral of the story: don’t write nasty nested lambdas like me.