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);
    }
}
Advertisements

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