Posts tagged with c - page 7

Localizing MVC for ASP.NET views and master pages

Microsoft’s MVC for ASP.NET is still under serious development but at the moment support for localization is a little weak. Here’s one approach that works with the 04/16 source-drop.

LocalizingWebFormViewLocator class

This class helps by trying to identify language-specific versions of views, user controls and master-pages where they exist, falling back to the generic one where necessary.

public class LocalizingWebFormViewLocator : ViewLocator {
  public LocalizingWebFormViewLocator() : base() {
    ViewLocationFormats = new[] { "~/Views/{1}/{0}.{2}aspx", "~/Views/{1}/{0}.{2}ascx", "~/Views/Shared/{0}.{2}aspx", "~/Views/Shared/{0}.{2}ascx" };
    MasterLocationFormats = new[] { "~/Views/{1}/{0}.{2}master", "~/Views/Shared/{0}.{2}master" };
  }

  protected override string GetPath(RequestContext requestContext, string[] locationFormats, string name) {
    string foundView = FindViewLocation(locationFormats, requestContext, name, CultureInfo.CurrentUICulture.Name + ".");
    if (String.IsNullOrEmpty(foundView))
      foundView = FindViewLocation(locationFormats, requestContext, name, "");
    return foundView;
  }

  protected string FindViewLocation(string[] locationFormats, RequestContext requestContext, string name, string cultureSuffix) {
    string controllerName = requestContext.RouteData.GetRequiredString("controller");
    foreach (string locationFormat in locationFormats) {
      string viewFile = string.Format(CultureInfo.InvariantCulture, locationFormat, name, controllerName, cultureSuffix);
      if (HostingEnvironment.VirtualPathProvider.FileExists(viewFile))
        return viewFile;
      }
    return null;
  }
}

Using the class

To use the class you must set the ViewLocator on the WebFormViewEngine to a new instance of LocalizingWebFormViewLocator (either in the constructor or in your common controller subclass) and ensure that any master pages are specified on the RenderView calls to ensure the localized version is detected.

public class HomeController : Controller {
  public HomeController() {
    ((WebFormViewEngine)ViewEngine).ViewLocator = new LocalizingWebFormViewLocator();
  }

  public ActionResult Index() {
    return RenderView("Index", "Site");
  }

  public ActionResult About() {
    return RenderView("About", "Site");
  }
}

You must also ensure the thread’s current UI culture is set. The easiest way to do this is to specify the following in your web.config file’s system.web section which will pick it up automatically from the user’s browser settings via the HTTP language-accept header.

<globalization responseEncoding="UTF-8" requestEncoding="UTF-8" culture="auto" uiCulture ="auto" />

MVC for ASP.NET default page in pseudo-Japanese via the Babelfish

Then all you need to do is create views and master pages that have the culture name appended between the name and .aspx, e.g:

  • /Views/Home/Index.aspx (common fall-back for this view)
  • /Views/Home/Index.ja.aspx (Japanese view)
  • /Views/Home/Index.en-GB.aspx (British English view)
  • /Views/Shared/Site.Master (common fall-back for this masterpage)
  • /Views/Shared/Site.ja.Master (Japanese masterpage)

Caveats

There are some limitations to this solution:

Only primary language is attempted

Only the user’s primary language specified in their browser is attempted despite browsers having a complete list in order of preference. Ideally we would scan down this entire list before giving up but that would need more code and there is the issue of whether scanning for several languages across several folders could be too much of a performance hit.

Specifying the masterpage on RenderView

It would be nice if you didn’t have to specify the masterpage on render view but if you do not then the ViewLocator never gets called to resolve the actual masterpage address. This may be for backward compatibility within MVC.

Creating files in Visual Studio

Visual Studio 2008 seems to get a little confused if you create a Index.ja.aspx or Site.ja.aspx – whilst the files are created okay the names are not and you will need to adjust the class names to ensure they don’t conflict and make sure the opening declaration on the .aspx file points to the right code-behind page and inherits from the correct name.

Of course the beauty of this approach is you can mix-and-match using dedicated views where required and localising labels in the fall-back view when it isn’t.

[)amien

Using LINQ to foreach over an enum in C#

I can’t be the only person in the world who wants to foreach over the values of an enum otherwise Enum.GetValues(Type enumType) wouldn’t exist in the framework. Alas it didn’t get any generics love in .NET 2.0 and unhelpfully returns an array.

Thanks to the power of LINQ you can do this:

foreach(var customerType in Enum.GetValues(typeof(CustomerTypes)).Cast<CustomerTypes>()))

That is okay, but this is more concise:

foreach(CustomerTypes customerType in Enums.Get<CustomerTypes>())

The tiny class to achieve that is, of course:

using System.Collections.Generic;
using System.Linq;

public static class Enums {
  public static IEnumerable<T> Get<T>() {
    return System.Enum.GetValues(typeof(T)).Cast<T>();
  }
}

Great.

[)amien

5 signs your ASP.NET application may be vulnerable to HTML injection

If you don’t encode data when using any of the following methods to output to HTML your application could be compromised by unexpected HTML turning up in the page and modifying everything from formatting though to capturing and interfering with form data via remote scripts (XSS). Such vulnerabilities are incredibly dangerous.

Using MonoRail or Microsoft’s MVC does not make you automatically immune – use {! } in MonoRail’s Brail engine and the HtmlHelpers in Microsoft’s MVC to ensure correct encoding.

Just imagine post.Author contains “><script src=”http://abadsite.com”></script> after an unscrupulous user entered that into a field your application uses and it got into the database. The following typical ASP.NET techniques would leave you open.

1. You use <%= %> or <%# %> tags to output data

Example showing outputting literals with <%= %> :

// Vulnerable
<p>Posted by <%= post.Author %></p>
// Secure
<p>Posted by <%= HttpUtility.HtmlEncode(post.Author) %></p>

2. You use Response.Write

Example showing writing out attributes with Response.Write and String.Format, again post.Author could contain

// Vulnerable
Response.Write(String.Format("<input type=\"text\" value=\"{0}\" />", post.Author);
// Secure
Response.Write(String.Format("<input type=\"text\" value=\"{0}\" />", HttpUtility.HtmlAttributeEncode(post.Author));

3. You set HRef or Src on HtmlAnchor, HtmlImage or HtmlnputImage controls

In general the HtmlControls namespace are very well behaved with encoding but there is a bug in the code that attempts to adjust the relative url’s for href and src attributes which causes those properties to bypass encoding (I’ve reported this to Microsoft).

Example showing anchor HRef attribute abuse:

// Vulnerable
outputDiv.Controls.Add(new HtmlAnchor() { Text = "Test", HRef = post.Author } );
// Secure
outputDiv.Controls.Add(new HtmlAnchor() { Text = "Test", HRef = HttpUtility.HtmlAttributeEncode(post.Author) } );

4. You set the Text property of WebControls/WebForms

You would imagine the high-level WebForms controls would take care of encoding and you’d be wrong.

Example showing the Label control being so easily taken advantage of:

// Vulnerable
outputDiv.Controls.Add(new Label() { Text = post.Author } );
// Secure
outputDiv.Controls.Add(new Label() { Text = HttpUtility.HtmlEncode(post.Author) } );

The one exception to this is the Text property of input controls – as they put the value into an attribute and therefore call HttpUtility.HtmlAttributeEncode for you.

5. You use the LiteralControl

LiteralControl is a useful control for adding text to the output stream that doesn’t require it’s own tag. It also helpfully, and uncharacteristically, provides a useful constructor. Unfortunately it fails encode the output.

Example showing poor LiteralControl wide open:

// Vulnerable
outputDiv.Controls.Add(new LiteralControl(post.Author));
// Secure
outputDiv.Controls.Add(new LiteralControl(HttpUtility.HtmlEncode(post.Author)));
Do not: 1. Encode data in the database – your contaminated data will be difficult to use elsewhere and will end up double-encoded 2. Look for script on submit – you won’t catch every combination and it might prevent valid data 3. Trap entry with client-side code – it is trivially bypassed

Just encode the output :)

[)amien

PS: The samples use .NET 3.5 object initializer syntax for brevity as many affected controls do not have useful constructors)

Calculating Elf-32 in C# and .NET

GitHub has the latest version of Elf32

Because you can never have enough hashing algorithms at your disposal this one is compatible with the elf_hash function that forms part of the Executable and Linkable Format.

using System;
using System.Security.Cryptography;

public class Elf32 : HashAlgorithm {
  private UInt32 hash;

  public Elf32() {
    Initialize();
  }

  public override void Initialize() {
    hash = 0;
  }

  protected override void HashCore(byte[] buffer, int start, int length) {
    hash = CalculateHash(hash, buffer, start, length);
  }

  protected override byte[] HashFinal() {
    byte[] hashBuffer = UInt32ToBigEndianBytes(hash);
    this.HashValue = hashBuffer;
    return hashBuffer;
  }

  public override int HashSize { get { return 32; } }

  public static UInt32 Compute(UInt32 polynomial, UInt32 seed, byte[] buffer) {
    return CalculateHash(seed, buffer, 0, buffer.Length);
  }

  private static UInt32 CalculateHash(UInt32 seed, byte[] buffer, int start, int size) {
    UInt32 hash = seed;

    for (int i = start; i < size; i++)
       unchecked {
          hash = (hash << 4) + buffer[i];
          UInt32 work = (hash & 0xf0000000);
          if (work != 0)
             hash ^= (work >> 24);
          hash &= ~work;
       }
    return hash;
  }

  private byte[] UInt32ToBigEndianBytes(UInt32 x) {
    return new byte[] {
       (byte)((x >> 24) & 0xff),
       (byte)((x >> 16) & 0xff),
       (byte)((x >> 8) & 0xff),
       (byte)(x & 0xff)
    };
  }
}

[)amien