How can i use custom attribute my c# project - c#

i want use custom attribute on my n-tier project. for
-Caching-
-Logging
-Validation
-Exception

First of all you should search for AOP. this is some kind of developing methodology
Aspect-Oriented Programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. Wikipedia
It is not as simple as you think,in C# you have to use some 3rd party Library.
I suggest to start with MrAdvice, it will helps you.

Writing your custom attributes would look a little something like this:
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method)]
public class LogAttribute : Attribute
{
public bool _loggingEnabled;
public LogAttribute(loggingEnabled)
{
_loggingEnabled = loggingEnabled;
}
}
Usage example:
[Log(true)]
public class SampleClass
{
}
If you require further clarification if you share a little bit more about your intended usage of the attributes I'd be able to clarify a bit more. For instance, I'm not sure if you wanted your logging attribute to give you a means to explicitly state if that class/struct would be logged, but that's how I decided to demonstrate this. Also, note you can apply that to properties, and various other members via the AttributeUsage attribute on your attribute class declaration. I hope that helps.
Update:
Save method example:
[Log(true)]
public void Save(Company company)
{
_context.Save();
}
Then you'll use the static method Attribute.GetCustomAttribute(MemberInfo element, Type attributeType) to retrieve information stored in that attribute. Since in this case, you'll likely want to use logging in many places you'd write another method (most likely static as well) somewhere else in your application that'd look something like this (see the link to the System.Reflection reference below for more information).
public static void Log(MemberInfo element)
{
LogAttribute attribute = Attribute.GetCustomAttribute(element, typeof(LogAttribute);
if (attribute._loggingEnabled)
{
// Create log file and add information from here.
}
}
Attribute Reference
Reflection Reference

Related

class attributes in c#

I need your help.
I have read about the class attributes in C# and I understood that we use them for authorization, authentication or to get some information about the class when you use reflection in the reverse process.
but really I want to understand how the attributes of authentication and authorization work and how really they can force the user to follow some restrictions when we just put the attribute above the class and we do not do any other thing, I cant understand the flow of the authentication or the authorization process using class attributes.
May be my question is not clear enough or has some mistakes but really I need some body to explain for me the authentication and the authorization process using class attributes in C#.
Clear example would be appreciated.
Thanks Every Body.
There are reflection libraries that let you get the attributes on a particular class and iterate over them.
once you understand how attribute values and properties can be iterated over with reflection then it's not too much of a stretch to conceptually understand how they can be used for validation.
You can also use reflection to iterate over methods and properties of an object, and invoke those methods/properties. Microsoft has some pretty good documentation out there for this, so if you want to look this up, you can just goggle it.
Here's a sample program. making use of attributes
class Program
{
static void Main(string[] args)
{
var something = new ClassWithAttributes();
var attributes = typeof(ClassWithAttributes).GetCustomAttributesData();
var attribute = (SomeAttribute) Attribute.GetCustomAttribute(typeof(ClassWithAttributes), typeof (SomeAttribute));
Console.WriteLine(attribute.Name);
Console.ReadKey(false);
}
}
[Some("larry")]
class ClassWithAttributes
{
}
public class SomeAttribute : System.Attribute
{
public string Name { get; set; }
public SomeAttribute(string name)
{
this.Name = name;
}
}
and here's the documentation that I used to help me make that sample
http://msdn.microsoft.com/en-us/library/sw480ze8.aspx
http://msdn.microsoft.com/en-us/library/71s1zwct%28v=vs.110%29.aspx
Attributes apply functionality to a class by means of Reflection. The class can get the attributes it is adorned with, and use them and any parameters as needed.
Further reading: Attributes Tutorial (MSDN)

Class decorator to declare static member (e.g., for log4net)?

I'm using log4net, and we have a lot of this in our code:
public class Foo {
private static readonly ILog log = LogManager.GetLogger(typeof(Foo));
....
}
One downside is that it means we're pasting this 10-word section all over, and every now and then somebody forgets to change the class name. The log4net FAQ also mentions this alternative possibility, which is even more verbose:
public class Foo {
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
...
}
Is it possible to write a decorator to define this? I'd really like to say simply:
[LogMe] // or perhaps: [LogMe("log")]
public class Foo {
...
}
I've done similar things in other languages, but never a statically-compiled language like C#. Can I define class members from a decorator?
Edit: Heh. I'm a Lisp programmer. I appreciate the suggestions to switch languages, but really, if I was going to switch languages for better metaprogramming capabilities, I'd go all the way to Lisp instead of being half-assed about it. Unfortunately using a different language isn't an option on this project.
This is exactly a task for AOP - Aspect Oriented Programming. Have a look at PostSharp, it's a .NET AOP framework, it will allow you to do exactly what you want.
This works by modifying (or weaving) IL code in post-compilation, and adding the logging aspect to the decorated method.
EDIT: It appears that PostSharp now is a commercial product. If you're looking for an open-source (free) solution, I suggest LinFu AOP.
We use something almost identical:
private static readonly ILog Logger = LogManager.GetLogger();
This method is implemented as follows:
[MethodImpl(MethodImplOptions.NoInlining)]
public static ILog GetLogger()
{
Type t;
try { t = new StackFrame(1, false).GetMethod().DeclaringType; }
catch { t = typeof(UnknownObject); }
return GetLogger(t);
}
private static class UnknownObject { }
It still proves to be more of a pain that I'm willing to go through. I much prefer a static object with static methods for logging. Obtaining the calling method is not that expensive provided your not getting file info. Compared to the expense of just calling Log4Net obtaining the calling type is nothing (depending some on the loggers used).
Attributes in .NET are not decorators / active components that influence the class/member they're attached to. Attributes are meta-data that can be retrived with reflection. There is no decorator-like facility in C#, although there are AOP solutions that extend .NET with what you want. The simplest solution is probably to just copy that line to each class though.
We wrapped log4net so we could switch it out with ease. It is something that we could very possibly change our mind on in the future.
While we are not doing this, and you will probably take a performance hit to do so....and I'm really hesitant to even suggest it because I'm not sure it is a good idea.....you could...if you felt devilish enough....wrap log4net and do something like this in your wrapper.
var callingType = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().DeclaringType
If you're smart about how you're logging you could only incur that cost when you need the log message.
Man this would be a breeze in python. I would look into C# Attributes.
If this is ASP.NET or Windows Forms, you can just create a base Page or base Form that all your Forms/Pages derive from. You can declare this member at that level and probably achieve what you desire.
You could probably implement a solution for this with the help of PostSharp, or another Aspect Oriented Programming tool.
It would be pretty trivial using a macro in Boo, but that wouldn't help your situation much.
Perhaps an easy way would be to write an extension method on an Interface, then your class just need to "implement" (but not really because the extension does the impl) the interface
public class Foo : IGetLog<Foo>
{
}
The extension something like....
public interface IGetLog<T> { }
public static class IGetLogExtension
{
public static ILog GetLogger<T>(this IGetLog<T> getLog)
{
return LogManager.GetLogger(typeof(T));
}
}

Attributes creating fields in C#

Alright, so after a few hours of me playing around to no avail, I built a model:
[AttributeUsage(AttributeTargets.All)]
public class PublicAttribute : System.Attribute
{
public enum Access { Public, Private }
public PublicAttribute(string Name, Access acs)
{
}
public PublicAttribute(string Name, Access acs, Action get, Action set)
{
}
}
So that if somebody were to do something like this:
[Public("PublicProperty", PublicAttribute.Access.Public)]
private string PrivateProperty = "hello";
or
[Public("PublicProperty", PublicAttribute.Access.Public, ()=>{return PrivateProperty;}, ()=>{PrivateProperty = value})]
private string PrivateProperty = "hello";
and then if somebody was trying to access PrivateProperty, they could just go:
ContainingClass.PublicProperty = //ect
"PublicProperty". and that is because of the attribute, and it would use those get/set accessors.
What I'd like to know:
Is this even possible?
Is there something that already does this?
If its possible, (even if there is something else) How do i do this?
Basically no to all 3, as C# is a strongly typed language. Even with duck typing what you're trying to achieve doesn't fit the language.
The attributes you've written allow you to interrogate the properties that have those attributes in the class, but you still need to use Reflection to discover which properties of the attribute class are set. The syntax you want to use is checked at compile-time.
No, this is not possible using attributes. Properties are part of the class metadata emitted by the C# compiler, and the C# compiler does not consider custom attributes.
You may be able to do this by using a post-processor such as PostSharp, which can rewrite your assembly after the fact, and can be instructed to consider custom attributes. However, you still wouldn't be able to include a delegate in the attribute: the set of types that can be stored in attribute state is extremely limited.
Microsoft made the WebMethodAttribute in a way reminiscent of what you're trying to describe making it represent more permission than C# public, effectively making a method available outside the application domain to the entire Internet (a very global scope). You might read it to get real implementation insight and ideas.
But you're hitting it very simply. You'll have to program some infrastructure to make it work. It's not automatic and you don't have access to Microsoft's source code for all the details.

C# share code between classes

In Visual Studio 2008 using C#, what is the best way to share code across multiple classes and source files?
Inheritance is not the solution as the classes already have a meaningful hierarchy.
Is there some neat feature that's like a C include file that let's you insert code anywhere you want in another class?
EDIT:
ok, i guess we need a concrete example...
There are several hundred classes in the domain with a well thought out class heirarchy. Now, many of these classes need to print. There is a utility printer class that handles the printing. Let's say there are 3 different print methods that are dependent on the class that is being printed. The code that calls the print method (6 lines) is what I'm trying to avoid copying and pasting across all the different client class pages.
It'd be nice if people wouldn't assume they knew more about the domain that the op - especially when they specifically mention techniques that don't fit...
If you have functionality that you use frequently in classes that represent very different things, in my experience that should fall into just a few categories:
Utilities (e.g. string formatting, parsing, ...)
Cross-cutting concerns (logging, security enforcement, ...)
For utility-type functionality you should consider creating separate classes, and referencing the utility classes where needed in the business class.
public class Validator
{
public bool IsValidName(string name);
}
class Patient
{
private Validator validator = new Validator();
public string FirstName
{
set
{
if (validator.IsValidName(value)) ... else ...
}
}
}
For cross-cutting concerns such as logging or security, I suggest you investigate Aspect-Oriented Programming.
Regarding the PrintA vs. PrintB example discussed in other comments, it sounds like an excellent case for the Factory Pattern. You define an interface e.g. IPrint, classes PrintA and PrintB that both implement IPrint, and assign an instance of IPrint based on what the particular page needs.
// Simplified example to explain:
public interface IPrint
{
public void Print(string);
}
public class PrintA : IPrint
{
public void Print(string input)
{ ... format as desired for A ... }
}
public class PrintB : IPrint
{
public void Print(string input)
{ ... format as desired for B ... }
}
class MyPage
{
IPrint printer;
public class MyPage(bool usePrintA)
{
if (usePrintA) printer = new PrintA(); else printer = new PrintB();
}
public PrintThePage()
{
printer.Print(thePageText);
}
}
You can't just load in code that you'd like to have added into a class in C# via a preprocessor directive like you would in C.
You could, however, define an interface and declare extension methods for that interface. The interface could then be implemented by your classes, and you can call the extension methods on those classes. E.g.
public interface IShareFunctionality { }
public static class Extensions
{
public static bool DoSomething(this IShareFunctionality input)
{
return input == null;
}
}
public class MyClass : Object, IShareFunctionality
{
public void SomeMethod()
{
if(this.DoSomething())
throw new Exception("Impossible!");
}
}
This would allow you to reuse functionality, but you cannot access the private members of the class like you would be able to if you could, say, hash include a file.
We might need some more concrete examples of what you want to do though?
A C# utility class will work. It acts like a central registry for common code (or like the VB.NET Module construct) - it should contain code that's not specific to any class otherwise it should have been attached to the relevant class.
You don't want to start copying source code around if you don't have to because that would lead to code update problems considering the duplication.
As long as the source doesn't need to retain state, then use a static class with static method.
static public class MySharedMembers {
static public string ConvertToInvariantCase(string str) {
//...logic
}
// .... other members
}
If the classes are in the same namespace, there's no need for an include analog. Simply call the members of the class defined in the other function.
If they're not in the same namespace, add the namespace of the classes you want to use in the usings directives and it should work the same as above.
I'm confused by the question: it seems you need to work on your basic OO understanding.
Checkout extension methods: http://msdn.microsoft.com/en-us/library/bb383977.aspx
I don't know of a way to include portions of files but one thing we do frequently is to add an existing file and "link" it from its current location. For example, we have an assemblyInfo.cs file that every project refers to from a solution directory. We change it once and all the projects have the same info because they're referring to the same file.
Otherwise, suggestions about refactoring "common" routines in a common.dll are the best thing I've come up with in .Net.
I am not sure exactly what you mean by a "meaningful" structure already, but this sounds like a place where you could use base class implementation. Though not as "verbose" as C++ multiple inheritance, you might get some benefit out of using chained base class implementation to reuse common functions.
You can preserve class hierarchy, at least visually and override behavior as needed.
Pull out the repetitive code into services. The repetitive code is a clue that there might be some room for refactoring.
For example, create a "PrintingService" which contains the logic needed to print. You can then have the classes that need to print have a dependency on this service (either via the constructor or a parameter in a method which requires the service).
Another tip i have along these lines is to create interfaces for base functionality and then use the interfaces to code against. For example, i had bunch of report classes which the user could either fax, email, or print. Instead of creating methods for each, i created a service for each, had them implement an interface that had a single method of Output(). I could then pass each service to the same method depending on what kind of output the user wanted. When the customer wanted to use eFax instead of faxing through the modem, it was just a matter of writing a new service that implemented this same interface.
To be honest I can't think of anything like includes in Visual C#, nor why you would want that feature. That said, partial classes can do something like it sounds what you want, but using them maybe clashes against your "classes already have a meaningful hierarchy" requirement.
You have many options, TT, extension method, delegate, and lambda

Why does my .NET Attribute not perform an action?

I've created a simple Attribute:
[AttributeUsage(AttributeTargets.Method)]
public class InitAttribute : System.Attribute
{
public InitAttribute()
{
Console.WriteLine("Works!");
}
}
and I apply it to a simple method:
static class Logger
{
public static string _severity;
public static void Init(string severity)
{
_severity = severity;
}
[Init()]
public static void p()
{
Console.WriteLine(_severity);
}
}
What is going on is pretty streight-forward. Only, I expect the attribute to perform an action (printing Works!), but this does not happen.
Addictionally, printing "Works!" is of course just for debugging purposes: I'd like to access the instance's property _severity (to check if is != null, for example), but everything I keep reading about attributes (that are pretty new to me) is about accessing the class' methods or properties and so on via reflection. Once I've evaluated _severity, how can I modify the behavior of the decorated method (in this case, rise an exception "Logger is not initialized" and do not execute it)?
Any help appreciated.
If you need to perform an action as control enters a method, you should look at aspect-oriented programming and frameworks such as PostSharp. Attributes are not designed to perform anything by themselves. They are just a bunch of data (or metadata if you will) attached to stuff in IL assemblies that can be queried at runtime.
Attributes only allow decoration of types and members, but the attribute itself cannot acces the decorated object. You will have to use the constructor parameters of the attribute to pass in any data you require to work with within the attribute.
If you wish to use attributes to automatically alter the behaviour of their target objects, you will have to look at AOP solutions like PostSharp.
The attribute is never actually instantiated and so its constructor is never called. The attribute remains as meta-data until you use reflection to retrieve it. As has been mentioned previously what you are after is an Aspect Oriented Programming tool. PostSharp works by altering the assembly as a post-build step. If you are using the Castle Windsor or Unity Inversion of Control Containers they both offer AOP capabilities as well.

Categories

Resources