I'm going to do an experiment today

I’ve started learning C# and ASP.NET MVC about 5 or 6 months ago. While learning I’ve developed a clone of Reddit that had a very clear differentiator: you could see the messages and the web page at the same time. When I was close to completion Reddit released exactly that feature. I scrapped that project.

Then I had the idea of making Is it Science Fiction?. I started coding and since the day of the idea to the day of deployment I had one full day of work and four days of part time work. I was really surprised by my productivity, and quite satisfied.

When I started to write some complex features for Is it Science Fiction? I hit a roadblock on writing tests for it. What sometimes is called functional tests are not trivial in ASP.NET MVC. I mean tests that hit controllers properly initialized and the database with some fixtures (but not touching HTTP). I spent three days developing a framework for those kind of tests when I realized I was wasting my time, Rails could do this out of the box.

I’ve decided to re-write Is it Science Fiction? on Ruby on Rails while I was reading Agile Web Development with Rails. Unfortunately, it took me more than a month to do it. I’ve moved to Rails because I thought it was more mature and had many more libraries and utilities that would make me more productive. I was extremely disappointed. But, my first ASP.NET MVC project also took a long time, while I was reading the book; so it’s not fair to compare my time at re-writing Is it Science Fiction? because I was reading a book while doing it and not skipping any part of the book even when it had no application to my current project.

I want to find out how productive I’m in Rails. So I’ve decided to try to do a simple project in a weekend. That day is, starting today. Today I will run the rails command and create the project and if everything goes well, today or tomorrow you’ll be able to use the app. It’s not going to be a very complex app; after all it’s only one weekend and I do aim to having tests and clean code. I’ll try to post as I go along so my blog is going to be quite noisy.

The project code name is Sano, it means health in Esperanto. It’s a health tracker. Both my wife and me want to be more healthy and the first step of course is for me to code an app for it. Let’s start with a spec for Sano.

Sano

Sano is a health tracker that can track many different health parameters of a person. The goal is for that person to have a clear view of how healthy they are and their health trends (am I getting better or worse?). It should also be a good tool to convey clear scientific non-biased information to a medic when the users needs that.

Countries that doesnt use SI

Countries that doesn't use SI

All units of measurement will be SI. My apologies to those three countries in the world that have not adopted these units and are using weird obsolete old units. Grow up!

Authentication

A user should be able to use the site without doing absolutely any authentication. The user should be able to enter data, see tables, see charts and all that information is stored in reference to a “ghost user”, that is session only. If the user closes the browser all that data will become inaccessible. The user will be warned several times about the potential losing of data if they are trying the application in this fashion. The warnings would be as notices on the page itself and if possible a pop up when closing the page.

For logging in, Sano will use OpenID and only OpenID with the usual friendly login pages. No other information will be asked and no registration page will exist. Users already in the system will log in to see their previous records, the rest will register on the fly silently. If a user has session data before logging in (previous paragraph), that data is going to be merged with their authenticated user.

The site won’t have any publicly viewable section. Even the sections that you can see without logging in are shown differently user by user. In a sense it’s like Facebook.

Profile

The profile of a user will be a set of meta-data associated with that user. It will contain the following fields:

  • name: the real name of a person (not broken into last name and first name, because that doesn’t make any sense; how would Madonna use my system?)
  • email
  • height (consideration: what about varying height? like in children, for version 2 or 3 or 23)
  • gender
  • birth date (important to know the age, maybe).

all fields are going to be optional.

Trackers

Sano will start with two trackers:

  • weight
  • blood pressure (systolic, diastolic and pulse)

Each of the trackers will have its own CRUD to add data and will be implemented as standalone controllers (that meaning no meta-tracker that can track anything astronaut-architect-style).

Each of the data points will be stored with time and date (most weight trackers only track date; this will allow for time variation compensation) and the form should allow the user to enter a data point as happened now (or just now) but also with a specific date and time (don’t ask for any more precision than the hour of the day, but store up to the seconds, just in case).

Every tracker should have a table for updating, deleting and exporting (it should export to CSV) but also a graphic view that is tracker dependant.

Weight tracker

The weight tracker asks only for one number: the weight. The first iteration will work only with kilograms.

The weight tracker will ask you to complete your profile to include your height to be able to calculate the range of acceptable weight.

In the table view three colors will be used, red, yellow and green to show under or over weights according to your height, gender and maybe age.

The chart should be a simple line chart at the beginning. In a second version it should have a weighted average according to the Hacker’s Diet rules.

Blood pressure tracker

Three pieces of information will be asked in this tracker:

  • systolic
  • diastolic
  • pulse

The table view again will use the red, green and yellow colors to show dangerous values.

The chart should be a bar chart showing sets of three bars (one for each measurement). Each of the three vars will be in a different tone of green to be able to distinguish them and when they reach dangerous levels they will turn yellow and red with different tones accordingly.

Dashboard

The dashboard is a chart of all or most of the data you have in the system. A one place to look at your current health.

Third party access

All the data in the system is private and sensitive so it’ll be kept private. But, a very important aspect of the system is to give other selected people access to your data.  There will be two ways to grant a third party person access to the system: permanent or temporary (both are revokable at any time).

The permanent access would mean giving access to another registered user in the system. That’s most likely your main medic or a medic that’s treating you. Consideration: what about write access to a trusted third party that helps keep track, what about allowing your medic to add information or annotations that require your approval?

It would be nice to be able to keep that kind of close relationship with a medic, but it’s not very realistic. So there’s a temporary access system. You will log in to your account and generate a token for half an hour access to your profile. The person that gets the token will be able to see your profile for half an hour. The use case is that you go to the doctor, you pick your phone (potentially while you are at the weighting room), log in to Sano, generate the token and the URL would be displayed big on the screen. You can then show your phone to your medic and he/she would have half an hour access to your data.

Let’s code!

It’s not a huge app, but it’s not a hello-world either. I don’t plan to be able to do all of it on one weekend and there are some parts, like charts, which I desgined without knowing the capabilities of available charting libraries. It may not be possible to do some of the things I mentioned without writing some custom charting which is out of the question.

Since my goal is to have something deployed, as soon as it is barely usable I will deploy it, and then I’ll keep adding features until the end of the weekend (or whenever I have to stop).

Sano is the code name for the app, I’m not sure about the public name. If you have any suggestion with an available domain name, please let me know (note: I won’t buy domain names unless you are doing it out of good faith and selling it for no more than 200% of its cost).

That’s all, let’s code!!!

Are dynamic languages just a temporary workaround?

This can unleash so much hate mail, but here it goes, my inbox is ready!

Are dynamic languages just a temporary workaround? I’m not sure! I’m switching between the two types of languages all the time: Java, Python, C#, JavaScript. I’ll try to make the long story short.

Statically typed languages, like Java and C#, are nice because when you do

blah.bleh()

you know that blah’s class has a bleh method, at compile time. But better than that, when you typed “blah.” you get a list of methods, and you already know whether there’s a bleh method or not, and if you typed bleh and it doesn’t exist, the IDE lets you know, no need to wait for the compiler. Also you can do very deterministic refactoring, renaming all “bleh” for “bluh” for example.

Statically typed languages are not nice because they are very verbose and require a lot of boilerplate (if you’ve used Haskell, just bear with me for now please), so you end up with things like:

List[Car] cars = new List[Cars]();
foreach (Car car in cars) {
    car.Crash();
}

How many “cars” do you read there? And that’s a nice example. There are worse. So come dynamically typed languages and you can write:

cars = []
for car in cars:
    car.crash()

You have less cars, and less (no) lists. That means you are more productive. You start chunking out code faster without having to stop and think “What type of object will this or that method return?”. But crash() can crash your application instead of just the car because you can’t know if it exists until run-time. That might be OK or not, testing and whatnot.

Then comes C# 3.0 where you can do:

var cars = new List[Car]();
foreach (var car in cars) {
    car.crash();
}

And you can see that syntactically it got closer to Python, which is what gives you the productivity. Don’t know the type? type “var”. But semantically, it’s still statically typed, like the previous statically typed example. You know that car is going to be of some class that has a crash method. You can actually know car’s class at compile time, no need to run it.

That’s called type inference. You don’t have to specify the type where the compiler is capable of inferring it for you. C# type inference system is still very limited (but better than Java’s). Let’s see an example in another language

cars = []
map crash cars

That means, create a list called cars, call the function crash on each car. Would you say that that is a statically typed language? or a dynamic one? I’d say it is dynamic, but it is static. Very static. It’s Haskell. Haskell’s compiler will infer all the types for you. It’s amazing, you’ll write code as robust as with C#, but as terse as Python’s (Monads will then kill your productivity, but that’s another story).

In Python 3 you can define types for arguments. They are mostly useless, but it’s an interesting direction. I think the best it can do is that when a program crashes it’ll tell you: “function blah expected an int, but got a float, not sure if that was the problem, but you might want to look into that”.

Now, my question is, are dynamically typed languages just a temporary workaround? As our compilers get better, our computers faster, will statically typed languages keep giving us as many or more reassurances about our code and utilities while at the same time they become as simple and terse as dynamically typed languages? Or will dynamically typed languages start to gain types and over time be more static without the programmers that use them ever noticing?

My question is, will we in the future, 50 or 100 years, look back and said “Dynamically typed languages where a temporary workaround to statically languages being painful to use when human beings and their toy computers were so primitive?” in the same way we can say today that “non-lexical scope was a limitation we had and have due to the limitations of computer hardware 30 years ago”.

Reviewed by Daniel Magliola. Thank you!

Formating strings in C#, like in Python

I like Python’s way to format strings because you can use it everywhere, it’s part of the strings. You can do

print("Welcome %s!" % user.name)

as you can do

Console.Writeln("Welcome {0}!", user.Name)

But then in Python you can also do

randomMethodThatTakesAString("Welcome %s!" % user.name)

In C# it gets trickier, because the call to Console.Writeln takes extra arguments for the string arguments, while RandomMethodThatTakesAString doesn’t. It just takes a string. So the only way to go is

RandomMethodThatTakesAString(String.Format("Welcome {0}!", user.Name))

which is ugly.

Thanfully C# 3.0 has extension methods, so I quickly wrote this method:

blah blah

and now I can write:

RandomMethodThatTakesAString("Welcome {0}".Args(user.Name))

which is more verbose that Python’s version, but equally nice in my eyes.

If you can understand why allowing the language to be extendable in one aspect was a win here, then you can understand why so many, me included, love Lisp that is extendable in every possible way.

Reviewed by Daniel Magliola. Thank you!

Update 2009-09-17: For those complaining that I didn’t show how I did it, here is the Args method:

public static class StringExtensions {
    public static string Args(this string str, params object[] args) {
        return String.Format(str, args);
    }
}

File input for forms in ASP.NET MVC

fileI’m not sure why ASP.NET MVC was shipped without a file input type for forms. Maybe it’ll come in MVC 2.0 or 3.0. Meanwhile, I created one. I spent two or three hours trying to figure out how to go from Object to IDictionary<String, Object> to follow the same ASP.NET MVC style where you have methods like:

TextBox(HtmlHelper, String, Object, IDictionary);
TextBox(HtmlHelper, String, Object, Object);

which are essentially the same. The last argument is a dictionary of extra HTML attributes, like style=”float: left;”. The good thing about accepting Object Is that you can call it this way:

Html.TextBox("email", new { style="float: left;" })

which is very handy for forms. The bad thing is that it is a pain in the ass to do that hocus pocus in C# using reflection. Thankfully ASP.NET MVC is open source. I downloaded the source and after 15 minutes I got it working nicely (and without manually using reflection). Use the source Luke!

In a recent episode of Hansel Minutes podcast someone argued what was the value of releasing the code of ASP.NET MVC at all. Well, this is the value. You help developers, you build a better developing community.

Without further ado, here’s the code:

public static class HtmlHelperExtensions {
   /// <summary>
   /// Returns a file input element by using the specified HTML helper and the name of the form field.
   /// </summary>
   /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
   /// <param name="name">The name of the form field and the <see cref="member">System.Web.Mvc.ViewDataDictionary</see> key that is used to look up the validation errors.</param>
   /// <returns>An input element that has its type attribute set to "file".</returns>
   public static string FileBox(this HtmlHelper htmlHelper, string name) {
       return htmlHelper.FileBox(name, (object)null);
   }

    /// <summary>
    /// Returns a file input element by using the specified HTML helper, the name of the form field, and the HTML attributes.
    /// </summary>
    /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
    /// <param name="name">The name of the form field and the <see cref="member">System.Web.Mvc.ViewDataDictionary</see> key that is used to look up the validation errors.</param>
    /// <param name="htmlAttributes">An object that contains the HTML attributes for the element. The attributes are retrieved through reflection by examining the properties of the object. The object is typically created by using object initializer syntax.</param>
    /// <returns>An input element that has its type attribute set to "file".</returns>
    public static string FileBox(this HtmlHelper htmlHelper, string name, object htmlAttributes) {
        return htmlHelper.FileBox(name, new RouteValueDictionary(htmlAttributes));
    }

    /// <summary>
    /// Returns a file input element by using the specified HTML helper, the name of the form field, and the HTML attributes.
    /// </summary>
    /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
    /// <param name="name">The name of the form field and the <see cref="member">System.Web.Mvc.ViewDataDictionary</see> key that is used to look up the validation errors.</param>
    /// <param name="htmlAttributes">An object that contains the HTML attributes for the element. The attributes are retrieved through reflection by examining the properties of the object. The object is typically created by using object initializer syntax.</param>
    /// <returns>An input element that has its type attribute set to "file".</returns>
    public static string FileBox(this HtmlHelper htmlHelper, string name, IDictionary<String, Object> htmlAttributes) {
        var tagBuilder = new TagBuilder("input");
        tagBuilder.MergeAttributes(htmlAttributes);
        tagBuilder.MergeAttribute("type", "file", true);
        tagBuilder.MergeAttribute("name", name, true);
        tagBuilder.GenerateId(name);

        ModelState modelState;
        if (htmlHelper.ViewData.ModelState.TryGetValue(name, out modelState)) {
            if (modelState.Errors.Count > 0) {
                tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
            }
        }

        return tagBuilder.ToString(TagRenderMode.SelfClosing);
    }
}

Reviewed by Daniel Magliola. Thank you!

Converting the ASP.NET MVC project into OpenID

When you create an ASP.NET MVC project it comes with a controller called AccountController that manages logging in, logging out, registering, changing password and so on. Since usernames and passwords are dead I converted it into OpenID and I’m just pasting it here for everybody to use.

I’m using the DotNetOpenAuth library which you have to download, put in your project and refer. The difference between what I’m pasting and the example provided by DotNetOpenAuth is that I’m actually storing the user in the membership database, like the original AccountController.

My work is based on the on the blog post Adding OpenID to your web site in conjunction with ASP.NET Membership. I really had to put a couple of hours on top of that, so I consider it worth it to post it. Scott Hanselman also provides useful information for integrating OpenID. I’m using the jQuery OpenID plug-in but I’m not going to post my views. They are really trivial and left as an exercise to the reader.

I’m not using any extra tables, I’m storing the OpenID identifier (the URI) in the field for the username. This has the advantage of not requiring any other fields but the disadvantage that you can have only one identifier per user. There are some unfinished parts but since you are likely to customize them anyway, I don’t feel too guilty about not finishing yet. If you find a bug, please, let me know.

Continue reading

SVGs in .Net using Cairo and Gtk+ (and C#)

If I was using C it would have been simply a couple of calls to librsvg, but on C# things got a bit more ugly because Rsvg, the wrapper around librsvg is not finished. And other bindings are also missing. Just getting a Cairo context out of a Gtk.DrawingArea was not as simple as I would have liked it to be (I describe how to do it in a previous post, but I’ll do it again here).

Continue reading