using attribute to read Method Parameters - c#

I want to log the entry of methods. In entry log I would have inputs\parameters received by the method. This has to be done for thousands of methods.
I thought of doing this logging of input parameters using C# ATTRIBUTES, since they fired before method call. (Something similar to ActionFilters in MVC)
Is that possible to read method parameters through attributes?

The concept you are looking for is called aspect oriented programming (AOP). It is a technique that allows you to "weave" in blocks of boilerplate code across your application code. Logging is a perfect example for that. You can either go the hard way and implement logging before and after each method call manually (which is on the one hand not feasible in large projects and on the other hand error prone).
Or you can use an AOP Framework that allows you to define these cross cutting functions in one place and apply it declaratively to your application code. There are several approaches to achieve this; one is to create IL after the build of the application logic and therefore integrating the aspects at compile time. A well known example for this is PostSharp. There also is a free edition that is good for the start.
BTW: PostSharp heavily relies on attributes, so you're on the right track.
Another option is to integrate the aspects at run time (keyword is interception). Most IoC Frameworks offer this. This approach is easy to use but has some downsides IMHO (weaker runtime Performance, only virtual methods can be intercepted).

Attributes are not 'fired before method call', the code that invokes a method that is decorated with an Attribute may (or may not) do something based on the presence of the Attribute.
The Attribute doesn't know the member it is applied on, nor can access it in any (straight forward) way.

Related

Why would you use 'custom attributes' in your code (.NET)

Could anyone explain the benefits (or reasons) to use custom attributes in your code. Of course I use (and understand the purpose of) defined attributes in certain scenarios (WCF, Serialization etc.), but I cannot imagine any algorithms where I would need to create and use my own custom attributes. Could someone provide a real-world case where usages of custom defined attributes bring something to a project.
The same reason as for WCF etc, but something that's specific to your project - you want to add some metadata to some members (types, fields, methods, whatever) to specify something about the mechanism involved, and it's not something which is covered by existing attributes.
For example, NUnit wanted to add their own indication that a particular type contained unit tests - there was no such existing attribute, so they created TestFixtureAttribute.
It's a relatively rare event, sure - but it can happen.
If you want to write your own system like WCF, Serialization, etc...
If you write code that iterates over types or members and does things with them, you will frequently want to use your own custom attributes to mark some members as being different or special.
I regularly use custom .Net attributes to support tooling in my infrastructure. One example was from very early in the .Net days (C# 1.0 to be exact). I was working on a research project which had a native C++ front and a brand new C# back end written by yours truly.
The front and back end shared a very similar object model which was evolving very rapidly. Not wanting to have to hand code both a C++ front end model, C++ serialization mechanism and a C# serialization mechanism I chose instead to attribute my C# types with custom attributes. They told me the parts of the model which were shared between the front and back end.
Once those attributes were in place I wrote a quick and dirty tool which
Parsed out the attributes to construct the core shared model
Generated the C# serialization code
Generated the C++ code
Generated the C++ serialization code
This made it dirt simple to keep my model up to date between my 2 projects. Just change the C# code, compile and re-run my tool.
I have used annotations in a custom AOP (Aspect-Oriented Programming) system I developed a while back. Attributes are also very useful for controlling orthogonal concerns like code generation.
Custom validation is a very good use case and can be seen from these links:
http://odetocode.com/blogs/scott/archive/2011/02/21/custom-data-annotation-validator-part-i-server-code.aspx
How to create Custom Data Annotation Validators
They can be used for marking tests, as in MBUnit for example. They can also be useful for code that inspects and loads classes (like a Plugin system) to provide meta-information.
They are really useful in building object mappers / ORM tools as well. If you ever decide to roll your own mapping system they are almost "required" to get all the functionality one would need. It's used more for making methods / classes more generic and using reflection to determine how to handle objects / select objects /etc...
To give you a specific case where I've used them. I once had to interact with a Mainframe screenscraper. I created a custom attribute to annotate which fields I wanted to send from my classes to the Mainframe, names that fell outside of conventions, special rules to deal with formatting and collections. I then had a class which was able to reflect over instances and realise which subset of fields were needed to interact with the mainframe screen scraper appropriately.

How can I make a program to support custom requirements for multiple customers with a single codebase?

As the title states, I'm looking for a way to organize code with various customer "settings" that control program logic and sometimes display logic without introducing a nest of if/else branches in both the client (javascript) and the server (C#).
What mechanisms do I have to choose from for making a series of modules used for validation, field visibility, processing rules and such that can be loaded dynamically based on, say, a username or other bit of customer data? I am aware of IOC, I need something more specific than "configurable modules". Are there libraries out there to provide a structure for organizing code and loading it conditionally?
What about in javascript? Are there well-known mechanisms for dynamically loading javascript from small files to be executed conditionally?
Most of all, is there a name for what I'm describing? I don't want a rules engine or decision engine where the code is stored as a set of values and operators. I want to keep the code in its original files. I also want to use strong typing and interfaces where I can.
Any ideas?
You should look at either (or both) of
Microsoft's Managed Extensibility Framework
http://msdn.microsoft.com/en-us/magazine/ee291628.aspx
Mono.Addins
Here's the MSDN docs on the System.Addin namespace(s) as well: http://msdn.microsoft.com/en-us/library/gg145020.aspx
This discussion talks about the difference between MEF and System.Addin: Choosing between MEF and MAF (System.AddIn)
The wiring and configuration of your extension system is of course highly domain specific.
Good Luck!
If you wish to use strong typing and interfaces, then why not just go that route? You could create an interface that defines callable methods for your individual customer logic, and then create the implementation classes for each. That way you would only have one piece of conditional logic, perhaps a switch statement, in your system startup routine that loads the correct implementation.

Simplest, fastest way to break out all dependencies from a class

When working with legacy code, and trying to create tests, I often break out dependencies from classes or methods so I can write unit tests using mocks for these dependencies. Dependencies most often come in the form of calls to static classes and objects created using the new keyword in the constructor or other locations in that class.
In most cases, static calls are handled either by wrapping the static dependency, or if its a singleton pattern (or similar) in the form of StaticClass.Current.MethodCall() passing that dependency by its interface go the constructor instead.
In most cases, uses of the new keyword in the constructor is simply replaced by passing that interface in the constructor instead.
In most cases, uses of the new keyword in other parts of the class, is handled either by the same method as above, or by if needed create a factory, and pass the factory's interface in the constructor.
I always use Resharpers refactoring tools to help me all of these break-outs, however most things are still manual labour (which could be automated), and for some legacy classes and methods that can be a very very tedious process. Is there any other refactoring plugins and/or tools which would help me in this process? Is there a "break out all depencencies from this class in a single click" refactoring tool? =)
It sounds to me like all these steps are common for many developers and a common problem, and before I attempt writing plugin to Resharper or CodeRush, I have to ask, because someone has probably already attempted this..
ADDED:
In reflection to answers below: even if you might not want to break out everything at once (one click total break out might cause more problems than it helps) still being able to simply break out 1 methods dependencies, or 1-2 dependencies easily, would be of big difference.
Also, refactoring code has a measure of "try and see what happens just to learn how everything fits together", and a one click total break out would help that process tons, even if you dont check that code in..
I don't think there is any tool that can automate this for you. Working with legacy code means -as you know- changing code with little steps at a time. The steps are often deliberately small to prevent errors from being made. Usually the first change you should make is one that makes that code testable. After you've written the test you change that part of the code in such way that you fix the bug or implement the RFC.
Because you should take small steps I believe it is hard to use a refactoring tool to magically make all your dependencies disappear. With legacy systems you would hardly ever want to make big changes at once, because the risk of breaking (and not finding out because of the lack of tests) is too big. This however, doesn’t mean refactoring tools aren’t useful in this scenario. On the contrary; they help a lot.
If you haven't already, I'd advise you to read Michael Feathers' book Working Effectively with Legacy Code. It describes in great details a series of patterns that help you refactor legacy code to a more testable system.
Good luck.
When it comes to static call dependencies, you might want to check out Moles. It's able to do code injection at run-time to stub out any static or non-virtual method call with your own test implementation. This is handy for testing legacy code that wasn't designed using testable dependency-injected interfaces.

Custom code access permissions

We have a server written in C# (Framework 3.5 SP1). Customers write client applications using our server API. Recently, we created several levels of license schemes like Basic, Intermediate and All. If you have Basic license then you can call few methods on our API. Similarly if you have Intermediate you get some extra methods to call and if you have All then you can call all the methods.
When server starts it gets the license type. Now in each method I have to check the type of license and decide whether to proceed further with the function or return.
For example, a method InterMediateMethod() can only be used by Intermediate License and All license. So I have to something like this.
public void InterMediateMethod()
{
if(licenseType == "Basic")
{
throw new Exception("Access denied");
}
}
It looks like to me that it is very lame approach. Is there any better way to do this? Is there any declarative way to do this by defining some custom attributes? I looked at creating a custom CodeAccessSecurityAttribute but did not get a good success.
Since you are adding the "if" logic in every method (and god knows what else), you might find it easier to use PostSharp (AOP framework) to achieve the same, but personally, I don't like either of the approaches...
I think it would be much cleaner if you'd maintained three different branches (source code) for each license, which may add a little bit of overhead in terms of maintenance (maybe not), but at least keep it clean and simple.
I'm also interested what others have to say about it.
Good post, I like it...
Possibly one easy and clean approach would be to add a proxy API that duplicates all your API methods and exposes them to the client. When called, the proxy would either forward the call to your real method, or return a "not licensed" error. The proxies could be built into three separate (basic, intermediate, all) classes, and your server would create instances of the approprate proxy for your client's licence. This has the advantage of having minimal performance overhead (because you only check the licence once). You may not even need to use a proxy for the "all" level, so it'll get maximum performance. It may be hard to slip this in depending on your existing design though.
Another possibility may be to redesign and break up your APIs into basic/intermediate/all "sections", and put them in separate assemblies, so the entire assembly can be enabled/disabled by the licence, and attempting to call an unlicensed method can just return a "method not found" error (e.g. a TypeLoadException will occur automatically if you simply haven't loaded the needed assembly). This will make it much easier to test and maintain, and again avoids checking at the per-method level.
If you can't do this, at least try to use a more centralised system than an "if" statement hand-written into every method.
Examples (which may or may not be compatible with your existing design) would include:
Add a custom attribute to each method and have the server dispatch code check this attribute using reflection before it passes the call into the method.
Add a custom attribute to mark the method, and use PostSharp to inject a standard bit of code into the method that will read and test the attribute against the licence.
Use PostSharp to add code to test the licence, but put the licence details for each method in a more data driven system (e.g. use an XML file rather than attributes to describe the method permissions). This will allow you to easily change the licensing across the entire server by editing a single file, and allow you to easily add whole new levels or types of licences in future.
Hope that gives you some ideas.
You might really want to consider buying a licensing solution rather than rolling your own. We use Desaware and are pretty happy with it.
Doing licensing at the method level is going to take you into a world of hurt. Maintenance on that would be a nightmare, and it won't scale at all.
You should really look at componentizing your product. Your code should roughly fall into "features", which can be bundled into "components". The trick is to make each component do a license check, and have a licensing solution that knows if a license includes a component.
Components for our products are generally on the assembly level, but for our web products they can get down to the ASP.Net server control level.
I wonder how the people are licensing the SOA services. They can be licensed per service or per end point.
That can be very hard to maintain.
You can try with using strategy pattern.
This can be your starting point.
I agree with the answer from #Ostati that you should keep 3 branches of your code.
What I would further expand on that is then I would expose 3 different services (preferably WCF services) and issue certificates that grant access to the specific service. That way if anyone tried to access the higher level functionality they would just not be able to access the service period.

Design Perspective: Static Methods vs. Classes

Although this is a fairly common problem, I am struggling with what the best way to approach it (if it needs approached at all in this case).
I have inherited a website (ASP.NET, C#) part of which contains a class full of static methods (it's a very large class, honestly). One method in particular is for sending e-mails. It has every possible parameter I can think of and it works well enough. However, the internals of that particular method are rather cumbersome to manage and understand due to the fact that everything is shoved inside - particularly when most of the parameters aren't used. In addition, it is somewhat difficult to handle errors, again, due to all the parameters for this one method.
Would it make more sense to actually have an EMail class which is instantiated when you want to send an e-mail? This just "feels" more right to me, though I can't full explain why. What are your thoughts on the way to go in this particular case? How about in general?
Thanks.
What you're describing sounds like an example of the aphorism, "You can write FORTRAN in any language."
A massive class full of static methods is often (not always) a sign that somebody just didn't "get" OOP, was stuck in a procedural-programming mindset and was trying to twist the language to do what he wanted.
As a rule of thumb: If any method, static or instance, takes more than about 5 parameters, it's often a sign that the method is trying to do too many things at once, and is a good candidate for refactoring into one or more classes.
Also, if the static methods are not really related, then they should at least be split up into classes that implement related functionality.
I'm actually wondering why you'd have a "send e-mail" method at all, given that the System.Net.Mail namespace handles just about every case, and is configurable via the app.config/web.config file, so you don't need to pass it a server name or port. Is this perchance a "notification" method - something that individual pages are supposed to call out to in order to send one of several "standard" messages based on templates with various values filled in, and certain headers/footers automatically added? If so, there are a number of designs for this type of interaction that are much easier to work with than what you seem to have inherited. (i.e. MailDefinition)
Update: Now having seen your comment that this is being used for exception handling, I think that the most appropriate solution is an actual exception handler. There are a ton of resources on this. For ASP.NET WebForms, I actually took the one Jeff Atwood wrote years ago, ported it to C# and made a few changes (like ignoring 404 errors). There are a number of good links in this previous question.
My preference these days is just to treat exception handling (and subsequent e-mailing of exception reports) as a subset of logging. log4net has an SmtpAppender that's quite capable, and you can configure it to only be used for "fatal" errors (i.e. unhandled exceptions - in your handler, you just make a LogFatal call).
The important thing, which you'll no doubt pick up from the SO link above and any referenced links, is that there are actually two anti-patterns here - the "miscellaneous" static class, and catching exceptions that you don't know how to handle. This is a poor practice in .NET - in most cases you should only catch application-specific exceptions that you can recover from, and let all other exceptions bubble up, installing a global exception handler if necessary.
Here are the Microsoft guidelines for when to use static types, generally.
Some things I would add, personally:
You must use static types to write extension methods.
Static types can make unit testing hard as they are difficult/impossible to mock.
Static types enforce immutability and referentially transparent functions, which can be a good design. So use them for things which are designed to be immutable and have no external dependencies. E.g., System.Math.
Some argue (e.g.) that the Singleton pattern is a bad idea. In any event, it would be wrong to think of static types as Singletons; they're much more broad than that.
This particular case has side-effects (sending e-mails) and doesn't appear to require extension methods. So it doesn't fit into what I would see as the useful case for static types. On the other hand, using an object would allow mocking the e-mail, which would be helpful for a unit test. So I think you're correct to say that a static type is inappropriate here.
Oh my gosh yes.
It sounds like its an old Classic ASP app that was ported.
It violates the single responsibility principle. If you can refactor that class. Use overloading for that function.
That is an example of the Utils anti-pattern.
It is always a good idea to separate those methods according on their responsibility. Creating an Email class is definitely a Good Idea™. It will give you a much nicer interface to use, and it allows you to mock out the Email in tests.
See The Little Manual of API Design, which describes the benefits of classes having minimal constructors and lots of getters/setters over the alternative of using constructor/methods having many parameters.
Since most of the parameters of the methods you mention are not used, a better approach is to use simple constructors that assume reasonable default settings for the internal variables. Having setter methods allows you to then set the few parameters (and only those parameters) that require non-default values.

Categories

Resources