Category: Technical

Posts related to programming or other highly technical stuff that can only be of interest to computer geeks.

  • In an effort to increase the quality of this blog I’ve engaged a couple of friends in reviewing my posts before they go out. I’m after typos, grammar and also “Are you serious? are you going to publish that crap?” or “You are going to get into trouble with that”.

    The best way to do this, in my and in the opinion of many, is to let the reviewer modify the post freely and then check the diff. I suppose we are too used to work with source code, where diffs are a necessity.

    I was positively surprised that WordPress can provide very nice colored diffs between each save of each post. Praise to WordPress! I was also surprised, but negatively, that WordPress doesn’t have a reviewer role. Users with the reviewer role would be able to edit unpublished posts but wouldn’t be able to modify published posts or publish drafts.

    I was pointed to Role Scope, an amazing plug in for WordPress. I spent an hour creating a group and trying to give it the proper access, and as that failed, trying to limit the Editor role to only edit drafts. I failed at that too.

    When I gave up and I went back to the usual blogging I found that Role Scoper allows you to give edit access to each post to any user. And that’s it. That’s what I’m using. Whenever I want something reviewed I give access only to that post to the user I want to review it. Quite simple.

    Reviewed by Daniel Magliola. Thank you!

  • 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);
        }
    }
  • forgot-passwordOpenID has many advantages. For the average user, the main one is not having to remember a thousand passwords. That’s obvious. But also consider not having to remember the username. Many web sites use the email address as username and that’s nice, but many don’t. And most people are not lucky enough to have a username that’s free everywhere. For my wife, remembering the username is sometimes as hard as remembering the password.

    Not having to worry about poorly programmed web sites leaking your password because they stored it in plain text and they have phpMyAdmin open without any password is also a big plus, but not something the average user would see.

    But for the developer, it has many, many advantages.

    Not having to decide on what identifier to use for your users (users vs emails vs ids). Not having to implement a log in screen, which means not having to worry about SSL encryption which means not having to get a dedicated IP address, a certificate, configure the web server accordingly and ensure that the site switches to https when it must.

    Not getting password for the user means you don’t have to store a password. You don’t have to figure out what is the appropriate encryption mechanism so that if your encrypted password leak, they are not readable. Not using plain text is not enough, as some encryption mechanisms are easily broken. Not having to worry about that is huge.

    You don’t have to create a signup page, people just log in. You don’t have to validate the password by asking for it twice or validate its strength or any other stuff like that.

    You don’t have to create a remember password page, which means one less place where you have to deal with sending emails. That’s always good. Also it means that you don’t need to store the email of the user. You may want to, but that’s your option.

    I’ve always been a fan of canned authentication and authorization systems. I’ve been using them since the days of PHP 4.0 and I used them in Django and ASP.NET (MVC). But with OpenID, it seems the authentication became almost trivial. Canned solutions were always troublesome because they had to work for everybody so they implemented a lot of stuff you don’t actually need and sometimes you spend more time fighting the bureaucracy of the system than producing something.

    Is it possible that without OpenID authentication and identity for the developer of a web site becomes something simple and trivial? Where rolling your own solution not only is simple enough, but also the way to go. I’m looking forward to my users being just in the user table, and not all over the place in users, profile, membership, etc. I’m giving the roll-your-own-with-OpenID a try. I hope to post positively about it soon.

  • 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!

  • Image taken from http://www.artlebedev.com/everything/defendius/

    I was writing this long post about how to use rewrite rules to make Apache query itself and serve various sites through the same SSLed virtual host using only one IP. After about four hours of struggling with it I thought I was done but then while writing this article I found out I was wrong. Something was not working as expected. Did I face another 4 hours of Apache struggling? (more…)

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

    (more…)

  • A friend of mine complained that after switching to my new site (from WordPress to Plone 3) my feeds stopped containing the full article and only the body. So this is how I fix it.

    Searching for how to fix it on the Internet I’ve found several articles (and I’m adding one more!):

    1. PLONE 3 RSS: this solution fails in that it outputs the text as description and doesn’t output the description at all.In my case, the description is the start of the article, so that didn’t work. Now I’m not 100% sure that’s the case, but I think so (sorry, I won’t break my site again to check it out). This article points to another three.
    2. Full RSS-feeds for Plone: this one adds the content in a separate tag after the description. This one is better, but pay close attention to the comment, otherwise it’ll fail.One problem I’ve had with this one is that readers show either the description or the content; they interpret description to be meta-data and it’s not shown when the content is shown. That’s probably correct, but in Plone, the description is like an introduction to the article, being shown just below the title and above the main body text, and that’s what I needed in my feeds.
    3. Add the body text to your rss feed: outdated, I ignored it. It might have worked but it would have required a lot of tweaking.
    4. Add the body text to your rss feed (2): it’s also marked as outdated, but it is the same as “Full RSS-feeds for Plone”, just more graphical and integrating the important.

    So, my solution is essentially 2 or 4, with the addendum of the description to the content:

      content
    

    If you are wondering, “74” is “<” and “76” is “>”.

  • Let’s compare how we print the class-path in Clojure and how we do it on Java.

    In Clojure:

    [sourcecode lang=”clojure”]
    (println (seq (.getURLs (java.lang.ClassLoader/getSystemClassLoader))))
    [/sourcecode]

    In Java:

    [sourcecode lang=”clojure”]
    import java.net.URL;
    import java.net.URLClassLoader;

    public class PrintClasspath {
    public static void main(String[] args) {
    //Get the System Classloader
    ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();

    //Get the URLs
    URL[] urls = ((URLClassLoader)sysClassLoader).getURLs();

    for(int i=0; i&lt; urls.length; i++)
    {
    System.out.println(urls[i].getFile());
    }
    }
    }
    [/sourcecode]

    To be fair, the output is not the same, but the effect is.

  • Being able to write, build and run a Clojure application, like I explained in a previous article, is not enough. You also want to hack on it, to iterative code on it, after all, you are using a Lisp.

    What I mean by iterative coding is something not very few know or do, but it’s extremely common in Lisp. You have you REPL running all the time (that is, generally, the interpreter). You load the code into the REPL, run it, modify some part of the code and re-load it. You may not reload the whole file but only a function on it, and you may have background process running on the REPL, like a web server. It is very powerful. (more…)

  • I always wondered why they didn’t allow an optional closing tag of “</>” that would close the corresponding open tag.

    For example:

    <p>This is a string with something <b>bold</> in it.</p>

    where “</>” is closing the <b> tag. Or:

    <blah><bleh><blih><bloh>bluh</></></></>

    which is shorter than:

    <blah><bleh><blih><bloh>bluh</bloh></blih></bleh></blah>

    I fell it is a shortcut like the stand-alone tag <tag/>.