Shared Method with callback argument - c#

I would like to create a pattern like the following:
namespace SharedUtilities
{
public partial class PartialClass
{
public void DoSomethingInteresting()
{
DoSomethingPlatformSpecific();
}
partial void DoSomethingPlatformSpecific();
}
}
But I would like to add a callback argument so that I can pass in a different callback depending on the platform. Can anyone point me in the right direction here? I have been reading up on Action, EventHandler<>, and delegate, but I'm not sure which one to use in this scenario. Any advice would be appreciated.

There are a lot of ways to do that and handle this kind of scenario, the simplest one would be like this -
namespace SharedUtilities
{
public partial class PartialClass
{
public void DoSomethingInteresting(Action<Type1, Type2> action)
{
//code logic
action(p1, p2);
}
}
}
Then use it like this -
With lambda
(new SharedUtilities.PartialClass()).DoSomethingInteresting((param1, param2)=>
{
//codes
});
Without Lambda
public void DoSomethingInterestingSpecific(Type1 param1, Type2 param2)
{
//code logic
}
(new SharedUtilities.PartialClass()).DoSomethingInteresting(DoSomethingInterestingSpecific);
That is one way of doing this, there are other ways too, like abstract factory pattern, event delegate callback, etc.

Func<...> has a return value, Action<...> does not. Callbacks should usually be Action<...>
If you want to structure the code such that classes other than the one calling the function can be notified when it's complete, define an event.

Related

Get Func<T> request method Parameters in C#

I have two function which have some common functionality (i.e. to make connection with service and close connection after calling). I made a method named "InvokeService" with parameter of Func in it.How can I get parameters of request in InvokeService? I mean I need to get the object value of request? You can clear be clear by my demo code given below:
public void Method1(){
InvokeService(()=> _service.getMathod1(request);
}
public void Method2(){
InvokeService(()=> _service.getMathod2(request);
}
public void InvokeService(Func<T> request){
//service open
//I need here a complete object of the request of Method2 and its parameters
request.Invoke();
//service close
}
If any thing ambiguous or not understandable feel free to ask me.
You may want to use the template method pattern:
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
In your case, you can have something like this:
public abstract class AbstractClass
{
protected abstract void PrimitiveOperation();
public void TemplateMethod()
{
// before common functionality
PrimitiveOperation();
// after common functionality
}
}
class ConcreteClassA : AbstractClass
{
protected override void PrimitiveOperation()
{
// your A logic
}
}
class ConcreteClassB : AbstractClass
{
protected override void PrimitiveOperation()
{
// your B logic
}
}
If you want to return something different for each concrete class or have a different parameter depending the concrete class, you can achieve that with generics. Let me know if that is the case.
It can be solve by using Reflection;
request.GetMethodInfo()

Trigger a method before other method execution

Is there a way to call a method to be executed before another method, like a trigger?
Something like an attribute that indicates the method to be executed, like this:
[OnBefore(MethodToBeExecutedBefore)]
public void MethodExecutedNormally()
{
//method code
}
I have a situation that I need to call a check method very often, and most of the time, they are before methods that take too long to execute.
There is no built in way to achieve this result, if you are using a dependency injection mechanism you can use the interception facilities if the DI framework supports this. (Ex: Unity, NInject)
If you want to go low level you can also use Reflection.Emit to create a derived class at runtime, that overrides methods with a particular attribute that invokes any extra functionality you want, but that is more difficult.
What you are talking about is called AOP or Aspect Oriented Programming.
There are no built-in options in C#. While Attributes exists, there is no mechanism to take any actions with them. You always need a piece of code that reads those attributes and then does something. Attributes themselves are only metadata and markers.
As far as external tools go, Postsharp is the de-facto standard AOP postcompiler for .NET, but it's not free (at least not for real use, there is a free version you may want to try, maybe it's enough for your use-case).
I think you should consider an event driven approach.
You could create an interface and some base classes to handle the event, then have your long running classes inherit from it. Subscribe to the event and handle accordingly:
public delegate void BeforeMethodExecutionHandler<TArgs>(ILongRunningWithEvents<TArgs> sender, TArgs args, string caller);
public interface ILongRunningWithEvents<TArgs>
{
event BeforeMethodExecutionHandler<TArgs> OnBeforeMethodExecution;
}
public class LongRunningClass<TArgs> : ILongRunningWithEvents<TArgs>
{
private BeforeMethodExecutionHandler<TArgs> _onBeforeMethodExecution;
public event BeforeMethodExecutionHandler<TArgs> OnBeforeMethodExecution
{
add { _onBeforeMethodExecution += value; }
remove { _onBeforeMethodExecution -= value; }
}
protected void RaiseOnBeforeMethodExecution(TArgs e, [CallerMemberName] string caller = null)
{
_onBeforeMethodExecution?.Invoke(this, e, caller);
}
}
public class ConcreteRunningClass : LongRunningClass<SampleArgs>
{
public void SomeLongRunningMethod()
{
RaiseOnBeforeMethodExecution(new SampleArgs("Starting!"));
//Code for the method here
}
}
public class SampleArgs
{
public SampleArgs(string message)
{
Message = message;
}
public string Message { get; private set; }
}
Sample usage:
public static void TestLongRunning()
{
ConcreteRunningClass concrete = new ConcreteRunningClass();
concrete.OnBeforeMethodExecution += Concrete_OnBeforeMethodExecution;
concrete.SomeLongRunningMethod();
}
private static void Concrete_OnBeforeMethodExecution(ILongRunningWithEvents<SampleArgs> sender, SampleArgs args, string caller)
{
Console.WriteLine("{0}: {1}", caller ?? "unknown", args.Message);
}
The message SomeLongRunningMethod: Starting! will be output before the long-running method executes.
You could add the caller name to the args. I whipped this out real quick to illustrate.
UPDATE: I see you added tags for ASP.NET MVC. The concept still applies to controllers as controllers are just classes.

How to call a method implicitly after every method call?

Sorry for the terrific Title for the post. I am bit curious to know if below problem does have any solutions or not. The situation is I have a function called SaveSecurity(); which I need to call after every function. Like below:
public void AddUser(string ID, string Name, string Password)
{
///some codes
SaveSecurity();
}
public void DeleteUser(User ObjUser)
{
///some codes
SaveSecurity();
}
public void AddPermission(string ID, string Name, AccessType Access)
{
///some codes
SaveSecurity();
}
public void DeletePermission(Permission ObjPermission)
{
///some codes
SaveSecurity();
}
public void AddRole(string ID, string Name)
{
Roles.AddRole(ID, Name);
SaveSecurity();
}
public void SaveSecurity()
{
///Saves the data
}
And many more. So now if we look there is a similarity to all the function is that at last it calls for the SaveSecurity() after the end of the function. My question is:
Is there a way to call this function after every function with out writing the same line again and again?
My Class Diagram looks like this
You need to look into repository pattern,
Seperate your classes and there operations,
Create another layer (call it business layer) or whatever which will be calling different methods of different classes...
ATM you are trying to follow OOP but all you are doing is functional programming..
Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application
Edit After adding class diagram
Your collection classes are actually repository class, you will need to move your methods like deletePermissions, deleteRole to there respective repository classes like permissionsRepo (keep it named as collections if you want) and roleRepo..
So you already have an object class and a repository class of object (can be together) but I like to keep them separate, repostory classes will do what they need to do, like..
// Make changes to DB
// Make changes to AD
// Makes changes to web services etc...
Your manager class may dulicate methods of repository classes but they will only calling them,
PermissionManager.DeletePermissions(PermissionObject);
Then in PermissionManager Class you will have method,
DeletePermissions(Permissions pObject)
{
PermissionRepo.Delete(pObject);
}
Above is just adding a layer to make your code look more readable and future proof in very short time, but if you have more time to invest you can look into Observer pattern too...
Implement Observer pattern in C#
Each time your object changes it's state you can call SaveSecurity method (which will be in another class (Name it Changes maybe). If you don't want to call SaveSecurity for each change of object, you can add a property to your object e.g. IsSecurityChanged ? if yes then call SaveSecurity.
More to explain but if you look at Observer pattern above you will get an idea.
One more way but I won't personally recommend is, to use IDisposable interface, then in dispose method call SaveSecurity method for the object. BUT ITS NOT RECOMMENDED BY ME.
With just C# you can't, but there are some solutions that might help.
The best I know is PostSharp. It will give you the ability to define actions before and after a method is being called (for example). Some information on it can be found here and here.
The only thing you have to do then is to decorate the methods you want to call SaveSecurity for with an attribute.
If you don't want to use such tools, just keep it as is. It is okay the way it is.
You can use some kind of Aspect oriented programming (don't know how to do it in C#, but try googling it).
Another way that would not be better than simply calling one function at the end of another, would be create helper function with functional parameter that execute its parameter and then call your security function. But then body of each function would look something like (if I remember C# lambda correctly):
CallAndSaveSecurity(() => /* some code */);
So it would contain something extra as much as your original solution.
Btw, maybe you need more in your call anyway. If you want that function to be called even when exception happen, you need
try{
// some code
} finally {
SaveSecurity();
}
and hiding that into functional helper makes sense.
using System;
namespace Shweta.Question
{
public class User
{ }
public class Permission
{ }
public enum AccessType
{
none,
full,
other
}
public class Roles
{
public static void AddRole(string id, string name)
{
}
}
public class Shweta
{
public void AddUser(string ID, string Name, string Password)
{
///some codes
SaveSecurity();
}
public void DeleteUser(User ObjUser)
{
}
public void AddPermission(string ID, string Name, AccessType Access)
{
}
public void DeletePermission(Permission ObjPermission)
{
}
public void AddRole(string ID, string Name)
{
Roles.AddRole(ID, Name);
}
public void SaveSecurity()
{
///Saves the data
}
public TResult CallMethod<TResult>(Func<TResult> func)
{
try
{
return func();
}
catch (Exception e)
{
// Add Handle Exception
// replace the next line by exception handler
throw e;
}
}
public void CallMethod(Action method)
{
this.CallMethod(() => { method(); return 0; });
this.SaveSecurity();
}
public static void test()
{
var s = new Shweta();
s.CallMethod(() => s.AddRole("theId", "theName"));
s.CallMethod(() => s.DeleteUser(new User()));
s.CallMethod(() => s.AddPermission("theId", "theName", AccessType.full));
s.CallMethod(() => s.DeletePermission(new Permission()));
s.CallMethod(() => s.AddRole("theId", "theName"));
}
}
}

Method or Extension Method to Handle InvokeRequired

I can't quite come up with the solution to creating a generic method to handle the InvokeRequired for void methods (I'll deal with return values later). I was thinking something like:
// Probably not the best name, any ideas? :)
public static void CheckInvoke(this Control instance,
,Action<object, object> action)
{
if (instance.InvokeRequired)
{
instance.Invoke(new MethodInvoker(() => action));
}
else
{
action()
}
}
Then I could write something like:
public partial class MyForm : Form
{
private ThreadedClass c = new ThreadedClass();
public MyForm()
{
c.ThreadedEvent += this.CheckInvoke(this
,this.MethodRequiresInvoke
,sender
,e);
}
}
This doesn't compile obviously, I just can't quite tie it together.
Hans is correct, in that you probably don't want to wrap code like this up, especially since it can cause some debugging issues down the road in determining what thread actions are happening on. That said, this would be the signature you'd want:
public static class FormsExt
{
public static void UnwiseInvoke(this Control instance, Action toDo)
{
if(instance.InvokeRequired)
{
instance.Invoke(toDo);
}
else
{
toDo();
}
}
}
Loose Action parameters of "object,object" (as JerKimball suggests), name it SafeInvoke, and attach to event via anonymous delegate:
c.ThreadedEvent += delegate
{
c.SafeInvoke(this.MethodRequiresInvoke);
};

C#: Generics -- Infer the Generic Type of a Generic Type

I don't even know how to ask this question so I'll just give the code example.
Here is the domain:
public interface ISubscriptionProvider<T>
{
void Subscribe(Action<T> callback);
}
public class Notification {}
public class CurrentUserNotifications : ISubscriptionProvider<Notification>
{
public void Subscribe(Action<Notification> callback) { }
}
Here is the method I want to make magical:
public void Subscribe<P, T>(Action<T> callback) where P : ISubscriptionProvider<T>
{
// body left out -- code uses P
}
This works, and here is how you call it:
Subscribe<CurrentUserNotifications, Notification>((n) => Console.WriteLine(n));
So the question is: Is there any way to make it callable like this:
Subscribe<CurrentUserNotifications>((n) => Console.WriteLine(n));
Basically, can it infer that the action type should be just from the ISubscriptionProvider<T>.
This subscribe method lives on a static class (its a static method, I left that part out). The idea is that it will take care of constructing the ISubscriptionProvider<T> and keeping it a singleton (probably with structuremap). So in use:
Messages.Subscribe<CurrentUserNotifications>((n) => Console.WriteLine(n));
Thanks!
Update:
This is kinda off topic, but if any scala people read this ...
... is be an example of a higher kinded type? Something like:
public void Subscribe<P<T>>(Action<T> callback) { }
Where P<_> is the higher kinded type?
Why can't you just use
public void Subscribe<T>(Action<T> callback)
{
}
The type P Parameter is irrelevant in your scenario as it is never used.

Categories