开发者

Generate resouce file (resx) from MVC model definition

开发者 https://www.devze.com 2023-03-17 18:57 出处:网络
I\'ve got a bunch of models to localize and I\'m looking for a way to keep my effort as small as possible :)

I've got a bunch of models to localize and I'm looking for a way to keep my effort as small as possible :)

Essentially, I have a model classes where all pr开发者_高级运维operties(as needed) are decrated with the DisplayNameAttribute.

What I'd like to do is, build a tool which looks for a property on the class definition (e.g. "Views.Contact") and then generates (updates) the default resx file (e.g. "Views.Contact.resx"). This implementation would follow a convention over configuration approach.

Are there any tools/examples out there, which I've missed, which will make this job easier? Is there any framework (.NET4) support for this?


Easier than I thought. Here is my (improvable) code:

 public void GenerateResx()
    {

        Type model = typeof(BuyCABModel);


        List<Type> member = new List<Type>();
        member.Add(typeof(RegisterModel));
        member.Add(typeof(AddOpenAuthAccountModel));
        member.Add(typeof(LoginModel));
        CreateRes(member, "Views.Member.resx");


    }
    private void CreateRes(List<Type> models, string resxFile)
    {

        using (ResXResourceWriter writer = new ResXResourceWriter("c:\\temp\\"+resxFile))
        {

            foreach(Type model in models) 
            {


                PropertyInfo[] ps= model.GetProperties();

                foreach (PropertyInfo p in ps)
                {
                    foreach (Attribute a in p.GetCustomAttributes(true))
                    {
                        if (a.GetType() == typeof(DisplayNameAttribute))
                        {
                            DisplayNameAttribute d = (DisplayNameAttribute)a;
                            writer.AddResource(p.Name + "_DisplayName", d.DisplayName);
                        }
                        else if (a.GetType() == typeof(DisplayAttribute))
                        {
                            DisplayAttribute d = (DisplayAttribute)a;
                            writer.AddResource(p.Name + "_DisplayName", d.Name);
                        }

                    }
                }
            }
            writer.Generate();
            writer.Close();

        }
    }

Tip: If you need the designer.cs code generated in Visual Studio just open the .resx in VS and toggle the Access Modifier DropDown

0

精彩评论

暂无评论...
验证码 换一张
取 消