A strongly typed, localizable DisplayNameAttribute - c#

I'm trying to write a strongly typed, localizable DisplayNameAttribute, but I can't get it to even compile. What I'd like to do on my viewmodel properties is something like
[LocalizedDisplayName<HomeResources>(r => r.WelcomeMessage)]
which would basically do the same thing as
[DisplayName("Welcome to my site!")]
except the message is localized. However, I can't get neither the generic constructor working (how do you supply type arguments to a constructor?) nor the choosing of what string to use. The current constructor looks like this
public class LocalizedDisplayNameAttribute<TResource> : DisplayNameAttribute
{
public LocalizedDisplayName(Expression<Func<TResource, string>> resource)
{ // ...
but the compiler complains that the input argument is not a compile time constant, so apparently this way of doing it is not valid.
Is there any way to get a strongly typed, localized attribute for display name? Is there one out there already?

You can't do it via an attribute. Keep in mind that an attribute is purely metadata embedded in an assembly. There's currently no way to embed a code construct such as an expression as metadata.
If you really really wanted to provide a means of specifying this metadata in a strongly typed way, you could write your own ModelMetadataProvider. It's a pretty advanced task, but I'm currently in the middle of a blog post that shows how to write one which I'll post soon hopefully.

Attribute classes cannot be generic.

IMO, the only way you can do that is:
[LocalizedDisplayName("WelcomeMessage")]
In fact framework attributes are not typed (like DefaultPropertyAttribute etc)

Since an attribute can't be generic and its arguments must be constants, you can't do it the way you describe. Anyway, members of the resource classes generated by the designer are static, so you can't access them through a instance.
Another option would be to pass only the name of the resource to the attribute :
[DisplayNameResourceKey("WelcomeMessage")]
When you want to retrieve the actual message, you just call ResourceManager.GetString with the resource key. But of course you lose the strong typing...

Related

Alias to static class in XAML

For localization I have one resx file per XAML file. They lie in the same directory and namespace. The resx name corresponds to the XAML name with the word Resources appended.
I access the resources like this:
<TextBlock Text="{x:Static r:MainWindowResources.SomeText}"/>
Since I find this quite lengthy (and there are even longer class names) I was wondering if there was some way I could define an alias to MainWindowResources. In C# I can do this with a using directive.
It would be a lot easier if the generated resource file wrapper wouldn't be a class with static properties. A possible solution would be to use a wrapper instance which inherits from DynamicObject. You could pass it a type and access the type's static members through it. Then you'd add an instance of this wrapper as a resource in XAML.
But I'd lose IntelliSense support and it probably wouldn't be great performance-wise either.
Another solution would be to use the WPF Localization Extension but I'd also lose IntelliSense support. Plus I'm curios whether there is any other way to create an alias to a static class. :)
No, there is no way to simply alias the class name in Xaml like you would in C# with using.
A custom markup extension with a short name is probably the best you could do, but as you say, you would lose editor completion support. If you're really desperate, you could write a T4 template that would generate an enum with one value for each string in your resource file, and then you could use an enum value as your markup extension parameter with completion support (e.g., {l:MainWindowString SomeText}), but that seems like a lot of work just to shorten some Xaml attributes, and they wouldn't be that much shorter.
I would just stick with what you have.

What is Reflection property of a programming language?

Its said that most high-level dynamically types languages are reflexive. Reflection (computer programming) on Wikipedia explains but it doesn't really give a very clear picture of what it means. Can anyone explain it in a simpler way by a relevant example?
To give you a example how to use Reflection in a practical way:
Let's assume you are developing an Application which you'd like to extend using plugins. These plugins are simple Assemblies containing just a class named Person:
namespace MyObjects
{
public class Person
{
public Person() { ... Logic setting pre and postname ... }
private string _prename;
private string _postname;
public string GetName() { ... concat variabes and return ... }
}
}
Well, plugins should extend your application at runtime. That means, that the content and logic should be loaded from another assembly when your application already runs. This means that these resources are not compiled into your Assembly, i.e. MyApplication.exe. Lets assume they are located in a library: MyObjects.Person.dll.
You are now faced with the fact that you'll need to extract this Information and for example access the GetName() function from MyObjects.Person.
// Create an assembly object to load our classes
Assembly testAssembly = Assembly.LoadFile(Application.StartUpPath + #"MyObjects.Person.dll");
Type objType = testAssembly.GetType("MyObjects.Person");
// Create an instace of MyObjects.Person
var instance = Activator.CreateInstance(objType);
// Call the method
string fullname = (string)calcType.InvokeMember("GetName",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
null, instance, null);
As you can see, you could use System.Reflection for dynamic load of Resources on Runtime. This might be a help understanding the ways you can use it.
Have a look on this page to see examples how to access assemblys in more detail. It's basically the same content i wrote.
To better understand reflection, think of an interpreter that evaluates a program. The interpreter is a program that evaluates other programs.
The program can (1) inspect and (2) modify its (a) own state/behavior, or the state/behavior of the interperter running it (b).
There are then four combinations. Here is an example of each kind of action:
1a -- Read the list of fields an object has
2a -- Modification of the value of one field based on the name of the field; reflective invocation of methods.
1b -- Inspect the current stack to know what is the current method that is executed
2b -- Modify the stack or how certain operations in the language are executed (e.g. message send).
Type a is called structural reflection. Type b is called behavioral reflection. Reflection of type a is fairly easy to achieve in a language. Reflection of type b is way more complicated, especially 2b--this is an open research topic. What most people understand by reflection is 1a and 2a.
It is important to understand the concept of reification to understand reflection. When a statement in the program that is interpreted is evaluated, the interpreter needs to represent it. The intepreter has probably objects to model field, methods, etc. of the program to be interpreted. After all, the interpreter is a program as well. With reflection, the interpreted program can obtain references to objects in the interpreter that represent its own structure. This is reification. (The next step would be to understand causal connection)
There are various kinds of reflective features and it's sometimes confusing to understand what's reflective or not, and what it means. Thinking in term of program and interpreter. I hope it will help you understand the wikipedia page (which could be improved).
Reflection is the ability to query the metadata the program that you wrote in run-time, For example : What classes are found inside an assembly, What methods, fields and properties those classes contains, and more.
.net contains even 'attributes', those are classes that you can decorate with them classes, methods, fields and more, And all their purpose is to add customized metadata that you can query in run-time.
Many time details depend on metadata only. At the time of validation we don't care about string or int but we care that it should not be null. So, in that case you need a property or attribute to check without caring about specific class. There reflection comes in picture. And same way if you like to generate methods on a fly, (as available in dynamic object of C# 4.0), than also it is possible using reflection. Basically it help to do behavior driven or aspect oriented programming.
Another popular use is Testing framework. They use reflection to find methods to test and run it in proxy environment.
It is the ability of a programming langauge to adapt it's behaviour based upon runtime information.
In the .Net/C# world this is used frequently.
For example when serializing data to xml an attribute can be added to specify the name of the field in the resultant xml.
This is probably a better question for programmers.stackexchange.com.
But it basically just means that you can look at your code from within your code.
Back in my VB6 days there were some UI objects that had a Text property and others that had a Description (or something other than 'Text' anyway, I forget). It was a pain because I couldn't encapsulate code to deal with both kinds of objects the same way. With reflection I would have at least been able to look and see whether an object had a Text or a Description property.
Or sometimes objects might both have a Text property, but they derive from different base classes and don't have any interface applied to them. Again, it's hard to encapsulate code like this in a statically typed language without the help of reflection, but with reflection even a statically typed language can deal with it.

What does this C# syntax do?

I am reading a post about mobile web development and ASP.NET MVC here: http://www.hanselman.com/blog/ABetterASPNETMVCMobileDeviceCapabilitiesViewEngine.aspx.
In the article, Scott Hanselman goes through the process of creating his own view engine to render different views based on whether the site is requested from a mobile web browser or not.
In his MobileHelpers class, he has several methods with signatures that are very foreign to me. Here's an example:
public static void AddMobile<T>(this ViewEngineCollection ves, Func<ControllerContext, bool> isTheRightDevice, string pathToSearch)
where T : IViewEngine, new()
{
ves.Add(new CustomMobileViewEngine(isTheRightDevice, pathToSearch, new T()));
}
I've worked a little bit with inline functions like this (I think thats what they're called) but this logic is eluding me. I don't understand the purpose of the where T : ...... line either.
Could you guys help me understand what is happening here?
It would help if you could identify which parts in particular are confusing to you. I've picked the two I think are the most likely based on your question, and explained those. If there is any other syntax that is confusing you, please edit your question to explain which.
Explanation for where T : IViewEngine, new()
C# allows you to place constraints on generic type parameters. You can read more about constraints here.
In your particular case, where T : IViewEngine means that whatever type T is must be a descendant of the IViewEngine type. where T : new() is special syntax that indicates that whatever type T is must have a default constructor.
Explanation for this ViewEngineCollection ves
The keyword this means that the method AddMobile is an extension method to the ViewEngineCollection class. This means that in addition to being called as AddMobile(someViewEngineCollection, ...), it can be called as someViewEngineCollection.AddMobile(...). You can read more about extension methods here.
This is known as an extension method. The this modifier on the first parameter allows the method to be called as if it's an instance method on the type `ViewEngineCollection. For example
ViewEngineCollection col = ...;
col.AddMobile<SomeType>(() => true, "thepath");
The second item you mentioned, where, is known as a generic constraint. It limits the set of types which can be used for T to those which have a public parameterless constructor and derive from IViewEngine
The this is for an extension method. So any reference to a ViewEngineCollection has an extension method called AddMobile. The where T : IViewEngine, new() is called a generic constraint.
Where the calling device contains identification information in its user agent details (this is typically the browser name or something in webapp the method is aiming to match up a custom view engine to the route table for that device.
It's a bit generic and without context can be quite confusing but each device identifies itself in a unique way (well unique by device name at least).
essentially this method is identifying the right veiw engine to use to handle the device information given.
Since everyone else is trying to explain constraints and generics i thought i would leave that to the pros ...
http://msdn.microsoft.com/en-us/library/bb384067.aspx
... best way really ...

Help understand syntax of this statement in C#

I'm currently working on DevExpress Report, and I see this kind of syntax everywhere. I wonder what are they? What are they used for? I meant the one within the square bracket []. What do we call it in C#?
[XRDesigner("Rapattoni.ControlLibrary.SFEAmenitiesCtrlTableDesigner," + "Rapattoni.ControlLibrary")] // what is this?
public class SFEAmenitiesCtrl : XRTable
Those are called Attributes.
Attributes can be used to add metadata to your code that can be accessed later via Reflection or, in the case of Aspect Oriented Programming, Attributes can actually modify the execution of code.
The [] syntax above a type or member is called an attribute specification. It allows a developer to apply / associate an attribute with the particular type or member.
It's covered in section 24.2 of the C# language spec
http://www.jaggersoft.com/csharp_standard/24.2.htm
They are called attributes. They are quite useful for providing metadata about the class (data about the data).
They are called Attributes, You can use them to mark classes, methods or properties with some meta-data that you can find by reflection at runtime.
For instance, one common one is Serializable which marks a class as suitable for conversion into an offline form for storage later.
It is called an attribute.
In this case, DevExpress is using custom attributes on their report classes.
If you're interested in why you want to create custom attributes, this article explains it.
Piling on to the previous answers, this is an attribute that takes a string value in its constructor. In this case, the '+' in the middle is a little confusing... it should also work correctly with:
[XRDesigner("Rapattoni.ControlLibrary.SFEAmenitiesCtrlTableDesigner,Rapattoni.ControlLibrary")]

C#: Making sure parameter has attribute

I have an attribute lets call it SomeAttribute and a class i need to make sure the class is passed a type which has SomeAttribute. So this is how i do it now:
public class Test()
{
public Test(SomeType obj)
{
if(!obj.GetType().IsDefined(typeof(SomeAttribute), false))
{
throw new ArgumentException("Errormessage");
}
}
}
But this means that i don't get any errors at compile time but somewhere at runtime, if obj does not have the attribute. Is there a way to specify in the method declaration that the parameter must have some attribute ? So i get errors i compile time when using the wrong parameters, or do i have to use an empty interface ?
There's no way to enforce an attribute at compile-time. You may want to reconsider your design - usually attributes are more about metadata, less about runtime behavior.
NDepend's Code Query Language is a static anlysis tool that could probably detect violations - but if you're not already using NDepend, I'd be hesitant to include it for this requirement alone.
Then again, lacking context of what you want to do - it's a bit like solving the other half your problem.
No, there's no way of requiring an attribute - but you could always write unit tests to scan through your assemblies and check that the appropriate attributes had been applied - assuming you can actually detect this requirement.
It sounds somewhat odd though - could you give some more details as to why you're using this scheme? Perhaps another approach would be more appropriate, such as another parameter to describe the extra data you're interested in.

Categories