Read posts about .net

April 16

C# vs F#: some parallel refactoring (and generalization) (MrKurt) by Kurt

So, shortly after adding the more in depth examples in my last post, I started playing around with the TryParse method in C# to see how "nice" I could make the example code:

public class User
{
    public int Age { get; set; }
    public DateTime SignupDate { get; set; }
    public Double Weight { get; set; }
 
    static string Post(string key)
    {
        return key;
    }
 
    static User Build()
    {
        var age = 0;
        var signupDate = DateTime.MinValue;
        var weight = 0.0;
 
        int.TryParse(Post("age"), out age);
        double.TryParse(Post("weight"), out weight);
        DateTime.TryParse(Post("signupDate"), out signupDate);
 
        return new User
        {
            Age = age,
            SignupDate = signupDate,
            Weight = weight
        };
    }
}

The first attempt I made involved a generic ParseOrDefault function and a corresponding TryFunc delegate:

delegate bool TryFunc<t>(string raw, out T value);
static T ParseOrDefault<t>(TryFunc<t> method, string raw)
{
    var local = default(T);
    method(raw, out local);
    return local;
}

Sadly, using that function in the most natural way possible caused type inferencing errors, so the end result of that little bit of work was this code:

var user = new User
{
    Age = ParseOrDefault<int>(int.TryParse, Post("age")),
    SignupDate = ParseOrDefault<datetime>(DateTime.TryParse, Post("signupDate")),
    Weight = ParseOrDefault<double>(Double.TryParse, Post("weight"))
};

It's not terrible, but the redundant type specifiers really chafe. The code could be much prettier with a smarter C# compiler.

As a fun little exercise, I also spent time making the F# from the previous example something more appealing. The original F# looked like this:

type User = { Age : int; SignupDate : DateTime; Weight : Double; }
 
let post key = key
 
let u =
    {
        Age = Int32.TryParse(post "age") |> snd;
        SignupDate = DateTime.TryParse(post "signupDate") |> snd;
        Weight = Double.TryParse(post "weight") |> snd;
    }

I started down the same path, with the F# equivalent of ParseOrDefault from above:

let parseOrDefault f v = f v |> snd

parseOrDefault takes a function (named f) and a value as parameters. It pipes the result of f(v) to the built in second function, which returns the second value in a two-value tuple.

Using that function lets me change my F# to something like this:

 
let u =
    {
        Age = post "age" |> parseOrDefault Int32.TryParse;
        SignupDate = post "signupDate" |> parseOrDefault DateTime.TryParse;
        Weight = post "weight" |> parseOrDefault Double.TryParse;
    }
 

It's actually a little bit more text than the original, but it seems a bit more straightforward to me. "Send the result of the post function to my parseOrDefault function, which should use Int32.TryParse to do its thing."

The level of repetition in that last bit of code annoys me, though. Fortunately for me, creating new functions in F# is such an easy task that I can do this instead:

 
let u =
    let parsePosted f key = parseOrDefault f (post key)
    {
        Age = parsePosted Int32.TryParse "age";
        SignupDate = parsePosted DateTime.TryParse "signupDate";
        Weight = parsePosted Double.TryParse "weight";
    }

Doing the equivalent in C# is just not worth it, at least in this case. A generic ParsePosted function would have to be a static member somewhere, since you can't do this in C#:

Func
<tryFunc<t>,string,T> ParsePosted =
    (method, key) => ParseOrDefault<t>(method, Post(key));
var user = new User
{
    Age = ParseOrDefault<int,string>(int.TryParse, Post("age")),
    SignupDate = ParseOrDefault<dateTime,string>(DateTime.TryParse, Post("signupDate")),
    Weight = ParseOrDefault<double,string>(Double.TryParse, Post("weight"))
};

Local, one-off functions are possible in C#, but I can't find any way to create a generic one. That really sucks at times like this when we're dealing with types that aren't anywhere in the same inheritance chain.

There's another interesting aspect to the F# version of the parseOrDefault method. F# automatically generalizes it to the equivalent of this in C#:

 
delegate bool TryFunc<t, K>(K raw, out T value);
static T ParseOrDefault<t,K>(TryFunc<t> method, K raw)
{
    var local = default(T);
    method(raw, out local);
    return local;
}
 

This version of the function might come in handy if I ever need the TryGetValue function of a dictionary with some-type-other-than-string as a key. The downside in C# is that it gets terribly verbose to use that kind of function, due to the limits in type inferencing:

 
return new User
{
    Age = ParseOrDefault<int,string>(int.TryParse, Post("age")),
    SignupDate = ParseOrDefault<dateTime,string>(DateTime.TryParse, Post("signupDate")),
    Weight = ParseOrDefault<double,string>(Double.TryParse, Post("weight"))
};
 

As I get deeper into F#, I'm beginning to realize just how empowering it is for function creation and composition to be such a cheap (from a development time perspective) operation.

kick it on DotNetKicks.com

Posted in: .net , c# , f# , generics , refactoring , tuples , type inferencing
April 8

Tuples rock my world (MrKurt) by Kurt

Value types in the .NET framework tend to have a static TryParse method for converting a string to a typed value.  Well, most of them do, the Guid type doesn't for some reason.  The method takes a string and an output parameter for the result.

Output parameters suck and require a local variable to be passed in, resulting in a ton of useless supporting code:

int val = 0;
string raw = "1234";
bool success = int.TryParse(raw, out val);
// success is true
// val is 1234
 

As I was working through the Expert F# book, I came across a neat little F# trick for dealing with .NET output parameters. When you leave the output parameter off of the method call, the function returns a tuple. Here's some overly explicit F# to demonstrate:

let raw = "1234"
let result = Int32.TryParse(raw)
(* result is (true, 1234) *)
 
let success, value = result
(* success is true *)
(* value is 1234 *)
 

The result value is particularly interesting to me, since I've not really used a language with the concept of tuples before. A tuple is basically a grouping of several values into a single value. The "let success, value..." line above is decomposes the result tuple into two separate values. You can read more about tuples in .NET if you'd like.

If we wanted to do it all as one assignment:

let success, value = Int32.TryParse("1234")
(* success is true *)
(* value is 1234 *)
 

This feature is really very small, but I've been annoyed enough about having to initialize extra variables for out parameters in the past that I really got a kick out of it.

Update: Just to clarify what I mean by "tons of useless supporting code", here's a slightly longer (and equally contrived!) example to illustrate the type of bloat I've run across:

If I were to build a User object from post data, the code might look something like this in C#:

public class User
{
    public int Age { get; set; }
    public DateTime SignupDate { get; set; }
    public Double Weight { get; set; }
 
    static string Post(string key)
    {
        return key;
    }
 
    static User Build()
    {
        var age = 0;
        var signupDate = DateTime.MinValue;
        var weight = 0.0;
 
        int.TryParse(Post("age"), out age);
        double.TryParse(Post("weight"), out weight);
        DateTime.TryParse(Post("signupDate"), out signupDate);
 
        return new User
        {
            Age = age,
            SignupDate = signupDate,
            Weight = weight
        };
    }
}

The alternative F#, however, is quite a bit more concise. Even better, it's much more declarative:

type User = { Age : int; SignupDate : DateTime; Weight : Double; }
 
let post key = key
 
let u =
    {
        Age = Int32.TryParse(post "age") |> snd;
        SignupDate = DateTime.TryParse(post "signupDate") |> snd;
        Weight = Double.TryParse(post "weight") |> snd;
    }

Now, there are a lot of other niceties in the F# version as well. But the important bit is that I can take the resulting tuples from the TryParse operations, pipe them into a the snd function, and suddenly I have valid values for my fields. snd does just what it's short for: it returns the second value in a two value tuple.

kick it on DotNetKicks.com

Posted in: .net , f# , tuples
August 14

My baby* (MrKurt) by MrKurt

I recently quit my job and moved to the sticks** to work full time on a bit of my own software.  It’s really very exciting.

The software is actually a continuation of a teeny little site I whipped up (which is no longer online) back in college for a class project.  Since that time, I’ve dinked around with it in my free time, devoted some nights to it to get Ars Technica up and running on it, and generally felt as though I haven’t made much progress on it.

I started looking at options for working on the thing full time about four months ago.  One of the first things I did was create a spreadsheet and figure out how much I thought it would cost to develop and market it for a year.  The number came out smaller than the total credit limit available to me on a couple of cards.  I figured I’d quit my job, and toil away while accumulating copious amounts of debt.

ramen Fortunately, things worked out slightly differently.  I was able to acquire a few contract projects that would cover the bare minimum of living expenses, so no crazy credit card debt required (yet).  We’re not precisely “rich” and we’re beginning to really enjoy the luxury that is Ramen, but it’s not an entirely bad way to live.

The publishing system is shaping up nicely, and it’s been wonderful to have a week and a half to work on it full time.  At the moment, it’s designed specifically for webzine*** sites, much like Ars Technica.  It’s very good at handling a couple of different types of content such sites generally publish, mainly blog/journal style sections, multipage articles, and the few supporting single page/non-content things that every site needs.

The coolest portions of it come directly as a result of using Lucene.net for backend indexing and querying.  Handling multi-value metadata queries is cake with Lucene and much more flexible than trying to build listings using SQL queries.  This is important for two sites that will be using the system in under a month.

For instance, it’s awesome to be able to pass “(Body:xbox OR Tag:(360 OR PS3 OR PSP)) AND Author:(kurt OR bill) AND Featured: true” and get back the right results.

It’s an odd type of application to work on, though.  All the real effort is put into the administrative side of it, which maybe 15 people see per day.  The majority of the “users” who browse the site don’t really get to see some of the more interesting stuff.

* Not my real baby
** Tulsa, OK ****
*** The word webzine really needs to make a comeback, it’s so descriptive and distinct from a “blog”
**** Cost of living in Tulsa is cheap to the point of being free.  And yes, that was a recursive footnote asterisk

Posted in: .net , development , mubble
July 18

Why C# generics are cool, besides the obvious (MrKurt) by MrKurt

In the process of hammering my way through the wholly undocumented SMO goodness available with .NET 2.0 and SQL Server 2005, I stumbled across a relatively cool use of generics.

SQL Server has this concept of "extended properties" available on most database objects and they're great for storing things like table versions if you happen to have the .NET equivalent of Migrations from Rails.  Database objects that allow extended properties implement the IExtendedProperties interface.  I wrote a super simplistic static function to retrieve arbitrary extended property values from these objects:

public static object GetExtendedPropertyValues(IExtendedProperties obj, string name)
        {
            if (obj.ExtendedProperties.Contains(name))
            {
                return obj.ExtendedProperties[name].Value;
            }
            else
            {
                return null;
            }
        }

This is all well and good, until you decide you need another static function to set the extended properties and discover that creating one requires some awesomeness like this:

new ExtendedProperty(obj, name, value)

Where obj is a SqlSmoObject. The problem is, SqlSmoObject doesn't implement IExtendedProperties, that's left to each individual subtype. Enter generic functions:

public static void SetExtendedPropertyValue<t>(T obj, string name, object value)
            where T : SqlSmoObject, IExtendedProperties
        {
            if (!obj.ExtendedProperties.Contains(name))
            {
                obj.ExtendedProperties.Add(new ExtendedProperty(obj, name, value));
            }
            else
            {
                obj.ExtendedProperties[name].Value = value;
            }
        }

This is a nice way of ensuring that an object implements multiple interfaces and inherits from a particular base class. At the same time, using the SetExtendedPropertyValue function is virtually identical to the way you'd use the GetExtendedProperty function. This particular bit of SMO nastiness is well hidden from anyone who uses these functions in the future. I don't like seeing nastiness, so I benefit.

Posted in: .net