The Conditional Attribute in .NET allows you to disable the invocation of methods at compile time. I am looking for basically the same exact thing, but at run time. I feel like something like this should exist in AOP frameworks, but I don't know the name so I am having trouble figuring out if it is supported.
So as an example I'd like to do something like this
[RuntimeConditional("Bob")]
public static void M() {
Console.WriteLine("Executed Class1.M");
}
//.....
//Determines if a method should execute.
public bool RuntimeConditional(string[] conditions) {
bool shouldExecute = conditions[0] == "Bob";
return shouldExecute;
}
So where ever in code there is a call to the M method, it would first call RuntimeConditional and pass in Bob to determine if M should be executed.
You can actually use PostSharp to do what you want.
Here's a simple example you can use:
[Serializable]
public class RuntimeConditional : OnMethodInvocationAspect
{
private string[] _conditions;
public RuntimeConditional(params string[] conditions)
{
_conditions = conditions;
}
public override void OnInvocation(MethodInvocationEventArgs eventArgs)
{
if (_conditions[0] == "Bob") // do whatever check you want here
{
eventArgs.Proceed();
}
}
}
Or, since you're just looking at "before" the method executes, you can use the OnMethodBoundaryAspect:
[Serializable]
public class RuntimeConditional : OnMethodBoundaryAspect
{
private string[] _conditions;
public RuntimeConditional(params string[] conditions)
{
_conditions = conditions;
}
public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
if (_conditions[0] != "Bob")
{
eventArgs.FlowBehavior = FlowBehavior.Return; // return immediately without executing
}
}
}
If your methods have return values, you can deal with them too. eventArgs has a returnValue property that is settable.
I believe this would be a very simple way of doing what you described:
public static void M()
{
if (RuntimeConditional("Bob"))
{
Console.WriteLine("Executed Class1.M");
}
}
Thanks
Related
I wrote a function in c# which initially returned a named tuple.
But now, I only need one field of this tuple and I would like to keep the name because it helps me to understand my code.
private static (bool informationAboutTheExecution, bool field2thatIdontNeedAnymore) doSomething() {
// do something
return (true, false);
}
This function compile. But It's the following function that I want
private static (bool informationAboutTheExecution) doSomething() {
// do something
return (true);
}
the error messages:
Tuple must containt at least two elements
cannot implcitly convvert type 'bool' to '(informationAboutTheExecution,?)
Has somebody a solution to keep the name of the returned value?
I just want to add another option, althought he out is the easiest workaround and Marc explained already why it's not possible. I would simply create a class for it:
public class ExecutionResult
{
public bool InformationAboutTheExecution { get; set; }
}
private static ExecutionResult DoSomething()
{
// do something
return new ExecutionResult{ InformationAboutTheExecution = true };
}
The class can be extended easily and you could also ensure that it's never null and can be created with factory methods like these for example:
public class SuccessfulExecution: ExecutionResult
{
public static ExecutionResult Create() => new ExecutionResult{ InformationAboutTheExecution = true };
}
public class FailedExecution : ExecutionResult
{
public static ExecutionResult Create() => new ExecutionResult { InformationAboutTheExecution = false };
}
Now you can write code like this:
private static ExecutionResult DoSomething()
{
// do something
return SuccessfulExecution.Create();
}
and in case of an error(for example) you can add a ErrorMesage property:
private static ExecutionResult DoSomething()
{
try
{
// do something
return SuccessfulExecution.Create();
}
catch(Exception ex)
{
// build your error-message here and log it also
return FailedExecution.Create(errorMessage);
}
}
You cannot, basically. You can return a ValueTuple<bool>, but that doesn't have names. You can't add [return:TupleElementNamesAttribute] manually, as the compiler explicitly does not let you (CS8138). You could just return bool. You can do the following, but it isn't any more helpful than just returning bool:
private static ValueTuple<bool> doSomething()
=> new ValueTuple<bool>(true);
Part of the problem is that ({some expression}) is already a valid expression before value-tuple syntax was introduced, which is why
private static ValueTuple<bool> doSomething()
=> (true);
is not allowed.
If you must name your return, you can do this:
private static void doSomething(out bool information) {
// do something
information = true;
}
then call it with
bool result;
doSomething(out result);
I'm trying to make a method, MethodA, only accessible when bool, executable, is true. Otherwise an other method, MethodB, is accessible. For example:
private bool executable = true;
public int MethodA(); <-- // Is accessible from outside of the class because executable is true
public string MethodB() <-- // Is not accessible because executable is true
The main reason I'm trying to do this is because the 2 methods return 2 different types. So my question is, is this even possible?
Option #1
You may be able to get what you want using Polymorphism and Generics. This would also allow you to add additional method strategies if needed.
public interface IMethodStrategy<out T>
{
T DoSomething();
}
public class MethodOneStrategy : IMethodStrategy<string>
{
public string DoSomething()
{
return "This strategy returns a string";
}
}
public class MethodTwoStrategy : IMethodStrategy<int>
{
public int DoSomething()
{
return 100; // this strategy returns an int
}
}
// And you would use it like so...
static void Main(string[] args)
{
bool executable = true;
object result = null;
if (executable)
{
MethodOneStrategy methodA = new MethodOneStrategy();
result = methodA.DoSomething();
}
else
{
MethodTwoStrategy methodB = new MethodTwoStrategy();
result = methodB.DoSomething();
}
}
Option #2
Another option could be a simple proxy method to wrap the worker methods.
// proxy class to wrap actual method call with proxy call
public class MethodProxy
{
public object DoMethodWork(bool executable)
{
if (executable)
{
return MethodA();
}
else
{
return MethodB();
}
}
private int MethodA()
{
return 100; // returns int type
}
private string MethodB()
{
return "this method returns a string";
}
}
// used like so
static void Main(string[] args)
{
var methodProxy = new MethodProxy();
object result = methodProxy.DoMethodWork(true);
}
Use conditional compilation for this.
#if RELEASE
public string MethodB() ...
#endif
Although I have my doubts about whether you need this or not. Your rationale doesn't make much sense.
You can use different Build Configurations to manage your conditional compile symbols.
if(executable)
MethodA();
else
MethodB();
OR
if(executable)
MethodA();
MethodB();
not entirely sure what you are trying to do but this could be one way, probably not the most efficient way but could work depending on what you are trying to do?
public int MethodA(executable)
{
if(executable = true)
{
//do stuff
}
else
{
return -1;
}
}
public String MethodB(executable)
{
if(executable = false)
{
//do stuff
}
else
{
String error = "MethodB cannot be used right now";
return error;
}
}
I am trying to use generics with specialization. See the code below. What I want to do is make runtime engine understand that specialization of the function is available based on type and it should use that instead of generic method. Is it possible without using keyword dynamic?
public interface IUnknown
{
void PrintName<T>(T someT);
}
public interface IUnknown<DerivedT> : IUnknown
{
//***** I am trying to make runtime engine understand that method below is
//***** specialization of void PrintName<T>(T someT);
void PrintName(DerivedT derivedT);
}
public class SoAndSo<DerivedT> : IUnknown<DerivedT>
{
public void PrintName<T>(T someT) { Console.WriteLine("PrintName<T>(T someT)"); }
public void PrintName(DerivedT derivedT) { Console.WriteLine("PrintName(DerivedT derivedT)"); }
}
public class Test
{
public static void TestIt()
{
List<IUnknown> unknowns = new List<IUnknown>();
unknowns.Add(new SoAndSo<int>());
unknowns.Add(new SoAndSo<string>());
//*** statement below should print "PrintName(DerivedT derivedT)"
unknowns[0].PrintName(10);
//*** statement below should print "PrintName<T>(T someT)"
unknowns[0].PrintName("abc");
//********** code snippet below works exactly as expected ************
dynamic d;
d = unknowns[0];
d.PrintName(10); // <=== prints "PrintName(DerivedT derivedT)"
d.PrintName("abc"); // <=== prints "PrintName<T>(T someT)"
}
}
EDIT
If there isn't any way to achieve what I want without use of keyword dynamic, could there be any elegant way to achieve casting to concrete type without huge enum\flag\switch-case?
EDIT - POSSIBLY ONE WAY OF ACHIEVING THIS
I wanted to post this as an answer but this is not really based on polymorphism or overloading so decided to put as an edit instead. Let me know if this makes sense.
public abstract class IUnknown
{
public abstract void PrintName<T>(T someT);
}
public abstract class IUnknown<DerivedT /*, DerivedType*/> : IUnknown //where DerivedType : IUnknown<DerivedT, DerivedType>
{
MethodInfo _method = null;
//***** I am trying to make runtime engine understand that method below is
//***** specialization of void PrintName<T>(T someT);
public override sealed void PrintName<T>(T derivedT)
{
bool isSameType = typeof(T) == typeof(DerivedT);
if (isSameType && null == _method)
{
//str = typeof(DerivedT).FullName;
Type t = GetType();
_method = t.GetMethod("PrintName", BindingFlags.Public |
BindingFlags.Instance,
null,
CallingConventions.Any,
new Type[] { typeof(T) },
null);
}
if (isSameType && null != _method)
{
_method.Invoke(this, new object[] { derivedT });
}
else
{
PrintNameT(derivedT);
}
}
public virtual void PrintNameT<T>(T derivedT)
{
}
public virtual void PrintName(DerivedT derivedT) { Console.WriteLine("PrintName(DerivedT derivedT)"); }
//public static DerivedType _unknownDerivedInstance = default(DerivedType);
}
public class SoAndSo<DerivedT> : IUnknown<DerivedT> //, SoAndSo<DerivedT>>
{
//static SoAndSo() { _unknownDerivedInstance = new SoAndSo<DerivedT>(); }
public override void PrintNameT<T>(T someT) { /*Console.WriteLine("PrintNameT<T>(T someT)");*/ }
public override void PrintName(DerivedT derivedT) { /*Console.WriteLine("PrintName(DerivedT derivedT)");*/ }
}
public static class Test
{
public static void TestIt()
{
List<IUnknown> unknowns = new List<IUnknown>();
unknowns.Add(new SoAndSo<int>());
unknowns.Add(new SoAndSo<float>());
//*** statement below should print "PrintName(DerivedT derivedT)"
unknowns[0].PrintName(10);
//*** statement below should print "PrintName<T>(T someT)"
unknowns[0].PrintName(10.3);
//*** statement below should print "PrintName(DerivedT derivedT)"
unknowns[1].PrintName(10);
//*** statement below should print "PrintName<T>(T someT)"
unknowns[1].PrintName(10.3f);
System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
for (int i = 0; i < 1000000; ++i)
{
unknowns[0].PrintName(10.3);
}
stopWatch.Stop();
System.Diagnostics.Trace.TraceInformation("Milliseconds: {0}", stopWatch.ElapsedMilliseconds);
//********** code snippet below works exactly as expected ************
dynamic d;
d = unknowns[0];
d.PrintName(10); // <=== prints "PrintName(DerivedT derivedT)"
d.PrintName("abc"); // <=== prints "PrintName<T>(T someT)"
}
Thanks in advance,
-Neel.
I don't believe there's any way of doing this. It's simply not part of the execution-time dispatch mechanism which the CLR supports. You could write this, of course:
public void PrintName<T>(T someT)
{
// This is assuming you want it based on the type of T,
// not the type of the value of someT
if (typeof(DerivedT).IsAssignableFrom(typeof(T))
{
PrintName((DerivedT)(object) someT);
return;
}
Console.WriteLine("PrintName<T>(T someT)");
}
... but that's not terribly pleasant.
You could achieve this with an explicit implementation of IUnknown<DerivedT>. However, I'm not sure this is what you are looking for.
public class SoAndSo<DerivedT> : IUnknown<DerivedT>
{
public void PrintName<T>(T someT) { Console.WriteLine("PrintName<T>(T someT)"); }
void IUnknown<DerivedT>.PrintName(DerivedT derivedT) { Console.WriteLine("PrintName(DerivedT derivedT)"); }
}
public class Test
{
public static void TestIt()
{
List<IUnknown> unknowns = new List<IUnknown>();
unknowns.Add(new SoAndSo<int>());
unknowns.Add(new SoAndSo<string>());
//*** statement below should print "PrintName(DerivedT derivedT)"
(unknowns[0] as IUnknown<int>).PrintName(10);
//*** statement below should print "PrintName<T>(T someT)"
unknowns[0].PrintName("abc");
}
}
I would suggest defining a generic static class NamePrinter<T>, with an Action<T> called PrintName, which initially points to a private method that checks whether T is a special type and either sets PrintName to either a specialized version or the non-specialized version (the non-specialized version could throw an exception if desired), and then invokes the PrintName delegate. If one does that, the first time one calls NamePrinter<T>.PrintName(T param) for any particular T, code will have to inspect type T to determine which "real" method to use, but future calls will be dispatched directly to the proper routine.
I want to write a rule that will fail if an object allocation is made within any method called by a method marked with a particular attribute.
I've got this working so far, by iterating up all methods calling my method to check using CallGraph.CallersFor(), to see if any of those parent methods have the attribute.
This works for checking parent methods within the same assembly as the method to be checked, however reading online, it appears that at one time CallGraph.CallersFor() did look at all assemblies, however now it does not.
Question: Is there a way of getting a list of methods that call a given method, including those in a different assembly?
Alternative Answer: If the above is not possible, how do i loop through every method that is called by a given method, including those in a different assembly.
Example:
-----In Assembly A
public class ClassA
{
public MethodA()
{
MethodB();
}
public MethodB()
{
object o = new object(); // Allocation i want to break the rule
// Currently my rule walks up the call tree,
// checking for a calling method with the NoAllocationsAllowed attribute.
// Problem is, because of the different assemblies,
// it can't go from ClassA.MethodA to ClassB.MethodB.
}
}
----In Assembly B
public var ClassAInstance = new ClassA();
public class ClassB
{
[NoAllocationsAllowed] // Attribute that kicks off the rule-checking.
public MethodA()
{
MethodB();
}
public MethodB()
{
ClassAInstance.MethodA();
}
}
I don't really mind where the rule reports the error, at this stage getting the error is enough.
I got round this issue by adding all referenced dlls in my FxCop project, and using the code below, which builds a call tree manually (it also adds calls for derived classes to work round another problem i encountered, here.
public class CallGraphBuilder : BinaryReadOnlyVisitor
{
public Dictionary<TypeNode, List<TypeNode>> ChildTypes;
public Dictionary<Method, List<Method>> CallersOfMethod;
private Method _CurrentMethod;
public CallGraphBuilder()
: base()
{
CallersOfMethod = new Dictionary<Method, List<Method>>();
ChildTypes = new Dictionary<TypeNode, List<TypeNode>>();
}
public override void VisitMethod(Method method)
{
_CurrentMethod = method;
base.VisitMethod(method);
}
public void CreateTypesTree(AssemblyNode Assy)
{
foreach (var Type in Assy.Types)
{
if (Type.FullName != "System.Object")
{
TypeNode BaseType = Type.BaseType;
if (BaseType != null && BaseType.FullName != "System.Object")
{
if (!ChildTypes.ContainsKey(BaseType))
ChildTypes.Add(BaseType, new List<TypeNode>());
if (!ChildTypes[BaseType].Contains(Type))
ChildTypes[BaseType].Add(Type);
}
}
}
}
public override void VisitMethodCall(MethodCall call)
{
Method CalledMethod = (call.Callee as MemberBinding).BoundMember as Method;
AddCallerOfMethod(CalledMethod, _CurrentMethod);
Queue<Method> MethodsToCheck = new Queue<Method>();
MethodsToCheck.Enqueue(CalledMethod);
while (MethodsToCheck.Count != 0)
{
Method CurrentMethod = MethodsToCheck.Dequeue();
if (ChildTypes.ContainsKey(CurrentMethod.DeclaringType))
{
foreach (var DerivedType in ChildTypes[CurrentMethod.DeclaringType])
{
var DerivedCalledMethod = DerivedType.Members.OfType<Method>().Where(M => MethodHidesMethod(M, CurrentMethod)).SingleOrDefault();
if (DerivedCalledMethod != null)
{
AddCallerOfMethod(DerivedCalledMethod, CurrentMethod);
MethodsToCheck.Enqueue(DerivedCalledMethod);
}
}
}
}
base.VisitMethodCall(call);
}
private void AddCallerOfMethod(Method CalledMethod, Method CallingMethod)
{
if (!CallersOfMethod.ContainsKey(CalledMethod))
CallersOfMethod.Add(CalledMethod, new List<Method>());
if (!CallersOfMethod[CalledMethod].Contains(CallingMethod))
CallersOfMethod[CalledMethod].Add(CallingMethod);
}
private bool MethodHidesMethod(Method ChildMethod, Method BaseMethod)
{
while (ChildMethod != null)
{
if (ChildMethod == BaseMethod)
return true;
ChildMethod = ChildMethod.OverriddenMethod ?? ChildMethod.HiddenMethod;
}
return false;
}
}
Did you give it a try in this way,
StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
object [] items = methodBase.GetCustomAttributes(typeof (NoAllocationsAllowed));
if(items.Length > 0)
//do whatever you want!
according to anti-if campaign it is a best practice not to use ifs in our code. Can anyone tell me if it possible to get rid of the if in this piece of code ?
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(OrganisationInput organisationInput)
{
if (!this.ModelState.IsValid)
{
return View(organisationInput.RebuildInput<Organisation, OrganisationInput>());
}
var organisation = organisationInput.BuildEntity<Organisation, OrganisationInput>();
this.organisationService.Create(organisation);
return this.RedirectToAction("Index");
}
Looks like a valid use for "if".
The anti-if campaign appears to be against the abuse of if statments (i.e. too many nested ifs) etc, not for complete eradication of them.
They are Necessary.
Since you are asking: Yes, it is possible.
Create an abstract class A with an abstract method that returns ActionResult, created via a factory method that uses a dictionary of Func's that creates A-subclassed instances based on Controller state computed from model (in your case, from the controllerInstance.Model.IsValid property value).
Sample code:
public abstract class ModelStateValidator
{
private Controller controller;
protected Controller Controller {
get { return controller; }
}
public abstract ActionResult GetResult();
#region initialization
static ModelStateValidator() {
creators[ControllerState.InvalidModel] = () => new InvalidModelState();
creators[ControllerState.ValidModel] = () => new ValidModelState();
}
#endregion
#region Creation
private static Dictionary<ControllerState, Func<ModelStateValidator>> creators = new Dictionary<ControllerState, Func<ModelStateValidator>>();
public static ModelStateValidator Create(Controller controller) {
return creators[GetControllerState(controller)]();
}
private static ControllerState GetControllerState(Controller c) {
return new ControllerState(c);
}
internal class ControllerState
{
private readonly Controller controller;
private readonly bool isModelValid;
public ControllerState(Controller controller)
: this(controller.ModelState.IsValid) {
this.controller = controller;
}
private ControllerState(bool isModelValid) {
this.isModelValid = isModelValid;
}
public static ControllerState ValidModel {
get { return new ControllerState(true); }
}
public static ControllerState InvalidModel {
get { return new ControllerState(false); }
}
public override bool Equals(object obj) {
if (obj == null || GetType() != obj.GetType()) //I can show you how to remove this one if you are interested ;)
{
return false;
}
return this.isModelValid == ((ControllerState)obj).isModelValid;
}
public override int GetHashCode() {
return this.isModelValid.GetHashCode();
}
}
#endregion
}
class InvalidModelState : ModelStateValidator
{
public override ActionResult GetResult() {
return Controller.View(organisationInput.RebuildInput<Organisation, OrganisationInput>());
}
}
class ValidModelState : ModelStateValidator
{
public override ActionResult GetResult() {
return this.Controller.RedirectToAction("Index");
}
}
80 additional lines, 4 new classes to remove a single if.
your usage then, instead of if, calls the method like this:
ActionResult res = ModelStateValidator.Create(this).GetResult();
NOTE: Of course it should be tweaked to acommodate the code that is between the ifs in your original question, this is only a sample code :)
Adds additional unnecessary complexity? YES.
Contains ifs? NO.
Should you use it? Answer that yourself :)
Use a ternary operator :-)
It's worse, but it's not an if.
It is a valid if in this case, as it can only be one of two states. The anti-if campaign seems more geared to the endlessly open-ended if/else/switch statments. Looks like a good campaign!
You could just use a While loop... but that seems like a glorified if statement.
private static bool Result(bool isValid)
{
while(!isValid)
{
return true;
}
return false;
}