Sergio and the sigil

Partial list of sessions for Chicago Code Camp

Posted by Sergio on 2009-04-19

We're happy to announce the first partial list of talks selected for the Chicago Code Camp. We hope there's a good mix of various different technologies and that it could spark even more interest in the event.

There are still a good number of time slots undecided for this event. If you want to submit a talk, you can do that until Saturday the 25th of April. The event will be on May 30th.

AuthorTitleAbstract
Curtis Mitchel Rails-like development using ASP.NET This is a discussion about .NET tools geared towards making your development life easier in ASP.NET. We will discuss and compare these tools with the default Rails technology stack.
Dean Wampler Better Ruby through Functional Programming Functional Programming (FP) has become popular as the most robust way to write concurrent applications. Functional ideas improve code in other ways, like reducing coupling between "elements" and eliminating some "surprises" that occur when objects are mutable. We'll discuss the key ideas in functional programming and the functional features that Ruby already supports. We'll describe how best to use these features and how to work around the missing functional features.
Your will learn:
1) What is Functional Programming (FP)?
2) How FP addresses several programming challenges faced today, like concurrency.
3) How FP improves the overall robustness of Ruby code.
4) Ruby's support for FP: what's supported and what isn't.
5) Practical tips for applying FP ideas in your Ruby code
Derik Whittaker Guarding your code with Code Contracts It is a common practice to put checks into our code to help ensure quality. Historically these checks have come in the form of if/then statements where you were attempting to guard against data out of range data. Although the if/then method works reasonably well, it only solves half our problem. These checks guard against only data coming into a method, not the data coming out of a method. Fortunately for us, there is a project coming out of Microsoft, named Code Contracts, which will help to solve this problem. Code Contracts provides a language-agnostic way to express coding assumptions in .NET programs. In this session we will take a look at how you can utilize Code Contracts within your codebase to take your code quality to the next level.
Eric Smith TDD for the iPhone Currently, the iPhone is the hottest platform for mobile development, with everyone wanting to develop on it. Test Driven Development is a proven technique for developing high-quality software, but isn’t encouraged by the iPhone development platform. Open Source developers have stepped in, creating Unit Test Libraries for the iPhone. We’ll show you how to get started, run your first tests, put tests in your build, and touch on advanced techniques like mock objects and dependency injection. Perfect for the Agile Developer looking to get started on iPhone.
After a brief introduction Eric and I will perform a code “Kata” on the iPhone, writing Conway’s Game of Life. Afterwards we will tell the story of the how the application was built with some code snippets, explaining the steps along the way so they can be repeated by the attendees. Finally this presentation ends with a demo, and a victory lap.

Learning outcomes

  • Setting up Unit Tests on Mac
  • Writing Unit Tests
  • Getting tests in your build
  • Making mocks and using protocols
  • Injecting dependencies into your application at the last minute.
Jim Suchy iPhone on Rails You don't have to use Objective-C and Xcode in order to build a killer application for the iPhone. With the full-featured Safari browser, building web applications that act like a native iPhone application is not only possible, but it can be easy to do. We will take a sample Rails application and make it sparkle on the iPhone.
Jim Suchy TDD and JavaScript JavaScript has earned a special, dark place in most programmer’s hearts as it is a necessary evil for making the web experience dynamic. You are test-driving your JavaScript, aren’t you? If not, why not? If the reason is that you don’t know how, or haven’t taken the time to learn the various testing frameworks, then this session is for you. We will explore the various testing frameworks and test-drive a small bit of functionality using the presenter’s favorite.
Len Smith Get rolling with NHibernate All the cool kids are using NHibernate. Come find out what all the buzz is about. We'll see how NHibernate can make your domain model beautiful, your application perform better and facilitate Rapid Application Development.
Len Smith jQuery Magic jQuery makes working with the DOM, AJAX and events easy, fun and magical. We'll get started with an overview of jQuery and examples of integrating jQuery into existing applications in both ASP.NET and ASP.NET MVC.
Micah Martin Ruby Kata and Sparring All respectable software craftsmen make efforts to keep their coding claws sharp. And solely working 9-5 on business applications will dull one's whit. In this session we will broaden your coding horizons with some Ruby Kata and test your skills will some Ruby Sparring.
With Ruby Kata we will code known solutions to simple problems all the while being mindful of our steps and striving to write code of the best possible form.
Ruby Sparring will put your skills up against your peers. Exercises will be presented and your solutions will be compete against those of other participants. The challenge may be to solve a problem in the fewest lines of code, or to build a warrior program that will fight with others in Core Wars fashion.
Michael Hall Introduction to AOP with PostSharp Starting with an example of how things are done using normal techniques. Then install PostSharp and then step by step refactor to using Aspects to replace things like logging, validation, security and/or transactions. Finally give a brief history of the PostSharp product and references to more info and alternative toolsets.
Narayanan Kulasekar "Tools to build an effective Extract, Transform and Load (ETL) process" The biggest and most complex aspect of a data warehouse project is to gain understanding of data in all the source systems that you are dealing with. The next thing is coming up with an auditable and repeatable Extract, Transform and Load (ETL) process to bring all the data from your source systems into the data warehouse. Various studies have identified ETL to consume about 80% of a total data warehouse project effort. This presentation will talk about some of the best practices and scripting techniques that can be handy in making your data warehouse development less painful and more methodical.”
Perry Hertler TDD in the Real World This is an in depth TDD presentation that involves a lot of real-time coding.
The session will start with a high level overview of TDD then move to an example that involves TDDing a design and implementation of a simple story. The presentation will then cover some TDD tips, benefits, weaknesses, and finally compare TDD to TAD (test after development).
The coding part of this presentation can be done in either Java or C#. If it is decided that the presentation would be of use to Code Camp, please respond with a language preference.
Scott Seely Introduction to Google App Engine (GAE) It provides services to handle web requests, store data, and cache values across the server farm. The platform language of choice is Python. It supports several web libraries, including the very popular Django. In this talk, we will build a photo storage application that takes advantage of the caching, data storage, and the web platform features in GAE.
Sean Blanton Trends in Continuous Integration and Software Delivery You have all this great code, but how do you get it out to the real world with some degree of quality? Developers are relying on increasingly sophisticated infrastructure for build, test and delivery automation.Sean will present the latest on Subversion, CVS, Git and commercial file control tools, and how build and workflow automation speed application delivery and align with Agile development. Other topics to be presented are: distributed development, shared library management, scaling development and delivery processes to larger organizations, and the concept of software resiliency.
Tim Barcz Regular Expressions for the .NET Developer Many developers suck at Regular Expressions, don't be one of them. You will leave this session with a better understanding of regular expressions, from how to read them to how to write them effectively. Never again will RegEx stand in your way.

The Code Camp will be a great event. If you haven't registered yet, what are you waiting for?

RSVP

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 - 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.

Playing with Ruby 1.9 - named parameters (sort of)

Posted by Sergio on 2008-12-31

I just installed Ruby 1.9.1 RC1 alongside my stable 1.8.6 installation. I'm planning to experiment with the changes and new language features for both using them in new code and upgrade old code (or at least protect old code from potential breaking changes.)

In light of the upcoming changes in C# 4, more specifically the addition of named and optional parameters, one of the new Ruby 1.9 features called my attention immediately.

Ruby, even 1.9, doesn't support named parameters in method calls. Instead, a common pattern is to provide a Hash parameter and call it something like options. Any optional argument is passed as an item of this hash, normally using a Symbol for the key. It helps that Ruby has special support for hash arguments, making the call look much cleaner:

def my_method(arg1, arg2, options)
  opt1 = options[:option1] || "default value for opt1"
  opt2 = options[:option2] || "default value for opt2"
  # ... etc ...
end

#calling the method:
my_method(val1, val2, { :option2 => "opt val 2", :something => "whatever"})
# simplified syntax
my_method(val1, val2, :option2 => "opt val 2", :something => "whatever")

In a way this is the poor man's version of named parameters, but it seems to do the job.

This is a very popular Ruby idiom (you can see that a lot in JavaScript as well,) so truly popular that the syntax was further simplified in 1.9. We can now ditch the arrow thingy and write the same exact code as follows:

#calling the method:
my_method(val1, val2, { option2: "opt val 2", something: "whatever"} )
# simplified syntax
my_method(val1, val2, option2: "opt val 2", something: "whatever")

The first syntax is identical to what you'd use in JavaScript. The second one is the same of named parameters in C# 4. I thought this was a welcome coincidence. See the C# 4 version below.

//NOTE: C# 4 code
void my_method(string arg1, string arg2, 
      string option1 = "default 1", string option2 = "default 2",
      string something = "")
{
  // ... method body here ...
}

//calling the method:
my_method(val1, val2, option2: "opt val 2", something: "whatever");

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