How to avoid a pair of repetitive lines before and after invocations in sample below ?
Details: This is compileable mock of what is real larger code. Generally it is a layer of proxy classes containing service clients with variety of APIs. The repetitive part is pre- and post- invocation for every method of every client. Unfortunately there is no single signature for all possible methods, the pre- and post- parts need a pointer to client's channel and context.
Is it possible to apply something advanced like AOP, Generics, Delegates, Attributes etc. ? Thank you
using System;
namespace ConsoleApplication
{
class ClassServiceClient: IDisposable
{
public Object channel()
{
return "something";
}
public Object context()
{
return "something other";
}
}
class ClassA : ClassServiceClient
{
public Object methodA()
{
return "something other";
}
}
class ClassB : ClassServiceClient
{
public void methodB(string param)
{
return;
}
}
class ClassAProxy
{
public Object methodA()
{
using (ClassA client = new ClassA())
{
Program.preparation(client.channel()); //<---- repetitive part
Object result = client.methodA();
Program.postinvocation(client.context());//<---- repetitive part
return result;
}
}
}
class ClassBProxy
{
public void methodB(string param)
{
using (ClassB client = new ClassB())
{
Program.preparation(client.channel()); //<---- repetitive part
client.methodB(param);
Program.postinvocation(client.context());//<---- repetitive part
return;
}
}
}
class Program
{
public static void preparation(Object channel)
{
// Do something with channel
}
public static void postinvocation(Object context)
{
// Do something with context
}
static void Main(string[] args)
{
}
}
}
If you can use a common base class, you can easily use a public sealed method that does the invocation and a protected abstract method that does the logic, e.g.
class ProxyBase{
public void Method(params object[] args){
PreConditions();
Invoke(args);
PostConditions();
}
protected abstract void Invoke(object[] args);
}
class ClassAProxy{
protected override void Invoke(object[] args){
client.Method(args[0]);
}
}
You can achieve similar results functionally by declaring a InvocationHandler in your Program class that takes an action:
class Program{
public static void Invoke(object[] args, Action action){
PreConditions();
action();
PostConditions();
}
}
class ClassAProxy{
public void MethodA(int i){
Program.Invoke(() => client.Something(i));
}
}
Related
In c# if I have this
private void Run(Web site) {
site.BreakRoleInheritance(false, false);
}
private void Run(ListItem folder) {
folder.BreakRoleInheritance(false, false);
}
How can I instead make 1 function that can accept either Site or Folder?
If Site and Folder are classes that you've created, then you can create a common interface which those classes inherit from. For example:
public interface IBreakable
{
void break();
}
public class Folder : IBreakable
{
public void break() { /* implementation here*/ }
}
public class Site : IBreakable
{
public void break() { /* implementation here*/ }
}
Usage
private void Run(IBreakable breakable)
{
breakable.break();
}
Edit
Here's a solution based on reflection, although this is not ideal.
void Run(object obj)
{
MethodInfo method = obj.GetType().GetMethod("break");
if (!(method is null))
{
method.Invoke(obj, new object[] {});
}
}
Given
public class Foo
{
public void break() {Console.WriteLine("Foo");}
}
public class Bar
{
public void break() {Console.WriteLine("Bar");}
}
public class Bad
{
public void NotBreak() {Console.WriteLine("Bad");}
}
Usage
Foo foo = new Foo();
Bar bar = new Bar();
Bad bad = new Bad();
Run(foo);
Run(bar);
Run(bad);
Output
Foo
Bar
As a later answer from #Pedro pointed out, those specific classes derive from a common ancestor, and that would be the preferred option. Assuming you did not have that option:
You can use the C# dynamic type (sorry if that is not the latest doc, I couldn't find a newer one):
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic
Example:
using System;
public class Program
{
public static void Main()
{
var foo = new Foo();
var bar = new Bar();
DoSomething(foo);
DoSomething(bar);
}
private static void DoSomething<T>(T someObjectWithDoMethod)
{
((dynamic)someObjectWithDoMethod).Do();
}
}
public class Foo
{
public void Do() { Console.WriteLine("Foo is doing something"); }
}
public class Bar
{
public void Do() { Console.WriteLine("Bar is doing something"); }
}
.Net Fiddle: https://dotnetfiddle.net/MShLK5
Based on your comments to other answers, Web and ListItem are types defined in the Microsoft.SharePoint.Client.
Checking the SDK docs, both types derive from SecurableObject where the BreakRoleInheritance method is defined.
That being the case, all you need to do is define one method that takes a SecurableObject object as an input:
public void Run(SecurableObject item)
{
item.BreakRoleInheritance();
}
And you should be able to pass a Web and a ListItem to this same method.
I seem to have some trouble understanding generics in c#.
Basically i have a base class called ConfigWorker and a bunch of sub classes which should all use their own config class deriving from BaseConfig.
The ConfigWorker class i want to use should be determined dynamically during runtime given the name of the class as a parameter.
I can instantiate the sub class given it's name, but no matter what i try, i can't get the casting to a sensible base class to work.
Here's my code:
namespace DocumentHandler
{
public class BaseConfig
{
}
public class ConfigWorker<T> where T : BaseConfig
{
public virtual void Work(T options)
{
}
}
public class Worker1 : ConfigWorker<Worker1.Config>
{
public class Config : BaseConfig
{
public string test = "";
}
public override void Work(Config options)
{
//do something
}
}
public class Worker2 : ConfigWorker<Worker2.Config>
{
public class Config : BaseConfig
{
public string test = "";
}
public override void Work(Config options)
{
//do something else
}
}
public class Test
{
public static BaseConfig config;
public static void test()
{
(Activator
.CreateInstance(Type.GetType("DocumentHandler.Worker2"))
as ConfigWorker<BaseConfig>)
.Work(config);
}
}
}
The crucial line is
(Activator
.CreateInstance(Type.GetType("DocumentHandler.Worker2"))
as ConfigWorker<BaseConfig>)
.Work(config);
The casting to ConfigWorker<BaseConfig> returns null, as the cast can not be performed.
Trying to simply cast to ConfigWorker does not compile as the type parameter is missing.
Anything else i can try? CreateInstance obviously just returns an object and i need to cast that to be able to call the Work method
Any help is appreciated.
An instance of Worker2 is not a ConfigWorker<BaseConfig>! It's a ConfigWorker<Worker2.Config>. These are two totally different types. Generic classes are invariant. Only interfaces and delegates can be co- or contra-variant.
In your example, ConfigWorker is even contra-variant in T, meaning you use T as the type of an input parameter to a method. So what you try is actually dangerous.
Imagine your line would work: you get an variable of type ConfigWorker<BaseConfig>, so you could rely on this instance having a method Work() which takes a BaseConfig (or something derived from it) as argument. So nothing could stop you from calling it like
worker.Work(new Worker1.Config());
Compiles fine. But wait a moment! Didn't your line state that worker is a Worker2? Worker2 instances can only handle Worker2.Config arguments!
You completely loose type safety this way (well, you would if it was allowed).
There is a flaw in your class design.
This looks like a good problem that factory pattern has good good solution for.
Here is a simplified solution
namespace DocumentHandler
{
public interface IBaseConfig
{
}
public class ConfiManager : IBaseConfig
{
}
public abstract class WorkerFactory
{
private readonly IBaseConfig _config;
protected WorkerFactory(IBaseConfig config)
{
this._config = config;
}
public virtual void Work()
{
}
}
public class Worker1 : WorkerFactory
{
private readonly IBaseConfig _config;
public Worker1(IBaseConfig config):base(config)
{
_config = config;
}
public string test = "";
public override void Work()
{
//do something
}
}
public class Worker2 : WorkerFactory
{
private readonly IBaseConfig _config;
public string test = "";
public Worker2(IBaseConfig config):base(config)
{
this._config = config;
}
public override void Work()
{
Console.WriteLine("Hello world");
}
}
public class Test
{
public static IBaseConfig config = new ConfiManager();
public static void test()
{
WorkerFactory worker =
(Worker2) Activator.CreateInstance(Type.GetType("DocumentHandler.Worker2"), config);
worker.Work();
}
}
}
Simple hierarchy, 3 levels and with a shared/single dependency to a class with overloaded methods that differ only by type signature:
When viewed in a debugger, the type of 'this' in Derived.Bar is the instantiated/concrete Double-Derived.
The below works as expected ONLY because of the (dynamic) cast. Remove it and you'll see that the overload resolution uses the calling class rather than the concrete class.
Curious if there's a 'purer' way of it working as expected without the performance hit of DLR (or some other reflection-based alternative):
public class PolymorphicConsumer
{
public void Foo(Base caller)
{
Console.WriteLine("Its all about the base.");
}
public void Foo(Derived caller)
{
Console.WriteLine("Its all about the Derived.");
}
public void Foo(DoubleDerived caller)
{
Console.WriteLine("Its all about the Double-Derived.");
}
}
public abstract class Base
{
protected PolymorphicConsumer _dep;
public Base (PolymorphicConsumer dep)
{
_dep = dep;
}
public virtual void Bar()
{
// No impl.
}
}
public class Derived : Base
{
public Derived(PolymorphicConsumer dep):base(dep)
{ }
public override void Bar()
{
_dep.Foo((dynamic)this);
}
}
public class DoubleDerived : Derived
{
public DoubleDerived(PolymorphicConsumer dep):base(dep)
{ }
}
class Program
{
static void Main(string[] args)
{
var dd = new DoubleDerived(new PolymorphicConsumer());
dd.Bar();
Console.ReadKey();
}
}
I want to create a generic mechanism for handling messages in C#. I have a need for this in my small application, so I don't want to use full blown message bus. My requirements are quite simple:
I want to have a couple of classes for messages i.e. Message1, Message2. They can inherit from one base class, that's not a problem, but if they don't I don't care. Currently they do inherit from Message.
be able to get handler for each and every message class. i.e. if I send Message1, then Message1Handler class should be instantiated. Handlers have to implement IMessageHandler<T> where T is the message class. IMessageHandler is defined as follows:
interface IMessageHandler<T>
{
void Execute(T message);
}
I wrote a simple "Resolver" class:
public static class HandlerRegistry
{
private static readonly Dictionary<string, Type> _handlers = new Dictionary<string, Type>();
public static void Register<T, T2>() where T2: IMessageHandler<T>
{
_handlers.Add(typeof(T).FullName, typeof(T2));
}
public static IMessageHandler<T> Resolve<T>(T parameters)
{
var type = _handlers[parameters.GetType().FullName];
return (IMessageHandler<T>) Activator.CreateInstance(type);
}
}
In this implementation everything is OK, but one part - the cast to IMessageHandler. When I'm trying to use this with a collection of messages this is what happens: the compiler doesn't know at compile time what actual messages are going to be in the collection - it just assumes that they are all subclasses of Message, so it's trying to cast IMessageHandler<ConcreteMessage> to IMessageHandler<Message> and obviously I'm getting an exception with invalid cast. In this case probably contravariance would help, but I'm not able to declare the parameter as out because I have the message in the Execute method parameters.
Does anyone know an elegant solution to this problem? I know I can make it "more runtime" - instead of using generics just declare
void Execute(Message m) and in each and every handler start with trying to cast to the type that I'm expecting, but as someone said somewhere - each and every cast that you write undermines the whole point of using a type system.
Option 1
If you do not care using reflection. You can add a Execute method to your HandlerRegistry instead of returning the handler back to the caller:
public static void Execute<T>(T parameters)
{
var type = _handlers[parameters.GetType().FullName];
var handler = Activator.CreateInstance(type);
type.GetMethod("Execute", new[] { parameters.GetType() })
.Invoke(handler, new object[] { parameters });
}
Option 2
If you do not care that one message handler can only subscribe to one message. We can take advantage of the Explicit Interface Implementation feature of C#:
// NOTE: This interface is not generic
public interface IMessageHandler
{
void Execute(object message);
}
public abstract class MessageHandler<T> : IMessageHandler
{
public abstract void Execute(T message);
// NOTE: Here we explicitly implement the IMessageHandler
void IMessageHandler.Execute(object message)
{
Execute((T)message);
}
}
Now your resolve method can change to:
public static IMessageHandler Resolve<T>(T parameters)
{
var type = _handlers[parameters.GetType().FullName];
return (IMessageHandler)Activator.CreateInstance(type);
}
By the way, personally I would prefer to pass in a Type instead of the message instance.
Then make your handlers inherit from the generic abstract MessageHandler<T> instead of implementing IMessageHandler:
public class HandlerA : MessageHandler<MessageA>
{
public override void Execute(MessageA message)
{
Console.WriteLine("Message A");
}
}
public class HandlerB : MessageHandler<MessageB>
{
public override void Execute(MessageB message)
{
Console.WriteLine("Message B");
}
}
How about this for a message router:
class Tester
{
public void Go()
{
var a = new MessageA();
var b = new MessageB();
var c = new MessageC();
var router = new MessageRouter();
router.RegisterHandler(new HandlerA());
router.RegisterHandler(new HandlerB());
router.Route(a);
router.Route(b);
router.Route(c);
}
}
class MessageRouter
{
Dictionary<Type, dynamic> m_handlers = new Dictionary<Type,dynamic>();
public void RegisterHandler<T>(IMessageHandler<T> handler)
{
m_handlers.Add(typeof(T), handler);
}
public void Route(dynamic message)
{
var messageType = message.GetType();
if (m_handlers.ContainsKey(messageType))
{
m_handlers[messageType].Handle(message);
}
else
{
foreach (var pair in m_handlers)
{
if(pair.Key.IsAssignableFrom(messageType))
{
pair.Value.Handle(message);
}
}
}
}
}
class MessageA
{
public virtual string A { get { return "A"; } }
}
class MessageB
{
public string B { get { return "B"; } }
}
class MessageC :MessageA
{
public override string A { get { return "C"; } }
}
interface IMessageHandler<T>
{
void Handle(T message);
}
class HandlerA : IMessageHandler<MessageA>
{
public void Handle(MessageA message)
{
Console.WriteLine(message.A);
}
}
class HandlerB : IMessageHandler<MessageB>
{
public void Handle(MessageB message)
{
Console.WriteLine(message.B);
}
}
How about taking a slightly different approach: Instead of registering the type of a handler, why not register the actual handler instance which will process the message? This gives you much greater flexibility in instantiation of the handler, and removes any type ambiguities.
The idea is to be able to do this:
// have several handler classes
class FooMessageHandler : IMessageHandler<Foo>
{ }
class BarMessageHandler : IMessageHandler<Bar>
{ }
// have them instantiated - allows you to pass much more context
// than Activator.CreateInstance is able to do
var fooMessageHandler = new FooMessageHandler(various params);
var barMessageHandler = new BarMessageHandler(various params);
// register actual instances
HandlerRegistry.Register<Foo>(fooMessageHandler);
HandlerRegistry.Register<Bar>(barMessageHandler);
// handler registry will simply dispatch the message to
// one of the handlers
HandlerRegistry.Dispatch(someFooMessage);
Not only that, but the approach allows you to register multiple handlers for each message type:
// these will all get called when a Foo message is received
HandlerRegistry.Register<Foo>(fooMessageHandler);
HandlerRegistry.Register<Foo>(someOtherFooHandler);
HandlerRegistry.Register<Foo>(yetAnotherFooHandler);
What if you inherit all you messages from common abstract MessageBase and instead of making message handler interface IMessageHandler<T> generic, put constraint on Execute method itself?
Namely void Execute<T>(T message) where T : MessageBase.
This way you get the desired functionality and your message handler resolver, HandlerRegistry, needs only a minor tweak. Just change return type & constraint from IMessageHandler<T> to IMessageHandler.
Below are slightly modified MessageBase, IMessageHandler and HandlerRegistry.
(Related dotnetfiddle here https://dotnetfiddle.net/e6M1UA)
// Message
public abstract class MessageBase
{
public virtual void Action() // ...for examples sake
{
Console.WriteLine(GetType().Name);
}
}
// Message handler
public interface IMessageHandler
{
void Execute<T>(T message) where T : MessageBase;
}
// Resolver
public static class HandlerRegistry
{
private static readonly Dictionary<string, Type> Handlers =
new Dictionary<string, Type>();
public static void Register<T, T2>() where T2 : IMessageHandler
{
Handlers.Add(typeof(T).FullName, typeof(T2));
}
public static IMessageHandler Resolve<T>(T parameters)
{
var type = Handlers[parameters.GetType().FullName];
return (IMessageHandler)Activator.CreateInstance(type);
}
}
Now, if you test it using e.g. following implementations
public class Message1 : MessageBase
{}
public class Message2 : MessageBase
{
public override void Action()
{
Console.Write(#"Overriding ");
base.Action();
}
}
public class Message1Handler : IMessageHandler
{
public void Execute<T>(T message) where T : MessageBase
{
Console.Write(#"MessageHandler1 > ");
message.Action();
}
}
public class Message2Handler : IMessageHandler
{
public void Execute<T>(T message) where T : MessageBase
{
Console.Write(#"MessageHandler2 > ");
message.Action();
Console.WriteLine(#"...and then some");
}
}
With this block of code
HandlerRegistry.Register<Message1, Message1Handler>();
HandlerRegistry.Register<Message2, Message2Handler>();
var messages = new List<MessageBase>()
{
new Message1(),
new Message2()
};
foreach (var message in messages)
{
var handler = HandlerRegistry.Resolve(message);
handler.Execute(message);
}
You'll end up with console log
MessageHandler1 > Message1
MessageHandler2 > Overriding Message2
...and then some
Let's say I have an interface IFoo
interface IFoo
{
int Bar();
int Bar2();
void VBar();
//etc,
}
Can I create a wrapper that takes any IFoo object and do something before/after the actual call?
e.g. when I do something like this
IFoo wrappedFoo = new Wrapper<IFoo>(actualFooObject).Object;
wrappedFoo.Bar();
then the wrapper.Bar() method actually execute something like this
PreCall(); //some code that I can define in the wrapper
actualFooObject.Bar();
PostCall();
Is there a simple and clean way to do this?
You can use Code Contracts for this approach. Take a look on section 2.8 Interface Contracts of user manual (pdf).
You can use AOP. I´ve been using this library for quite some time now:
http://www.postsharp.net/products
if you need to have something on PreCall() and PostCall , the simple way is to wrap under the proxy base approach
public abstract class ProxyBase
{
public void Execute()
{
PreCondition();
Call();
PostCondition();
}
private void PreCondition()
{
Console.WriteLine("ProxyBase.PreCondition()");
}
private void PostCondition()
{
Console.WriteLine("ProxyBase.PreCondition()");
}
protected abstract void Call();
}
public class AppProxy<T> : ProxyBase where T : IApp
{
private IApp _app;
public AppProxy<T> Init(IApp app)
{
_app = app;
return this;
}
protected override void Call()
{
Console.WriteLine("AppProxy.Call()");
_app.Call();
}
public IApp Object
{
get { return _app; }
}
}
public interface IApp
{
void Call();
}
public interface IFoo : IApp
{
}
public class ActualFoo : IApp
{
public void Call()
{
Console.WriteLine("ActualFoo.Call()");
}
}
class Program
{
static void Main(string[] args)
{
ActualFoo actualFoo = new ActualFoo();
var app = new AppProxy<IFoo>().Init(actualFoo);
app.Execute();
var o = app.Object as ActualFoo;
Console.ReadLine();
}
}
--------------- Output --------------
ProxyBase.PreCondition()
AppProxy.Call()
ActualFoo.Call()
ProxyBase.PreCondition()
I don't see a "clean and simple" way of doing this.
The best option I can come up with is writing a generic Wrapper<T> that encapsulates and instance of T and implements generic Precall and Postcall methods:
public class Wrapper<T>
{
protected T _instance;
public Wrapper(T instance)
{
this._instance = instance;
}
protected virtual void Precall()
{
// do something
}
protected virtual void Postcall()
{
// do something
}
}
So that you can write your own FooWrapper for interface IFoo (or any other interface) and just delegate method calls:
public class FooWrapper :Wrapper<IFoo>, IFoo
{
public FooWrapper(IFoo foo)
: base(foo)
{
}
public int Bar()
{
base.Precall(); return base._instance.Bar(); base.Postcall();
}
public int Bar2()
{
base.Precall(); return base._instance.Bar2(); base.Postcall();
}
public void VBar()
{
base.Precall(); base._instance.VBar(); base.Postcall();
}
}
So you can use it like this:
IFoo f = new ActualFooClass();
IFoo wf = new FooWrapper(f);
f.Bar();
Of course, if your Precall and Postcall methods are not generic, then there is really no point in using the Wrapper<T> class. Just go with the FooWrapper.