Some stuff about Web and .NET development
RSS icon Email icon Home icon
  • A standards-compliant alternative to target=”_blank”

    Posted on March 28th, 2010 Thibaut No comments

    1. The context

    At least once in every web developer’s life, the target attribute of an anchor link (<a>) was used with the “_blank” value to tell the browser “open this link into a new window”. The problem is that this attribute is deprecated and thus doesn’t pass the W3C Validation.

    Although it’s considered a usability error to force that behaviour (the user should be the only one take that decision) and usability experts such as Jakob Nielsen totally agree with this, it’s sometimes a need to control this. It can be within the context of a web application to satisfy a customer request for example and I think a lot of people needed to use this once for a good reason.

     

    2. The alternatives

    • Add a “external” css class to the anchors links in the server-side code, and in javascript open those ones in a new window
    • In javascript, find links having a URL starting with “http://” and open them in a new window

    The first solution isn’t ideal according to me :

    1. You don’t always have access to the server-side code
    2. If the website uses a CMS, you don’t wanna force your users to add these classes by themselves
    3. It generates a heavier markup (with useless “class” attributes)
    4. It requires a manual intervention to add these classes and is thus error-prone

    The second solution is better but yet imperfect :

    1. It’s better because it’s an automatic process
    2. It works quite well as internal links are relative paths (ex: “products.aspx”) so URLs starting with “http://” will open in a new window
    3. Sometimes you have absolute paths who are not real external links. It’s sometimes the case for websites with a CMS. Example : you have a website, “http://mysite.com”, you don’t want a URL “http://mysite.com/products.aspx” to open in a new window, even if it’s starting with “http://”.

     

    3. The solution : target_blank.js

    With all of this in mind, I created a target_blank.js file that does the job, using the great jQuery library :

    $(document).ready(function() {

        $("a").filter(function() {

            return this.hostname && this.hostname.replace("www.", "") != location.hostname.replace("www.", "");

        }).click(function() {

            window.open($(this).attr("href"));

            return false;

        });

    });

    1. When the DOM is loaded (document ready)
    2. Find all the links having a hostname (thus not links such as “mailto:” etc) and having a hostname different from the one of your website (without the “www.” as you want to consider “http://mysite.com” and “http://www.mysite.com” as the same domain)
    3. When clicked, open that link into a new window (passing the href value as argument) and return false to cancel the standard behaviour (which would have been to change the URL within the current window)

     

    4. Conclusion

    We’ve seen here a standards-compliant alternative to target=”_blank” using non-obtrusive Javascript (it degrades well as a browser with javascript disabled simply won’t offer that functionality without crashing the whole thing) and that requires no manual intervention from the developer or the user (case of a CMS). Just keep in mind that it’s not a good usability practice and thus this technique should be used for a good reason (eg : within the context of a web application for a particular need).

    Make good use of it ;)

    Share/Save/Bookmark

  • [FR] DotNetHub : C# 4.0 et les améliorations à la BCL

    Posted on March 28th, 2010 Thibaut No comments

    Bonjour à tous,

    Ci-dessous, vous trouverez en vidéo la conférence de la précédente édition de DotNetHub. Celle-ci, présentée par Pierre-Emmanuel Dautreppe, abordait C# 4.0 et les améliorations à la BCL.

    Plan de la conférence

    • Co & Contra Variance des types génériques
    • Paramètres nommées et optionnels des méthodes
    • Types dynamiques
    • Simplification pour l’interopérabilité COM
    • Améliorations apportées à la BCL (Base Class Library)

    1ère partie

    2ème partie

    Notez également que DotNetHub aura un stand aux Techdays cette fin de mois, n’hésitez donc pas à passer pour vous renseigner, rencontrer ses membres ou devenir sponsor. A bientôt ;)

    Share/Save/Bookmark

  • W3C : Validate green in XHTML strict with ASP.NET

    Posted on March 2nd, 2010 Thibaut 4 comments

    ASP.NET is a fantastic technology for website development. It’s being used by major companies and it has already proven itself over the years. However, I recently encountered some strangy things. If you ever wondered “is it possible to develop a XHTML strict website in ASP.NET ?”, then my answer is : “yes it is, but not that straightforward”. Let’s discuss about that :

     

    1. ASP.NET pages should have the strict DTD by default

    ASP.NET pages have the transitional DTD defined. They should have been strict, in my opinion.

    • Transitional is for projects using legacy code and allows you to write code the bad way. It was useful during the transition phase from HTML to XHTML but it’s over for a good time now
    • Standards compliant websites have usually lighter markup, thus faster to display and easier to maintain due to separation of concerns
    • It’s about to become illegal, in some cases, to develop websites which are not standard compliant. It’s already illegal for an organization to discriminate against disabled people and it’s pretty easy to argue that inaccessible Web sites are discriminatory – that’s what happened in the Sydney 2000 case
    • A lot of other things but it ain’t the point of this article

    Fix this and get strict

    When you create a new ASP.NET page (web form, master page, …), Visual Studio uses template files. You can change these ones to specify a strict DTD by default. They’re located in C:\Program Files\Microsoft Visual Studio\Web\WebNewFileItems\CSharp.

    Here’s what the section above the <head> tag of a WebForm template should look like :

    <%@ Page Language="C#" %><?xml version="1.0" encoding="UTF-8"?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

     

    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">

    • Notice that the <xml version=”…” > tag is placed next to the Page directive. If it’s placed below, the XHTML output code will start with a blank line and as the W3C validator expects it to be on the first line, you’ll get an error :  Unable to Determine Parse Mode!
    • Don’t forget to adapt the lang attribute of the <html> tag. It’s set to french in the example
    • I recommend you to modify the MasterPage template as well to get rid of the transitional doctype definitely

     

    2. Configure the ASP.NET engine to generate XHTML strict markup

    By default, ASP.NET generates markup which does not conform to XHTML strict. One of the most obvious examples is the <form> tag. It’s written like this in the .aspx :

    <form id="form1" runat="server">

    And is rendered like this :

    <form name="aspnetForm" method="post" action="accueil.aspx" id="aspnetForm">

    Try validating this (XHTML strict of course) and you’ll get :

    Pretty annoying ! Hopefully there’s an easy way to fix this. In the web.config file, specify the xhtmlConformance setting :

    <system.web>

      <xhtmlConformance mode="Strict" />

    And you’ll no longer see the name attribute in the <form> tag anymore if you look in the source code with your browser. Try validating again, and you’ll get :

    What the hell !? will you say… Here’s the explanation :

    The W3C validator uses a custom browser which is not recognized by ASP.NET. Thus, it will downgrade the rendering process (legacy mode), generating again the same invalid code. And as the DOCTYPE is not changed and remains to strict, you’ll get that same error again. The solution proposed by Microsoft is to create a browser definition for the W3C validator in the App_Browsers folder of your Web project. Put the lines below in a w3cvalidator.browser file and you’re done with this.

    <browsers>

      <browser id="w3cValidator" parentID="default">

        <identification>

          <userAgent match="^W3C_Validator" />

        </identification>

        <capture>

          <userAgent match="^W3C_Validator/(?’version’(?’major’\d+)(?’minor’\.\d+)\w*).*" />

        </capture>

        <capabilities>

          <capability name="browser" value="w3cValidator" />

          <capability name="majorversion" value="${major}" />

          <capability name="minorversion" value="${minor}" />

          <capability name="version" value="${version}" />

          <capability name="w3cdomversion" value="1.0" />

          <capability name="xml" value="true" />

          <capability name="tagWriter" value="System.Web.UI.HtmlTextWriter" />

        </capabilities>

      </browser>

    </browsers>

     

    3. Learn to deal with ampersands

    In the text of your website, you’ll most probably use ampersands sometimes (&). You know that you shouldn’t type them as is, but rather as &amp;. Easy to do in regular files, but can cause problems sometimes. I recently encountered a “special” case when using master pages : the title is written in the title attribute of the @Page directive…

    <%@ Page Title="Title with an ampersand &amp;"

    …and ASP.NET automatically converts the &amp; to & in the <title> tag of the generated output ! And here’s the result :

    You could use &amp;amp; in this case to overcome the problem. But you’ll agree that it’s not convenient at all and error-prone. Maybe there is a “official” solution to this problem, but here’s my humble trick anyway :

    In the Page_Load event of the MasterPage, encode the content of the <title> tag.

    protected void Page_Load(object sender, EventArgs e)

    {

        this.Page.Title = Server.HtmlEncode(this.Page.Title);

    }

     

    4. Go green

    This is where the article ends. This is a vast subject and if you want to go deeper in this, check out the following MSDN article : Building ASP.NET 2.0 Web Sites Using Web Standards. But for now, with the stuff we’ve just discussed here, this should be enough for you to get :

    See you ;)

    Share/Save/Bookmark