First time here? You are looking at the most recent posts. You may also want to check out older archives or the tag cloud. Please leave a comment, ask a question and consider subscribing to the latest posts via RSS. Thank you for visiting! (hide this)

November 2012 Blog Posts

MountainJS: JavaScript conference in the Swiss Alps

UPDATE (15 December): Boo... The Conference has been cancelled.


mountainjs_200_160.png

Do you use JavaScript? Do you like skiing or snowboarding? Do you live in Europe? If you answered yes to at least the first 2 questions than you definitely have to attend the MountainJS conference held on the 4th and 5th of February in ski station of Leysin, near Geneva Lake, in the Swiss Alps.

The conference will be about JavaScript being used as the unique and exclusive language for both frontend and backend web development, covering the hottest topics, technologies, techniques and platforms to build the next generation of web and mobile applications and data services. Also the speakers are the top expert in JS and Node.js, including Felix Geisendörfer, from the Node.js core team and of Nodecopter fame.

I think it's the first conference of that kind organized in our industry: a good combination of high quality technical contents and lots of fun.

I say fun because the conference organizer has already 3 après-ski après-conference events for the 2 evenings: dinner in panoramic restaurant, a snow tubing evening session and finally a cheese fondue/raclette dinner.

yeti_60.png

And if you plan on arriving the weekend before the conference (the 4th and 5th are Monday and Tuesday) there will be ski events and real àpres-ski parties.

Registrations just opened last week: the ticket for the two days of the conference and all side activities of Monday and Tuesday are on sale for 429€. And the first 30 women will get a 100€ discount, thus paying 329€.

They also arranged some special packages with hotels for there 2 days, but also if you intend to arrive the weekend before or stay for till the end of the week.

Unfortunately I'll not be able to attend, as I have the MVP Summit the week immediately after, but I would have really loved to go there, for the technical content but also for the atmosphere.

A big congratulation to Bertrand Dufresne for the awesome conference he is organizing.

If you want to keep yourself informed, follow @mountain_js on twitter and on the Facebook page, monitor the #mntnjs hashtag and subscribe to the blog.

How to return a CSV file with ASP.NET MVC

Continuing with my series of posts inspired by the work done on the Web.NET Conference web site, after telling you why you should not use Boolean fields when modeling your objects, today I want to share with you an ActionResult I wrote to get a CSV from a generic list of object.

I needed to download the list of all attendees in csv format so that I could import them into Excel for doing various free-form analysis: I looked around the net to see if something was available but I found nothing, so I decided to write it myself and do it the most reusable way possible.

I’m not just going to give you the code, but I’d also try and comment the most important part of the class.

Extend ActionResult

Obviously, being used as result returned from an action, the class has to extend ActionResult, and in this case, since what I’m returning is a file, I’m extending FileResult: this provides all the standard file-related tasks, like setting the content type and setting the filename that will be suggested when saving it.

Constructor and declaration

The values for these two properties will be set in the ActionResult’s constructor:

public class CsvActionResult<T> : FileResult
{
    private readonly IList<T> _list;
    private readonly char _separator;

    public CsvActionResult(IList<T> list,
        string fileDownloadName, 
        char separator=',')
        : base("text/csv")
    {
        _list = list;
        FileDownloadName = fileDownloadName;
        _separator = separator;
    }
...

I’m also passing in an optional separator because in many countries the the separator for fields is not a comma, but a semi-column.

Override WriteFile

In order to extend FileResult, you also need to override the WriteFile method, which is the one responsible of getting the value of the file and sending it to the user. The standard implementation just takes a file from the disk and send it to the browser: in this case I have to write to the OutputStream directly the value of my list of objects.

protected override void WriteFile(HttpResponseBase response)
{
    var outputStream = response.OutputStream;
    using (var memoryStream = new MemoryStream())
    {
        WriteList(memoryStream);
        outputStream.Write(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
    }
}

Discovering the property names at runtime

The csv file needs to have the list of all the columns’ names so that Excel can give a name to it once imported: since the action results accepts any object I needed to find out the name of the property. This was easily done via reflection and passed to a function that writes it in the OutputStream of the response.

foreach (MemberInfo member in typeof(T).GetProperties())
{
    WriteValue(streamWriter, member.Name);
}

The write value method is an utility method that formats the value in the proper way and with the correct separator. I’ll show this later in the post.

Writing each object of the list

After having written the header, always via reflection I get the values of the properties, and write them in the OutputStream.

foreach (T line in _list)
{
    foreach (MemberInfo member in typeof(T).GetProperties())
    {
        WriteValue(streamWriter, GetPropertyValue(line, member.Name));
    }
    streamWriter.WriteLine();
}

If a property is of a complex type, and you still want to export it into the csv file, all you need to do is override the ToString method to format it into a string. Here is the GetPropertyValue method that does the actual work of retrieving the value from object.

public static string GetPropertyValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null).ToString()??"";
}

Formatting the property value

Care must be given when writing the actual string otherwise Excel (or any other csv parser) will not be able to get the data correctly: the value must be enclosed in double quotes, and all double quotes inside the value must be escaped. And furthermore the separator has to be different based on the culture of the user, but to make it simple I take the value supplied during the instantiation of the action result.

private void WriteValue(StreamWriter writer, String value)
{
    writer.Write("\"");
    writer.Write(value.Replace("\"", "\"\""));
    writer.Write("\"" + _separator);
}

How to use it

Using the action result is pretty easy: you just create a new instance of the class, and pass it a IList of something. And then return the class in you action method.

public ActionResult CsvList()
{
    var model = CreateUserListViewModel();
    return new CsvActionResult<UserListViewModelItem>(model.Items, "UserExport.csv");
}

Get the complete code

You can get the complete code of the class on this gist. I’ll be creating a NuGet package with binaries and some enhancements soon.

Why you should never use a boolean field (use an Enum instead)

Over the last few months I worked, on my spare time, on a new web development project: the site for the Web.NET Conference. It was a refreshing experience, going back working on custom development on ASP.NET MVC 4 and all the latest bits of technology.

That gave me quite a few ideas for posts, so over the next weeks I'm going to blog about some of the bits and pieces of code that I think are worth sharing with the community, like ActionResults, HtmlHelpers together with my first real-coding experiences with RavenDb.

As first post I’m not focusing on something about a technology, but I want to tell why you should never model a data field as Boolean, and instead start directly with an Enum.

How the problem started

I'm going to tell you what happened during the development of the registration and payment parts of the Web.NET Conference.

I needed to keep track of whether someone has paid or not, so I started modeling that field as a simple boolean value, HasPaid. I also wanted to show them a different message depending on whether they paid or not, to remind them they had to pay in order to get the meal they ordered. To achieve that I checked the value of the HasPaid field: after a while I realized that also people that didn't order a meal had the HasPaid to false, as indeed they didn't pay because they didn't have to.  
So in this confirmation screen I also checked whether the total of what they had to pay was different from 0. And it was still manageable.

After a while someone asked if they could pay at the registration desk as in their country PayPal was not operating: so I moved them manually to HasPaid=true and added in the note field that they will pay at the desk, so that their lunch and were taken into account.

Then again something else happened: someone that has already paid unregistered and left what he paid as donation for the conference. Now I needed to filter out their meals, their participation at the conference, but still keep their payment in the count of the donations received, unlike the ones that asked for a refund for which I need to filter out also the payment: this was becoming a nightmare to handle with the original HasPaid field.

On with the refactoring

One evening I sat down, and refactored the payment procedure and all reports to go from a simple boolean to an Enum with the following options:

  • Undefined
  • DidntPay (the original HasPaid=false)
  • NoNeedToPay (for those how didn't reserve a meal or gave no donation)
  • Paid (the original HasPaid=true)
  • PaysAtRegistration (for the guys who couldn't pay online)
  • Refunded (if someone cancels, and wants his money back)

And after the refactoring and making sure all reports and state transitions were using the new Enum, I also had to build a small script to convert all the data inside the RavenDb repository (and this is something interesting I’d probably write a blog post about).

Another example of the same problem

The same problem occurred with the registration status: it started with 2 booleans, IsRegistered and IsWaitlist, then expanded with HasCancelled and WasApprovedFromWaitList and all crazy combinations of boolean expressions to understand his real status, and then, in that very same refactoring session, it all became a more clear and easier with that Enum:

public enum RegistrationStatus
{
    Undefined,
    Confirmed,
    WaitingForPayment,
    Waitlist,
    Cancelled,
    Approved,
    ApprovalNotConfirmed
}

State Machine/Workflow

The benefit of this approach is that both registration and payment became two state machines, and it was much more easy to implement a very simple workflow with the possibility to set allowed and forbidden transition (for example, someone in waitlist couldn’t become “confirmed” without passing from the “approved” status), and action that needs to be done when a given state transition happens. Here is an example of what the transition rules look like: previously with the combination of booleans it was crazy, and very easy to make logical mistakes.

public static class RegistrationFlow
{
    public static void RegistrationStatusTransition(RegistrationStatus newStatus,
        Registration registration)
    {
        switch (newStatus)
        {
        ...
        case RegistrationStatus.WaitingForPayement:
            if(registration.RegistrationStatus!=RegistrationStatus.Undefined &&
            registration.RegistrationStatus!=RegistrationStatus.Approved)
                throw new ArgumentOutOfRangeException("newStatus",
                String.Format("{0} -> WaitingForPayement not allowed",
                registration.RegistrationStatus));
            if(registration.PaymentStatus==PaymentStatus.NoNeedToPay)
                registration.RegistrationStatus = RegistrationStatus.Confirmed;
            else
                registration.RegistrationStatus = RegistrationStatus.WaitingForPayement;
            break;
        case RegistrationStatus.Confirmed:
            if(registration.RegistrationStatus!=RegistrationStatus.Undefined &&
            registration.RegistrationStatus!=RegistrationStatus.WaitingForPayement &&
            registration.RegistrationStatus!=RegistrationStatus.Approved)
                throw new ArgumentOutOfRangeException("newStatus",
                String.Format("{0} -> Confirmed not allowed",
                registration.RegistrationStatus));

            registration.RegistrationStatus = RegistrationStatus.Confirmed;
            break;
        ...
        }
    }
}

Lesson Learned

When I tweeted about this while I was refactoring, someone told me: “Using a boolean is an antipattern”… well… now I experienced it myself.

From this experience, in the future, I’ll never use a Boolean field again, and always start with an Enum, especially with a Document database where migrating data is a bit more complex than with relational databases.

UPDATE: Given the comments received I’d like to clarify a bit my position. I’m not saying booleans are not to be used at all: booleans have value, just not when the the thing you are trying to model is a state and not just a real/physically boolean value.

OpenROV at Node.js Conf Italy and Maker Italy

On the 11 of November I had the pleasure to present at the Node.js Conference Italy the work I’ve been doing with Dominik and a bunch of other guys in the San Francisco area on the “brain” of the robotic submarine called OpenROV.

On my way back from Brescia I stopped by at the first Italian Maker Faire, held in the big expo area of Milano Rho, where I wandered among stands full of flying drones, biped robots, 3D printers, FabLabs and electronics shops.

Together with web development, the makers and open hardware movement is something I’m getting interested in, and after few months dedicated totally to web development, this was a weekend totally devoted to these two new interests.

Slide and resource of my OpenROV presentation at Node.js Conference

During the 30 minutes presentation I went over the physical design of the OpenROV, the reasons why it has been build in the first place, and an overview of the architecture of the software that runs on the small board inside the robot itself.

I was the only one doing a presentation in JavaScript, using Reveal.js, which was shocking being it a conference on JavaScript: the slides are available both as JavaScript presentation but also published on Slideshare.

On my other blog about all things HW and makers I also wrote a blog post with a bit more of resources and a longer commentary of the event.

The Italian Maker Faire

On my way back home, after the Node.js conference hackathon, I spent a few hours wandering among the stands at Makers Italy: the maker movement is invading Italy too… finally!

Not only robots and drones, but also a lot of stands on digital fabrication tools (3D printers above everything) and of small makers’ founded companies making various items like custom skateboards, guitars, bags, jewelries and so on.

Not sure if that movement will bring innovation or it’s just yet another trend, but for the moment it seems like a lot of people are getting interested, building tools for makers, and it won’t be long before digital fabrication tools will land in every house. Already now, 3D printers are less expensive of a low level PC 10 years ago, and I guess they’ll reach the cost of an entry level laptop.

Again on my drones&rovs blog I wrote my impressions and a small review of the stands I found more interesting.