C# Function Prefix Attribute Names? - c#

In C# what are those brackets called above a method in MVC 3?
[ErrorHandler, SomethingHere]
public function Test() {
}

Not sure what you mean by "those brackets". What is preceding the function is an Attribute.
Microsoft MSDN: System.Attribute
And to expand a little in regards to usage:
An attribute is an annotation that can be placed on an element of source code and used to store application-specific information at compile time. This information is stored in the metadata and can be accessed either during application execution, through a process known as reflection, or when another tool reads the metadata. Attributes might change the behavior of the application during execution, provide transaction information about an object, or convey organizational information to a designer. gnu.org

These are called Attributes.An attribute is a class that inherits from the abstract class System.Attribute. By convention, all attributes are given a class name that ends with the word “Attribute”. Here are some MVC3 Attributes:
AcceptViewAttribute
ActionFilterAttribute
ActionMethodSelectorAttribute
ActionNameAttribute
ActionNameSelectorAttribute
AuthorizeAttribute
BindAttribute
CustomModelBinderAttribute
FilterAttribute
HandleErrorAttribute
HiddenInputAttribute
HttpDeleteAttribute
HttpGetAttribute
HttpPostAttribute
HttpPutAttribute
ModelBinderAttribute
NonActionAttribute
OutputCacheAttribute
RequireHttpsAttribute
ValidateAntiForgeryTokenAttribute
ValidateInputAttribute
and you can create your Custom Attributes

The MVC runtime uses Reflection to find attributes. Then MVC uses this information about located attributes to find the way how the method will be executed, what are the security restrictions and so on

Attributes
It infers the word Attribute, so your example is synonymous with:
[ErrorHandlerAttribute, SomethingHereAttribute]
public function Test() {

those are called method attributes. you can read more on the msdn site

Related

How to create attribute with class restrictions

In C# there is a attribute called AttributeUsage, if you want to set this attribute to a class it automatically detects if the class is derived from the Attribute class and if not it will throw an error.
How can I create such restrictions?
I want to create an attribute which should only be available/settable on a specific class.
What you are trying to do is not possible via attributes AttributeUsage alone, but can be achieved in other way.
AttributeUsage has ValidOn property, that is of AttributeTarget type. It lets you specify that it's valid only on class, but not type of this class.
So, why AttributeUsage only works on classes that derive from Attribute? It's a compiler rule CS0641
'attribute' : attribute is only valid on classes derived from System.Attribute
An attribute was used that can only be used on a class that derives from System.Attribute.
It's not part of AttributeUsage itself.
If you want to achieve something like this, you will need to write your own Roslyn analyzer, that will check it for you. There are few tutorials on how to do write one, i.e. official one or this), I also suggest to look at roslyn-analyzers code, CS0641 is not there, since it's a compiler error, not an analyzer, but you can get quite a lot of references here.
I hope it helps you, wish you good luck!

Attribute that excludes method from the class attribute

I have a WCF service with a security attribute that's applicable only for a class. Is there a built-in .NET attribute or can I create an attribute that marks the method as 'excluded' where I could put in a method so that the class attribute won't be applied? I don't have access to the security attribute so I can't do any modifications with it. I can obviously create a separate class for the method, but it will involve a lot of refactoring.
[SecuredService] // I don't have access to this custom attribute
public class MyClass
{
[DoNotApplySecuredService]//is there a built in attribute like this?
public void MyMethod(){...}
}

Apply Attribute with AttributeTargets = Method to all methods in a class

There is an Attribute called DataSourceAttribute in C#. It needs to be declared on each Method again and again. Is it possible to declare it one time at the class level so that I don't need to repeat myself. If so, how?
In Data Driven UnitTesting, the data source need to be specified with the help of this attribute: [DataSource (...),...]. There are about 10-15 such methods, and I do not want to declare the attribute for each method. I'd like to declare it once and have all the methods inherit it from the class level usage.
Take a look at Afterthough. It is a framework that applies custom chunks of code, including properties, methods, attributes to your solution post-compile.
You might be able to create a custom class attribute that applies the method attribute to all methods in the class.
Here is the MSDN for custom attributes.
http://msdn.microsoft.com/en-us/library/sw480ze8(v=VS.100).aspx

Is there any way to change a class' attributes?

I am using Microsoft REST Stark Kit Preview 2 to explore REST Collection WCF Service. Within the Service.svc.cs class, there are some classes and interfaces being used as base or component classes. For example:
public interface ICollectionService<TItem> where TItem : class
{
...
[WebHelp(Comment = "Returns the items in the collection in JSON format, along with URI links to each item.")]
[WebGet(UriTemplate = "?format=json", ResponseFormat = WebMessageFormat.Json)]
ItemInfoList<TItem> GetItemsInJoson();
...
}
[CollectionDataContract(Name = "ItemInfoList", Namespace = "")]
public class ItemInfoList<TItem> : List<ItemInfo<TItem>> where TItem : class
...
where ICollectionServices and ItemInfoList are all in Microsoft.ServiceModel.Web.dll in the Preview 2. I would change those item's attributes such as WebHelp's Comment and CollectionDataContract's Name so that I could customize help message and templates for xml node names. The Preview 2's change with embedding those interfaces and classes in its dll makes it difficult to do any customization.
So my question is that if there is any way to change a class or interface's attributes or overwrite their existing attributes so that I don't need to get the source codes to make changes?
No, you can't.
What you might be able to do is inherit from the classes. If the attributes in question are not inheritable, you can add your own to your subclasses to override them.
I checked the CollectionDataContractAttribute, and it, at least, is not inheritable. That means if you create a subclass, you can apply a different CollectionDataContract attribute to that subclass.
[CollectionDataContract(Name = "MyItemInfoList", Namespace = "MyNamespace")]
public class MyItemInfoList<TItem> : ItemInfoList<TItem> where TItem : class
However, with members, this approach will only work if they are virtual, so you can override them.
Attributes are burnt in at compile time, and cannot for reflection be set at runtime. There are a few things you can do in "ComponentModel", but they wouldn't apply here. The only other common case here is for "i18n", where an attribute might be designed to pick up different values at runtime (from resx etc, based on a key rather than the description being set in the code) - and again, this doesn't apply in this case.
So, no.
In terms of REST Start kit Preview 2's customization issue, it look like the customization was disabled when the template basic classes are moved to its core dll. According to WCF REST Start kit forum at ASP.NET, the customization features will be back in the next release (soon).

Is there a difference between name decoration/mangling and attribute decoration?

I've been reading a text about an extension to C# and at one point it says that "An attribute decoration X may only be applied to fields of type Y."
I haven't been able to find a definition for attribute decoration, and I'm not making much sense out of this by exchanging the two.
It's probably referring to the Attribute class. For example, you can mark a type as serializable via the SerializableAttribute. When you apply an attribute, you can leave off the "Attribute" suffix.
[Serializable]
public class SomeClass {
}
Attributes provide a means to add meta-data about the code.
Attributes are used to add metadata to .NET (C#) code in a structured manner. What a lot of people don't realise, though, is that there are actually two types of attribute.
The simplest is custom attributes, where you define an attribute that specific classes look for to alter the way they work. A common example is the System.Xml.Serialization attributes which are read by the XmlSerializer to alter its output, e.g. a class could be marked up something like the following to specify its namespace and that the field should be an attribute:
[XmlType(Namespace = "http://mycompany.com/")]
public class MyClass
{
[XmlAttribute]
public string MyField;
}
Custom attributes like this have no meaning to the compiler or the runtime, they are just added to the class as part of its metadata, and can be retrieved by a call to Type.GetCustomAttributes.
The other main group of attributes is pseudo-custom attributes, which actually have meaning to either the compiler or the runtime. The example in the post by Haacked with SerializableAttribute is actually an example of a pseudo-custom attribute. It is actually stored as part of the type definition and cannot be retrieved using Type.GetCustomAttributes. You cannot create your own pseudo-custom attributes.
So it's likely what you're dealing with here is a custom attribute which is being looked for by a specific tool.

Categories

Resources