Mark method as obsolete for a single project - c#

Due to the way our codebase works, I was advised to not edit certain methods in a shared codebase. Instead, I decided to make a new method that calls the old one and also does the new work our team wanted that method to do. The issue I am foreseeing is not everyone on the team being aware of the new method and still using the old one from the shared codebase.
TLDR:
Shared codebase has SharedCode.Function.
I created OurCode.Function which does some stuff, and then calls SharedCode.Function.
I cannot edit SharedCode.Function or it's containing project.
Is it possible to mark SharedCode.Function as obsolete within our project as a compiler warning somehow or otherwise mark that OurCode.Function essentially replaces it?
EDIT:
Might be pertinent to mention- these are logging functions, so if a dev accidentally calls SharedCode.Function instead of OurCode.Function, the only result is that we capture less data than we desired, it will still compile and run fine. This is a major reason I want to try to make it a compiler warning, so that any dev that doesn't know to use the new function will find out to.

The shortest way is by adding the ObsoleteAttribute as an attribute
to the method. Make sure to include an appropriate explanation:
[Obsolete("Method1 is deprecated, please use Method2 instead.")]
public void Method1()
{ … }

I think the adapter pattern could work wonders in this particular scenario. Essentially you end up creating an abstraction between OurCode and SharedCode.
This isolates access to SharedCode functions so that only the adapter can use the shared code's functions. It may end up that some of the functions in the adapter simply provide a pass through, but some of those functions will have extra logic that needs to be applied (such as in the scenario you are asking about), and having the adapter makes it easy for you to enforce that.
All client code is forced to use the adapter since they cannot directly access the shared code.
If you had access to the source code, I would recommend using the Obsolete attribute that the others have pointed out. But since you don't have access to the code base, I think it could be extremely beneficial to have a layer of abstraction between your code and the non-accessible code.
Now obviously I do not have the full scope of your scenario as to whether or not this makes sense to actually implement, so don't drive blindly, but hopefully this gives you some ideas! :)
Reference the gang of four book or see the following resources:
https://martinfowler.com/bliki/RequiredInterface.html
https://www.dofactory.com/net/adapter-design-pattern
Understanding Adapter Pattern

Related

Mock an object with a private constructor of a class which I can't modify

I'm facing the following issue:
I'm using a really badly designed API (and no there is no alternative, using a different one is not an option) and I would like to write a few tests but they rely on an instance of a class, let's call it A, that have a private constructor.
I need to mock that A, I don't care about original behavior at all, the problem is that I can't change the original class.
What are my alternatives? Coming from ruby which is not statically typed, I think there is no way to do this, so I have no idea how to come up with this problem.
It's not the first time that I have a private constructor for a class that it's not a singleton (probably it's not private, it's internal, but in any case I don't have access to it)
I've had this problem working with legacy code, leading to the classic chicken and egg problem: you can't change the code unless you've got tests, but you can't write tests without changing the code.
I found my way out using Microsoft Fakes, which can mock almost everything, including private constructors. Unfortunately, it's only included with the Premium and Ultimate editions of Visual Studio (not Professional). If you don't have that, all is not lost -- Moles, the research project that eventually spawned Fakes, is still available as a free download and works mostly the same.
I should point out that, once you are able to write tests and change code reliably using Fakes/Moles, the best thing to do is to use this new power to make the API more testable, if only because Fakes/Moles are fairly slow and will add overhead to the testing process.

Adding -Ex to the name of a type in .Net

I've noticed a pattern recently in our codebase at work, where most of our model class have a name such as User, and there is an inheriting type that has extra fields on it called UserEx. I've also noticed this in the C# async CTP where they put the additional static methods for Task in a class called TaskEx (due to technical restrictions, since they couldn't alter the existing library). Talking to someone at work, I learned that -Ex classes exist to optimize network transfers (you can pull only the bare minimum if you need). My question, then, is what does -Ex stand for? The only thing I can think of is possibly "Extra".
The other answers all got it correct: the Ex suffix stands for "extended". It's a way of introducing a new class or method without obsoleting or removing the old one, a common way of retaining backwards compatibility while introducing new features.
The Windows API does this all over the place, as explained here.
Hans hints at the problem with this approach in his explanation: it doesn't scale. What if you want to extend an "extended" function? Do you call it FunctionExEx? That looks stupid.
So stupid, in fact, that Microsoft's own coding guidelines for .NET (subjective though they are) specifically recommend against appending Ex to a type. Instead, if you must do this, you should use a number:
MyType
MyType2 // modified version
MyType3 // oh wait, we had to modify it again!
Blaming this on poor planning as dowhilefor tries to do is a bit premature. When writing real world applications and frameworks, you often need to ship. That means getting out a quick-and-dirty version of the function that works. Later, you decide this is a poor design and something needs to change. Rather than throwing up your hands and completely re-writing (producing giant delays and obsoleting all of the old code), you introduce a new type with a different name. Hindsight is always 20/20.
Ending a new class or method or type in Ex is a naming convention, and like any naming convention, it is subject to the whims of those implementing it.
There are no hard and fast rules, and it is no more or less correct than appending 2 to the end of the class (or Extra, or More, or DidntWantToMessWithThePublicApi).
As for why it is used, Microsoft has a long history of using it to provide a revision to an existing API without breaking older code. You can find examples of this in classes, in methods, and in structures. You can also find different examples, which instead use 2.
It stands for "Extension" or "Extended", as far as I know. It's a common suffix to when you need to add functionnality to something that you can't change. A good example was the various -Ex functions in the Win32 APIs, which were added because C does not support function overloading.
This practice is NOT industry-standard. I'll admit I do it myself, but it's mostly vestigial emulation of some of the old win32 kernel functions. for example, they initially had a "beginthread" C function and later created another new-and-improved "begintreadEx".
I would suggest that you start using the [Deprecated] attribute to signal to other coders (or yourself) to stop using the old function in favor of the new one. That has more intrinsic meaning.
Long story short -- you should name classes & functions based on what they are or do, and try to avoid pseudo-meaningful prefixes/suffixes that create confusion such as this. That is the industry-standard approach.
I thought possibly:
external
extricated
simply 'ex' (as in 'out of' or 'beyond')
Honestly, i think it means "We didn't plan this feature long enough, didn't thought about the changed requirements, and we have to deal with this now close to the deadline". Of course this is not always the case, but everytime i find a class with Ex i try to figure out why it was introduced and not properly added into the framework. For me its mostly like // HACK:
This only counts for our code, if it is in a framework i "hope" thats just naming convention.
What it could mean was already answered, my guess was always "Extended"

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.

Is there an equivalent to Java's ClassFileTransformer in .NET? (a way to replace a class)

I've been searching for this for quite a while with no luck so far. Is there an equivalent to Java's ClassFileTransformer in .NET? Basically, I want to create a class CustomClassFileTransformer (which in Java would implement the interface ClassFileTransformer) that gets called whenever a class is loaded, and is allowed to tweak it and replace it with the tweaked version.
I know there are frameworks that do similar things, but I was looking for something more straightforward, like implementing my own ClassFileTransformer. Is it possible?
EDIT #1. More details about why I need this:
Basically, I have a C# application and I need to monitor the instructions it wants to run in order to detect read or write operations to fields (operations Ldfld and Stfld) and insert some instructions before the read/write takes place.
I know how to do this (except for the part where I need to be invoked to replace the class): for every method whose code I want to monitor, I must:
Get the method's MethodBody using MethodBase.GetMethodBody()
Transform it to byte array with MethodBody.GetILAsByteArray(). The byte[] it returns contains the bytecode.
Analyse the bytecode as explained here, possibly inserting new instructions or deleting/modifying existing ones by changing the contents of the array.
Create a new method and use the new bytecode to create its body, with MethodBuilder.CreateMethodBody(byte[] il, int count), where il is the array with the bytecode.
I put all these tweaked methods in a new class and use the new class to replace the one that was originally going to be loaded.
An alternative to replacing classes would be somehow getting notified whenever a method is invoked. Then I'd replace the call to that method with a call to my own tweaked method, which I would tweak only the first time is invoked and then I'd put it in a dictionary for future uses, to reduce overhead (for future calls I'll just look up the method and invoke it; I won't need to analyse the bytecode again). I'm currently investigating ways to do this and LinFu looks pretty interesting, but if there was something like a ClassFileTransformer it would be much simpler: I just rewrite the class, replace it, and let the code run without monitoring anything.
An additional note: the classes may be sealed. I want to be able to replace any kind of class, I cannot impose restrictions on their attributes.
EDIT #2. Why I need to do this at runtime.
I need to monitor everything that is going on so that I can detect every access to data. This applies to the code of library classes as well. However, I cannot know in advance which classes are going to be used, and even if I knew every possible class that may get loaded it would be a huge performance hit to tweak all of them instead of waiting to see whether they actually get invoked or not.
POSSIBLE (BUT PRETTY HARDCORE) SOLUTION. In case anyone is interested (and I see the question has been faved, so I guess someone is), this is what I'm looking at right now. Basically I'd have to implement the profiling API and I'll register for the events that I'm interested in, in my case whenever a JIT compilation starts. An extract of the blogpost:
In your ICorProfilerCallback2::ModuleLoadFinished callback, you call ICorProfilerInfo2::GetModuleMetadata to get a pointer to a metadata interface on that module.
QI for the metadata interface you want. Search MSDN for "IMetaDataImport", and grope through the table of contents to find topics on the metadata interfaces.
Once you're in metadata-land, you have access to all the types in the module, including their fields and function prototypes. You may need to parse metadata signatures and this signature parser may be of use to you.
In your ICorProfilerCallback2::JITCompilationStarted callback, you may use ICorProfilerInfo2::GetILFunctionBody to inspect the original IL, and ICorProfilerInfo2::GetILFunctionBodyAllocator and then ICorProfilerInfo2::SetILFunctionBody to replace that IL with your own.
The great news: I get notified when a JIT compilation starts and I can replace the bytecode right there, without having to worry about replacing the class, etc. The not-so-great news: you cannot invoke managed code from the API's callback methods, which makes sense but means I'm on my own parsing the IL code, etc, as opposed to be able to use Cecil, which would've been a breeze.
I don't think there's a simpler way to do this without using AOP frameworks (such as PostSharp). If anyone has any other idea please let me know. I'm not marking the question as answered yet.
I don't know of a direct equivalent in .NET for this.
However, there are some ways to implement similar functionality, such as using Reflection.Emit to generate assemblies and types on demand, uing RealProxy to create proxy objects for interfaces and MarshalByRefObject objects. However, to advise what to use, it would be important to know more about the actual use case.
After quite some research I'm answering my own question: there isn't an equivalent to the ClassFileTransformer in .NET, or any straightforward way to replace classes.
It's possible to gain control over the class-loading process by hosting the CLR, but this is pretty low-level, you have to be careful with it, and it's not possible in every scenario. For example if you're running on a server you may not have the rights to host the CLR. Also if you're running an ASP.NET application you cannot do this because ASP.NET already provides a CLR host.
It's a pity .NET doesn't support this; it would be so easy for them to do this, they just have to notify you before a class is loaded and give you the chance to modify the class before passing it on the CLR to load it.

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.

Categories

Resources