How to call a method implicitly after every method call? - c#

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"));
}
}
}

Related

How/where to create a void method in CQRS pattern

I am trying to implement the CQRS pattern in clean architecture.
I know If a commads/query then i need to add a folder named as commads/query in applictionLayer.
Now I want to create a void method. not a command or query it is just a void method. and I want to use this again into my queries and commands.
public void FormatSomethingHtml(Something something)
{
something.FinePrint = _helper.FormatHtml(something.FinePrint, something.SiteCode.Name);
// removed rest
}
I don't know where should create this method.
If I create this method inside commandHandler, I could not reuse it.
i.e:
public class UpdateSomethingCommandHandler : IRequestHandler<UpdateSomethingCommand, Something>
{
// removed rest
public void FormatSomethingHtml(Something something)
{
something.FinePrint = _helper.FormatHtml(something.FinePrint, something.SiteCode.Name);
// removed rest
}
}
In above method I can use inside UpdateSomethingCommandHandler.
But I could not reuse it in another handler.
ie. When I call like this
new UpdateSomethingCommandHandler.FormatSomethingHtml(something); I got error.
Where can create a common method?
This should be a utility service and inject it in any query/handler you need.
Ex:
public interface IFormatService
{
void FormatSomethingHtml(Something something)
}
public class HtmlFormatService: IFormatService
{
public void FormatSomethingHtml(Something something)
{
something.FinePrint = _helper.FormatHtml(something.FinePrint, something.SiteCode.Name);
// removed rest
}
}
In your handler, you would inject it and use it just like any other service
Also, I would consider changing the return type to either Something so you can update the object and return ot or simply accept a string and return the formatted string like this:
public string FormatSomethingHtml(string something)
{
return _helper.FormatHtml(something.FinePrint, something.SiteCode.Name);
}
In your handler/query
var something = new Something();
something.Fingerprint = _formatter.FormatSomethingHtml(...)

Wrap all base calls in a derived type

So I have a few instances where I'd like to be able to do this but essentially I'd like to be able to wrap all calls to a Superclass in a derived type. Right now I'm trying to wrap all calls to base method in an Impersonator but I can see other uses for this as well.
An example being
public void CopyFile(string filePath, string destPath)
{
using(var I = new Impersonator("user", ".", "password"))
{
base.CopyFile(string filePath, string destPath);
}
}
Another convenient use might be
public void CopyFile(string filePath, string destPath)
{
try
{
base.CopyFile(string filePath, string destPath);
} catch(Exception e)
{
Log(e.Message);
}
}
Now I'd like to wrap all base calls similarly. Is there a convenient way to do this or do I have to wrap all of these manually?
I'm looking for something like a "foreach baseMethod in Superclass Do This"
Perhaps finding some way to capture incoming calls to the class and wrapping them as an action?
public void ActionWrapper(Action action)
{
try
{
action.Invoke();
} catch(Exception e)
{
Log(e.Message);
}
}
But how would I catch calls to the class in that way?
Honestly this is just to make the class more maintainable and reduce code bloat. I'm open to these or any other approaches.
First, I want to applaud your instinct to deconstruct code this way. Separating concerns like error handling/logging and security/identity from your business logic can do wonders for maintainability.
What you're describing is known as either decoration or interception. Mark Seemann has a good blog post comparing the two approaches in the context of logging.
Without using external tools (like a DI or AOP framework), I think the ActionWrapper method you proposed is a good start. I modified it to show impersonation rather than logging, since I think impersonation is a more interesting use case:
public void ActionWrapper(Action action)
{
using(var I = new Impersonator("user", ".", "password"))
{
action.Invoke();
}
}
So the question is: How to apply this method efficiently?
Let's assume your existing class is:
public class FileCopier
{
public void CopyFile(string filePath, string destPath)
{
// Do stuff
}
}
You could, as you suggested, create a derived class to add impersonation:
public class FileCopierWithImpersonation : FileCopier
{
public void CopyFile(string filePath, string destPath)
=> WithImpersonation(base.CopyFile(filePath, destPath));
public void WithImpersonation(Action action)
{
using(var I = new Impersonator("user", ".", "password"))
{
action.Invoke();
}
}
}
Here, FileCopierWithImpersonation serves as a decorator over FileCopier, implemented via inheritance. The WithImpersonation method serves as an interceptor that can apply an impersonation scope over any method.
That should work well enough, but it forces some compromises in implementation. The base class's methods will all need to be marked as virtual. The child class's constructor might need to pass arguments to the base class. It will be impossible to unit test the child class's logic independently of the base class's logic.
So, you might want to extract an interface (IFileCopier) and apply the decorator using composition rather than inheritance:
public class FileCopierWithImpersonation : IFileCopier
{
private readonly IFileCopier _decoratee;
public FileCopierWithImpersonation(IFileCopier decoratee)
{
// If you don't want to inject the dependency, you could also instantiate
// it here: _decoratee = new FileCopier();
_decoratee = decoratee;
}
public void CopyFile(string filePath, string destPath)
=> WithImpersonation(_decoratee.CopyFile(filePath, destPath));
public void WithImpersonation(Action action)
{
using(var I = new Impersonator("user", ".", "password"))
{
action.Invoke();
}
}
}
If you're using Visual Studio 2019, there's a refactoring option to "Implement Interface through..." that will automatically implement an interface by calling methods of a dependency of the same type. After that, a simple find/replace should be all that's needed to add the interceptor.
You could also look into code generation tools, like T4 Templates to auto-generate the decorators. Beware, though, that T4 is not supported in .NET Core. It looks to be a legacy technology at this point.
From a good design perspective, I would advise not to do this for 2 reasons:
If catching exception is the sole purpose, then don't do it. Catching and swallowing system exceptions is a bad practice
If you want to do some pre-setup or post-processing on every method of base then may be you should choose composition rather than inheritance here.
However, if you have made up your mind then using an array of delegates can solve your problem.
class Derived : Base
{
private Action[] AllActions;
public Derived()
{
AllActions = new Action[]
{
base.DoSomething1,
base.DoSomething2,
base.DoSomethingMore
};
}
public ActionWrapper(int index)
{
try
{
AllActions[index].Invoke();
} catch(Exception e)
{
Log(e.Message);
}
}
}
For simplicity I have used an array. Use a dictionary to keep a key for each base class method.
I see AOP has been suggested but not expanded upon, so I will attempt to cover it then.
I am assuming you are open to making your base class methods virtual. In this case using a Castle DynamicProxy might give you the flexibility you are after. It will allow you to not only inject code before and after parent method execution, but also change input/output parameters depending on your business requirements.
Here's an artist's impression on what your class might look like should you opt for it:
public class FileCopier
{
public virtual void CopyFile(string filePath, string destPath)
{
// do things here
}
}
public class ImpersonationInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
using (var I = new Impersonator("user", ".", "password"))
{
invocation.Proceed();
}
}
}
public class LoggingInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
try
{
invocation.Proceed();
}
catch (Exception e)
{
Log(e.Message);
}
}
}
public class CustomProxyGenerationHook : IProxyGenerationHook
{
public void MethodsInspected() {}
public void NonProxyableMemberNotification(Type type, MemberInfo memberInfo) {}
public bool ShouldInterceptMethod(Type type, MethodInfo methodInfo)
{
// decide whether you need to intercept your method here
return true;
}
}
void Main()
{
var generator = new ProxyGenerator();
var options = new ProxyGenerationOptions(new CustomProxyGenerationHook());
var fileCopierProxy = generator.CreateClassProxy(typeof(FileCopier),
options
new IInterceptor[] { // specify list of interceptors
new ImpersonationInterceptor(),
new LoggingInterceptor()
}
) as FileCopier;
fileCopierProxy.CopyFile("src", "dest");
}
Even if you've got a ton of classes and modifying them all by hand is not feasible, you can still work around it by opting for yet another technique called assembly weaving. Project Fody is a good starting point, and this particular problem is best solved with Virtuosity plugin - it basically rewrites your assembly on build to mark all methods virtual so you don't have to do it yourself.
public static T DecoratorActions<T>(string desc, Func<T> func)
{
return Log(desc, () => ImpersonateAndAct(func));
}
public static void DecoratorActions(string desc, Action action)
{
Log(desc, () => ImpersonateAndAct(action));
}
public string Read(string filepath)
{
return DecoratorActions($"Reading file at '{filepath}'",
() => fileService.Read(filepath));
}
Based on these very helpful answers I've been able to determine that, while I may not be able to automatically wrap all methods of a class. I can at least reduce boilplate code and separate concerns by using the Decorator Pattern instead of the standard inheritance.
As such I have a Log method which calls "Entering {methodName}" and "Exiting {methodName}" as well as try/catching for exceptions which it also logs before throwing.
Additionally an inline way of impersonating for a specific action in the ImpersonateAndAct method.
Both of these return type of T so they wrap calls to my decorated fileService without interfering with the products of those methods.
I marked #Xander as the correct answer as he was the chief inspiration for this approach but I wanted to leave an answer to share what I came up with.

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.

First experience of using interfaces in C#?

I have an interface:
interface ISqlite
{
void insert();
void update();
void delete();
void select();
}
And custom service class:
class SqliteService
{
public SQLiteDatabase driver;
public SqliteService() {
SqliteConnection(new SQLiteDatabase());
}
public void SqliteConnection(SQLiteDatabase driver)
{
this.driver = driver;
}
public void select(ISqlite select) {
select.select();
}
public void insert(ISqlite insert) {
insert.insert();
}
public void delete(ISqlite delete)
{
delete.delete();
}
}
And last class Pacients that realizes ISqlite interface:
class Pacients: ISqlite
{
public List<ClientJson> pacients;
public Pacients() {
this.pacients = new List<ClientJson>();
}
public void add(ClientJson data) {
this.pacients.Add(data);
}
public void insert()
{
throw new NotImplementedException();
}
/* Others methos from interface */
}
I try to use my code like as:
/* Create instance of service class */
SqliteService serviceSqlite = new SqliteService();
/* Create instance of class */
Pacients pacient = new Pacients();
pacient.add(client);
serviceSqlite.insert(pacient);
As you can see above I send object pacient that realizes interface ISqlite to service. It means that will be called method insert from object pacient.
Problem is that I dont understand how to add data in this method using external class: SQLiteDatabase()? How to get access to this.driver in service class from object pacient?
Edit 1
I think I must move instance of connection new SQLiteDatabase() to db inside Pacients class is not it?
Generally speaking, I would favor a solution where the data objects themselves don't know anything about how they're stored, i.e. they have no knowledge of the class that communicates with the database. Many ORMs do just that.
Of course it might not be easy depending on the specifics of your situation... Try to examine what your methods on each object actually need; generally speaking they need the values of properties, and what column each property corresponds to, right? So any external class can do this if it knows these bits of information. You can specify the name of the column with a custom attribute on each property (and if the attribute isn't there, the column must have the same name as the property).
And again, this is the most basic thing that ORMs (Object Relational Mappers) do, and in addition they also manage more complicated things like relationships between objects/tables. I'm sure there are many ORMs that work with SqlLite. If you're OK with taking the time to learn the specifics of an ORM, that's what I would recommend using - although they're not silver bullets and will never satisfy all possible requirements, they are in my opinion perfect for automating the most common day to day things.
More to the point of the question, you can of course make it work like that if you pass the SQLiteDatabase object to the methods, or keep it in a private field and require it in the constructor or otherwise make sure that it's available when you need it; there's no other simple solution I can think of. And like you pointed out, it implies a certain degree of coupling.
You can change the signature of interface's methods to pass an SQLiteDatabase object.
interface ISqlite
{
void insert(SQLiteDatabase driver);
void update(SQLiteDatabase driver);
void delete(SQLiteDatabase driver);
void select(SQLiteDatabase driver);
}
Example call from the service:
public void insert(ISqlite insert)
{
insert.insert(driver);
}
I think you can figure out the rest by yourself.

Organizing methods for better accessing them

I'm trying to create a general library which would have all methods for managing data on our database.
This library will have a lot of methods so I would like to make it more organized. I would like it to be used with the following syntax.
db.setData().insertNewAccount(username, password);
db.modifyData().deleteAccount(username, password);
db.getData().getAccount();
How would I make it work like that if I type setData for example methods related to setData would show up.
It sounds like you're approaching this the wrong way - typically you'd have something like an AccountRepository class with all the members relating to accounts; then you'd have (say) an ArticleRepository class with all the members relating to articles.
In other words, organize by the kind of data you're dealing with rather than whether you're trying to fetch, update, insert etc.
Then you can use dependency injection so that each business class will be given just the repositories it uses.
If you really want to do it that way, then you could do something like this (pseudo code):
class DataRepository
{
public SetDataHelper setData()
{ return new SetDataHelper(); }
public ModifyDataHelper modifyData()
{ return new ModifyDataHelper(); }
public GetDataHelper getData()
{ return new GetDataHelper(); }
}
class SetDataHelper
{
public void insertNewAccount(username, password) { ... }
}
class ModifyDataHelper
{
public void deleteAccount(username, password) { ... }
}
class GetDataHelper
{
public Account getAccount() { ... }
}
And then you could do it your way, more fluently:
var db = new DataRepository();
db.setData().insertNewAccount(username, password);
db.modifyData().deleteAccount(username, password);
db.getData().getAccount();
You can create different interfaces, with different functionality, and your class can implement all of them. And then, your setData() can return the class itself, cast to the correcponding interface. E.g:
interface SetData {
int insertNewAccount(A, B);
}
interface ModifyData {
int deleteAccount(A, B);
}
interface GetData {
int getAccount(A, B);
}
class DBHandler : SetData, ModifyData , GetData {
//
// Implement the interfaces...
//
// Returns the interfaces
SetData setData(){ return (SetData)this; }
ModifyData modifyData (){ return (ModifyData )this; }
GetData getData (){ return (GetData )this; }
}
It does what you want, of course use the access modifiers accordingly your project. And this solution doesn't stop you from reaching the implemented interface functions directly, that would need another class, or something to proxy all call toward the DB class.

Categories