Intercept Method/Property call in c# - c#

In the code below I have a class Foo which is called (without an interface) by my main method. There is no backing field or setter for the property, instead it calls a private method. Foo cannot be changes, nor can the usage of foo be changed to an IFoo interface.
- How do I change the value of foo.FooValue?
- Is there anything in the System.Reflection, System.Reflection.Emit, .NET standard libraries etc (unsafe code, whatever) that I can include in a unit test to change the return value?
I appreciate if there is something it's bound to be quite "evil", but I am interested in "evil" answers.
public class Program
{
public static void Main(){
Foo foo = new Foo();
int bar = foo.FooValue;
}
}
public class Foo{
public int FooValue
{
get
{
return this.FooMethod();
}
}
private int FooMethod
{
return 0;
}
}
Related questions:
How to set value of property where there is no setter - Related but unanswered - Maybe the answer is "no", but I'm not convinced by the top answer which merely points out you can't achive this by changing a (non-existent) backing field.
Intercept call to property get method in C# - Interesting. Not sure whether this is my answer and if it is, not sure how it could be used in a unit test.
EDIT: Okay. I'm going to re-write my code to make it more testable. However, out of interest, has anyone out there successfully hacked their way through this situation?

You could create a proxy for Foo that could be mocked:
public class FooProxy : IFoo
{
private Foo _Foo;
public FooProxy(Foo foo)
{
_Foo = foo;
}
public int FooValue
{
get {return _Foo.FooValue();
}
}
public interface IFoo
{
public int FooValue {get;}
}
then you can use DI to "inject" an IFoo and make your code more testable.

Related

Using new keyword in interfaces for methods with different return types to wrap/unwrap data

Consider the following interface and class setup setup
class A {
public string SomeData {get;set;}
}
class B {
public string Test{get;set;}
public int Other{get;set;}
public decimal Stuff{get;set;}
}
interface Foo {
A GetA();
B GetB();
}
interface Bar : Foo {
new string GetB();
}
class BarImplementer : Bar {
private readonly Foo _foo;
A GetA(){
// Check cache for existance of A, otherwise use _foo to get A...
}
string GetB(){
// Check cache for existance of B, otherwise use _foo to get B...
return b.Test;
}
// This is forced upon me by the compiler because otherwise this class "does not implement all methods of interface 'Bar'"
B Foo.GetB(){}
}
Ideally, users of the BarImplementer class should not need to deal with the B class as they're only interested in the Test property of a B object.
As you can see from the comments, this won't compile without adding a B Foo.GetB implementation with no access modifier. I'm struggling to find examples of the new keyword being used to hide methods like this structure in interfaces online.
My question is, what's the most correct way to go about achieving this or equivalent result. Is it better to subclass an implementation of Foo in some way to implement the equivalent of Bar rather than a Bar interface inherit from Foo and then implement Bar and Foo separately.
If it helps, in the reality of this simplified setup (in a Dependency Injection environment), an implementation of Foo is used to get data from HTTP calls, and an implementation of Bar can cache the result of those calls to avoid making them multiple times.
It's not 100% clear to me what all you are trying to accomplish, but I believe your primary issue is the name GetPropertyOfB. Because the name differs from Foo's GetB, it isn't hiding it like you expect. Try changing
interface Bar : Foo {
new string GetPropertyOfB();
}
to:
interface Bar : Foo {
new string GetB();
}

Is it possible to create an instance of an class without running ANY code from the class? (no ctor, no field initializations)

I have created an engine that takes in 3rd party plugins (DLL's) that implement an interface.
Since I have no control over the code that gets plugged in, I want to be able to run 1 specific method (from the interface) from the correct class (GetTypes loop untill I find the interfaced class ).
Since anyone can create nice constructor code that executes on Activator.CreateInstance, I can solve that by using FormatterServices.GetUninitializedObject. But that does not help when code is being initialized on fields in the class.
public class myclass : myinterface {
public someotherclass name = new someotherclass()
public myclass() {
//Unknown code
}
//I only want this run.
public string MyProperty{
get {
return "ANiceConstString";
}
}
}
The problem with both ways (CreateInstance/GetUninitializedObject) is that the constructor of someotherclass will be run.
Before you start analyze my needs. This is only run in the initializing of the engine to get a set of standard values. If this get'er relies on other initialized values the "plugin" will be marked as failed as there is no valid value returned. If not marked as failed, later on the class will be loaded properly with Activator.CreateInstance().
So stick to this question:
Does .Net support any way to create an 100% non-initialized class?
Update for the answers. I tested this before I posted my question.
For the answer that someotherclass wont run, I allready tested that and it is run if static.
public class myclass : myinterface {
static Tutle test;
public myclass () {
test = new Tutle();
}
public class Tutle {
public Tutle() {
MessageBox.Show("RUN!");
}
}
}
CreateInstance shows the messagebox. GetUninitializedObject does not.
public class myclass : myinterface {
static Tutle test = new Tutle();
public myclass () {
}
public class Tutle {
public Tutle() {
MessageBox.Show("RUN!");
}
}
}
CreateInstance shows the messagebox. GetUninitializedObject shows the messagebox.
Is there a way to get around static field intializers and ctors?
Simply:
var obj = (myclass)FormatterServices.GetUninitializedObject(typeof(myclass));
That will not run the constructor / field initializers. At all. It will not run the constructor for someotherclass; name will be null.
It will, however, execute any static constructor that exists, if necessary under standard .NET rules.
HOWEVER! I should note that this method is not intended for ad-hoc usage; its primary intent is for use in serializers and remoting engines. There is a very good chance that the types will not work correctly if created in this way, if you have not subsequently taken steps to put them back into a valid state (which any serializer / remoting engine would be sure to do).
As an alternative design consideration:
[SomeFeature("ANiceConstString")]
public class myclass : myinterface {
public someotherclass name = new someotherclass()
public myclass() {
//Unknown code
}
}
Now you can access the feature without instantiation; just use:
var attrib = (SomeFeatureAttribute)Attribute.GetCustomAttribute(
type, typeof(SomeFeatureAttribute));
string whatever = attrib == null ? null : attrib.Name;
with:
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum)]
public sealed class SomeFeatureAttribute : Attribute
{
private readonly string name;
public string Name { get { return name; } }
public SomeFeatureAttribute(string name) { this.name = name; }
}

C#: Giving access to private members without 3-fold code duplication

I have a class
public class Foo{
public Foo{...}
private void someFunction(){...}
...
private Acessor{
new Acessor
}
}
with some private functionality (someFunction). However, sometimes, I want to allow another class to call Foo.SomeFunction, so I have an inner class access Foo and pass out that:
public class Foo{
public Foo{...}
private void someFunction(){...}
...
public Acessor{
Foo _myFoo;
new Acessor(Foo foo){_myFoo = foo;}
public void someFunction(){
_myFoo.someFunction();
}
}
}
With this code, if I want a Foo to give someone else pemission to call someFunction, Foo can pass out a new Foo.Accessor(this).
Unfortunately, this code allows anyone to create a Foo.Accessor initiated with a Foo, and they can access someFunction! We don't want that. However, if we make Foo.Accessor private, then we can't pass it out of Foo.
My solution right now is to make Acessor a private class and let it implement a public interface IFooAccessor; then, I pass out the Foo.Accessor as an IFooAccessor. This works, but it means that I have to declaration every method that Foo.Accessor uses an extra time in IFooAccessor. Therefore, if I want to refactor the signature of this method (for example, by having someFunction take a parameter), I would need to introduce changes in three places. I've had to do this several times, and it is starting to really bother me. Is there a better way?
If someFunction has to be accessible for classes in the same assembly, use internal instead of private modifier.
http://msdn.microsoft.com/en-us/library/7c5ka91b(v=vs.71).aspx
If it has to be accessible for classes which are not in the same assemble then, it should be public. But, if it will be used by just a few classes in other assemblies, you probably should think better how you are organizing you code.
It's difficult to answer this question, since it's not clear (to me at least) what exactly you want to achieve. (You write make it difficult for someone to inadverdantly use this code in a comment).
Maybe, if the method is to be used in a special context only, then explicitly implementing an interface might be what you want:
public interface ISomeContract {
void someFunction();
}
public class Foo : ISomeContract {
public Foo() {...}
void ISomeContract.someFunction() {...}
}
This would mean, that a client of that class would have to cast it to ISomeContract to call someFunction():
var foo = new Foo();
var x = foo as ISomeContract;
x.someFunction();
I had a similar problem. A class that was simple, elegant and easy to understand, except for one ugly method that had to be called in one layer, that was not supposed to be called further down the food chain. Especially not by the consumers of this class.
What I ended up doing was to create an extension on my base class in a separate namespace that the normal callers of my classes would not be using. As my method needed private access this was combined with explicit interface implementation shown by M4N.
namespace MyProject.Whatever
{
internal interface IHidden
{
void Manipulate();
}
internal class MyClass : IHidden
{
private string privateMember = "World!";
public void SayHello()
{
Console.WriteLine("Hello " + privateMember);
}
void IHidden.Manipulate()
{
privateMember = "Universe!";
}
}
}
namespace MyProject.Whatever.Manipulatable
{
static class MyClassExtension
{
public static void Manipulate(this MyClass instance)
{
((IHidden)instance).Manipulate();
}
}
}

Unit testing passing arguments to base constructor

I have the following code:
using System;
using NUnit.Framework;
using Rhino.Mocks;
public class A
{
}
public class B
{
}
public interface IStatementExecutor
{
void Exec(string statement);
}
public abstract class Foo<T>
{
private readonly IStatementExecutor _statementExecutor;
private readonly string _targetSegment;
protected Foo(IStatementExecutor statementExecutor, string targetSegment)
{
_statementExecutor = statementExecutor;
_targetSegment = targetSegment;
}
public void Update(T item)
{
_statementExecutor.Exec("sp_" + _targetSegment + "Update");
}
}
public class Bar : Foo<A>
{
public Bar(IStatementExecutor statementExecutor)
: base(statementExecutor, "ATable")
{
}
}
public class Baz : Foo<B>
{
public Baz(IStatementExecutor statementExecutor)
: base(statementExecutor, "BTable")
{
}
}
[TestFixture]
public class Foo_Tests
{
[Test]
public void Update_CallsStatementExecutorWithTableName()
{
const string tableName = "TestTable";
var mockStatementExecutor = MockRepository.GenerateMock<IStatementExecutor>();
mockStatementExecutor.Expect(m => m.Exec("sp_" + tableName + "Update"));
var sut = MockRepository.GeneratePartialMock<Foo<A>>(mockStatementExecutor, tableName);
var testModel = new A();
sut.Update(testModel);
mockStatementExecutor.AssertWasCalled(m => m.Exec("sp_" + tableName + "Update"));
}
}
I already have unit tests for the base class Foo<T>. Since the base class is already covered, I don't want to write identical tests for the derived classes Bar and Baz.
The only thing I really care about in the derived classes is that the correct string target is passed to the base class.
I'm struggling on how to unit test this without breaking encapsulation of the derived classes or writing redundant unit tests.
So, the question is, how do I test that the correct value gets passed to the base class from the derived classes for the target parameter?
(If your answer is "use composition...", please back it up with a code sample modified from above.
Thanks!
Think I'be more likely to test through the other methods on Bar and Baz, as you'd expect something bad to happen if you'd put ZTable in there instead of BTable
You could add a method to Foo that would return what ever had been passed to it
and then after creating the descendant call it and validate against the expected value.
Or you could do something like
public class Bar : Foo<A>
{
private static String _tableName = "ATable";
public String TableName {get {return _tableName;}}
public Bar() : base(_tableName)
{
}
}
Then you could test testBar.TableName
Another Option would be T was a struct or a class with a TableName property, then you wouldn't need Bar and Baz descendants, just for this.
Your Foo and Bar unit test methods could call helper methods that contain the common testing code.
You can do this in many ways. One way you could use a mocking framework like TypeMock to effectively mock the based class and thus get more information from TypeMock about internal variables.
It't not apparently clear from your post, though, why it's important that the base class be used in a specific why by the bar class. This isn't clear because you have no way of testing it. i.e. there's no external behaviour that you can monitor to guarantee Bar is using Foo in the expected way. You could redirect console output then monitor that output to do the verification. But, I don't think that's really what you're looking for.
You should provide an more testable example; something that doesn't just output text, something that had real behaviour that you can observe by a test.

class properties

I've just began using classes and would like to make some functions of a class visible outside that class. The problem is that I haven't got (and unable to have) a variable of type Abc.
Let me explain with a snippet of code:
class Abc
{
private float foo;
public float Foo {
get { return foo; }
set { foo = value; }
}
public static void Hello() {
foo = 5.0f;
Console.WriteLine("Hello everyone!");
}
}
.... somewhere else ....
Abc bar;
bar.Foo = 5.0f; // ok, I know this
bar.Hello(); // fine, I know this too
Abc.Hello(); // I'm trying to do this!
EDIT:
Ok, now suppose I would like to assign something to foo in Hello (as in my code). I know this might sound like a nonsense, so I'm not sure it's even possible.
You need a static member function. static member functions are not associated with a particular instance of the class, which is what you will need if you want to access them via the class itself. The specifics vary slightly depending on whether you're interested in C++ or C#.
Make Hello() static; that way it does not require an instantiation of the class.
public static void Hello() { ...

Categories

Resources