Sergio and the sigil

Language Envy - C# needs Ranges

Posted by Sergio on 2010-01-02

As soon as I started learning Ruby, a few years ago, I got immediately hooked on its Range class. I could not believe I had been programming in .NET without them for so long.

I like to think of range objects as the specification for a for loop, packaged in an object that can be passed around. That's not the whole story, though. Ranges also represent sequences or intervals, which can be queried for intersection or containment. See the following Ruby sample code.

#declare a Range object
summer_months = 6..9
#enumerate it
summer_months.each {|m| puts "#{Date.new(2000, m, 1).strftime('%B')} is a Summer month." }
#other handy features
summer_months.include? 7 # ==> true
summer_months.to_a # ==> [6, 7, 8, 9]  (converted to array)

I needed that in C#

That was back when the CLR 2.0 was just about to be released and I ended up writing my own Range

Language Envy - Juicy, a simple webserver

Posted by Sergio on 2009-04-13

Many times when I'm writing JavaScript code with Ajax calls I don't have an URL to call and get the data yet. Or sometimes I have an URL that gives me valid data and I need to test the code against invalid data or some other variation that I don't have handy.

WEBrick

In these situations, instead of creating a temporary ASP.NET application, I learned to love using Ruby and the adorable simplicity of WEBrick. Imagine that I needed an URL that simulated latency on the server.

require 'webrick'
include WEBrick

server = HTTPServer.new( :Port => 2000 )

server.mount_proc("/getData"){|req, res|
  res.body = "{result: 'ok', accountId: 123}"
  res['Content-Type'] = "application/json"
  delay = req.query['delay'] || "0"
  sleep(delay.to_i)
}

trap("INT"){ server.shutdown }
server.start

After running the script I can open use the URL http://localhost:2000/getData?delay=5 in my Ajax call and, after a delay of five seconds, the JSON string {result: 'ok', accountId: 123} will be returned. The server will stay there, in a console window, running until I kill it with CTRL+C.

I could add more mount points on that server for as many test URLs as I wish. I find this incredibly practical.

I wish there was something as simple in .NET

Well, I couldn't find anything as easy in .NET. The few offerings I found were not as straight forward. Some of the alternatives are distributed in .msi files, which makes them less convenient, especially for integration testing or JavaScript unit testing (which is my end goal.)

Hello Juicy

Envy sometimes makes you move forward. I played around with sockets and the HTTP protocol and ended up with a library that looks promising. See that same code written using the Juicy.DirtCheapDaemons.Http.HttpServer class, a.k.a. the Juicy Web Server.

using System;
using System.IO;
using System.Threading;
using Juicy.DirtCheapDaemons.Http;

  class Program
  {
    static void Main(string[] args)
    {
      HttpServer server = new HttpServer{ PortNumber = 2000 };
      server.Start();

      server.Mount("/getData", 
        (req, resp) =>
          {
            resp.Output.Write("{result: 'ok', accountId: 123}");
            resp["Content-Type"] = "application/json";
            var delay = int.Parse(req.QueryString["delay"] ?? "0");
            Thread.Sleep(1000 * delay);
          }
      );

      Console.WriteLine("Press enter to stop server");
      Console.ReadLine();
      server.Shutdown();
    }
  }

There are a few things more that can be done with HttpServer.

//mounting virtual path with a lambda (shown in previous example)
server.Mount("/virtual/path", (req, resp) => DoSomethingWith(req, resp));

//mounting virtual path to serve static files
server.Mount("/virtual/path", @"c:\some\directory");

//hiding a virtual path
server.Mount("/virtual/path/subdir", new ResourceNotFoundHandler());

As it is, HttpServer supports only GET requests. The plan is to add more support (for features that make sense in a unit testing scenario) with time.

I obviously don't envision Juicy becoming a full-fledged web server that I can recommend using in a live web site. But I can see it being helpful in the scenarios I've just described and for testing in general.

I'm sold. Where can I get it?

This project is hosted at GitHub: http://github.com/sergiopereira/juicy/tree/master, where you can download the source directly or even clone the repository :

c:\projects>git clone git://github.com/sergiopereira/juicy.git

Language Envy - String Interpolation

Posted by Sergio on 2009-01-17
Language Envy: This post is part of a series where I wish C# had a particular feature I came to like when working with other programming languages.

Every time I have to produce a string in C# the little groaning chimp that lives inside my head pulls his hair out. It's about time we had a better way of doing this.

We all use string.Format to make these string concatenations more readable, but it's still too easy to get the order wrong or miss one of the argument values and get an exception. JetBrain's Resharper can be helpful here, giving hints when you have too many or too few arguments in a call to string.Format.

So what am I whining about?

When you need to create a string that mixes literals with variables in PHP (or Ruby, or Boo, or Perl, etc) it's so much easier to type, read and maintain than in C#:

<?php
	$price = 12.34;
	$product = "DVD Media";
	echo "$product costs $price";
	//ouputs: DVD Media costs 12.34
?>

Although this would be enough to get a lot done, the interpolation syntax can help with more complicated expressions beyond simple variables:

<?php
	$order = $user->getLastOrder();
	echo "The first item in the order was {$order->item[0]}.";
	//ouputs: The first item in the order was DVD Media.
?>

One interesting thing to note is that this is a syntax for combining expression values and literals. The interpolation isn't evaluated in strings that already exist and are passed in (like some user input.) In other words, the interpolation happens at parsing time, where the string is declared. The parser will not look into an existing string and replace tokens that look like variables — at least not without you explicitly asking it to do so.

In PHP the interpolation goes a little further. Just for the sake of curiosity, check this out.

<?php
	$var1 = 1000;
	$name = 'var1';
	//recursive interpolation:
	echo "The value of the variable named $name is {${$name}}";
	//outputs: This is the value of the var named var1 is 1000 
?>

Wouldn't it be nice to have such syntax in C#? The string would probably need to be taken care of at compile time, so a statement like this:

//DOESN'T WORK YET. JUST A DAYDREAM
var text = "The price of a ${product.Name} is ${product.Price}.";

At compile time would be treated as if it had been written as follows.

var text = "The price of a " + product.Name + 
           " is " + product.Price + ".";
// OR ...
var text = string.Concat("The price of a ", product.Name, 
           " is ", product.Price, ".");

Done like the example above this would be a backwards compatibility problem. I'm sure it's possible to put some symbol before the opening double quote to make this compatible.

Language Envy - hash literals

Posted by Sergio on 2009-01-05
Language Envy: This post is part of a series where I wish C# had a particular feature I came to like when working with other programming languages.

It's easy to let a small language feature go unnoticed. The more I spend time writing JavaScript and Ruby, the more one little detail shows itself loud and clear when I go back to my trusty C# (well, it shows itself by not being absent, if that makes any sense.)

The little language detail I'm writing about today is the literal syntax for hashes. Especially in JavaScript, because all objects are just hashes on steroids, which makes the literal object syntax become one and the same with the hash literals.

In JavaScript it's easy as 1-2-3. It's not surprising so many libraries are adopting hash parameters.

//Prototype.js sample
var elements = { success: 'myDiv', failure: 'errorDiv' };
var ajax = new Ajax.Updater(
	elements, 
	'getData.aspx', 
	{ method: 'get', onFailure: reportError }
	);
//jQuery sample (jQuery UI)
$('#fromDate').datepicker({rangeSelect: true, firstDay: 1});
$("#search").autocomplete("/product/find",
	{ autoFill: true, delay: 10, minChars: 3 }
	);

Now, I understand that part of the popularity of hashes in JavaScript and Ruby is due to the loose typing of these languages. But if the syntax wasn't light, APIs like the above ones would be much more painful to use.

C# 3 does have a hash syntax (or, more accurately, a dictionary one.) Unfortunately, dictionary initializers, although being a step forward, still leave noise to be removed.

// hypothetical search API 
var books = FindWithCriteria<Product>(
              new Dictionary<string,object>
              {
                {"Category", Category.Books},
                {"MinPrice", 33.45},
                {"MaxPrice", 50.00},
                {"Contains", "asp.net"}
              });

Hmmm, no, thanks. Maybe that's the reason we are starting to see some APIs that use (abuse?) anonymous objects and reflection to create hashes.

// hypothetical search API 
var books = FindWithCriteria<Product>(
              new { 
                Category = Category.Books,  
                MinPrice = 33.45,
                MaxPrice = 50.00, 
                Contains = "asp.net" 
              });

This last one doesn't look so bad on the surface, but we know what is going on under the covers so it's like putting lipstick on a pig. If, instead of using reflection at run-time, the compiler had support for converting the above anonymous object into a IDictionary<string,object>, then we would have a more convenient and efficient way of creating hashes. Maybe it's too late to introduce a feature like that while maintaining backwards compatibility.

I believe when you add a language feature that is elegantly designed (i.e. clean and unnoticeable,) it becomes popular more quickly — just like what is happening with lambdas . The existing alternatives for creating hashes in C# 3 are still too noisy or inefficient to be integrated in our code without reducing the readability or incurring a performance penalty.

Language Envy - episode 0

Posted by Sergio on 2008-12-24

Although C# is the language that I can call myself proficient enough to make a living these days, there are other languages that I have to use for specific tasks (like JavaScript, SQL, XSLT.) I also like using other general purpose languages for pure exploration or pet projects. I'd include Ruby, ObjectiveC and PHP in this group.

When using other languages it often happens that I encounter features that I wish C# had or that the C#-equivalent was as easy (it works both ways — I miss some C# feature on the other side as well.)

In this series of undetermined length I will be posting some of the items from my wish list as I remember them.

The case statement

To start things off, let's check out C#'s case statement, straight from the language specification.

switch-statement:
    switch   (   expression   )   switch-block
switch-block:
    {   switch-sectionsopt   }
switch-sections:
    switch-section
    switch-sections   switch-section
switch-section:
    switch-labels   statement-list
switch-labels:
    switch-label
    switch-labels   switch-label
switch-label:
    case   constant-expression   : // <-- line 14
    default   :

I know that doesn't look like C# code. What I'd like to point is in line 14. The expression in each case label has to be a constant. I'm sure that helps making the switch statement compile to a very efficient MSIL code, but let's consider what we are missing because of that.

Here's a sample of what you can do in a Ruby case expression.

SIDE NOTE: The hawk-eyed reader will catch the terminology difference here. Many language constructs that are mere statements in C# are expressions in Ruby. But that's not the feature I'll write about today. Maybe in a future installment.
Months = %w(JAN FEB MAR APR MAY\
        JUN JUL AGO SEP OCT NOV DEC)

def get_month(value)
  case value
    when Date # class name (instance of?)
      return Months[value.month - 1]

    when /\d{4}-(\d{2})-\d{2}/ # Regular expression (matches ?)
      return Months[$1.to_i  - 1]

    when 1..12  # Range of values (contained ?)
      return Months[value - 1]

  end
end

puts get_month(Date.today)
puts get_month("2008-10-20")
puts get_month(8)

As you can hopefully see in the above example, the expressions in each when statement do not need to be constants (class names like Date are constants, by the way)

Ruby defines the === (triple equal) comparison operator that can be overriden in each class and is used in the case expression to test each when condition. This is usually read as "when value matches with this expression here...".

Not surprisingly, the built-in classes in Ruby do override the triple equal operator to add a more meaningful implementation for it. Range matches the values that are within the range. RegExp matches values that agree with the regular expression, Class objects match values that are instances of that class, etc.

I use this feature all the time and it's so convenient that I'd be thrilled to see it in C# one day.

So, what is my suggestion?

I wouldn't be a real programmer if I didn't try to sell my own suggestion, would I? Since IComparable is taken and means something different, I was thinking of maybe something like this.

public interface ICanMatch
Filed under: