How to create a custom attribute in C# - c#

Can anyone please explain to me a very basic example of a custom attribute with code?

You start by writing a class that derives from Attribute:
public class MyCustomAttribute: Attribute
{
public string SomeProperty { get; set; }
}
Then you could decorate anything (class, method, property, ...) with this attribute:
[MyCustomAttribute(SomeProperty = "foo bar")]
public class Foo
{
}
and finally you would use reflection to fetch it:
var customAttributes = (MyCustomAttribute[])typeof(Foo).GetCustomAttributes(typeof(MyCustomAttribute), true);
if (customAttributes.Length > 0)
{
var myAttribute = customAttributes[0];
string value = myAttribute.SomeProperty;
// TODO: Do something with the value
}
You could limit the target types to which this custom attribute could be applied using the AttributeUsage attribute:
/// <summary>
/// This attribute can only be applied to classes
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute
Important things to know about attributes:
Attributes are metadata.
They are baked into the assembly at compile-time which has very serious implications of how you could set their properties. Only constant (known at compile time) values are accepted
The only way to make any sense and usage of custom attributes is to use Reflection. So if you don't use reflection at runtime to fetch them and decorate something with a custom attribute don't expect much to happen.
The time of creation of the attributes is non-deterministic. They are instantiated by the CLR and you have absolutely no control over it.

While the code to create a custom Attribute is fairly simple, it's very important that you understand what attributes are:
Attributes are metadata compiled into your program. Attributes themselves do not add any functionality to a class, property or module - just data. However, using reflection, one can leverage those attributes in order to create functionality.
So, for instance, let's look at the Validation Application Block, from Microsoft's Enterprise Library. If you look at a code example, you'll see:
/// <summary>
/// blah blah code.
/// </summary>
[DataMember]
[StringLengthValidator(8, RangeBoundaryType.Inclusive, 8, RangeBoundaryType.Inclusive, MessageTemplate = "\"{1}\" must always have \"{4}\" characters.")]
public string Code { get; set; }
From the snippet above, one might guess that the code will always be validated, whenever changed, accordingly to the rules of the Validator (in the example, have at least 8 characters and at most 8 characters). But the truth is that the Attribute does nothing; as mentioned previously, it only adds metadata to the property.
However, the Enterprise Library has a Validation.Validate method that will look into your object, and for each property, it'll check if the contents violate the rule informed by the attribute.
So, that's how you should think about attributes -- a way to add data to your code that might be later used by other methods/classes/etc.

Utilizing/Copying Darin Dimitrov's great response, this is how to access a custom attribute on a property and not a class:
The decorated property [of class Foo]:
[MyCustomAttribute(SomeProperty = "This is a custom property")]
public string MyProperty { get; set; }
Fetching it:
PropertyInfo propertyInfo = typeof(Foo).GetProperty(propertyToCheck);
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
}
You can throw this in a loop and use reflection to access this custom attribute on each property of class Foo, as well:
foreach (PropertyInfo propertyInfo in Foo.GetType().GetProperties())
{
string propertyName = propertyInfo.Name;
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
// Just in case you have a property without this annotation
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
// TODO: whatever you need with this propertyValue
}
}
Major thanks to you, Darin!!

The short answer is for creating an attribute in c# you only need to inherit it from Attribute class, Just this :)
But here I'm going to explain attributes in detail:
basically attributes are classes that we can use them for applying our logic to assemblies, classes, methods, properties, fields, ...
In .Net, Microsoft has provided some predefined Attributes like Obsolete or Validation Attributes like ( [Required], [StringLength(100)], [Range(0, 999.99)]), also we have kind of attributes like ActionFilters in asp.net that can be very useful for applying our desired logic to our codes (read this article about action filters if you are passionate to learn it)
one another point, you can apply a kind of configuration on your attribute via AttibuteUsage.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)]
When you decorate an attribute class with AttributeUsage you can tell to c# compiler where I'm going to use this attribute: I'm going to use this on classes, on assemblies on properties or on ... and my attribute is allowed to use several times on defined targets(classes, assemblies, properties,...) or not?!
After this definition about attributes I'm going to show you an example:
Imagine we want to define a new lesson in university and we want to allow just admins and masters in our university to define a new Lesson, Ok?
namespace ConsoleApp1
{
/// <summary>
/// All Roles in our scenario
/// </summary>
public enum UniversityRoles
{
Admin,
Master,
Employee,
Student
}
/// <summary>
/// This attribute will check the Max Length of Properties/fields
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)]
public class ValidRoleForAccess : Attribute
{
public ValidRoleForAccess(UniversityRoles role)
{
Role = role;
}
public UniversityRoles Role { get; private set; }
}
/// <summary>
/// we suppose that just admins and masters can define new Lesson
/// </summary>
[ValidRoleForAccess(UniversityRoles.Admin)]
[ValidRoleForAccess(UniversityRoles.Master)]
public class Lesson
{
public Lesson(int id, string name, DateTime startTime, User owner)
{
var lessType = typeof(Lesson);
var validRolesForAccesses = lessType.GetCustomAttributes<ValidRoleForAccess>();
if (validRolesForAccesses.All(x => x.Role.ToString() != owner.GetType().Name))
{
throw new Exception("You are not Allowed to define a new lesson");
}
Id = id;
Name = name;
StartTime = startTime;
Owner = owner;
}
public int Id { get; private set; }
public string Name { get; private set; }
public DateTime StartTime { get; private set; }
/// <summary>
/// Owner is some one who define the lesson in university website
/// </summary>
public User Owner { get; private set; }
}
public abstract class User
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
}
public class Master : User
{
public DateTime HireDate { get; set; }
public Decimal Salary { get; set; }
public string Department { get; set; }
}
public class Student : User
{
public float GPA { get; set; }
}
class Program
{
static void Main(string[] args)
{
#region exampl1
var master = new Master()
{
Name = "Hamid Hasani",
Id = 1,
DateOfBirth = new DateTime(1994, 8, 15),
Department = "Computer Engineering",
HireDate = new DateTime(2018, 1, 1),
Salary = 10000
};
var math = new Lesson(1, "Math", DateTime.Today, master);
#endregion
#region exampl2
var student = new Student()
{
Name = "Hamid Hasani",
Id = 1,
DateOfBirth = new DateTime(1994, 8, 15),
GPA = 16
};
var literature = new Lesson(2, "literature", DateTime.Now.AddDays(7), student);
#endregion
ReadLine();
}
}
}
In the real world of programming maybe we don't use this approach for using attributes and I said this because of its educational point in using attributes

Related

Add custom attribute to a class generated by Entity Framework

I am trying to use a custom attribute on a Entity class generated automatically by the Entity Framework.
The problem is how to add an property attribute on an existing field?
Here the point where I am right now:
// the custom attribute class
public class MyCustomAttribute : Attribute
{
public String Key { get; set; }
}
// Entity Framework class generated automatically
public partial class EntityClass
{
public String Existent { get; set; }
//...
}
// set a metadata class for my entity
[MetadataType(typeof(EntityClassMetaData))]
public partial class EntityClass
{
// if I add a new property to the entity, it works. This attribute will be read
[MyCustomAttribute(Key = "KeyOne" )]
public int newProp { get; set; }
}
public class EntityClassMetaData
{
// adding the custom attribute to the existing property
[MyCustomAttribute(Key = "keyMeta") ]
public String Existent { get; set; }
}
Running this test:
[TestMethod]
public void test1()
{
foreach (var prop in typeof(EntityClass).GetProperties())
{
var att = prop.GetCustomAttribute<MyCustomAttribute>();
if (att != null)
{
Console.WriteLine($"Found {att.Key}");
}
}
}
will produce:
Found KeyOne
Or the Metadata class store the attribute in a different way or only works for data annotations.
I am stuck here, how can I set and read custom attributes of the generated class without having to edit the generated file?
I came across this same problem today. I figured EF magic would do the trick and map the attribute across to each model property. Turns out it does, but only for EF data annotations and I couldn't find an answered solution to pull out custom attributes so made this function. Hope it helps dude.
private object[] GetMetadataCustomAttributes(Type T, string propName)
{
if (Attribute.IsDefined(T, typeof(MetadataTypeAttribute)))
{
var metadataClassType =
(T.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault() as
MetadataTypeAttribute).MetadataClassType;
var metaDataClassProperty = metadataClassType.GetProperty(propName);
if (metaDataClassProperty != null)
{
return metaDataClassProperty.GetCustomAttributes(true);
}
}
return null;
}
I believe if you want to set an attribute in the metadata class, you have to use this syntax:
public class EntityClassMetaData
{
// adding the custom attribute to the existing property
[MyCustomAttribute(Key = "keyMeta") ]
public String Existent;
}
You must not have { get; set; } on your pre-existing property - just the property with the correct name and datatype.

Does Getter and Setter in ASP.MVC can instantiate an object?

From Microsoft MVC doc, related to Authoring Tag Helpers, I can read this:
using System;
namespace AuthoringTagHelpers.Models
{
public class WebsiteContext
{
public Version Version { get; set; }
public int CopyrightYear { get; set; }
public bool Approved { get; set; }
public int TagsToShow { get; set; }
}
}
and this:
using System;
using AuthoringTagHelpers.Models;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace AuthoringTagHelpers.TagHelpers
{
public class WebsiteInformationTagHelper : TagHelper
{
public WebsiteContext Info { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "section";
output.Content.SetHtmlContent(
$#"<ul><li><strong>Version:</strong> {Info.Version}</li>
<li><strong>Copyright Year:</strong> {Info.CopyrightYear}</li>
<li><strong>Approved:</strong> {Info.Approved}</li>
<li><strong>Number of tags to show:</strong> {Info.TagsToShow}</li></ul>");
output.TagMode = TagMode.StartTagAndEndTag;
}
}
}
I never saw this kind of code before, where public WebsiteContext Info { get; set; } can automagically instantiate an object???
How it works? Is there any documentation on it?
The answer is in the document you linked:
Note
In the Razor markup shown below:
<website-information info="new WebsiteContext {
Version = new Version(1, 3),
CopyrightYear = 1638,
Approved = true,
TagsToShow = 131 }" />
Razor knows the info attribute is a class, not a string, and you want to write C# code. Any non-string tag helper attribute should be written without the # character.
The tag helper itself doesn't know how to instantiate the instance. You have to do it manually in the Razor markup or set it to a default value in the property declaration or class constructor in order for it to be non-null. Here is an example of setting the instance in the property declaration.
public WebsiteContext { get; set; } = new WebSiteContext
{
Version = new Version(1, 3),
CopyrightYear = 1638,
Approved = true,
TagsToShow = 131
};
public WebsiteContext Info { get; set; } is not instantiating anything here. If you call the following code:
var websiteInformationTagHelper = new WebsiteInformationTagHelper();
then websiteInformationTagHelper.Info will be equal to null
Note, that it is now possible in c# to assign default values like the following which is a little bit different than what you are wondering about:
public WebsiteContext Info { get; set; } = new WebsiteContext()
Not automatically, but yes. The get and set keywords are shorthand for methods that are called after the property is accessed (get) or assigned to (set). You can add a body with a regular code block:
get { return _backingField; }
set { _backingField = value; }
The value keyword represents the value being assigned to the property and you can do most things in those blocks, same as any method, including instantiating an object.
Microsoft documentation - Auto implemented properties:
learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties
If you're referring to instantiating the parent object, that I don't believe makes sense.

Adding validations on class fields in WCF

I have a class Customers. I want to put some validations on it.
e.g. CustGuidId is not Guid.Empty, CustName is NOT NULL (Required).
public class Customer
{
public int CustId;
public string CustName;
public Guid CustGuid;
public Guid[] OrderGuids;
}
I have such collection of customers. So I have ended up adding code like this, which makes it look ugly.
public class BatchError
{
public int Index;
public string ErrorCode;
public string ErrorMessage;
}
public void GenerateValidationErrors(List<Customer> customers, out List<BatchError> batchErrors)
{
int rowNum = 0;
batchErrors = new List<BatchError>(customers.Count);
foreach (var customer in customers)
{
rowNum ++;
Guid customerGuidParsed;
if(!Guid.TryParse(customer.CustGuid.ToString(), out customerGuidParsed))
{
batchErrors.Add(new BatchError { Index = rowNum, ErrorCode = "CustomerGuidcannotBeNull", ErrorMessage = "Customer guid cannot be null." });
}
if (string.IsNullOrEmpty(customer.CustName))
{
batchErrors.Add(new BatchError { Index = rowNum, ErrorCode = "CustomerNamecannotBeEmpty", ErrorMessage = "Customer Name cannot be empty." });
}
}
}
Can we write separate validator classes, like GuidValidator, StringValidator.
and Create array of delegates & chain their invokes ?
(Customer c) => new GuidValidator(c.CustGuid.toString()),
(Customer c) => new StringValidator(c.CustName.toString())
But what design pattern would be best suitable for this scenario?
Is there any other way to add validations in WCF?
There are many ways to do the validation. I prefer to validate DataContract itself before any action.
It can also be done in many like :
DatamemberAttribute has many properties. One of them is
IsRequired,it controls the minOccurs attribute for the schema
element. The default value is false. You can use it like:
[DataContract(Name ="Place", Namespace ="")]
public class DataContractExample
{
[DataMember(IsRequired=true)]
public string DataMemberExample;
}
For more information refer: DataMemberAttribute Class on MSDN.
Easiest way is to validate property like:
[DataContract]
public class Customer
{
[DataMember]
public string CustName
{
get
{
return this._custName;
}
set
{
if(string.IsNullOrEmpty(value))
throw new MyValidationException();
else
this._custName=value;
}
}
}
Another way can be to use Microsoft Enterprise Library. In order to enable validation of the properties of a request message, you only need to add a [ValidationBehavior] attribute to your service interface, just next (or before) the [ServiceContract], and a [FaultContract(typeof(ValidationFault))] on the method declaration. The ValidationBehaviorAttribute and ValidationFault classes are defined in the Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WCF assembly and are part of the Validation Application Block of the Enterprise Library 4.1, more specifically, of the WCF integration module. See full implementation in detail at: http://weblogs.asp.net/ricardoperes/validation-of-wcf-requests-with-the-enterprise-library-validation-block
Finally one more solution cane be to use WCF Data Annotations from http://wcfdataannotations.codeplex.com/. Using this you can use validations like:
[DataMember]
[Required]
[StringLength(500, MinimumLength = 5)]
public string Description{ get; set; }
Choose which ever suite your requirements. Cheers.

Attributes of properties in MetadataType are ignored by EntLib Validation

It's an EntLib-Validator-issue again. I'm playing with EntLib 5.0 in C# and .Net 4.0 on XP pro.
I have some business objects (partial classes) generated by T4 templates. So I decided to put their validation attributes in buddy-classes by using MetadataTypeAttribute as definitely recommended by the documentation of entLib 5.0 (msdn).
But the Validator object I get from the ValidatorFactory doesn't know about the validation attributes, defined in the metadata-class.
The business object is defined like this:
[MetadataType(typeof(PatientMetadata))]
public partial class Patient
{
private string _Name;
private int _DiagnosisCount;
public int DiagnosisCount
{
get
{
return _DiagnosisCount;
}
set
{
if (value != _DiagnosisCount)
{
_DiagnosisCount = value;
}
}
}
public string Name
{
get
{
return _Name;
}
set
{
if (value != _Name)
{
_Name = value;
}
}
}
}
And the metadata class like this, according to documentation:
public class PatientMetadata
{
[RangeValidator(4)]
public int DiagnosisCount { get; set; }
[StringLengthValidator(64, ErrorMessage = "Name must not exceed 64 chars.")]
public string Name { get; set; }
}
If I know try to do validation this way:
var factory = ValidationFactory.DefaultCompositeValidatorFactory;
var validator = factory.CreateValidator<Patient>();
...then watching into validator (during debugging) already says, that it's just an AndCompositeValidator without any children validators.
Again, if I put the validation attributes right in the Patient class, it works perfectly.
By now, I have no real idea, what I'm missing here, since I think doing everything according to the docs.
Thanks in advance to you guys!
The property names of the metadata class must match the property names of the main class.
In your case your metadata class should look like:
public class PatientMetadata
{
[RangeValidator(0, RangeBoundaryType.Inclusive, 10, RangeBoundaryType.Ignore)]
public int DiagnosisCount { get; set; }
[StringLengthValidator(6, ErrorMessage = "Name must not exceed 6 chars.")]
public string Name { get; set; }
}
Also, the docs indicate the accepted approach is to declare all return types as object. However, the docs also talk about using properties but in their example use fields so take it under advisement. :)

Custom DataAnnotation attributes

When I use DisplayAttribute in ASP.NET MVC 3 models it quickly becomes a pain writing them because we have to either hardcode the string or reference the string from a some static class that contains const strings (which is what I have now, see below). But even that is too much for me.
I would like to come up with an attribute that would be called something like [SimpleDisplay] and it would implicitly construct the string for resources by looking at
class name,
property name that the attribute is attached to.
Is this possible?
Something like this
public class Product {
[SimpleDisplay] // it will take Product and Name and do something like this Product_Name
public string Name { get; set; }
}
This is what I want to get rid of, if possible:
[Display(ResourceType = typeof(Resources.Localize), Name = ResourceStrings.product_prettyid)]
public virtual int PrettyId
{
get;
set;
}
[Display(ResourceType = typeof(Resources.Localize), Name = ResourceStrings.product_name)]
public virtual string Title
{
get;
set;
}
Now I know that it is not possible to inherit the DisplayAttribute cause it's sealed. What other options I have? Does it even make sense?
I would try creating just a standard attribute and custom DataAnnotationsModelMetadataProvider. You can override CreateMetadata method, which gets IEnumerable<Attribute>. You should than search for your attribute
attributes.OfType<SimpleDisplayAttribute>().FirstOrDefault();
and populate model metadata in any way you want.
If i have a correct understanding what you mean, you may just create a simple custom attribute like this one:
public class LocalizedDisplayNameAttribute : DisplayNameAttribute {
public LocalizedDisplayNameAttribute(string expression) : base(expression) { }
public override string DisplayName {
get {
try {
string[] vals = base.DisplayName.Split(',');
if(vals != null && vals.Length == 2)
return (string)HttpContext.GetGlobalResourceObject(vals[0].Trim(), vals[1].Trim());
} catch {}
return "{res:" + base.DisplayName + "}";
}
}
}
You may then use it as an attribute on your properies. MVC HTML extensions will pickup your custom attribute.
[LocalizedDisplayName("LBL, lbl_name1")]
public string[] Name1 { get; set; }

Categories

Resources