Method I Wish Was There: ContainsDigit

Sometimes when dealing with lots of strings or parsing text, I don’t always want to turn directly to regular expressions. I might want to just say “if this thing has a digit”.

public static bool ContainsDigit(this string source) {
  return @"\d".Regex().IsMatch(source);
}

This uses yesterday’s Regex() extension method on string and simply returns true or false, exactly as it reads.

string field1 = GetFieldFromSomeParserOrSomething();
if (field1.ContainsDigit()) …

Method I Wish Was There: Regex

I don’t want to have to pull in System.Text.RegularExpression every time I want a new Regex. Perl, boo, awk and javascript just say // for regex. In C#, I can just say “abc\d{3}”.Regex().

public static System.Text.RegularExpressions.Regex Regex(this string source)
{
  return new System.Text.RegularExpressions.Regex(source);
}

Now I can write:

if (“there are (\d+) lights”.Regex().Match().Groups[1].Value > 0) …

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)) …

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.

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.

Learning WPF… For real this time.

I’ve been diving into WPF, again.

WPF is different now and will be even more different in 4.0. The WPF Toolkit is not an “option” in 3.5, it is a requirement. Just like I wouldn’t want to write .NET Code without certain 3rd party libraries (castle, elevate, etc..), I would not want to write WPF without the toolkit.

WPF in .NET 4.0 includes many things from the WPF Toolkit. The one thing that makes Winforms developers like me feel right at home is DataGrid, but the WPF DataGrid is not DataGridView for WPF. I keep running into surprises.

The latest surprise had to do with a prototype I was building. In Winforms, I often just databind a DataGridView to any IList<T>, and let magic do the rest for me. After all, it is just a prototype.

I tried to do the same thing with WPF DataGrid and I was met with a surprise. Surprise! Don’t do that. As soon as I changed from a IList<T> to an ObservableCollection<T> the binding worked. AutoGenerateColumns=”True” makes it very easy to prototype.

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.