Help understand syntax of this statement in C# - 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")]

Related

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 ...

WM_SETFOCUS, where defined for C#?

I need to find out where WM_SETFOCUS is defined.
For instance, I know it isn't System.Windows.Forms.WM_SETFOCUS
I've looked online, and everything seems to just use the name with no mention of how to let your compiler know the name.
I DO know the integer value it represents, but I really want to reference an authoritative assembly, and not just litter my code with constants.
I am using the value in a class which implements IMessageFilter.
ADDED DETAILS:
Using IMessageFilter,
I am getting messages, and the messages have a Msg field (int) which identifies its type. Where can I find C# definitions of those integer values? (I don't need one named WM_SETFOCUS, I just need something with all the definitions of the values I am receiving.)
Since Microsoft supplies IMessageFilter, shouldn't they also supply the information needed to make it useful?
It would seem to be defined in System.Windows.Forms.NativeMethods.WM_SETFOCUS (Which, unfortunately is an internal class). It's also defined in Microsoft.VisualStudio.NativeMethods.WM_SETFOCUS
If you're worried about littering your code with native methods, I would do as the framework does and create an internal NativeMethods static class, and dump everything interop-related in it. At least you can keep it all in one place.

A strongly typed, localizable DisplayNameAttribute

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...

PropertyInfo.AddValueChanged Equivalent for Fields?

I'm trying to find the equivalent of PropertyInfo.AddValueChanged for FieldInfo. I basically just need to receive an event any time the field's value changes. I'm assuming there's nothing like this and I'll have to manipulate IL code or something like that. I'm willing to go that route, but any suggestions on how I should go about it? And is there an AddValueChanged equivalent for fields that I'm not aware of so I don't have to go that route?
Thanks.
Why not just wrap the field in a property, and implement an event on change (ie: make your class INotifyPropertyChanged or your own equivelent)?
That's one the beautiful things about properties - they allow you to define behavior in this manner. Fields do not have any equivelent, and manipulating IL is not going to change this. As long as it's a field, it will not notify.
Let me just confirm that there's nothing built-in like what you're after. Properties can easily implement that because the setter is a method, while fields by design don't have setter methods, their value is just modified and that can happen from any place in the code. To do what you're after, I think you could take a look at PostSharp.
As indicated in the other answers, with the limited information you provided, I would suggest you make any value assignments via the field's accessor. If it needs to be outside of any class, you can create a separate class (or struc) (and put your field change in an accessor.) If you do not need multiple instances of the field, you can declare it static and only access it via its accesor.
Are you exposing public fields that you are trying to monitor? It seems like you should wrap them in properties and expose them that way. Then you can use the monitoring code you've already got.

Categories