Tag Archive for asp.net

Internet Explorer style limit

Today I discovered something amazing and nasty at the same time, the page looked good in any other browser but it didn’t rendered in any version of IE (9, 8, 7). After taking a look at the network traffic I discovered one of the style pages was not loaded (IE never did the proper request to the server asking for the css file). That sounds weird… I looked at the source code and the correct <link> sentence was there, then looked at the HTML structure in the IE developer tools, bam! the link was not processed.

After some research in the internet I found something amazingly nasty: Internet Explorer cannot handle more than 31 <style> sentences in a page. This applies to every version of IE (Internet Explorer 10 fixes this issue and won’t be a problem any more). This applies even with the combination of <link rel=”stylesheet” /> and <style> tags in the same page. This article by Microsoft explains that there is not only a limit for the styles defined but the rules (the article says that you cannot apply more than 4095 rules to a webpage in IE).

I found a nice blog post by John Albin (Drupal Evangelist) about the issue and looks that even using the ugly @import rule you would be limited to 993 stylesheets in the same page for Internet Explorer, ugly.

How to solve this issue? well, the easy way is simplifying your styles and using a style minizer and compressor (like the Bundler or SquishIt for ASP.NET). Lesson learned: “don’t abuse of your stylesheets”.

ASP.NET MVC3, Filter attributes and dependency injection

Today a co-worker made me a nice question regarding ASP.NET MVC3, sounds like a simple question with a simple answer, but I think it worth the blog post.

How do I inject a concern into my custom authorization attribute (or any other filter attribute) in the ASP.NET MVC3 framework?

The case is pretty simple, let’s say you have the following service and of course you are using a container to inject your dependencies

public interface ILogger {
    void Log(string message);
}

Well, let’s say that we need to use that service inside our custom attribute for logging:

public class LogAttribute : FilterAttributeProvider {
    public override void OnActionExecuting(ActionExecutingContext context) {
       // I need to use the ILogger service here!
    }
}

Well, we have two options here, the proper and the hack… let’s see the hack option first!

For the hack option we just need to use the Service Locator included with the ASP.NET MVC3 framework:

public class LogAttribute : FilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext context) {
	var log = DependencyResolver.Current.GetInstance<ILogger>();
	// do whatever you want to do here
    }
}

This probably would be one of the only two places you should use a Service Locator, and of course I don’t like it… Thanks to the guys in the ASP.NET MVC framework we have a ‘proper-like’ way to do it, using a filter provider:

The idea is simple, we have an specific special class to provide the attributes that we need to do the job, in ASP.NET MVC3 that class is an implementation of FilterAttributeFilterProvider, most container integrations already has support for it and bundle your filter provider, in this example we would use Autofac (because was the container used in that particular project).

First we need to register the needed service and the provider in your registration code (generally in your Global.asax.cs file), maybe something like this:

var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<Logger>().As<ILogger>().InstancePerHttpRequest();
builder.RegisterFilterProvider();

DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));

To make this work remember to add a reference to Autofac’s MVC3 integration assembly.

Now just create a property dependency in your FilterAttribute

public class LogAttribute : FilterAttribute {
    public ILogger Log { get; set; }
    public override void OnActionExecuting(ActionExecutingContext context) {
	// Now we can use Log here!
    }
}

And well, that’s all… just matter of apply the attribute to your actions/controllers

Personally I don’t like neither of the approaches, I think attributes should be only markers, not behaviour concerns. A good implementation would be splitting the attribute in two, a marker interface and a behaviour class that would act if the attribute is present. With a little of hack this could be possible (would involve creating your own FilterProvider class that would get the present attributes and apply the correct filter attribute action to the engine, something like that)… Well, you got the point =)

As always, I’m open to suggestions and I hope this would help you my friend.

Brad Wilson has a really good blog post series about Dependency Injection and MVC3, including Filter Providers, go and give a read.

Sample solution in bitbucket https://bitbucket.org/cprieto/blogsamplecode/src/

VAN en Alt.Net Hispano–ASP.NET 4.5 y Visual Studio vNext

.NET y Configuraciones – Parte 10

.NET y Configuraciones – Parte 9

Luego de varias semanas de ausencia creo que llego la hora de continuar con nuestra serie (no se preocupen, ya estamos llegando al final).

Converters

Es muy comun encontrarnos con momentos en que necesitamos transformar de un tipo a otro en un archivo de configuracion, por ejemplo, necesitamos transformar de un texto a un enumerador dado sin necesidad de usar la funcion “Enum.Parse”. Bien, para esos menesteres existen lo que en el namespace de Configuration se le llama “converters”, o clases especiales que se encargan de transformar de una representacion a un tipo dado.

System.Configuration viene con varios converters dentro de la cajita, algunos bastante utiles:

CommaDelimitedStringCollectionConverter Transforma de una cadena separada por comas a una coleccion de tipo CommaDelimitedStringCollection
GenericEnumConverter Transforma de una representacion de cadena a un Enum
InfiniteIntConverter Tranforma de un entero de tipo entero ilimitado
InfiniteTimeSpanConverter Un tipo TimeSpan con soporte para representacion al infinito
TimeSpanMinutesConverter Tipo TimeSpan usando minutos
TimeSpanMinutesOrInfiniteConverter Tipo TimeSpan usando minutos con representacion al infinito
TimeSpanSecondsConverter Tipo TimeSpan usando segundos
TimeSpanSecondsOrInfiniteConverter Tipo TimeSpan usando segundos con representacion al infinito
TypeNameConverter Retorna un “Tipo” a partir del nombre del tipo
WhiteSpaceTrimStringConverter Retorna una cadena sin los espacios

Una forma facil de enteder como funciona los converters es facil, simplemente veamos un ejemplo:

using System;
using System.ComponentModel;
using System.Configuration;

namespace ConfigurationSample {
    internal struct ConfigurationConsts {
        public const string Name = &quot;type&quot;;
    }

    public class SampleConfigurationSection : ConfigurationSection {
        [ConfigurationProperty(ConfigurationConsts.Name, IsRequired = true)]
        [TypeConverter(typeof(TypeNameConverter))]
        public Type Type {
            get { return base[ConfigurationConsts.Name] as Type; }
            set { base[ConfigurationConsts.Name] = value; }
        }
    }
}

Y bueno, veamos el archivo de configuracion, observen como se usa el nombre del tipo, mientras que en la seccion de configuracion retornamos el tipo (no la cadena que representa el tipo, ven? type safety de "gratis").

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="sample" type="ConfigurationSample.SampleConfigurationSection, ConfigurationSample" />
  </configSections>
  <sample type="ConfigurationSample.SampleTypeStuff, ConfigurationSample" />
</configuration>

Y para probar que todo funciona bien, nada mejor que nuestro "hola mundo"

using System;
using System.Configuration;

namespace ConfigurationSample {
    class Program {
        static void Main(string[] args) {
            var configuration = ConfigurationManager.GetSection(&quot;sample&quot;) as SampleConfigurationSection;
            if (configuration != null) {
                var type = configuration.Type;
                Console.WriteLine("The type name is {0}", type.Name);
                Console.WriteLine("The type's assembly is {0}", type.Assembly);
            }
            Console.ReadLine();
        }
    }
}

Ven? bastante simple :) los leo en la siguiente entrega