Setting a generic delegate to a class-level variable - asp.net

I bumped into an additional question that I needed in regards to this: Using an IEnumerable<T> as a delegate return type
From the above solution, the following was suggested:
class Example
{
//the delegate declaration
public delegate IEnumerable<T> GetGridDataSource<T>();
//the generic method used to call the method
public void someMethod<T>(GetGridDataSource<T> method)
{
method();
}
//a method to pass to "someMethod<T>"
private IEnumerable<string> methodBeingCalled()
{
return Enumerable.Empty<string>();
}
//our main program look
static void Main(string[] args)
{
//create a new instance of our example
var myObject = new Example();
//invoke the method passing the method
myObject.someMethod<string>(myObject.methodBeingCalled);
}
}
Notice that in someMethod, the delegate "method()" is called. Is there anyway to set a class-level delegate that is called later on?
I.e:
class Example {
//the delegate declaration
public delegate IEnumerable<T> GetGridDataSource<T>();
//this fails because T is never provided
private GetGridDataSource<T> getDS;
//the generic method used to call the method
public void someMethod<T>(GetGridDataSource<T> method)
{
getDS = method;
}
public void anotherMethod() {
getDS();
}
}

Depending on what you are trying to achieve and where you have flexibility in your design, there are a number of options. I've tried to cover the ones that I feel most probably relate to what you want to do.
Multiple values of T in a single instance of a non-generic class
This is basically what you seem to want. However, because of the generic nature of the method call, you'll need a class level variable that can support any possible value of T, and you will need to know T when you store a value for the delegate.
Therefore, you can either use a Dictionary<Type, object> or you could use a nested type that encapsulates the class-level variable and the method, and then use a List<WrapperType<T>> instead.
You would then need to look up the appropriate delegate based on the required type.
class Example {
//the delegate declaration
public delegate IEnumerable<T> GetGridDataSource<T>();
//this works because T is provided
private Dictionary<Type, object> getDSMap;
//the generic method used to call the method
public void someMethod<T>(GetGridDataSource<T> method)
{
getDSMap[typeof(T)] = method;
}
//note, this call needs to know the type of T
public void anotherMethod<T>() {
object getDSObj = null;
if (this.getDSMap.TryGetValue(typeof(T), out getDSObj))
{
GetGridDataSource<T> getDS = getDSObj as GetGridDataSource<T>;
if (getDS != null)
getDS();
}
}
Single value of T in a single instance of a non-generic class
In this case, you could store the delegate instance in a non-typed delegate and then cast it to the appropriate type when you need it and you know the value of T. Of course, you'd need to know T when you first create the delegate, which negates the need for a generic method or delegate in the first place.
Multiple values of T in multiple instances of a generic class
Here you can make your parent class generic and supply T up front. This then makes the example you have work correctly as the type of T is known from the start.
class Example<T> {
//the delegate declaration
public delegate IEnumerable<T> GetGridDataSource<T>();
//this works because T is provided
private GetGridDataSource<T> getDS;
//the generic method used to call the method
public void someMethod<T>(GetGridDataSource<T> method)
{
getDS = method;
}
public void anotherMethod() {
if (getDS != null)
getDS();
}
}

You either need to make the type generic as well, or use plain Delegate and cast back to the right type when you need to invoke it. You can't just use T outside a generic context - the compiler will think you're trying to refer to a normal type called T.
To put it another way - if you're going to try to use the same type T in two different places, you're going to need to know what T is somewhere in the type... and if the type isn't generic, where is that information going to live?

Related

How to make a field set-able only inside extension method

Hello i want to be able to set the a of a field of an object only in an extension method. I would want that this field to either be completelely private , or be just get-able from outside:
public class Myclass
{
private int Value{get;set;}
}
public static class Ext
{
public Myclass SetValue(this Myclass obj,int val)
{
this.obj.Value=val;
return obj;
}
}
As you can see in the above example , i have to declare Value public to be able to access it inside the extension , i would be ok with that if i could make the variable only get-ablefrom outside.
I need this functionality because i want to develop something like a fluent api , where you can only set some variables using the extension.
ex:
a=new Myclass();
a.SetValue1(1).SetValue2(2);//--some code //--a.SetValue3(3);
It sounds like you're using the wrong tool for the job, extension methods don't have access non-public members.
The behavior you want is restricted to instance methods or properties. My recommendation is to add an instance method to the class.
If that doesn't persuade you, then you can instead use reflection to update the private instance variable:
public static class Ext
{
public Myclass SetValue(this Myclass obj,int val)
{
var myType = typeof(Myclass);
var myField = myType.GetField("Value", BindingFlags.NonPublic | BindingFlags.Instance);
myField.SetValue(obj, val);
return obj;
}
}
Please note that this has the following gotchas:
There are no compile time checks to save you if you decide to rename the field Value. (though unit tests can protect you)
Reflection is typically much slower than regular instance methods. (though performance may not matter if this method isn't called frequently)
you want it to do it with extension method but you cannot in this case.
Your best option is
public class Myclass
{
public int Value{get; private set;}
public Myclass SetValue(int val)
{
this.Value=val;
return obj;
}
}

Pass object between two Around functions - AOP

I am doing Auditing for my Controller, Service and Dao layer. I have three Around aspect functions for Controller, Service and Dao respectively. I use a custom annotation which if present on the Controller method will invoke an Around aspect function. Inside the annotation I set a property which I wish to pass from the Controller Around function to the Service around function inside the Aspect class.
public #interface Audit{
String getType();
}
I will set the value of this getType from an interface.
#Around("execution(* com.abc.controller..*.*(..)) && #annotation(audit)")
public Object controllerAround(ProceedingJoinPoint pjp, Audit audit){
//read value from getType property of Audit annotation and pass it to service around function
}
#Around("execution(* com.abc.service..*.*(..))")
public Object serviceAround(ProceedingJoinPoint pjp){
// receive the getType property from Audit annotation and execute business logic
}
How can I pass an object between two Around functions?
Aspects are, by default, singleton objects. However, there are different instantiation models, which could be useful in use cases like yours. Using a percflow(pointcut) instantiation model, you could store the value of the annotation in your controller around advice and retrieve it in your service around advice. The following is just an example on how it would look like:
#Aspect("percflow(controllerPointcut())")
public class Aspect39653654 {
private Audit currentAuditValue;
#Pointcut("execution(* com.abc.controller..*.*(..))")
private void controllerPointcut() {}
#Around("controllerPointcut() && #annotation(audit)")
public Object controllerAround(ProceedingJoinPoint pjp, Audit audit) throws Throwable {
Audit previousAuditValue = this.currentAuditValue;
this.currentAuditValue = audit;
try {
return pjp.proceed();
} finally {
this.currentAuditValue = previousAuditValue;
}
}
#Around("execution(* com.abc.service..*.*(..))")
public Object serviceAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("current audit value=" + currentAuditValue);
return pjp.proceed();
}
}

Asp.Net Web Api - attribute for not binding/formatting a parameter?

I have a method on an ApiController that looks like this:
public IEnumerable<Items> GetSlideSets() {
IServiceClass serviceClass = new ServiceClass();
//...
Yes, I am aware that this is not good design but I'm addressing this issue in a different iteration.
At a certain point in my application I need to call this functionality from within the project itself so I thought I could simply reuse the controller (and why not, I can pluck it out of my IoC container). The only problem is that in this case, I need to inject my own implementation of IServiceClass, easy enough:
public IEnumerable<Items> GetSlideSets(IServiceClass serviceClass = null) {
serviceClass = serviceClass ?? new ServiceClass();
//...
Except now I am getting errors when calling this via a regular Api call Optionalparameter 'serviceClass' is not supported by FormatterParameterBinding.
I know that there are various attributes that control bindings. Is there one that I can put on the parameter to say it shouldn't bind.
Like others have mentioned, it's probably a better idea to inject the dependency in the constructor.
But if you really must avoid binding an action parameter, there isn't a built-in attribute but you can create one pretty easily. Here's what it could look like:
public class DontBindAttribute : ParameterBindingAttribute
{
public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
{
return new DontBindParameterBinding(parameter);
}
private class DontBindParameterBinding : HttpParameterBinding
{
public DontBindParameterBinding(HttpParameterDescriptor parameter) : base(parameter)
{
}
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
{
actionContext.ActionArguments.Add(Descriptor.ParameterName, Descriptor.DefaultValue);
var completedTaskSource = new TaskCompletionSource<object>();
completedTaskSource.SetResult(null);
return completedTaskSource.Task;
}
}
}
You just need to apply the attribute to the parameter afterwards:
public IEnumerable<Items> GetSlideSets([DontBind] IServiceClass serviceClass = null)

When extending an object; why not use "this" instead of "super" when changing object members

This question is posed from an ActionScript context but could be from a Java one equally.
The code I am using as a sample comes from adobe.com/devnet/flex/articles/flex4_skinning.html. In the code extract below the NoteCard class has an enabled and a disabled state which it inherits from the SkinnableComponent class. My question is; why in the enabled setter do we call super.enabled = value; and not this.enabled = value;. We have created our NoteCard object instance from the constructor and should we not then be able to set the value of the enabled member using the "this" keyword. If you do swap super for this no errors are shown by the compiler but the code fails to work.
package
{
import spark.components.supportClasses.SkinnableComponent;
public class NoteCard extends SkinnableComponent
{
public function NoteCard()
{
super();
}
override public function set enabled(value:Boolean) : void
{
if (enabled != value)
invalidateSkinState();
super.enabled = value;
}
override protected function getCurrentSkinState() : String
{
if (!enabled)
return "disabled";
return "normal"
}
}
}
If we'll use:
override public function set enabled(value:Boolean) : void
{
if (enabled != value)
invalidateSkinState();
enabled = value;
}
We'll run into infinite loop. This line:
enabled = value;
will call the same setter again and again.
In this special case you override a setter for a class. You can implement your own additional code to handle the newly set value, but the code from your superclass should also be called, because you may not know, what the base class setter will do (may be set a private variable with a value). You have to call super.setterName = value to assure this. If you would call with this you would call your implemented setter in an infinite loop. You may omit the super call, if you are sure, this isn't necessary.

Mocking a base class method call with Moq

I am modifiying a class method which formats some input paramater dates which are subsequently used as params in a method call into the base class (which lives in another assembly).
I want to verify that the dates i pass in to my method are in the correct format when they are passed to the base class method so i would like to Moq the base class method call. Is this possible with Moq?
As of 2013 with latest Moq you can. Here is an example
public class ViewModelBase
{
public virtual bool IsValid(DateTime date)
{
//some complex shared stuff here
}
}
public class MyViewModel : ViewModelBase
{
public void Save(DateTime date)
{
if (IsValid(date))
{
//do something here
}
}
}
public void MyTest()
{
//arrange
var mockMyViewModel = new Mock<MyViewModel>(){CallBase = true};
mockMyViewModel.Setup(x => x.IsValid(It.IsAny<DateTime>())).Returns(true);
//act
mockMyViewModel.Object.Save();
//assert
//do your assertions here
}
If I understand your question correctly, you have a class A defined in some other assembly, and then an class B implemented more or less like this:
public class B : A
{
public override MyMethod(object input)
{
// Do something
base.MyMethod(input);
}
}
And now you want to verify that base.MyMethod is called?
I don't see how you can do this with a dynamic mock library. All dynamic mock libraries (with the exception of TypeMock) work by dynamically emitting classes that derive from the type in question.
In your case, you can't very well ask Moq to derive from A, since you want to test B.
This means that you must ask Moq to give you a Mock<B>. However, this means that the emitted type derives from B, and while it can override MyMethod (which is still virtual) and call its base (B.MyMethod), it has no way of getting to the original class and verify that B calls base.MyMethod.
Imagine that you have to write a class (C) that derives from B. While you can override MyMethod, there's no way you can verify that B calls A:
public class C : B
{
public override MyMethod(object input)
{
// How to verify that base calls its base?
// base in this context means B, not A
}
}
Again with the possible exception of TypeMock, dynamic mock libraries cannot do anything that you cannot do manually.
However, I would assume that calling the base method you are trying to verify has some observable side effect, so if possible, can you use state-based testing instead of behaviour-based testing to verify the outcome of calling the method?
In any case, state-based testing ought to be your default approach in most cases.
Agree with Mark, it's not possible using Moq.
Depending on your situation you may consider swithcing from inheritance to composition. Then you'll be able to mock the dependency and verify your method. Of course in some cases it just might not worth it.
wrap the base class method in a method and setup that method
e.g.
public class B : A
{
public virtual BaseMyMethod(object input)
{
// Do something
base.MyMethod(input);
}
public override MyMethod(object input)
{
// Do something
BaseMyMethod(input);
}
}
and now Setup the BaseMyMethod
It is quite possible mocking base class. But you will have to modify target class.
For ex. DerivedClass extends BaseClass.
BaseClass has methods MethodA(), MethodB(), MethodC()...
The DerivedClass has this method:
void MyMethod() {
this.MethodA();
this.MethodB();
this.MethodC();
}
You want to mock base class in order to validate that all MethodA(), MethodB(), MethodC() are being called inside MyMethod().
You have to create a field in the DerivedClass:
class DerivedClass {
private BaseClass self = this;
...
}
And also You have to modify the MyMethod():
void MyMethod() {
self.MethodA();
self.MethodB();
self.MethodC();
}
Also add a method, which can inject the this.self field with Mock object
public void setMock(BaseClass mock) {
this.self = mock;
}
Now you can mock:
DerivedClass target = new DerivedClass ();
BaseClass mock = new Mock(typeof(BaseClass));
target.setMock(mock);
target.MyMethod();
mock.verify(MethodA);
mock.verify(MethodB);
mock.verify(MethodC);
Using this technic, you can also mock nested method calls.
I found this solution - ugly but it could work.
var real = new SubCoreClass();
var mock = new Mock<SubCoreClass>();
mock.CallBase = true;
var obj = mock.Object;
mock
.Setup(c => c.Execute())
.Callback(() =>
{
obj.CallBaseMember(typeof(Action), real, "Execute");
Console.WriteLine(obj.GetHashCode());
}
);
public static Delegate CreateBaseCallDelegate(object injectedInstance, Type templateDelegate, object instanceOfBase, string methodName)
{
var deleg = Delegate.CreateDelegate(templateDelegate, instanceOfBase, methodName);
deleg.GetType().BaseType.BaseType.GetField("_target", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(deleg, injectedInstance);
return deleg;
}
public static object CallBaseMember(this object injectedInstance, Type templateDelegate, object instanceOfBase, string methodName, params object[] arguments)
{
return CreateBaseCallDelegate(injectedInstance, templateDelegate, instanceOfBase, methodName).DynamicInvoke(arguments);
}

Resources