viernes, 17 de febrero de 2017

Cuando tu aplicación es multi-idioma

Estoy  es un proyecto que es .net 4.5 en  asp web forms, nada de mvc

Quiero que las propiedades de mis clase sean multi-idioma,  por ejemplo que  las validaciones sean multi-idioma.
Yo tengo mi clase :
    public class Foo
    {
        public Int32 Id { get; set; }
        [Display(ResourceType = typeof(PropertyNames), Name = "Descripcion")]     
        public string Descripcion { get; set; }
          
    }

Tengo una función

public static string GetDisplayName(Type type, string property)
        {
            var members = type.GetMember(property);
            if (members.Length == 0) throw new ArgumentException(String.Format("Propiedad  '{0}' no esta en el tipo '{1}'", property, type.Name));

            var member = members[0];
            var attributes = member.GetCustomAttributes(typeof(DisplayAttribute), false);
            if (attributes.Length == 0) throw new ArgumentException(String.Format("'{0}.{1}' no tiene display property", type.Name, property));
            var attribute = (DisplayAttribute)attributes[0];
            return attribute.GetName();
        }

Por supuesto tengo un resource PropertyNames.res donde tengo escrito el texto para los usuarios de la propiedad Descripcion
Y en la función   validar

private void Validar (Foo oFoo)
{

            if (String.IsNullOrWhiteSpace(oFoo.Descripcion))
                throw new Exception(Resource.msgCamposObligatorios + Comun.GetDisplayName(typeof(Foo), "Descripcion") )
               
}

Un pasito más. Tengo varios enum que por puesto también quiero sea multi-idioma y que si tengo que sacarlos en un combo o radiobuton list no tenga que llenar el código de id o case.


public static List<KeyValuePair<string, string>> ObtenerTextosEnum(Type tp)
        {
            List<KeyValuePair<string, string>> oret = new List<KeyValuePair<string, string>>();
            if (!tp.IsEnum)
                throw new Exception("No es un tipo Enum reconocible ");
            Array items = Enum.GetNames(tp);
            foreach (string item in items)
            {
                oret.Add(new KeyValuePair<string, string>((string)item, GetDisplayName(tp, item)));
            }
            return oret;
        }


Acepto que las validaciones de una web puede estar perfectamente por JavaScript, siempre que no sean validaciones complejas o funciones que en un futuro se vayan a llamar creando un sw o una app de móvil o escritorio.
Acepto también que se hacen muchas aplicaciones preparadas para el multiidioma con ficheros de recursos que nunca se traducen.